C# and the .NET Platform [2 ed.] 9781590590553, 1590590554

The first edition of thise book was released during the 2001 TechEd conference in Atlanta, Georgia. Since then, C# and t

453 32 18MB

English Pages 1187 Year 2003

Report DMCA / Copyright

DOWNLOAD PDF FILE

Recommend Papers

C# and the .NET Platform [2 ed.]
 9781590590553, 1590590554

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Ba ck Co ver ISBN:1590590554 by Andr ew Tr oelsen C# an d t h e .NET Plat for m , Secon d Ed it ion star ts w ith a brief over view of the C# langu age and then quickly m oves Apr ess © 2003 (1200 pages) to key technical and ar chitectur al issues for .NET dev eloper s. Not only is ther e ex tensive cover age of t he .NET This ehensiv texts star ts am w ith a sbrief ovthey er view of the Fr amew or k, but Andr ew compr Tr oelsen also e show pr ogr m er w hat need to know abou t such necessar y , but language then and quickly oves to keythe technical and r em ot ing pr otocol. Reader s w ill also subtle, ar eas as the C# pr oper use ofand thr eads howmto leverage new .NET ar chitectur al issues for developer s. see how to use C# for GUI applications wit h.NET a com plete discussion of Windows Form s, custom contr ols, and GDI + . Ther e are equally useful discussions on how to use C# and .NET for Web developm ent, Web ser vices, and data access Fr om Window s- based t o Web- based applications, it's all her e. Ther e ar e det ailed discussions Ta ble ousing f ConADO.NET. t en t s of every aspect of .NET development and useful examples w ith no t oy code. C# and t he .NET Plat for m, Second Edition I ntr oduction

Ab ou t th e Aut h or

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Andr ew Tr1oelsen a partn er , tofrainer Chapter - TheisPhilosophy .NET, and consultant at I nter tech- I nc., a .NET and J2EE developer education center ( http: / / w w w .inter tech-inc.com ) . He is a leading author ity on both .NET and COM. His ear lier five-star t reatm ent of - Building C# -selling Applications trChapter aditional2 COM in the best Dev eloper 's Wor kshop to COM and ATL 3.0 is mir r or ed in his latest book , COM Pa r t Tw o The C# Pr ogr am m ing and .NET I nter oper ability , and his La awngua ard- wge inning tr eatm ent of C# in C# an d t h e .NET Plat for m , as w ell as his fivestar invest igation of VB .NET in Visu al Basic .NET an d t h e .NET Plat for m : An Ad van ced Gu id e . He has a degr ee in Chapter 3 - C# Language Fundamentals m athematical linguistics and South Asian studies fr om the Univ er sit y of Minnesota and is a fr equent speaker at Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# num er ous .NET- related confer ences. Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion C# and the .NET Platform, Second Edition ISBN:1590590554 by Andr ew Tr oelsen

ANDREW TROELSEN Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s

Copyright © 2003 Troelsen C# and t he .NET Platby forAndrew m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, Philosophy of .NET electronic -orThe mechanical, including photocopying, recording, or by any information storage or retrieval Chapter 2 Building C# Applications system, without the prior written permission of the copyright owner and the publisher. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge ISBN: 1-59059-055-4 Chapter 1

Chapter 3

- C# Language Fundamentals

Printed4and bound in iented the United Chapter - Obj ect -Or Pr ogrStates am mingofwAmerica ith C# 12345678910 Chapter 5

- Exceptions and Obj ect Lifetim e

Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence - I nter faces and Collections of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark Chapter 7 - Callback I nter faces, Delegates, and Ev ents owner, with no intention of infringement of the trademark. Chapter 6 Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ngGregory w i th .N ET bl ie s Technical Reviewers: A.Assem Beamer, Gary

Cornell, Eric Gunnerson, Joe Nalewabau, Kent

Chapter 9 Nick - Under standing .NET AssemTapadiya blies Sharkey, Symmonds, Pradeep Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Editorial Dan Appleman, Gary Cornell, Simon Martin Chapter 11 Directors: - Type Reflection, Late Binding, and Attr ibuteBasedHayes, Pr ogramm ingStreicher, Karen Watterson, John Zukowski Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Assistant Publisher: Grace Wong

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better ing Fr amew or k ( Knox GDI + ) Copy Editors: AnnePaint Friedman and Ami Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Proofreader: LizSyBerry Chapter 16 - The stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Production Goddess: Susan Glinert Stevens

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 Ron - ASP.NET Web Pages and Web Contr ols Indexer: Strauss Chapter 19 - ASP.NET Web Applicat ions

Artist and Designer: Chapter 20 - Cover XML Web Ser vices Kurt Krames I ndex

Manufacturing Manager: Tom Debolski

List of Figur es List Distributed of Tables to the book trade in the United States by Springer-Verlag New York, Inc., 175 Fifth Avenue,

New York, NY, 10010 and outside the United States by Springer-Verlag GmbH & Co. KG, Tiergartenstr. 17, 69112 Heidelberg, Germany. In the United States: phone 1-800-SPRINGER, email , or visit http://www.springer-ny.com. Outside the United States: fax +49 6221 345229, email , or visit http://www.springer.de. For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley, CA 94710. Phone 510-549-5930, fax 510-549-5939, email , or visit http://www.apress.com. 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 http://www.apress.com in the Downloads C# an d th e .N ET Plat f orm , Se con d Ed it ion section. ISBN:1590590554

by Andr ew Tr oelsen

Apr ess this © 2003 (1200 I would like to dedicate book topages) my father, Wally Troelsen. Thanks, Dad, for all of your support over the years and theThis years to com e. e text star ts w ith a brief ov er view of the compr ehensiv C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Luv ya, Damn Kid

the tAuthor TaAbout ble o f Con en t s C# and t he .NET Plat for m, Second Edition

Andrew Troelsen is a partner, trainer, and consultant at Intertech-Inc., a .NET and J2EE developer education center (http://www.intertech-inc.com). He is a leading authority on both .NET and Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m COM. His earlier five-star treatment of traditional COM in the best-selling Developer's Workshop to COM Chapter 1 - The Philosophy of .NET and ATL 3.0 is mirrored in his latest book, COM and .NET Interoperability, and his award-winning Chapter 2 - Building C# Applications treatment of C# in C# and the .NET Platform, as well as his five-star investigation of VB .NET in Visual Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Basic .NET and the .NET Platform: An Advanced Guide. He has a degree in mathematical linguistics and Chapter 3 - C# Language Fundamentals South Asian studies from the University of Minnesota and is a frequent speaker at numerous .NET-related Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# conferences. I ntr oduction

Chapter 5

- Exceptions and Obj ect Lifetim e He currently livesfaces in Minneapolis, Minnesota, with his wife Amanda, and spends his free time investigating Chapter 6 - I nter and Collections

.NET and forI the win the Stanley Chapter 7 waiting - Callback nterWild faces,toDelegates, and Ev Cup, ents the Vikings to win the Super Bowl (before he retires would be and the to grab numerous NBA championship titles. Chapter 8 nice), - Advanced C#Timberwolves Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Acknowledgments

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, and Threads Completing the secondAppDomains, edition of C#Cont andexts, the .NET Platform would have been completely impossible Chapter Type Reflection, Late Binding, Attr ibute- Based Pr ogramm without11 the- assistance and talent offered and by numerous individuals. Firsting of all, many thanks to my copy Pa r t Four Anne - Le veFriedman r a ging the and .NETAmi LibrKnox. a r ie s editors,

Both of you, as always, did an outstanding job massaging my raw

Chapter 12 - into Obj ect Ser ialization and the .NET Lay er manuscript a polished product. (See youRemoting both on the nextbook?) Next, I must thank the numerous Chapter technical 13 reviewers - Building who a Bettook ter Win thedow time( Int to roducin read these g Window chapters s For ms) for any coding faux pas: Gregory A. Beamer,

Gary Cornell, Eric Gunnerson, Joe Nalewabau, Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Kent Sharkey, Nick Symmonds, and Pradeep Tapadiya. Special15thanks toam Beth Christmas, Ron Form Strauss, Susan Chapter - Pr ogr ming with Windows s Contr ols Glinert Stevens, and Liz Berry, whose combined efforts formatted, and espace finalized this text to completion. Of course, any remaining errors (spelling, Chapter 16 - The Syindexed, stem .I O Nam coding,17 or -otherwise) that may have snuck into this book are my sole responsibility. Chapter Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

I also must say a huge thanks to all of those at Apress who have made a publishing company that is a pleasure to work with. Thanks to Hollie Fisher (for many things), Doris Wong (for many more things), and Chapter 19 - ASP.NET Web Applicat ions Grace Wong, my chaka friend, for not totally blasting me into pieces when I abused the phrase "I'll get it to Chapter 20 - one XMLtoo Web Ser vices you today" many times. Chapter 18 - ASP.NET Web Pages and Web Contr ols

I ndex

Thanks toes my friends and family who (once again) tolerated my lack of time and sometimes grumpy List of Figur demeanor. List of Tables More thanks to my friends at Intertech-Inc. (not Tom Salonek, who I still don't like much). Your support (directly and indirectly) is greatly appreciated. Finally, thanks to my wife Mandy and "all the kids" for their love and encouragement.

C# an d th e .N ET Plat f orm , Se con d Ed it ion Introduction by Andr ew Tr oelsen

ISBN:1590590554

Apryears ess © ago 2003 when (1200 pages) I remember a time I proposed a book to Apress regarding a forthcoming software SDK This compr ehensiv e text star(NGWS). ts w ith a brief ov er viewalready of the know, NGWS eventually named Next Generation Windows Services As you may C# language and then quickly m oves to key technical and became what we now know as the .NET platform. My research of the C# programming language and the ar chitectur al issues for .NET developer s.

.NET platform took place in parallel with the authoring of the text. It was a fantastic project; however, I must confess that it was more than a bit nerve-wracking writing about a technology that was undergoing changes Tadrastic ble o f Con t en t sover the course of its development. It pains me to recall how many chapters had to be completely destroyed and rewritten during that time. Thankfully, after many sleepless nights, the first C# and t he .NET Plat for m, Second Edition edition of C# and the .NET Platform was published in con-junction with the release of .NET Beta 2, circa I ntr oduction the summer of 2001. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 -point, The Philosophy of extremely .NET Since that I have been happy and grateful to see that the first edition of this text was very Chapter 2 Building C# Applications well received by the press and, most importantly, the readers. Over the years, it was nominated as a Jolt Pa r t Tw ofinalist - The C# Pr ogr m ing ngua gethe award (I lost ... am crap!) asLawell as

2003 Referenceware programming book of the year (I won ...

Chapter - C# Language Fundamentals cool!). 3Although the first edition of this book has enjoyed a good run, it became clear that a second edition Chapter 4 - Obj ect -Or iented Pr ogr am ith C# brought about with the minor release of the .NET was in order—not only to account forming the w changes Chapter platform, 5 but - Exceptions to expandand upon Objand ect Lifetim improve e the existing content. As I write this frontmatter, version 1.1 of the

.NET platform is faces just about official, and I am happy to say that C# and the .NET Platform, Second Edition is Chapter 6 - I nter and Collections being released in tandem. Chapter 7 - Callback I nter faces, Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

As in the first edition, this second edition presents the C# programming language and .NET base class libraries using a friendly and approachable tone. I have never under-stood the need some technical Chapter 9 - Under standing .NET Assem blies authors have to spit out prose that reads more like a GRE vocabulary study guide than a readable Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads discourse. As well, this new edition remains focused on providing you with the information you need to Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing build software solutions today, rather than spending too much time focusing on esoteric details that few Pa r t Four - Le ve r a ging the .NET Libr a r ie s individuals will ever actually care about. To this end, when I do dive under the hood and check out some Chapter 12 - Obj ect Ser ialization andCLR the .NET Remoting Lay code), er more low-level functionality of the (or blocks of CIL I promise it will prove enlightening (rather Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms) than simple eye candy). Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

We 're a Team, You and I

Chapter 16 - The Sy stem .I O Nam espace

Chapter 17 - Data Access w ith Technology authors write for ADO.NET a demanding group of people (I should know, I'm one of them). You know Pa r t Fibuilding ve - W e b Appl ica tisolutions ons and Xusing ML W any e b Se r vi ces that software platform

is extremely detailed and is very specific to your

Chapter 18 - ASP.NET Web Pages and and Websubject Contr olsmatter. Perhaps you work in the electronic publishing department, company, client base, Chapter 19develop - ASP.NET Web Applicat industry, systems for the ions state or local government, work at NASA or a branch of the military. Chapter Speaking 20 for - XML myself, Web ISer have vices developed children's educational software, various n-tier systems, as well as

numerous projects within the medical and financial world. The chances are almost 100 percent that the I ndex code you write at your place of employment has little to do with the code I write at mine (unless we List of Figur es happened List of Tablesto work together previously! ). Therefore, in this book, I have deliberately chosen to avoid creating examples that tie the example code to a specific industry or vein of programming. Rather, I choose to explain C#, OOP, the CLR, and the .NET base class libraries using industry-agnostic examples. Rather than having every blessed example fill a grid with data, calculate payroll, or whatnot, I'll stick to subject matter we can all relate to: automobiles (with some geometric structures and employees thrown in for good measure). And that's where you come in. My job is to explain the C# programming language and the core aspects of the .NET platform the best I possibly can. As well, I will do everything I can to equip you with the tools and strategies you need to continue your studies at this book's conclusion. Your job is to take this information and apply it to your specific programming assignments. I obviously understand that your projects most likely don't revolve around automobiles with pet names; however, that's what applied knowledge is all about! Rest assured, once you understand the concepts presented within this text, you will be in a perfect position to build .NET solutions that map to your own unique programming environment.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# of an dthe th e .N ET Plat f ormEdition , Se con d Ed it ion An Overview Second ISBN:1590590554

by Andr ew Tr oelsen

C# and the .NET Apr Platform, Second Edition is logically divided into five distinct sections, each of which ess © 2003 (1200 pages) contains some number of chapters together." you read the first edition of this text, This compr ehensiv ethat textsomehow star ts w ith"belong a brief ov er view of Ifthe you will notice some similarities in chapter names; however, be aware that just about every page has been C# language and then quickly m oves to key technical and chitecturYou al issues for .NET developer s. topics in the first edition (such as .NET updated with newarcontent. will also notice that some delegates) have been moved into an entire chapter of their very own. Of course, as you would hope, the second edition contains several brand new chapters (such as an exploration of .NET Remoting, and a Tamuch ble o fdeeper Con t enexamination ts of ASP.NET). C# and t he .NET Plat for m, Second Edition

Onoduction the flip side, I did choose to remove some topics from the second edition to make room for new I ntr content. most ng notable omission topic Pa r t One - The I nt r oduci C# a nd the .NETisPthe la tf or m

of COM and .NET interoperability, which in no way, shape,

or form1reflects importance of this topic. In fact, I felt this topic was so important, that I wrote an entire Chapter - The the Philosophy of .NET book on subject.C# If you require a detailed examination, check out COM and .NET Interoperability Chapter 2 the - Building Applications (Apress, Pa r t Tw o - 2002). The C# Pr ogr am m ing La ngua ge Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

These things being said, here is a chapter-by-chapter breakdown of the text.

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET C# Plat fand orm , Se con d.NET Ed it ionPlatform Part One: Introducing the by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

Chapter 1: This Thecompr Philosophy of .NET ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

This first chapter ar functions as the backbone for the remainder of this text. We begin by examining the chitectur al issues for .NET developer s. world of traditional Windows development and uncover the short-comings with the previous state of affairs. The primary goal of this chapter, however, is to acquaint you with a number of .NET-centric building blocks such thet en common language runtime (CLR), Common Type System (CTS), Common Language Ta ble oas f Con ts Specification (CLS), and the base class libraries. You also take an initial look at the C# programming C# and t he .NET Plat for m, Second Edition language, the role of the .NET assembly, and various development utilities that ship with the .NET SDK. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter - The 2:Philosophy Building of .NET C# Applications

Chapter 1 Chapter 2

- Building C# Applications

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

The goal of this introduce you Pa r t Tw o - The C# chapter Pr ogr amismto ing La ngua ge

to the process of compiling and debugging C# source code files using various approaches. First, you learn to make use of the command-line compiler (csc.exe) and Chapter 3 - C# Language Fundamentals examine each of the corresponding command-line flags. Over the remainder of the chapter, you learn Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# how to make use of the Visual Studio .NET IDE, navigate the official .NET help system (MSDN), and Chapter 5 - Exceptions and Obj ect Lifetim e understand the role of XML-based source code comments.

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# anC# d th Programming e .N ET Plat f orm , Se con d Ed it ion Part Two: The Language by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

Chapter 3: This C#compr Language Fundamentals ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

This chapter examines the core constructs of the C# programming language. Here you come to ar chitectur al issues for .NET developer s. understand basic class construction techniques, the distinction between value types and reference types, iteration and decision constructs, boxing and unboxing, and the role of everybody's favorite base class, TaSystem.Object. ble o f Con t en t sAlso, Chapter 3 illustrates how the .NET platform places a spin on various commonplace programming such asEdition enumerations, arrays, and string processing. C# and t he .NETconstructs Plat for m, Second I ntr oduction

Chapter 4: Object-Oriented Programming with C#

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET The role 4 isApplications to examine the details of how C# accounts for each "pillar" of object-oriented Chapter 2 of- Chapter Building C#

programming: encapsulation, Pa r t Tw o - The C# Pr ogr am m ing inheritance, La ngua ge

and polymorphism. In addition to examining the syntax used to build class hierarchies, you are exposed to various tools within Visual Studio .NET which may be used to Chapter 3 - C# Language Fundamentals decrease your typing time. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 5: faces Exceptions - I nter and Collectionsand Object Lifetime

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Here you learn how to handle runtime anomalies using the official error handling mechanism of the .NET Chapter 8 - Advanced C# Type Const ruction Techniques platform: structured exception handling. As you will see, exceptions are class types that contain Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s information regarding the error at hand and can be manipulated using the "try", "catch", "throw", and Chapter 9 - Under standing .NET Assem blies "finally" keywords of C#. The latter half of this chapter examines how the CLR manages the memory Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads consumed by allocated objects using an associated garbage collector. This discussion also examines the Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing role of the IDisposable interface, which is a perfect lead-in to the next chapter. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 6: Interfaces and Collections

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

This material builds upon your understanding of object-based development by checking out the topic of interface-based programming. Here you learn how to define types that support multiple behaviors, how to Chapter 16 - The Sy stem .I O Nam espace discover these behaviors at runtime, and how to selectively hide select behaviors using explicit interface Chapter 17 - Data To Access w ith ADO.NET implementation. showcase the usefulness of interface types, the remainder of this chapter examines Pa r t Fi ve W e b Appl ica ti ons and X ML WAs e byou Se r vi cessee, this region of the base class libraries contains the System.Collections namespace. will Chapter 18 ASP.NET Web Pages and Web Contr ols or serve as a foundation for the development of strongly numerous types that may be used out of the box, Chapter 19 - ASP.NET Web Applicat ions typed collections. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 20 - XML Web Ser vices I ndex

Chapter 7: Callback Interfaces, Delegates, and Events

List of Figur es

List of chapter Tables begins by examining how interface-based programming techniques can be used to build an This

event-based system. This will function as a point of contrast to the meat of Chapter 7: the delegate type. Simply put, a .NET delegate is an object that "points" to other methods in your application. Using this pattern, you are able to build systems that allow multiple objects to engage in a two-way conversation. After you examine the use of .NET delegates, you are then introduced to the C# "event" keyword, which is used to simplify the manipulation of raw delegate programming.

Chapter 8: Advanced C# Type Construction Techniques The final chapter of this section completes your study of the C# programming language by introducing you to a number of advanced programming techniques. For example, here you learn how to overload operators and create custom conversion routines (both implicit and explicit), as well how to manipulate Cstyle pointers within a *.cs code file. This chapter also takes the time to explain how these C#-centric programming constructs can be accessed by other .NET programming languages (such as Visual Basic .NET), which is a natural lead-in to the topic of .NET assemblies.

an d th e .N ET Plat f orm , Se.NET con d EdAssemblies it ion Part Three:C#Programming with by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

Chapter 9: This Understanding .NET Assemblies compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

From a very highar level, an assembly can be considered the term used to describe a managed *.dll or *.exe chitectur al issues for .NET developer s. file. However, the true story of .NET assemblies is far richer than that. Here you learn the distinction between single-file and multifile assemblies and how to build and deploy each entity. Next, this chapter and shared assemblies may be configured using XML-based *.config files and Taexamines ble o f Conhow t en tprivate s publisher policy *.dlls. Along the Edition way, you investigate the internal structure of the Global Assembly Cache C# and t he .NET Plat for m, Second (GAC) and learn how to force Visual Studio .NET to display your custom assemblies within the Add I ntr oduction Reference dialog box (trust me, this is one of the most common questions I am asked). Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

Chapter 10: Processes, - Building C# Applications AppDomains, Contexts, and Threads

Chapter 2

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Now that a solidFundamentals understanding of assemblies, this chapter dives much deeper into the Chapter 3 you - C#have Language

composition of a loaded .NET executable. The goal of Chapter 10 is to define several terms and illustrate - Obj ect -Or iented Pr ogr am ming w ith C# the relationship between processes, application domains, contextual boundaries, and threads. Once these Chapter 5 - Exceptions and Obj ect Lifetim e terms have been qualified, the remainder of this chapter is devoted to the topic of building multithread Chapter 6 - I nter faces and Collections applicationsusing the types of the System.Threading namespace. Be aware that the information Chapter 7 - Callback I nter faces, Delegates, and Ev ents presented here provides a solid foundation for understanding the .NET Remoting layer (examined in Chapter 8 - Advanced C# Type Const ruction Techniques Chapter 12). Chapter 4

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 11: Type Reflection, Late Binding, and Attribute-Based Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Programming Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter our examination of .NET assemblies Chapter 1211 - concludes Obj ect Ser ialization and the .NET Remoting Lay er by checking out the process of runtime type discovery the System.Reflection Using these types, you are able to build applications that Chapter 13 via - Building a Bet ter Win dow namespace. ( Int roducin g Window s For ms) can read onorthe fly (think object browsers). Next, you learn how to dynamically Chapter 14 an - Aassembly's Better Paintmetadata ing Fr amew k ( GDI +)

activate and manipulate types at runtime using late binding. The final topic of this chapter explores the role of .NET attributes (both standard and custom). To illustrate the usefulness of each of these topics, the Chapter 16 - The Sy stem .I O Nam espace chapter concludes with the construction of an extendable Windows Forms application. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat , Se con d Ed it ion Part Four: Leveraging thef orm .NET Libraries ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Chapter 12:This Object Serialization and the .NET Remoting Layer compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

Contrary to popular belief, XML Web services are not the only way to build distributed applications under ar chitectur al issues for .NET developer s. the .NET platform. Here you learn about the managed equivalent of the (now legacy) DCOM architecture: .NET Remoting. Unlike DCOM, .NET supports the ability to easily pass objects between application and boundaries using marshal-by-value (MBV) and marshal-by-reference (MBR) semantics. Also, the Tamachine ble o f Con t en t s runtime behavior of a distributed .NET application can be altered without the need to recompile the client C# and t he .NET Plat for m, Second Edition and server code bases using XML configuration files. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter - The 13: Philosophy Building of .NET a Better Window (Introducing Windows Forms)

Chapter 1 Chapter 2

- Building C# Applications

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Despite term .NET, the base classgelibraries Pa r t Tw o -the The C# Pr ogr am m ing La ngua

provide numerous namespaces used to build traditional GUI-based desktop applications. Here you begin your examination of the System.Windows.Forms Chapter 3 - C# Language Fundamentals namespace and learn the details of building main windows (as well as MDI applications) that support Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# menu systems, toolbars, and status bars. As you would hope, various aspects of the Visual Studio .NET Chapter 5 - Exceptions and Obj ect Lifetim e IDE are examined over the flow of this material.

Chapter 14: A C# Better Painting Framework (GDI+) Chapter 8 - Advanced Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

This chapter examines how to dynamically render graphical data in the Windows Forms environment. In - Under standing .NET Assem blies addition to learning how to manipulate fonts, colors, geometric images, and image files, you also examine Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads hit testing and GUI-based drag-and-drop techniques. You learn about the new .NET resource format, Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing which, as you may suspect by this point in the text, is based on XML data representation. By way of a Pa r t Four - Le ve r a ging the .NET Libr a r ie s friendly heads up, don't pass over this chapter if you are primarily concerned with ASP.NET. As you will Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er see later in Chapter 18, GDI+ can be used to dynamically generate graphical data on the Web server. Chapter 9

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15: Programming with Windows Forms Controls

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

This final Windows-centric chapter examines numerous GUI widgets that ship with the .NET Framework.

Chapter 17do - Data Access w ith Not only you learn how to ADO.NET program against the core Windows Forms controls, but you also learn about Pa r t Fi ve - W topics e b Applof ica ti ons and ML W e b Se r viand ces the related dialog box Xdevelopment

Form inheritance, and how to build customWindows

Chapter - ASP.NET Pages and Web Contr ols Forms 18 controls. If youWeb have a background in ActiveX control development, you will be pleased to find that Chapter 19 - ASP.NET Web Applicat ions the process of building a custom GUI widget has been greatly simplified (especially with regard to design Chapter 20 - XML Web Ser vices time support). I ndex List of Figur es

Chapter 16: The System.IO Namespace

List of Tables

As you can gather from its name, the System.IO namespace allows you to interact with a machine's file and directory structure. Over the course of this chapter, you learn how to programmatically create (and destroy) a directory system as well as move data into and out of various streams (file based, string based, memory based, and so forth). In addition, this chapter illustrates some more exotic uses of System.IO, such as monitoring a set of files for modification using the FileSystemWatcher type. We wrap up by building a complete Windows Forms application that illustrates the relationship between object serialization (described in Chapter 12) and file I/O operations.

Chapter 17: Data Access with ADO.NET ADO.NET is an entirely new data access API that has practically nothing to do with classic (COM-based) ADO. Here you learn about the fundamental shift away from Universal Data Access (UDA) to a namespace-based data access mentality. As you will see, you are able to interact with the types of ADO.NET using a "connected" and disconnected" layer. Over the course of this chapter, you have the chance to work with both modes of ADO.NET, and come to understand the role of data readers,

DataSets, and DataAdapters. The chapter concludes with coverage of various data-centric wizards of C# an d th e .N ET Plat f orm , Se con d Ed it ion Visual Studio .NET. by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dApplications th e .N ET Plat f orm ,and Se conXML d Ed it ion Part Five: Web Web Services by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

Chapter 18:This ASP.NET Web Pages and Web Controls compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

This chapter begins your study of Web technologies supported under the .NET platform. ASP.NET is a ar chitectur al issues for .NET developer s. completely new approach for building Web applications and has absolutely nothing to do with classic (COM-based) ASP. For example, server-side scripting code has been replaced with "real" object-oriented Talanguages ble o f Con t(such en t s as C#, VB.NET, managed C++ and the like). This chapter introduces you to key ASP.NET topics such asSecond workingEdition with (or without) code behind files, the role of ASP.NET Web controls C# and t he .NET Plat for m, (including the mighty DataGrid), validation controls, and interacting with the base class libraries from I ntr oduction *.aspx files. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

Chapter 19: ASP.NET Web Applications - Building C# Applications

Chapter 2

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

This chapter extends yourFundamentals current understanding of ASP.NET by examining various ways to handle state Chapter 3 - C# Language management under .NET. Like classic ASP, ASP.NET allows you to easily create cookies, as well as - Obj ect -Or iented Pr ogr am ming w ith C# application-level and session-level variables. However, ASP.NET also introduces a new state Chapter 5 - Exceptions and Obj ect Lifetim e management technique: the application cache. Once you examine the numerous ways to handle state Chapter 6 - I nter faces and Collections with ASP.NET, you then learn the role of the System.HttpApplication base class (lurking within the Chapter 7 - Callback I nter faces, Delegates, and Ev ents Global.asax file) and how to dynamically alter the runtime behavior of your Web application using the Chapter 8 - Advanced C# Type Const ruction Techniques web.config file. Chapter 4

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 20: XML Web Services

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

In this final chapter of this book, you examine the role of .NET XML Web services. Simply put, a Web serviceis an assembly that is activated using standard HTTP requests. The beauty of this approach is the Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er fact that HTTP is the one wire protocol that is almost uni-versal in its acceptance and is, therefore, an Chapter 13 choice - Building a Bet ter Win dow ( Int roducin g Window s Fordistributed ms) excellent for building platformand language-neutral systems. You also check out Chapter 14 -surrounding A Better Paint ing Fr amew or(WSDL, k ( GDI + )SOAP, and UDDI) which enable a Web service and external numerous tech-nologies Chapter - Pr ogr am ming with Windows Form s Contr ols client to15communicate in harmony. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dBook's th e .N ET Plat f orm , SeCode con d Ed it ion Obtaining This Source by Andr ew Tr oelsen

ISBN:1590590554

All of the code examples within this book (minus small code snippets here and there) are Apr ess © contained 2003 (1200 pages) available for free This and compr immediate download theaApress Simply navigate to ehensiv e text starfrom ts w ith brief ovWeb er viewsite. of the http://www.apress.com and look up this title by name. Once you are on the homepage for C# and C# language and then quickly m oves to key technical and ar chitectur issues you for .NET the .NET Platform, Second al Edition, may developer downloads.a self-extracting .zip file. After you unzip the contents, you will find that the code has been logically divided by chapter. Do be aware that the following icon: Ta ble o f Con t en t s

SOURCE is for your that Edition the example under discussion may be loaded into Visual Studio .NET for C# and t he .NET Plat m, cue Second CODE I ntr oduction

further examination and modification. To do so, simply open the *.sln file found in the

correct Pa r t One - I nt r oduci ng C# subdirectory. a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

Note All of the source code for this book as been compiled using Visual Studio .NET 2003. Sadly, - Building C# Applications *.sln files created with VS .NET 2003 cannot be open using VS .NET 2002. If you are still Pa r t Tw o - The C# Pr ogr am m ing La ngua ge currently running Visual Studio .NET 2002, my advice is to simply create the appropriate project Chapter 3 - C# Language Fundamentals work-space, delete the auto-generated C# files, and copy the supplied *.cs files into the project Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# using the Project | Add Existing Item menu selection. Chapter 2

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f ormBook , Se con d Ed it ion Obtaining Updates for This by Andr ew Tr oelsen

ISBN:1590590554

As you read overApr thisess text, you(1200 maypages) find an occasional grammatical or code error (although I sure hope © 2003 not). If this is the This case,compr my apologies. Being am sure ehensiv e text starhuman, ts w ith aI brief ov erthat view aofglitch the or two may be present, despite my best efforts. IfC# thislanguage is the case, you can obtain the current errata list from the Apress Web site (located and then quickly m oves to key technical and chitectur al issues for book) .NET developer s. information on how to notify me of any errors you once again on thear"homepage" for this as well as might find. Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion ContactingC#Me by Andr ew Tr oelsen

ISBN:1590590554

If you have any questions regarding this book's source code, are in need of clarification for a given Apr ess © 2003 (1200 pages) example, or simply wish to offer your thoughts feel free to drop me a line at This compr ehensiv e text star ts regarding w ith a briefthe ov .NET er viewplatform, of the the following e-mail address (to ensure your messages don't end up in my junk mail folder, please include C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. "C# SE" in the title somewhere! ): . Please understand that I will do my best to get back to you in a timely fashion; however, like yourself, I get Tabusy ble ofrom f Contime t en t sto time. If I don't respond within a week or two, do know I am not trying to be a jerk or don't

care talk.NET to you. I'mm,just busy (or if I'm lucky, on vacation somewhere). C# andtot he Plat for Second Edition I ntr oduction

So then! Thanks for buying this text (or at least looking at it in the bookstore, trying to decide if you will buy it). I hope you enjoy reading this book and put your newfound knowledge to good use.

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2 - Building C# Applications Take care, Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Andrew3 Troelsen Chapter - C# Language Fundamentals Minneapolis, MN Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Part One:C# Introducing C# and the .NET Platform ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Chapter List This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Chapter 1: The Philosophy of .NET Ta ble o f Con t en t s

Chapter 2: Building C# Applications

C# and t he .NET Plat for m, Second Edition I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

d th e .N ET Plat f orm , Se con d Ed it ion Chapter C# 1:anThe Philosophy of .NET ISBN:1590590554 by Andr ew Tr oelsen

Overview

Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and Every few years or ar chitectur so, THEalmodern issues for day.NET programmer developer s. must be willing to perform a self-inflicted knowledge

transplant to stay current with the new technologies of the day. The languages (C++, Visual Basic 6.0, Java), frameworks (MFC, ATL, STL), and architectures (COM, CORBA, EJB) that were touted as the silver Tabullets ble o f Con t en t s development, eventually become overshadowed by something better or at very least of software C# and t he .NET for m, Second Edition something new.Plat Regardless of the frustration you can feel when upgrading your internal knowledge base, I ntr it isoduction unavoidable. Microsoft's .NET platform represents the latest wave of (positive) changes coming from Pa those r t Onekind - I nt folks r oduci in ng Redmond. C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

The point of this chapter is to lay the conceptual groundwork for the remainder of the book. It begins with a - Building C# Applications high-level discussion of a number of .NET-related atoms such as assemblies, the common intermediate Pa r t Tw o - The C# Pr ogr am m ing La ngua ge language (CIL), and just-in-time (JIT) compilation. In addition to previewing some key features of the C# Chapter 3 - C# Language Fundamentals programming language, you will also come to understand the relationship between various aspects of the Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# .NET Framework, such as the common language runtime (CLR), the Common Type System (CTS), and Chapter 5 - Exceptions and Obj ect Lifetim e the Common Language Specification (CLS). As you would hope, many of these topics are explored in Chapter 6 - I nter faces and Collections further detail throughout the remainder of this text. Chapter 2

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter This chapter 8 - Advanced also provides C# Type youConst with an ruction overview Techniques of the functionality supplied by the .NET base class Pa libraries, r t Thre e sometimes - Pr ogr am mabbreviated i ng w i th .N ETas Assem the "BCL" bl ie s

or alternatively as the "FCL" (being the Framework Class

Library). examine number of helpful utilities (such as ildasm.exe and wincv.exe) that may be Chapter 9 Finally, - Underyou standing .NETa Assem blies used to10 investigate the AppDomains, structure of these libraries your leisure. Chapter - Pr ocesses, Cont exts, and at Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET Plat f orm ,State Se con d of Ed itAffairs ion Understanding Previous ISBN:1590590554

by Andr ew Tr oelsen

Before examiningApr theess specifics of the .NET universe, it's helpful to consider some of the issues that © 2003 (1200 pages) motivated the genesis of this new platform. mindset, This compr ehensiv e text starTo ts get w ithina the briefproper ov er view of the let's begin this chapter with a brief and painlessC#history lesson to remember our roots and understand language and then quickly m oves to key technical and the limitations of the previous ar chitectur al issues for have .NET adeveloper state of affairs (after all, admitting you problems.is the first step toward finding a solution). After completing this quick tour of life as we knew it, we turn our attention to the numerous benefits provided by C# and the .NET platform. Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

Life As a C/Win32 API Programmer

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Traditionally speaking, developing software for the Windows family of operating systems involved using the

Chapter 1 - The Philosophy of conjunction .NET C programming language in with the Windows API (Application Programming Interface). Chapter 2 Building C# Applications While it is true that numerous applications have been successfully created using this time-honored Pa r t Tw o - The am m disagree ing La ngua ge approach, fewC#of Pr usogr would that

Chapter 3

building applications using the raw API is a complex undertaking.

- C# Language Fundamentals

The first that a very terse Chapter 4 obvious - Obj ectproblem -Or ientedisPr ogr C amisming w ith C# language. C developers are forced to contend with manual5 memory management, pointer arithmetic, and ugly syntactical constructs. Furthermore, given Chapter - Exceptions and Obj ectugly Lifetim e that C is it lacks the benefits provided by the object-oriented approach (can anyone Chapter 6 a -structured I nter faceslanguage, and Collections sayspaghetti code?) IWhen you Delegates, combine the of global functions and data types defined by the Chapter 7 - Callback nter faces, andthousands Ev ents raw Win32- API to an already formidable language, it is little wonder that there are so many buggy Advanced C# Type Const ruction Techniques applications floating around today. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 8 Chapter 9

- Under standing .NET Assem blies

Life As a C++/MFC Programmer

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

One vast- improvement raw Pa r t Four Le ve r a ging theover .NET LibrC/API a r ie s

development is the use of the C++ programming language. In many ways, C++ can be thought of as an object-oriented layer on top of C. Thus, even though C++ Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er programmers benefit from the famed "pillars of OOP" (encapsulation, inheritance, and polymorphism), Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) they are still at the mercy of the painful aspects of the C language (e.g., manual memory management, Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) ugly pointer arithmetic, and ugly syntactical constructs). Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter The Sy stemmany .I O Nam espace Despite16its- complexity, C++ frameworks exist today. For example, the Microsoft Foundation Classes Chapter - Datathe Access w ith ADO.NET (MFC) 17 provides developer with a set of existing C++ classes that facilitate the construction of Windows Pa r t Fi ve - W e bThe Applmain ica ti ons X ML W Se r vi ces applications. roleand of MFC is etob wrap a "sane

subset" of the raw Win32 API behind a number of

Chapter classes, 18magic - ASP.NET macros, Weband Pages numerous and Webcode ContrWizards ols (i.e., AppWizard, ClassWizard, and so forth).

Regardless of the helpful assistance Chapter 19 - ASP.NET Web Applicat ions offered by the MFC framework (as well as many other C-based windowing of the matter is C++ programming remains a difficult and error-prone Chapter 20 - toolkits), XML Webthe Serfact vices experience, given its historical roots in C. I ndex List of Figur es

Life As a Visual Basic 6.0 Programmer

List of Tables

Due to a heartfelt desire to enjoy a simpler lifestyle, many programmers have shifted away from the world of C(++)-based frameworks to kinder, gentler languages such as Visual Basic 6.0 (VB). VB is popular due to its ability to build complex user interfaces, code libraries (e.g., COM servers), and data access logic with minimal fuss and bother. Even more than MFC, VB hides the complexities of the raw Win32 API from view using a number of integrated code Wizards, intrinsic data types, classes, and VB-centric functions. The major downfall of VB (at least until the advent of VB .NET) is that it is not a fully object-oriented language, but rather "object aware." For example, VB 6.0 does not allow the programmer to establish "isa" relationships between types (i.e., no classical inheritance) and has no support for parameterized class construction. Moreover, VB 6.0 doesn't support the ability to build multithreaded applications (unless you are willing to drop down to low-level API calls, which is complex at best and dangerous at worst).

Life As a Java/J2EE Programmer

Enter Java. The Java programming language is (almost) completely object oriented and has its syntactic C# an d th e .N ET Plat f orm , Se con d Ed it ion roots in C++. As many of you are aware, Java's strengths are far greater than its support for platform ISBN:1590590554 by Andr Tr oelsen cleans up the unsavory syntactical independence. Java (as ew a language) aspects of C++. Java (as a Apr ess © 2003 (1200 pages) platform) provides programmers with a large number of predefined "packages" that contain various class This compr ehensiv e text starJava ts w ith a brief ov er view theto build "100% Pure Java" and interface definitions. Using these types, programmers are of able C# language and then quickly m oves to key technical and applications complete with database connectivity, messaging support, Web-enabled front ends, and a richar chitectur al issues for .NET developer s. user interface. Although Java is a very elegant language, one potential problem is that using Java typically means that you must use Java front-to-back during the development cycle. In effect, Java offers little hope of C# and t he .NET Plat for m, Second Edition language independence, as this goes against the grain of Java's primary goal (a single programming I ntr oductionfor every need). In reality however, there are millions of lines of existing code out there in the language Pa r t One - I nt r oduci ng C# like a nd to the .NET P la tf or m newer Java code. Sadly, Java makes this task problematic. world that would ideally commingle with

Ta ble o f Con t en t s

Chapter 1

- The Philosophy of .NET Pure Java simply not appropriate for many graphically or numerically intensive applications. For Chapter 2 -isBuilding C# Applications

example, if you building a graphics Pa r t Tw o - The C#are Pr ogr am m ing La ngua geintensive

product (such as a 3D-rendered video game), you will find Java's execution speed will leave something to be desired. A better approach for such programs would be Chapter 3 - C# Language Fundamentals to use a lower-level language (such as C++) where appropriate. Alas, while Java does provide a limited Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# ability to access non-Java APIs, there is little support for true cross-language integration. Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

I nter faces, Delegates, and Ev ents Life As- aCallback COM Programmer

Chapter 7 Chapter 8

- Advanced C# Type Const ruction Techniques

The truth is,wifi th you areAssem not currently Pa r t Thre e -ofPrthe ogrmatter am m i ng .N ET bl ie s

building Java-based solutions, the chances are very good that you have invested your time and energy understanding Microsoft's Component Object Model (COM). Chapter 9 - Under standing .NET Assem blies COM is an architecture that says in effect, "If you build your classes in accordance with the rules of COM, Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads you end up with a block of reusable binary code." Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

The beauty of a binary COM server is that it can be accessed in a language-independent manner. Thus,

Chapter 12 - Obj ect Ser and classes the .NETthat Remoting er by VB. Delphi programmers can use COM C++ programmers canialization build COM can beLay used Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s Foraware, ms) classes built using C, and so forth. However, as you may be COM's language independence is Chapter 14 - limited. A BetterFor Paint ing Fr amew or kis( no GDIway + ) to derive a new COM type using an existing COM type (no somewhat example, there Chapter Pr ogr am ming with Windows Form s Contr support15for- classical inheritance). Rather, you mustols make use of the more cumbersome "has-a" Chapter 16 - The Sy stem .I O Nam espace relationship to reuse COM types. Chapter 17 - Data Access w ith ADO.NET

Another of COM is its location-transparent Pa r t Fi ve -benefit W e b Appl ica ti ons and X ML W e b Se r vi ces

nature. Using constructs such as application identifiers (AppIDs), stubs, proxies, and the COM runtime environment, programmers can avoid the need to work Chapter 18 - ASP.NET Web Pages and Web Contr ols with raw sockets, RPC calls, and other lowlevel details. For example, ponder the following Visual Basic 6.0 Chapter 19 - ASP.NET Web Applicat ions COM client code: Chapter 20 - XML Web Ser vices I ndex

' of This of VB 6.0 code can activate a COM class written in List Figurblock es ' any COM-aware language, which may be located anywhere ' on the network (including your local machine). Dim c as MyCOMClass Set c = New MyCOMClass ' Location resolved using AppID. c.DoSomeWork

List of Tables

Although COM is a very dominant object model, it is extremely complex under the hood (at least until you have spent many months exploring its plumbing...especially if you happen to be a C++ programmer). To help simplify the development of COM binaries, numerous COM-aware frameworks have come into existence. For example, the Active Template Library (ATL) provides another set of C++ -based classes, templates, and macros to ease the creation of classic COM types. Many other languages (such as Visual Basic 6.0) also hide a good part of the COM infrastructure from view. However, language support alone is not enough to hide the complexity of classic COM. Even when you choose a relatively simply COM-aware language such as VB 6.0, you are still forced to contend with fragile registration entries and numerous deployment-related issues (collectively termed DLL hell).

C# an d th e .N ET Plat f orm , Se con d Ed it ion Life As a Windows DNA Programmer by Andr ew Tr oelsen

ISBN:1590590554

ess © 2003 (1200 the pages) Finally, there is aApr little thing called Internet. Over the last several years, Microsoft has been adding more Internet-aware into its family systems. seems This features compr ehensiv e text starofts operating w ith a brief ov er viewIt of the that the popularity of Web C# expanding. language and thenbuilding quickly m to keyWeb technical and applications is ever Sadly, a oves complete application using classic Windows DNA ar chitectur al issues .NET s. (Distributed iNternet Architecture) is for also verydeveloper complex.

Some of this complexity is due to the simple fact that Windows DNA requires the use of numerous Tatechnologies ble o f Con t en t s languages (ASP, HTML, XML, JavaScript, VBScript, COM(+), as well as a data access and C# and t heas .NET Plat for m, problem Second Edition API such ADO). One is that many of these items are completely unrelated from a syntactic I ntr oduction point of view. For example, JavaScript has a syntax much like C, while VBScript is a subset of Visual Basic Pa r t One The - I nt rCOM oduci servers ng C# a nd the .NET P la tf or proper. that are created tomrun

under the COM+ runtime have an entirely different look

Chapter and feel 1 from - The thePhilosophy ASP pages of .NET that invoke them. The result is a highly confused mishmash of technologies.

Furthermore, and perhaps more important, each language and/or technology has its own type system Chapter 2 - Building C# Applications (that looks nothing likeLathe other Pa r t Twtypically o - The C# Pr ogr am m ing ngua ge

type systems). An "int" in JavaScript is not the same as an "int" in C, which is different from an "Integer" in VB proper. Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion The .NET Solution ISBN:1590590554

by Andr ew Tr oelsen

So much for the brief history The bottom line is that life as a Windows programmer has been Apr ess © 2003lesson. (1200 pages) tough. The .NET This Framework is a rather approach compr ehensiv e text radical star ts wand ith abrute-force brief ov er view of the to making our lives easier. The solution proposedC#bylanguage .NET is "Change everything from here on out" you can't blame the messenger and then quickly m oves to key technical (sorry, and chitectur al issues for .NET s. of this book, the .NET Framework is a completely for the message).arAs you will see during the developer remainder new model for building systems on the Windows family of operating systems, and additional (nonMicrosoft) operating systems now and in the future. To set the stage, here is a quick rundown of some Tacore ble ofeatures f Con t enprovided ts courtesy of .NET: C# and t he .NET Plat for m, Second Edition

Full interoperability with existing Win32 code. This is (of course) a good thing. Existing COM binaries I ntr oduction can- commingle withPnewer Pa r t One I nt r oduci ng(i.e., C# ainterop) nd the .NET la tf or m.NET

binaries and vice versa. Also, PInvoke (Platform

Invocation) you of to .NET invoke invoke raw C-based functions (such as the Win32 API) from Chapter 1 - The allows Philosophy managed code.C# Applications Chapter 2 - Building Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Complete and total language integration . Unlike classic COM, .NET supports cross-language - C# Language Fundamentals inheritance, cross-language exception handling, and crosslanguage debugging.

Chapter 3 Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - Exceptions Obj ect Lifetim A common runtime and engine shared bye all .NET-aware languages. One aspect of this engine is a wellChapter defined 6 - Iset nterof faces types and that Collections each .NET-aware language "understands." Chapter 7

- Callback I nter faces, Delegates, and Ev ents

A base class library that provides shelter from the complexities of raw API calls, and offers a Chapter 8 - Advanced C# Type Const ruction Techniques consistent object model used by all .NET-aware languages. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter - Under standing .NETIClassFactory, Assem blies No9more COM plumbing! IUnknown, IDispatch, IDL code, and the evil VARIANTChapter 10 Pr ocesses, AppDomains, Cont exts, andand Threads compliant data types (BSTR, SAFEARRAY, so forth) have no place in a native .NET binary. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

A truly simplified Pa r t Four - Le ve r a ging deployment the .NET Librmodel. a r ie s

Under .NET, there is no need to register a binary unit into the

system registry. Furthermore, runtime allows Chapter 12 - Obj ect Ser ialization and the the .NET .NET Remoting Lay er multiple versions of the same *.dll to exist in harmony on a single machine an approach termed "side-by-side execution"). Chapter 13 - Building a Bet ter Win dow(using ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# Blocks an d th e .N ET f orm , Se con d Ed it ion The Building ofPlat the .NET Platform (CLR, CTS, and CLS) ISBN:1590590554

by Andr ew Tr oelsen

Now that you have a peek into some of the benefits provided by .NET, let's preview three key Aprbeen ess ©given 2003 (1200 pages) (and interrelated)This entities that make it all possible: CLR, CLS. From a programmer's point of compr ehensiv e text star ts w iththe a brief ovCTS, er viewand of the view, .NET can be simply understood as a new runtime environment and C# language and then quickly m oves to key technical and a common base class library. al referred issues forto.NET developer s. language runtime, or CLR. The primary role of The runtime layerarischitectur properly as the common the CLR is to locate, load, and manage .NET types on your behalf. The CLR also takes care of a number of low-level details such as automatic memory management, language integration, and ensuring type Tasafety. ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

Another building block of the .NET platform is the Common Type System, or CTS. The CTS fully I ntr oduction describes allr oduci possible data types and programming Pa r t One - I nt ng C# a nd the .NET P la tf or m

constructs supported by the runtime, specifies how

these entities can interact with each other and details how they are represented in the .NET metadata Chapter 1 - The Philosophy of .NET format 2(more information on "metadata" later in this chapter). Chapter - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Understand that a given .NET-aware language might not support each and every entity defined by the - C# Language Fundamentals CTS. The Common Language Specification (CLS) is a set of rules that define a subset of common types Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# and programming constructs that all .NET programming languages can agree on. Thus, if you build .NET Chapter 5 -only Exceptions Obj ect Lifetim e types that expose and CLS-compliant features, you can rest assured that all .NET-aware languages could Chapter 6 I nter faces and Collections make use of your types. Conversely, if you make use of a data type or programming construct that is Chapter Callback I ntercannot faces, Delegates, ents .NET programming language can interact with your outside7of -the CLS, you guarantee and thatEv every Chapter 8 - Advanced binary code library. C# Type Const ruction Techniques Chapter 3

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d.NET th e .N ET Plat f orm , Se conLibraries d Ed it ion The Role ofC#the Base Class by Andr ew Tr oelsen

ISBN:1590590554

In addition to the Apr CLR and CTS/CLS specifications, the .NET platform provides a base class library that is ess © 2003 (1200 pages) available to all .NET programming languages. does base class library encapsulate various This compr ehensiv e text star ts Not w ith only a brief ov erthis view of the primitives such asC#threads, file IO, graphical rendering and interaction with language and then quickly m oves to key technical and various hardware devices, but it ar chitectur issues of forservices .NET developer s. by most real-world applications. also provides support for a al number required For example, the base class libraries define types that facilitate database manipulation, XML integration, Taprogrammatic ble o f Con t en tsecurity, s and the construction of Web-enabled (as well as traditional desktop and console-

based) front ends. From a conceptual C# and t he .NET Plat for m, Second Edition point of view, you can visualize the relationship between the .NET runtime layer and the corresponding base class library as shown in Figure 1-1. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Figure 1-1: The CLR, CTS, CLS base class library relationship

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th .N ET Plat f orm , Se con d Ed it ion What C# Brings toe the Table ISBN:1590590554

by Andr ew Tr oelsen

Given that .NET is such radical from the current thoughts of the day, Microsoft has developed Apr ess ©a 2003 (1200departure pages) a new programming language (C#) specifically newovplatform. This compr ehensiv e text star ts wfor ith this a brief er view of C# theis a programming language that looksvery similar C# (butlanguage not identical) to the syntax of Java. For example, and then quickly m oves to key technical andlike Java, a C# class definition is chitectur al issues forfile .NET developer contained within aarsingle-source code (*.cs) rathers.than the C++-centric view of splitting a class definition into discrete header (*.h) and implementation (*.cpp) files. However, to call C# a Java rip-off is inaccurate. Both C# and Java are based on the syntactical constructs of C++. Just as Java is in many Taways ble o fa Con t en t s cleaned-up version of C++, C# can be viewed as a cleaned-up version of Java—after all, they are C# t hesame .NET Plat for m, Second Edition alland in the family of languages. I ntr oduction

The truth- Iof matter many ofPC#'s Pa r t One nt rthe oduci ng C#isathat nd the .NET la tf orsyntactic m

constructs are modeled after various aspects of

Visual Basic andPhilosophy C++ itself.ofFor example, like Visual Basic, C# supports the notion of formal class Chapter 1 - The .NET properties well the of methods that take a varying number of arguments (via parameter Chapter 2 -as Building C#declaration Applications arrays). you to overload Pa r t Tw o -Like The C++, C# PrC# ograllows am m ing La ngua ge

operators on your custom types, as well as create structures (value types) and enumerations (as you may know, Java lacks all of these features). Chapter 3 - C# Language Fundamentals Chapter 4

Obj ect -Or iented Pr ogr am ming w ith C# Given that-C# is a hybrid of numerous languages, the result is a product that is as syntactically clean (if not

Chapter 5 than - Exceptions Obj ect Lifetim eas Visual Basic 6.0, and provides just about as much power and cleaner) Java, justand about as simple Chapter 6 I nter faces and Collections flexibility as C++ (without the associated ugly bits). In a nutshell, the C# languages offers the following Chapter 7 (many - Callback I nterare faces, Delegates, and.NET-aware Ev ents features of which shared by other programming languages): Chapter 8 - Advanced C# Type Const ruction Techniques

No pointers required! programs Pa r t Thre e - Pr ogr am m i ng w C# i th .N ET Assemtypically bl ie s

have no need for direct pointer manipulation (although you are free to drop down to that level if you desire, as seen in Chapter 8). Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Automatic memory management. Given this, C# does not support a "delete" keyword.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s Formal syntactic constructs for enumerations,

structures, and class properties.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

The ability a custom type, Chapter 13C++-like - Building a Betto teroverload Win dow operators ( Int roducinfor g Window s For ms) without the complexity (i.e., making sure to "return *this toPaint allow Chapter 14 - A Better ingchaining" Fr amew orisk not ( GDIyour + ) problem). Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Full support for interface-based programming techniques. However, unlike classic COM, the interface isnot the only way to manipulate types between binaries. .NET supports true object references that Chapter Data Access w ith ADO.NET can17be- passed between boundaries (by reference or by value). Chapter 16 - The Sy stem .I O Nam espace

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter Full 18support - ASP.NET for aspect-based Web Pages andprogramming Web Contr ols techniques via attributes. This brand of development

allows to assign to types and their members (much like COM IDL) to further qualify Chapter 19 - you ASP.NET Web characteristics Applicat ions the20behavior of a Ser given entity. Chapter - XML Web vices I ndex

Perhaps the most important point to understand about the C# language shipped with the .NET platform is that it can only produce code that can execute within the .NET runtime (you could never use C# to build a List of Tables classic COM server or a traditional Win32 API application). Officially speaking, the term used to describe the code targeting the .NET runtime is managed code. The binary unit that contains the managed code is termed an assembly (more details in just a bit). List of Figur es

C# an d th e .N ET Plat f orm , Se con d Ed it ion Additional .NET-Aware Programming Languages ISBN:1590590554

by Andr ew Tr oelsen

On a related language-centric note,pages) understand that C# is not the only language targeting the .NET Apr ess © 2003 (1200 platform. When the .NET platform was theovgeneral public This compr ehensiv e textfirst starrevealed ts w ith a to brief er view of the during the 2000 Professional Developers Conference (PDC), several vendors announced they were C# language and then quickly m oves to key technical andbusy building .NET-aware versions chitectur al At issues developer of their respectivearcompilers. the for time.NET of this writing,s.dozens of different languages are slated to undergo (or have undergone) .NET enlightenment. In addition to the five languages that ship with Visual Studio .NET Professional (C#, J#, Visual Basic .NET, "Managed C++," and JScript .NET), be on the Talookout ble o f Con en t s for t.NET-aware compilers targeting Smalltalk (S#), COBOL, Pascal, Python, and Perl (as well as C# and others). t he .NET Plat for m, Second Edition many I ntr oduction

Although bookng focuses Pa r t One - Ithis nt r oduci C# a nd(almost) the .NETexclusively P la tf or m

on C#, Table 1-1 lists a number of .NET-enabled

programming languages where to learn more about them (do note that the exact URLs are subject to Chapter 1 - The Philosophyand of .NET change). Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Table 1-1: Sampling .NET-Aware Programming Languages Chapter 3 - AC# LanguageofFundamentals Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# .NET-Centric Web Link Chapter 5

http://www.oberon.ethz.ch Chapter 6 - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8 - Advanced C# Type Const ruction Techniques http://www.dyadic.com Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

Meaning in Life

- Exceptions and Obj ect Lifetim e

- Under standing .NET Assem blies

http://www.adtools.com

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa rhttp://www.eiffel.com t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

http://research.microsoft.com/projects/ilx/fsharp.htm

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

http://lahey.com Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

http://www.cs.inf.ethz.ch

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

http://www.activestate.com Chapter 20 - XML Web Ser vices I ndex List of Figur es Listhttp://smallscript.org of Tables

Homepage for Active Oberon .NET Homepage for Dyalog APL .NET For those interested in COBOL .NET For those interested in Eiffel .NET Details of the F# language For those interested in Fortran .NET For those interested in Oberon .NET Details regarding Perl .NET and Python .NET Yes, even Smalltalk .NET (S#) is available

Also be aware that Table 1-1 is not exhaustive. Microsoft maintains a list of vendors who are currently building (or have built) .NET implementations for their respective compilers, so check http://msdn.microsoft.com/vstudio/partners/language for the most up-to-date listings (again, the exact URL is subject to change).

Life in a Multi-Language World As developers first come to understand the language-agnostic nature of .NET, numerous questions arise. The most prevalent of these questions would have to be, "If all .NET languages compile down to managed code, why do we need more than one compiler?" There are a number of ways to answer this question. First, we programmers are a very particular lot when it comes to our choice of programming languages (myself included). Some of us prefer languages full of semicolons, curly brackets, and as few language

keywords as possible. Others enjoy a language that offers more "human-readable" syntactic tokens (such an d th e .N ET Plat f orm , Se con d Ed it ion as VB .NET). StillC# others may want to leverage their mainframe skills while moving to the .NET platform ISBN:1590590554 by Andr ew Tr oelsen (via COBOL .NET). Apr ess © 2003 (1200 pages)

Now, be honest: If Microsoft were toe text buildstar a single .NET language This compr ehensiv ts w ith"official" a brief ov er view of the that was derived from the C# languagecan andyou then quickly oves to key technical andbe happy with this choice? Or, if the BASIC family of languages, really saymall programmers would ar chitectur al issues for based .NET developer s. single official managed language was on C syntax, imagine all the folks out there who would ignore .NET altogether. Because the .NET runtime could care less where a block of managed code originated, .NET programmers can stay true to their syntactic preferences, and share the compiled assemblies Ta ble o f Con t en t s among teammates, departments, and external organizations (regardless of which .NET language others C# and t he .NET Plat for m, Second Edition choose to use). I ntr oduction Pa r t One - excellent I nt r oducibyproduct ng C# a nd of theintegrating .NET P la tf or m Another various

.NET languages into a single unified software solution is

Chapter the simple 1 - fact Thethat Philosophy all programming of .NET languages have their own sets of strengths and weaknesses. For

example, programming languages offer excellent intrinsic support for advanced mathematical Chapter 2 some - Building C# Applications processing. offer support Pa r t Tw o - TheOthers C# Pr ogr amsuperior m ing La ngua ge

for graphical rendering, financial calculations, logical calculations, interaction with mainframe computers and so forth. When you take the strengths of a Chapter 3 - C# Language Fundamentals particular programming language and then incorporate the benefits provided by the .NET platform, Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# everybody wins. Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Of course, in reality the chances are quite good that you will spend much of your time building software Callback I nter faces, Delegates, and Ev ents using your-.NET language of choice (which is great! ) However, as you may be expecting, once you learn Chapter 8 -ofAdvanced Type Const ruction Techniques the syntax one .NETC#language, it is very easy to master another. This is also quite beneficial, especially Pa Thre e - Pr ogr amof mthe i ng world. w i th .NIfETyour Assem bl ie s tor tthe consultants language of choice happens to be C#, but you are placed at a client Chapter - Under standing Assemyou blies site that9 has committed to .NET VB .NET, should be able to parse the existing code body almost instantly Chapter 10 while - Pr ocesses, AppDomains, Cont exts, Threads (honest!) still continuing to leverage the and .NET Framework. Enough said. Chapter 7

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# of an d.NET th e .N ET Plat f orm , Se con d Ed it ion An Overview Binaries (aka Assemblies) by Andr ew Tr oelsen

ISBN:1590590554

Regardless of which .NET language you choose to program with, understand that despite the fact that Apr ess © 2003 (1200 pages) .NET binaries take the same file extension astsclassic binaries (*.dll This compr ehensiv e text star w ith a COM brief ov er view of theor *.exe), they have absolutely no internal similarities. For example, *.dll .NET binaries do not export methods to facilitate communications C# language and then quickly m oves to key technical and ar chitectur al issues developer s. with the classic COM runtime (given for that.NET .NET is not COM). Furthermore, .NET binaries are not described using IDL and are not registered into the system registry. Perhaps most important, unlike classic COM servers, .NET binaries do not contain platform-specific instructions, but rather platform-agnostic Ta"intermediate ble o f Con t enlanguage" ts (IL). Conceptually, Figure 1-2 shows the big picture of the story thus far. C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

Advanced C# Type Const ruction Techniques Figure- 1-2: All .NET-aware compilers emit IL instructions and metadata.

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies Note is one AppDomains, point to be made regarding the acronym "IL." During the development of .NET, the Chapter 10 There - Pr ocesses, Cont exts, and Threads

for "IL" was Microsoft language (MSIL). Chapter 11 official - Type term Reflection, Late Binding, andintermediate Attr ibute- Based Pr ogramm ing However with the final release of ve .NET, thethe (new) term Pa r t Four - Le r a ging .NETofficial Libr a r ie s

is common intermediate language (CIL). Thus, as you read the .NET literature (including the first of this text), understand that IL, MSIL and CIL are all Chapter 12 - Obj ect Ser ialization and the .NET edition Remoting Lay er describing the same exact entity. In keeping with the current terminology, I will use the term CIL Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) throughout this text from here on out. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter - Pror ogr am ming ols When a15*.dll *.exe has with beenWindows created Form usings aContr .NET-aware compiler, the resulting module is bundled into Chapter 16 The Sy stem .I O Nam espace an "assembly." You examine numerous details of .NET assemblies in Chapter 9. However to facilitate the Chapter 17 - of Data w ith ADO.NET discussion the Access .NET runtime environment, you do need to examine some basic properties of this new Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces file format.

Chapter 18 - ASP.NET Web Pages and Web Contr ols

As mentioned, an assembly contains Chapter 19 - ASP.NET Web Applicat ions CIL code, which is conceptually similar to Java byte code in that it is not compiled to platform-specific instructions until absolutely necessary. Typically "absolutely necessary" Chapter 20 - XML Web Ser vices

is the point at which a block of CIL instructions (such as a method implementation) are referenced for use by the .NET runtime engine.

I ndex

List of Figur es

List of Tablesto CIL instructions, assemblies also contain metadata that describes in vivid detail the In addition

characteristics of every "type" living within the binary. For example, if you have a class named Car contained within a given assembly, the type metadata describes details such as Car's base class, which interfaces are implemented by Car (if any), as well as a full description of each member supported by the Car type. In many respects, .NET metadata is a dramatic improvement to classic COM type information. As you may already know, classic COM binaries are typically described using an associated type library (which is little more than a binary version of IDL code). The problems with COM type information are that it is not guaranteed to be present, and the fact that IDL code has no way to catalog externally referenced servers that are required for the correct operation of the contained coclasses (a.k.a. 'COM class'). In contrast, .NET metadata is always present and is automatically generated by a given .NET-aware compiler. Finally, in addition to CIL and type metadata, assemblies themselves are also described using metadata, which is officially termed a manifest. The manifest contains information about the current version of the assembly, culture information (used for localizing string and image resources), and a list of all externally

referenced assemblies that are required for proper execution. You examine various tools that can be used C# an d th e .N ET Plat f orm , Se con d Ed it ion to examine an assembly's underlying CIL, type metadata and manifest information later in this chapter. by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

Single File This andcompr Multifile Assemblies ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

In a great numberarof cases,althere is for a simple one-to-one chitectur issues .NET developer s. correspondence between a .NET assembly and the underlying *.dll or *.exe binary. Thus, if you are building a .NET *.dll, it is safe to consider that the binary and the assembly are one and the same. Likewise, if you are building a .NET *.exe desktop thet s*.exe can simply be referred to as the assembly itself. As seen in Chapter 9 however, this Taapplication, ble o f Con t en is not completely accurate. Technically C# and t he .NET Plat for m, Second Edition speaking, if an assembly is composed of a single *.dll or *.exe module, you have a "single file assembly." Single file assemblies contain all the necessary CIL, metadata I ntr oduction and associated manifest in an autonomous, single, well-defined package. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

Multifile assemblies, on the other hand, are composed of numerous .NET binaries, each of which is - Building C# Applications termed a module. When building a multifile assembly, one of these modules (termed the primary module) Pa r t Tw o - The C# Pr ogr am m ing La ngua ge must contain the assembly manifest (and possibly CIL instructions and metadata for various types). The Chapter 3 - C# Language Fundamentals other related modules contain a module level manifest, CIL and type metadata. As you might suspect, the Chapter - Obj ect -Or iented Pr ogrset am of ming w ith C# primary4 module documents the required secondary modules within the assembly manifest. Chapter 2

Chapter 5

- Exceptions and Obj ect Lifetim e So, why6 would you choose to create a multifile assembly? When you partition an assembly into discrete Chapter - I nter faces and Collections

modules, end upI nter withfaces, a more flexible deployment Chapter 7 you - Callback Delegates, and Ev ents option. For example, if a user is referencing a remote8assembly thatC# needs be downloaded onto his or her machine, the runtime will only download Chapter - Advanced TypetoConst ruction Techniques the required Therefore, areblfree Pa r t Thre e - Prmodules. ogr am m i ng w i th .N ETyou Assem ie s

to construct your assembly in such a way that less frequently required types (such as a type named HardDriveReformatter) are kept in a separate standChapter 9 - Under standing .NET Assem blies alone module. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

In contrast, if all your types were placed in a single file assembly, the end user may end up downloading a large chunk of data that is not really needed (which is obviously a waste of time). Thus, as you can see, an Chapter 12 is - Obj ect a Ser ialization and the Lay er modules that are intended to be deployed and assembly really logical grouping of.NET one Remoting or more related Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms) versioned as a single unit. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an dCommon th e .N ET Plat fIntermediate orm , Se con d Ed it ion The Role ofC#the Language by Andr ew Tr oelsen

ISBN:1590590554

Now that you have better feel for pages) .NET assemblies, let's examine the role of the common intermediate Apraess © 2003 (1200 language (CIL) inThis a bitcompr moreehensiv detail.eCIL a language that sits textisstar ts w ith a brief ov erabove view ofany theparticular platform-specific instruction set. Regardless of which .NET-aware language you choose C# language and then quickly m oves to key technical and(C#, Visual Basic .NET, Eiffel ar chitectur al issues compiler for .NET developer .NET, and so forth), the associated emits CILs.instructions. For example, the following C# namespace definition models a trivial calculator (which is only capable of returning the sum of 10 and 84...). Don't concern yourself with the exact syntax for the time being, but do notice the signature of the TaAdd() ble o fmethod: Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction

// We will examine namespaces later in the chapter... using System;

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2 - Building C# Applications namespace Calculator Pa {r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter // 3 - This C# Language class Fundamentals contains the app's entry point. Chapter public 4 - Obj ect -Or iented Pr ogr am ming w ith C# class CalcApp Chapter { 5 Chapter 6

- Exceptions and Obj ect Lifetim e

Chapter 7

{ - Callback I nter faces, Delegates, and Ev ents

Chapter 8

Calc = new Calc(); - Advanced C# c Type Const ruction Techniques

- Ipublic nter faces static and Collections void Main()

int c.Add(10, Pa r t Thre e - Pr ogr am m i ngans w i th =.N ET Assem bl ie s 84); Chapter 9

Console.WriteLine("10 + 84 is {0}.", ans); - Under standing .NET Assem blies

Console.ReadLine(); // Threads Wait for user key-press. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and } Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Chapter 11 - Type Pa r t Four} - Le ve r a ging the .NET Libr a r ie s

// The C# calculator. public class Calc 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) { 14 - A Better Paint ing Fr amew or k ( GDI + ) // A single method. 15 - Pr ogr am ming with Windows Form s Contr ols public int Add(int x, int y) 16 - The Sy stem .I O Nam espace { return x + y; } 17 - Data Access w ith ADO.NET }

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter Chapter Chapter Chapter Chapter

Pa }r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Once the compiler (csc.exe) compiles this source code file, you end up with a single file *.exe Chapter 20 C# - XML Web Ser vices assembly that contains a manifest, CIL instructions, and metadata describing each aspect of the Calc and I ndex CalcApp For example, if you peek inside this binary using ildasm.exe (examined a little later in this List of Figurclasses. es chapter) you find the Add() method is represented using CIL such as the following: List of Tables .method public hidebysig instance int32 Add(int32 x, int32 y) cil managed { // Code size 8 (0x8) .maxstack 2 .locals init ([0] int32 CS$00000003$00000000) IL_0000: ldarg.1 IL_0001: ldarg.2 IL_0002: add IL_0003: stloc.0 IL_0004: br.s IL_0006 IL_0006: ldloc.0 IL_0007: ret } // end of method Calc::Add

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Don't worry if you are unable to make heads or tails of the resulting CIL for this method. The point to ISBN:1590590554 by Andr ew Tr oelsen concentrate on is that the C# compiler emits CIL, not platform specific instructions. Apr ess © 2003 (1200 pages)

Thisiscompr ehensiv e text star tscompilers. w ith a brief er view of assume the Now, recall that this true of all .NET-aware Toovillustrate, you created the Calc language then quickly m oves application using C# Visual Basic and .NET, rather than C#: to key technical and ar chitectur al issues for .NET developer s.

' The VB .NET calculator... Calc TaClass ble o f Con t en t s Public Add(ByVal x As Integer, ByVal y As Integer) As Integer C# and t he .NET Function Plat for m, Second Edition ' Yes! VB .NET (finally) supports a 'Return' keyword. I ntr oduction Return x + y Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m End Function Chapter 1 - The Philosophy of .NET End Class Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

' A VB .NET 'Module' is a class that only contains - C# Language Fundamentals ' static members. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Module CalcApp Chapter 5 - Exceptions and Obj ect Lifetim e Sub Main() Chapter 6 - Dim I nter ans faces As and Integer Collections Chapter 7 - Dim Callback I nter faces, Delegates, and Ev ents c As New Calc Chapter 8 - ans Advanced C# Type Const ruction Techniques = c.Add(10, 84) Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl s Console.WriteLine("10 +ie84 is {0}.", ans) Chapter 9 - Console.ReadLine() Under standing .NET Assem blies ChapterEnd 10 - Sub Pr ocesses, AppDomains, Cont exts, and Threads Chapter End Module 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Chapter 3

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

If you examine the CIL forter theWin Add() you find thessame sort of instructions (slightly tweaked by the Chapter 13 - Building a Bet dow method, ( Int roducin g Window For ms) VB .NET compiler):

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

.method instance int32 Add(int32 x, int32 y) cil managed Chapter 16 - public The Sy stem .I O Nam espace { Chapter 17 - Data Access w ith ADO.NET 9 X(0x9) Pa r t // Fi veCode - W e b size Appl ica ti ons and ML W e b Se r vi ces .maxstack 2 .locals init ([0] int32 Add) Chapter 19 - ASP.NET Web Applicat ions IL_0000: nop Chapter 20 - XML Web Ser vices IL_0001: ldarg.1 I ndex IL_0002: ldarg.2 List of Figur es IL_0003: add.ovf List of Tables IL_0004: stloc.0 IL_0005: br.s IL_0007 IL_0007: ldloc.0 IL_0008: ret } // end of method Calc::Add

Chapter 18 - ASP.NET Web Pages and Web Contr ols

SOURCE CODE

The CSharpCalculator and VBCalculator applications are both included under the Chapter 1 subdirectory.

Benefits of CIL At this point, you might be wondering exactly what benefits are gained by compiling source code into CIL (with the associated metadata) rather than directly to a specific instruction set. One benefit of compiling to CIL (with the associated metadata) is language integration. As you have already seen, each .NET-aware

language produces the same underlying CIL. Therefore, all languages are able to interact within a wellC# an d th e .N ET Plat f orm , Se con d Ed it ion defined binary arena. by Andr ew Tr oelsen

ISBN:1590590554

Aprthat ess ©CIL 2003 pages)agnostic, the .NET runtime is poised to become a platformFurthermore, given is (1200 platform independent architecture, providing Javaovdevelopers have grown accustomed to (i.e., This compr ehensiv e the textsame star tsbenefits w ith a brief er view of the language and then quickly oves to key technicalsystems). and the potential of a C# single code base running on m numerous operating In fact, there is an ar chitectur issues for .NET developer s. international standard for a allarge subset of the .NET platform and implementations already exist on a few non-Windows operating systems. For example, you can run basic C# programs on both FreeBSD Unix and Apple (under OS X) platforms already. Unlike Java however, .NET allows you to build applications in Ta ble o f Con t en t s a language-independent fashion. Thus, .NET has the potential to allow you to develop an application in C# and t he .NET Plat for m, Second Edition any language and have it run on any platform. I ntr oduction Pa r t One - I I'll nt rcomment oduci ng C#a bit a ndmore the .NET P laplatform-independent tf or m Note on the

nature of .NET at the conclusion of this

Chapter 1 chapter. - The Philosophy of .NET Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d thType e .N ET Plat f orm , Se con d Ed it ion The Role ofC#.NET Metadata by Andr ew Tr oelsen

ISBN:1590590554

COM programmers a doubt Apr are ess ©without 2003 (1200 pages) familiar with the Interface Definition Language (IDL). IDL is a "metalanguage" that is used to describe within This compr ehensiv e text the star types ts w ithcontained a brief ov er view a ofgiven the COM server. IDL is compiled into a binary format (termed a type library) using the midl.exe compiler, C# language and then quickly m oves to key technical andwhich can then be used by a COMar chitectur al issues for .NET developer aware language to manipulate the contained types. s. In addition to describing the types within a COM binary, IDL has minimal support to describe characteristics Taabout ble o fthe ConCOM t en t sbinary itself, such as its current version (e.g., 1.0, 2.0, or 2.4) and intended locale (e.g.,

English, The problem with COM metadata is that it may or may not be present C# and t heGerman, .NET PlatUrdu, for m, Russian). Second Edition and it is often the role of the programmer to ensure the underlying IDL accurately reflects the internal I ntr oduction types. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

The .NET Framework makes no use of IDL whatsoever. However, the spirit of describing the types - Building C# Applications residing within a particular binary lives on. In addition to the underlying CIL instructions, a .NET assembly Pa r t Tw o - The C# Pr ogr am m ing La ngua ge contains full, complete and accurate metadata. Like COM IDL, .NET metadata describes each and every Chapter 3 - C# Language Fundamentals type (class, structure, enumeration, and so forth) defined in the binary, as well as the members of each Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# type (properties, methods, events, and so on). Chapter 2

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter Furthermore, 6 - I nter thefaces .NETand manifest Collections (which as you recall is metadata describing the assembly itself) is far

more complete than IIDL, in thatDelegates, it also describes each externally referenced assembly that is required by Chapter 7 - Callback nter faces, and Ev ents the executing assembly operate Because .NET metadata is so wickedly meticulous, Chapter 8 - Advanced C# toType Constcorrectly. ruction Techniques assemblies are selfdescribing Pa r t Thre e - Pr ogrcompletely am m i ng w i th .N ET Assem blentities. ie s

So much so in fact, .NET binaries have no need to be registered into the system registry (more on that little tidbit later in the text). Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

A Quick Metadata Example

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

To illustrate theect format of .NETand metadata, take a Lay look Chapter 12 - Obj Ser ialization the .NETlet's Remoting er at the metadata that has been generated for the Add() ofathe you examined previously (the metadata generated for the VB Chapter 13 method - Building BetC# ter Calculator Win dow ( Intclass roducin g Window s For ms) .NET Add() similar). Usingorthe ildasm.exe utility (examined at the end of this chapter) you can Chapter 14 - method A Better is Paint ing Fr amew k ( GDI +)

view your metadata by hitting thes Ctrl+M keystroke. Within the resulting "MetaInfo" window, you Chapter 15 assembly's - Pr ogr am ming with Windows Form Contr ols will find a description of the Add() method looking something like the following::

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Method #2e b Appl ica ti ons and X ML W e b Se r vi ces Pa r t Fi ve - W ------------------------------------------------------Chapter 18 - ASP.NET Web Pages and Web Contr ols MethodName: Add Web (06000002) Chapter 19 - ASP.NET Applicat ions Flags : [Public] [HideBySig] [ReuseSlot] (00000086) RVA : 0x00002064 I ndex ImplFlags : [IL] [Managed] (00000000) List of Figur es CallCnvntn: [DEFAULT] List of Tables hasThis ReturnType: I4 2 Arguments Argument #1: I4 Argument #2: I4 2 Parameters (1) ParamToken : (08000001) Name : x flags: [none] (00000000) (2) ParamToken : (08000002) Name : y flags: [none] (00000000) Chapter 20 - XML Web Ser vices

Here you can see that the Add() method, return type, and method arguments have been fully described by the C# compiler. Needless to say, metadata is used by numerous aspects of the .NET runtime environment, as well as by various development tools. For example, the IntelliSense feature provided by Visual Studio .NET is made possible by reading an assembly's metadata at design time. Metadata is also used by various object browsing utilities, debugging tools, and even the C# compiler itself. To be sure, metadata is the backbone of numerous .NET technologies such as .NET Remoting, reflection services,

and object serialization.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an dAssembly th e .N ET Plat f orm , Se con d Ed it ion The Role ofC#the Manifest by Andr ew Tr oelsen

ISBN:1590590554

Last but not least,Apr recall validpages) .NET assembly will also contain metadata that describes the code ess ©that 2003a(1200 library itself (technically termed a manifest). type metadata, it isofalways the job of the compiler to This compr ehensiv e text starLike ts w ith a brief ov er view the generate the assembly's manifest. For example, here are some relevant details of the CSharpCalculator C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. assembly: .assembly extern mscorlib { C# and t he .NET Plat for m, Second Edition .publickeytoken = (B7 7A 5C 56 19 34 E0 89) I ntr oduction .ver 1:0:3300:0 Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m } Chapter 1 - The Philosophy of .NET .assembly CSharpCalculator Chapter 2 Building C# Applications { Pa r t .hash Tw o - The C# Pr ogr am0x00008004 m ing La ngua ge algorithm Chapter 3 1:0:932:40235 - C# Language Fundamentals .ver Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# } Chapter 5 - Exceptions and Obj ect Lifetim e .module CSharpCalculator.exe Chapter .imagebase 6 - I nter faces 0x00400000 and Collections .subsystem 0x00000003 Chapter 7 - Callback I nter faces, Delegates, and Ev ents .file alignment Chapter 8 - Advanced C# 512 Type Const ruction Techniques 0x00000001 Pa r t .corflags Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Ta ble o f Con t en t s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

In a nutshell, this manifest metadata documents the list of external assemblies that have been referenced by the CSharpCalculator.exe (via the .assembly extern directive) as well as various characteristics of the Pa r t Four - Le ve r a ging the .NET Libr a r ie s binary itself (via the .assembly, .ver, .module (etc.) directives). Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# anto d thPlatform-Specific e .N ET Plat f orm , Se con d Ed it ion Compiling CIL Instructions by Andr ew Tr oelsen

ISBN:1590590554

Due to the fact that contain Aprassemblies ess © 2003 (1200 pages)CIL instructions and metadata, rather than platform-specific instructions, the underlying CIL must be compiled This compr ehensiv e text star ts w ithon a the brieffly ovbefore er view use. of theThe entity that compiles the CIL into meaningful CPU instructions is termed a just-in-time (JIT) compiler C# language and then quickly m oves to key technical andthat sometimes goes by the ar chitectur al .NET issuesruntime for .NETenvironment developer s. leverages a JIT compiler for each CPU targeting friendly name of "Jitter." The the CLR, each of which is optimized for the platform it is targeting. TaFor ble example, o f Con t enift syou are building a .NET application that is to be deployed on a handheld device, the

corresponding well-equipped to run within a low-memory environment. On the other hand, if you C# and t he .NET Jitter Plat forism, Second Edition areoduction deploying your assembly to a back end server (where memory is seldom an issue), the related Jitter I ntr will be optimized function a high-memory Pa r t One - I nt r oducitong C# a nd in the .NET P la tf or m environment.

In this way, developers can write a single body

of code1 that canPhilosophy be efficiently JIT-compiled and executed on machines with different architectures. Chapter - The of .NET Chapter 2

- Building C# Applications

Furthermore, as a given Jitter compiles CIL instructions into corresponding machine code, it will cache the results in memory in a manner suited to the target OS. In this way, if a call is made to a method named Chapter 3 - C# Language Fundamentals Bar() defined within a class named Foo, the Bar() CIL instructions are compiled into platform-specific Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# instructions on the first invocation and retained in memory for later use. Therefore, the next time Bar() is Chapter - Exceptions Obj ect Lifetim called, 5there is no needand to recompile theeCIL. As you will see in Chapter 9, the .NET SDK also provides a Chapter 6 I nter faces and Collections tool called ngen.exe that will compile CIL code to a native image at the time of installation. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET Plat f orm , Type Se con d System Ed it ion Understanding Common ISBN:1590590554

by Andr ew Tr oelsen

As already mentioned, assembly Apr essa©given 2003 (1200 pages) (single file or multifile) may contain any number of distinct "types." In the world of .NET, a type simply generic term refer to an entity from the This compr ehensiv e is text star tsa w ith a brief ov used er viewtoofcollectively the set {class, structure, interface, enumeration, delegate}. When you build solutions using a .NET-aware C# language and then quickly m oves to key technical and ar chitectur issues forlikely .NETinteract developer s. each of these types. For example, your assembly language (such as C#), youalwill most with may define a single class that implements some number of interfaces. Perhaps one of the interface methods takes a custom enum type as an input parameter and returns a populated structure to the caller. Ta ble o f Con t en t s

Recall the Common Type System C# and t that he .NET Plat for m, Second Edition (CTS) is a formal specification that describes how a given type (class, structure, interface, etc.) must be defined in order to be hosted by the CLR. Also recall that the I ntr oduction CTS defines a number syntactic constructs Pa r t One - I nt r oduci ng C#ofa nd the .NET P la tf or m

(such as the use of unsigned types) that may or may not be

supported a given .NET-aware Chapter 1 -by The Philosophy of .NET language. When you wish to build assemblies that can be used by all possible you need to conform your exposed types to the rules of the CLS (defined Chapter 2 .NET-aware - Building C#languages, Applications shortly). let's Pa r t Tw o -For Thethe C# time Pr ogrbeing, am m ing Lapreview ngua ge Chapter 3

the formal definitions of all possible CTS types.

- C# Language Fundamentals

- Obj ectTypes -Or iented Pr ogr am ming w ith C# CTS Class

Chapter 4 Chapter 5

- Exceptions and Obj ect Lifetim e Every .NET-aware language supports, at the very least, the notion of a "class type," which is the Chapter 6 - I nter faces and Collections

cornerstone of object-oriented Chapter 7 - Callback I nter faces, programming. Delegates, and A Evclass ents may be composed of any number of members (such

as constructors, operators, properties, methods, and events) and data points (fields). As you would expect, - Advanced C# Type Const ruction Techniques the CTS allows a given class to support virtual and abstract members that define a polymorphic interface Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s for derived classes. On the limiting side of the equation, CTS classes may only derive from a single base Chapter 9 - Under standing .NET Assem blies class (multiple inheritance is not allowed for class types). Chapter 4 provides all the gory details of building Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads CTS class types with C#, however, Table 1-2 documents a number of characteristics pertaining to class Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing types. Chapter 8

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Table 1-2: CTS Class Characteristics

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Class Meaning in+ ) Life Chapter 14 - A Better Paint ing Fr amew or k ( GDI Characteristic Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Is the class "sealed" or not?

Sealed classes are types that cannot function as a base class to other types.

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Does 18 the- class implement is ols a collection of abstract members that provide a Chapter ASP.NET Web Pages An andinterface Web Contr any interfaces? contract between the object and object user. The CTS allows a Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex Is the class abstract or Listconcrete? of Figur es List of Tables

What is the "visibility" of this class?

class to implement any number of interfaces. Abstract classes cannot be directly created, but are intended to define common behaviors for derived types. Concrete classes can be created directly. Each class must be configured with a visibility attribute. Basically this trait defines if the class may be used by external assemblies, or only from within the containing assembly (e.g., a private helper class).

CTS Structure Types The concept of a structure is also formalized under the CTS. If you have a C background, you should be pleased to know that these user-defined types (UDTs) have survived in the world of .NET (although they behave a bit differently under the hood). In general, a structure can be thought of as a lightweight class type having value semantics. For more details on the subtleties see Chapter 3. For example, CTS structures may define any number of parameterized constructors (the no-argument constructor is reserved). In this way, you are able to establish the value of each field during the time of construction.

While structures are best suited for modeling geometric and mathematical types, the following type offers C# an d th e .N ET Plat f orm , Se con d Ed it ion a bit more pizzazz (at the risk of offending the C++ purists): ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

// Create a C# structure. This compr ehensiv e text star ts w ith a brief ov er view of the struct Baby C# language and then quickly m oves to key technical and { ar chitectur al issues for .NET developer s. // Structures can contain fields. public string name; Ta ble o f Con t en t s

Structures can contain constructors (with arguments). C# and t// he .NET Plat for m, Second Edition public Baby(string name) I ntr oduction name; } P la tf or m Pa r t One{- Ithis.name nt r oduci ng C#=a nd the .NET Chapter 1

- The Philosophy of .NET may take methods. Chapter // 2 - Structures Building C# Applications

Cry() Pa r t Tw opublic - The C# void Pr ogr am m ing La ngua ge { Console.WriteLine("Waaaaaaaaaaaah!!!"); } - C# Language Fundamentals

Chapter 3 Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

public bool IsSleeping() { return false; } - Exceptions and Obj ect Lifetim e public bool IsChanged() { return false; }

Chapter 5 Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

}

Pa r t Thre e - Pr ogr am m in i ngaction w i th .N ET Assem bl ielogic s Here is our structure (assume this

Chapter 9

is contained in some Main() method):

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, Cont exts, and Threads // Welcome to theAppDomains, world Max Barnaby!! Chapter 11 - Type Reflection, Binding, and Attr ibute- Based Pr ogramm ing Baby barnaBaby = new Late Baby("Max"); Pa r t Four - Le ve r a ging the .NET Libr a r ie s Console.WriteLine("Changed?:

{0} ", barnaBaby.IsChanged());

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Console.WriteLine("Sleeping?: {0} ", barnaBaby.IsSleeping()); Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter // Show 14 - your A Better true Paint colors ing Fr amew Max... or k ( GDI + )

for(int i < with 10000; i++) Chapter 15 - iPr = ogr0; am ming Windows Form s Contr ols Chapter barnaBaby.Cry(); 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

As you will see, all CTS structures are derived from a common base class: System.ValueType. This base class configures a type to behave as a stack-allocated entity rather than a heap-allocated entity. Finally, Chapter 19 - ASP.NET Web Applicat ions be aware that the CTS permits structures to implement any number of interfaces; however, structures may Chapter 20 - XML Web Ser vices not function as the base type to other classes or structures and are therefore explicitly "sealed." Chapter 18 - ASP.NET Web Pages and Web Contr ols

I ndex

List of Figur es

CTS Interface Types

List of Tables

Interfaces are nothing more than a named collection of abstract member definitions, which may be supported (i.e., implemented) by a given class or structure. Unlike classic COM, .NET interfaces do not derive a common base interface such as IUnknown. In fact, interfaces are the only .NET type that do not derive from a common base type (not even System.Object). This point should be clear, given that interfaces typically express pure protocol and do not provide an implementation. On their own, interfaces are of little use. However when a class or structure implements a given interface in its unique way, you are able to request access to the supplied functionality using an interface reference in a polymorphic manner. As well, when you create custom interfaces using a .NET-aware programming language, the CTS permits a given interface to derive from multiple base interfaces (unlike classic COM). As you might suspect, this allows us to build some rather exotic behaviors. Interface-based programming in will be fully detailed in Chapter 6.

CTS Enumeration Types

Enumerations are a handy programming construct that allows you to group name/value pairs under a C# an d th e .N ET Plat f orm , Se con d Ed it ion specific name. For example, assume you are creating a video game application that allows the user to ISBN:1590590554 by player Andr ewtypes Tr oelsen select one of three (Wizard, Fighter, or Thief). Rather than keeping track of raw numerical Apr ess © 2003 (1200 pages) values to represent each possibility, you could build a custom enumeration: This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and // A C# enumeration. ar chitectur al issues for .NET developer s.

public enum PlayerType { Wizard = 100, Fighter = 200, Thief = 300 } ; Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

By default, the storage used to hold each item is a System.Int32 (i.e., a 32-bit integer), however it is possible to alter this storage slot if need be (e.g., when programming for a low memory device such as a Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Pocket PC). Also, the CTS demands that enumerated types derive from a common base class, Chapter 1 - The Philosophy of .NET System.Enum. As you will see in Chapter 3, this base class defines a number of interesting members that Chapter 2 - Building C# Applications allow you to extract, manipulate, and transform the underlying name/value pairs at runtime. I ntr oduction

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

CTS Delegate Types - Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 4 Chapter 5

- Exceptions and Obj ect Lifetim e

Delegates are the .NET equivalent of a type safe C style function pointer. The key difference is that a .NET - I nter faces and Collections delegate is a class that derives from System.MulticastDelegate, rather than a simple pointer to a raw Chapter 7 - Callback I nter faces, Delegates, and Ev ents memory address. These types are useful when you wish to provide a way for one entity to forward a call to Chapter 8 - Advanced C# Type Const ruction Techniques another entity. Furthermore, delegates provide intrinsic support for multicasting (i.e., forwarding a request Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s to multiple recipients) and asynchronous method invocations. As you will see in Chapter 7, delegates Chapter Under standing .NET.NET Assem blies protocol. provide9the- foundation for the event Chapter 6

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

CTS Type Members

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Now that you have previewed each of the .NET types formalized by the CTS, realize that each may take

Chapter 13 - Building a Bet ter Win dowspeaking, ( Int roducin Window s For is ms) any number of members. Formally a gtype member constrained by the set {constructor, static Chapter 14 - Anested Better type, Paint ing Fr amewmethod, or k ( GDIproperty, +) constructor, operator, field, constant, event}. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

The CTS various "adornments" that may be associated with a given member. For example, Chapter 16 defines - The Sythe stem .I O Nam espace each member has a given "visibility" Chapter 17 - Data Access w ith ADO.NETtrait (e.g., public, private, protected, and so forth). A member may be declared ase "abstract" enforce a polymorphic Pa r t Fi ve - W b Appl ica tito ons and X ML W e b Se r vi cesbehavior

on derived types as well as "virtual" to define a

canned18(but overridable) As well, Chapter - ASP.NET Web implementation. Pages and Web Contr ols most members may be configured as "static" (bound at

the class or "instance" levelions (bound at the object level) entities. The construction of type members is Chapter 19 level) - ASP.NET Web Applicat examined over the course of the next several chapters.

Chapter 20 - XML Web Ser vices I ndex

Intrinsic CTS Data Types

List of Figur es List of Tables

The final aspect of the CTS to be aware of for the time being, is that it establishes a well-defined set of intrinsic data types used by all .NET-aware languages. Although a given language typically has a unique keyword used to declare an intrinsic data type, all languages ultimately resolve to the same type defined in mscorlib.dll. Consider Table 1-3, which documents how key CTS data types are expressed in various .NET languages. Table 1-3: The Intrinsic CTS Data Types

.NET Base Type System.Byte

Visual Basic C# an d th e .N ET Plat f orm , Se conC# d Ed it ion Keyword by Andr.NET ew Tr oelsen Apr ess © 2003 (1200 pages)

Keyword

C++ with Managed Extensions Keyword ISBN:1590590554

Byte

byte

char

System.Int16

Short

short

short

System.Int32

Integer

int

int or long

long

__int64

ushort

unsigned short

uint

unsigned int or unsigned long

ulong

unsigned __int64

float

float

double

double

object

Object*

This compr ehensiv e text star ts w ith a brief ov er view of the and then quickly m oves to key technical and char System.SByte C# language Not supported sbyte signed ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s

C# System.Int64 and t he .NET Plat for m,Long Second Edition I ntr oduction

System.UInt16

Not supported

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - The Philosophy .NET System.UInt32 Not of supported Chapter 2

- Building C# Applications

System.UInt64

Not supported

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - C# Language Fundamentals System.Single Single Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

System.Double

Double

Chapter 6 - I nter faces and Collections System.Object Object Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

System.Char

Char

Pa rSystem.String t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s String

Chapter 9

- Under standing .NET Assem blies

System.Decimal

Decimal

char

__wchar_t

string

String*

decimal

Decimal

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter System.Boolean 11 - Type Reflection, Boolean Late Binding, and Attr ibuteboolBased Pr ogramm booling Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter As you 12 can- see, Obj ect not Ser allialization languages and are the able .NET to Remoting represent Laythe er same intrinsic data types of the CTS using

specific13keywords. youter might imagine, it would be verys helpful Chapter - BuildingAs a Bet Win dow ( Int roducin g Window For ms) to create a well-known subset of the CTS that defines common, set of constructs (and data types) for all .NET-aware Chapter 14 - Aa Better Paintshared ing Fr amew or programming k ( GDI + ) languages. theming CLS. Chapter 15 - Enter Pr ogr am with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET Plat f orm , Language Se con d Ed it ion Specification Understanding Common by Andr ew Tr oelsen

ISBN:1590590554

As you are aware, different languages express the same programming constructs in unique, languageApr ess © 2003 (1200 pages) specific terms. For example, in C#, string concatenation is ov denoted This compr ehensiv e text star ts w ith a brief er view using of the the plus operator while in Visual Basic you typically make use of the ampersand. Even when two distinct C# language and then quickly m oves to key technical andlanguages express the same ar chitectur al issuesafor .NET developer s. programmatic idiom (for example, function with no return value) the chances are very good that the syntax will appear quite different on the surface: Ta ble o f Con t en t s

' VB .NET function returning void (aka VB .NET subroutines). Public Sub Foo() I ntr oduction ' stuff... Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m End Sub C# and t he .NET Plat for m, Second Edition

Chapter 1

- The Philosophy of .NET

Chapter - Building C# Applicationsvoid. // C#2 function returning Pa r t Tw o - The C# Foo() Pr ogr am m ing La ngua ge public void

Chapter 3 {

- C# Language Fundamentals

Chapter // 4 - stuff... Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e } Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

As you 8have already seen, these minor syntactic variations are inconsequential in the eyes of the .NET Chapter - Advanced C# Type Const ruction Techniques runtime, given that the respective compilers (csc.exe or vbc.exe in this case) are configured to emit the Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s same CIL instruction set. However, languages can also differ with regard to their overall level of Chapter 9 - Under standing .NET Assem blies functionality. For example, some languages (C#) allow you to overload operators for a given type while Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads others (VB .NET) do not. Some languages may support the use of unsigned data types, which will not map Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing correctly in other languages. What we need is to have a baseline to which all .NET aware languages are Pa r t Four - Le ve r a ging the .NET Libr a r ie s expected to conform. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 is- a Building a Bet ter Win dowdescribe ( Int roducin g Window For ms) The CLS set of guidelines that in vivid detail,s the minimal and complete set of features a Chapter 14 - A Bettercompiler Paint ing must Fr amew or k ( GDI +) given .NET-aware support to produce code that can be hosted by the CLR, while at the Chapter same time 15 - be Pr ogr accessed am minginwith a uniform Windows manner Form s by Contr all ols languages that target the .NET platform. In many ways

the CLS be Sy viewed a physical Chapter 16can - The stem .Ias O Nam espacesubset of the full functionality defined by the CTS. Chapter 17 - Data Access w ith ADO.NET

The CLS is ultimately a set of rules that compiler builders must conform to, if they intend their products to function seamlessly within the .NET universe. Each rule is assigned a simple name (e.g., "CLS Rule 6"), Chapter 18 - ASP.NET Web Pages and Web Contr ols and describes how this rule affects those who build the compilers as well as those who (in some way) Chapter 19 - ASP.NET Web Applicat ions interact with them. For example, the crème de la crème of the CLS is the mighty Rule 1: Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 20 - XML Web Ser vices I ndex

1: CLS rules apply only to those parts of a type that are exposed outside the defining assembly. List ofRULE Figur es List of Tables

Given this key rule you can (correctly) infer that the remaining rules of the CLS do not apply to the internal logic used to build the inner workings of a .NET type. Assume you are building a .NET application that exposes three classes, each of which defines a single function. Given the first rule of the CLS, the only aspects of the classes that must conform to the CLS are the member definitions (i.e., naming conventions, parameters, and return types). The internal implementations of each method may use any number of nonCLS techniques, as the outside world won't know the difference. For example, if you were to add the following member to the C# Calc class type seen previously in this chapter, you would have just written a non-CLS-compliant method, as the parameters and return values make use of an unsigned data type: public class Calc { // CLS compliant! public int Add(int x, int y) { return x + y; }

C# an d th e .N ET Plat f orm , Se con d Ed it ion // Not CLS compliant! by AndrAdd(ulong ew Tr oelsen x, ulong y) public ulong © 2003 (1200 pages) { return Apr x ess + y;}

}

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

However, if you were to update your CLS-compliant method as follows: Ta ble o f Con t en t s

public class Calc { I ntr oduction // Still CLS compliant! Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public int Add(int x, int y) Chapter 1 - The Philosophy of .NET { Chapter 2 - // Building C# Applications As this ulong is only used internally, we are still Pa r t Tw o - The C# Pr ogr am m ing La ngua ge // CLS compliant. Chapter 3 - ulong C# Language Fundamentals theAnswer = (ulong)(x + y); Chapter 4 - Console.Write("Answer Obj ect -Or iented Pr ogr am ming w ith ulong: C# as {0}\n", Chapter 5 - Exceptions and Obj ect Lifetim e theAnswer); Chapter 6 - return I nter facesxand + Collections y; Chapter}7 - Callback I nter faces, Delegates, and Ev ents ... 8 - Advanced C# Type Const ruction Techniques Chapter }r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Pa C# and t he .NET Plat for m, Second Edition

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

You have still conformed to the rules of the CLS, and can rest assured that all .NET languages are able to interact with this implementation of the Add() method.

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - inBuilding a to BetRule ter Win ( Int roducin Window s For ms) rules. For example, the CLS describes Of course, addition 1, dow the CLS definesg numerous other Chapter 14 - Alanguage Better Paint ing represent Fr amew or ktext ( GDI +) how a given must strings, how enumerations should be represented internally (the Chapter 15 -used Pr ogr amstorage), ming withhow Windows s Contr base type for to useForm static types,olsand so forth. Again, remember that in most cases Chapter these rules 16 - do Thenot Sy stem have.Ito O be Nam committed espace to memory (unless you need to build a LISP .NET compiler!). Chapter 17 - Data Access w ith ADO.NET

Ensuring CLS Compliance

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter ASP.NET Webcourse Applicat As you 19 will- see over the ofions this book, C# does define a number of constructs that are not CLS Chapter compliant. 20 - The XMLgood Web Ser news, vices however, is that you are always free to inform the C# compiler to check your

code for CLS compliance using a single .NET attribute (which must be placed outside the scope of any I ndex namespace List of Figur es or type definitions): List of Tables

// Tell the C# compiler to check for CLS compliance. [assembly: System.CLSCompliant(true)]

Chapter 11 dives into the details of attribute-based programming in detail. For the time being, simply understand that this line of code will instruct the C# compiler to check your code for complete CLS compliance. If any non-CLS-compliant syntactic tokens are discovered, you are issued a compiler error and a description of the offending code. Note If you are interested in investigating each constraint imposed by the CLS, check out Partition I of the Common Language Infrastructure (CLI, not to be confused with CIL). By default, this Word document is located under :\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\ Tool Developers Guide\Docs. If you can't locate this path on your machine, simply do a search for a folder named "Tool Developers Guide".

C# an dthe th e .N ET Plat f orm , Language Se con d Ed it ion Runtime Understanding Common ISBN:1590590554

by Andr ew Tr oelsen

In addition to the Apr CTS and CLS specifications, the final TLA (three-letter-acronym) to contend with at the ess © 2003 (1200 pages) moment is the CLR. Programmatically speaking, thea term runtime be understood as a collection of This compr ehensiv e text star ts w ith brief ov er viewcan of the external services C# thatlanguage are required to execute a given compiled unit of code. For example, when and then quickly m oves to key technical and chitectur issues forFoundation .NET developer s. developers makearuse of thealMicrosoft Classes (MFC) to create a new application, they are (painfully) aware that their binary is required to link with the rather hefty MFC runtime library (e.g., mfc42.dll). Other popular languages also have a corresponding runtime. Visual Basic 6.0 programmers Taare ble also o f Con t en tied tot sa runtime module or two (e.g., msvbvm60.dll). Java developers are tied to the Java Virtual C# and t he(e.g., .NET JVM) Plat forand m, Second Edition Machine so forth. I ntr oduction

The .NET platform offers another runtime Pa r t One - I nt r oduci ng C# a yet nd the .NET P la tf or m system.

The key difference between the .NET runtime and

the various runtimes Iofhave Chapter 1 - other The Philosophy .NETjust mentioned is the fact that the .NET runtime provides a single welldefined2 runtime layerC#that is shared by all languages and platforms that are .NET aware. As mentioned Chapter - Building Applications earlier runtime Pa r t Tw oin- this The chapter, C# Pr ogrthe am m.NET ing La ngua geis Chapter 3

officially termed the common language runtime, or simply CLR.

- C# Language Fundamentals

The crux of the CLR is physically represented by an assembly named mscoree.dll (aka, the Common - Obj ect -Or iented Pr ogr am ming w ith C# Object Runtime Execution Engine). When an assembly is referenced for use, mscoree.dll is loaded Chapter 5 - Exceptions ect Lifetim e automatically, which in and turnObj loads the required assembly into memory. The runtime engine is responsible Chapter 6 I nter faces and Collections for a number of tasks. First and foremost, it is the entity in charge of resolving the location of an assembly Chapter 7 - the Callback I nter faces, Delegates, Ev ents structure, etc.) within the binary by reading the and finding requested type (e.g., class,and interface, Chapter 8 -metadata. Advanced The C# Type Const engine ruction Techniques contained execution lays out the type in memory, compiles the associated CIL into Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie(optional) s platform-specific instructions, performs any security checks and then executes the code in Chapter 9 - Under standing .NET Assem blies question. Chapter 4

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

In addition loading your custom assemblies and creating custom Chapter 11 - toType Reflection, Late Binding, and Attr ibuteBasedyour Pr ogramm ingtypes, the CLR will also interact with the types thea .NET Pa r t Four - Le ve contained r a ging the within .NET Libr r ie s

base class libraries. Although the entire base class library has been broken into a number of discrete assemblies, the key binary is mscorlib.dll. This .NET assembly Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er contains a large number of core types that encapsulate a wide variety of common programming tasks as Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) well as the core data types used by all .NET languages. When you build .NET solutions, you always make Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) use of this particular assembly, and perhaps numerous other .NET binaries (both system supplied and Chapter 15 - Pr ogr am ming with Windows Form s Contr ols custom). Chapter 16 - The Sy stem .I O Nam espace

Chapter Data Access ith ADO.NET Figure 17 1-3- illustrates thewworkflow that takes place between your source code (which is making use of Pa r t Fi ve - W library e b Appltypes), ica ti onsa and X ML W e bcompiler, Se r vi ces and base class given .NET

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

the .NET execution engine.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure mscoree.dll in espace action Chapter 16 - 1-3: The Sy stem .I O Nam Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e Namespaces .N ET Plat f orm , Se con d Ed it ion A Tour of the .NET ISBN:1590590554

by Andr ew Tr oelsen

Each of us understands importance Apr ess ©the 2003 (1200 pages) of code libraries. The point of libraries such as MFC, J2EE, or ATL is to give developers a well-defined existing to leverage This compr ehensiv eset textofstar ts w ithcode a brief ov er view in of their the applications. For example, MFC defines a numberC#of language C++ classes that provide canned implementations and then quickly m oves to key technical andof dialog boxes, menus, and chitectur al for issues .NET developer s. of the world, as they can spend less time toolbars. This is aargood thing the for MFC programmers reinventing the wheel, and more time building a custom solution. Visual Basic and Java offer similar notions: intrinsic types/global functions and packages, respectively. Ta ble o f Con t en t s

Unlike Java, or m, Visual Basic 6.0, the C# language does not come with a predefined set of languageC# and tMFC, he .NET Plat for Second Edition specific classes. Ergo, there is no C# class library. Rather, C# developers leverage existing types supplied I ntr oduction by all the types Pa r t the One.NET - I nt rFramework. oduci ng C# aTo nd keep the .NET P la tf or m

within this binary well organized, the .NET platform makes

extensive of Philosophy the namespace concept. Chapter 1 use - The of .NET Chapter 2

- Building C# Applications

The key difference between this approach and a language-specific library such as MFC, is that any language targeting the .NET runtime makes use of the same namespaces and same types as a C# Chapter 3 - C# Language Fundamentals developer. For example, the following three programs all illustrate the ubiquitous "Hello World" Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# application, written in C#, VB .NET, and C++ with managed extensions (MC++): Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

// Hello world in C# - Callback I nter faces, Delegates, and Ev ents using System; Chapter 8 - Advanced C# Type Const ruction Techniques public class MyApp Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s { Chapter public 9 - Understatic standing void .NET Assem blies Main() Chapter { 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and from Attr ibuteBased Pr ogramm ing Console.WriteLine("Hi C#"); Pa r t Four} - Le ve r a ging the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er } Chapter 7

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter ' Hello 14 - world A Betterin Paint VB ing.NET Fr amew or k ( GDI + )

Imports Chapter 15 - System Pr ogr am ming with Windows Form s Contr ols Public MyApp Chapter 16 Module - The Sy stem .I O Nam espace Main() Chapter Sub 17 - Data Access w ith ADO.NET from Pa r t Fi ve - W e b Console.WriteLine("Hi Appl ica ti ons and X ML W e b Se r vi ces

VB .NET")

Sub Chapter End 18 - ASP.NET Web Pages and Web Contr ols End Module Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

// Hello world in Managed C++ (MC++) #using List of Figur es using namespace System; List of Tables void main() { Console::WriteLine(S"Hi from MC++"); } I ndex

Notice that each language is making use of the Console class defined in the System namespace. Beyond minor syntactic variations, these three applications look and feel very much alike, both physically and logically. As you can see, the .NET platform has brought a streamlined elegance to the world of software engineering. Clearly, your primary goal as a .NET developer is to get to know the wealth of types defined in the numerous base class namespaces. The most fundamental namespace to get your hands around is named "System." This namespace provides a core body of types that you will need to leverage time and again as a .NET developer. In fact, you cannot build any sort of functional C# application without at least making a reference to the System namespace.

System is the root namespace for numerous other .NET namespaces. Simply put, namespaces are a way C# an d th e .N ET Plat f orm , Se con d Ed it ion to group semantically related types (classes, enumerations, interfaces, delegates, and structures) under a ISBN:1590590554 by Andr ew Tr oelsen single umbrella. For example, the System.Drawing namespace contains a number of types to assist you in Apr ess © 2003 (1200 pages) rendering images onto a given graphics device. Other namespaces exist for data access, Web This compr ehensiv e text starsecurity ts w ith a(among brief ov er view others). of the From a very high level, Table development, threading, and programmatic many C# language and then quickly m oves to key technical and 1-4 offers a rundown of some (but certainly not all) of the .NET namespaces. ar chitectur al issues for .NET developer s. Table 1-4: A Sampling of .NET Namespaces Ta ble o f Con t en t s

.NET Namespace

Meaning in Life

C# and t he .NET Plat for m, Second Edition I ntrSystem oduction

Within System you find numerous low-level classes dealing types, mathematical manipulations, garbage collection, as well as a number of commonly used exceptions and predefined attributes.

primitive Pa r t One - I nt r oduci ng C# a nd the .NET Pwith la tf or m Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

System.Collections

Chapter 3 Chapter 4

This namespace defines a number of stock container objects

- C# Language Fundamentals(ArrayList, Queue, etc.) as well as base types and interfaces - Obj ect -Or iented Pr ogr am ming ith C#you to build customized collections. thatwallow

Chapter 5

- Exceptions and Obj ect Lifetim e System.Data Chapter 6 - I nter faces and Collections These namespaces are (of course) used for database

manipulations (ADO.NET). You will see each of these later in this book.

System.Data.Common Chapter 7 - Callback I nter faces, Delegates, and Ev ents

Chapter 8 - Advanced C# Type Const ruction Techniques System.Data.OleDb Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

System.Data.SqlClient

Chapter 9

- Under standing .NET Assem blies System.Diagnostics Here, numerous types that can be used by any Chapter 10 - Pr ocesses, AppDomains, Cont exts,you andfind Threads

.NET-aware language toogramm programmatically debug and trace Chapter 11 - Type Reflection, Late Binding, and Attr ibuteBased Pr ing Pa r t Four - Le ve r a ging the .NET Libr a r ie syour

source code.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

System.Drawing

Here, you find numerous types wrapping GDI+ primitives

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Windowfonts, s For ms) such as bitmaps, icons, printing support, and advanced System.Drawing.Drawing2D Chapter 14 - A Better Paint ing Fr amew orgraphical k ( GDI + ) rendering support.

System.Drawing.Printing Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 16 - The Sy stem .I O Nam espace This namespace includes file IO, buffering, and so forth. System.IO Chapter 17 - Data Access w ith ADO.NET

(as Pa rSystem.Net t Fi ve - W e b Appl ica ti ons and X ML W eThis b Senamespace r vi ces

well as other related namespaces)

contains types related to network programming Chapter 18 - ASP.NET Web Pages and Web Contr ols

Chapter 19 - ASP.NET Web Applicat ions (requests/responses, sockets, end points, etc.). Chapter 20 - XML Web Ser vices System.Reflection I ndex

System.Reflection.Emit

Defines types that support runtime type discovery and dynamic creation and invocation of custom types.

List of Figur es

ListSystem.Runtime.InteropServices of Tables

Provides facilities to allow .NET types to interact with "unmanaged code" (e.g., C-based DLLs and classic COM servers) and vice versa.

System.Runtime.Remoting

This namespace (and other related namespaces) define types used to build solutions that incorporate the new .NET Remoting layer (which has nothing to do with classic DCOM whatsoever).

System.Security

Security is an integrated aspect of the .NET universe. In the security-centric namespaces you find numerous types dealing with permissions, cryptography, and so on.

System.Threading

You guessed it, this namespace deals with threading issues. Here you will find types such as Mutex, Thread, and Timeout.

System.Web

number of namespaces are specifically geared toward the C# an d th e .N ET PlatAf orm , Se con d Ed it ion applications, including ASP.NET ISBN:1590590554 by Andr ew Tr oelsen development of .NET Web and XML Web services. Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts the w ithname, a briefthe ov er viewplatform of the does contain System.Windows.Forms Despite .NET C# language and then quickly m oves to key technical and namespaces that facilitate the construction of more ar chitectur al issues for .NET developer s. traditional main windows, dialog boxes, and custom widgets.

System.Xml

The XML-centric namespaces contain numerous types that represent core XML primitives and types used to interact with C# and t he .NET Plat for m, Second EditionXML data.

Ta ble o f Con t en t s I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET Accessing a Namespace Programmatically - Building C# Applications

Chapter 2

Pa t Tw o - The C# Pr ogr am a m namespace ing La ngua geis Itris worth reiterating that

nothing more than a convenient way for us mere humans to

Chapter 3 understand - C# Language Fundamentals logically and organize related types. For example, consider again the System namespace. Chapter 4 - perspective, Obj ect -Or iented ograssume am ming that w ith System.Console C# From your you Pr can represents a class named Console that is Chapter 5 -within Exceptions and Obj ect Lifetim e contained a namespace called System. However, in the eyes of the .NET runtime, this is not so. The Chapter - I nteronly faces and aCollections runtime6 engine sees single entity named System.Console. Chapter 7

- Callback I nter faces, Delegates, and Ev ents

As you 8build your custom types, youruction have the option of organizing your items into a custom namespace. Chapter - Advanced C# Type Const Techniques Again, a namespace is a logical naming scheme used by .NET languages to group related types under a Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s unique umbrella. When you group your types into a namespace, you provide a simple way to circumvent Chapter 9 - Under standing .NET Assem blies possible name clashes between assemblies. For example, if you were building a new Windows Forms Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads application that references two external assemblies, and each assembly contained a type named GoCart, Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing you would be able to specify which GoCart class you are interested in by appending the type name to its Pa r t Four - Le ve r a ging the .NET Libr a r ie s containing namespace (i.e., "Intertech.CustomVehicles.GoCart" not "SlowVehicles.GoCart"). Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 -"using" Building a Bet tersimplifies Win dow (the Int roducin g Window s For ms) In C#, the keyword process of declaring types defined in a particular namespace. Chapter - Ait Better Fr amew or kinterested ( GDI + ) in building a traditional desktop application. The main Here is14 how works.Paint Let'singsay you are Chapter window15renders - Pr ograam bar ming chart with based Windows on some Form information s Contr ols obtained from a back-end database and displays

your company using Bitmap type. While learning the types each namespace contains takes study Chapter 16 - Thelogo Sy stem .I OaNam espace and experimentation, here some obvious candidates to reference in your program: Chapter 17 - Data Access w ithare ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - are ASP.NET and Web Contr ols to build this application. // Here allWeb thePages namespaces used Chapter using19System; - ASP.NET Web Applicat ions // General base class library types.

using20System.Drawing; Chapter - XML Web Ser vices using System.Windows.Forms; I ndex using System.Data; List of Figur es using System.Data.OleDb; List of Tables

// // // //

Rendering types. GUI widget types. General data centric types. OLE DB data access types.

Once you have referenced some number of namespaces (and set a reference to the associated external assembly), you are free to create instances of the types they contain. For example, if you are interested in creating an instance of the Bitmap class (defined in the System.Drawing namespace), you can write: // Explicitly list the namespaces used by this file... using System; using System.Drawing; class MyClass { public void DoIt() { // Create a 20×20 pixel bitmap. Bitmap bm = new Bitmap(20, 20);

// Use the bitmap... C# an d th e .N ET Plat f orm , Se con d Ed it ion

}

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

}

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to keythe technical andis able to resolve the Bitmap class Because your application is referencing System.Drawing, compiler ar chitectur al issues for .NET developer as a member of this namespace. If you did not directlys.reference System.Drawing in your application, you would be issued a compiler error. However, you are free to declare variables using a "fully qualified name" as well:

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

// Not listing System.Drawing namespace! using System; Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m class MyClass Chapter 1 - The Philosophy of .NET { Chapter 2 - Building C# Applications public void DoIt() Pa r t Tw o - The C# Pr ogr am m ing La ngua ge { Chapter 3 - C# Language Fundamentals // Using fully qualified name. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ithbm C# = new System.Drawing.Bitmap(20, 20); System.Drawing.Bitmap Chapter 5 - Exceptions and Obj ect Lifetim e ... Chapter } 6 - I nter faces and Collections Chapter 7 - Callback I nter faces, Delegates, and Ev ents } I ntr oduction

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies While defining a type using the fully Cont qualified provides greater readability, I think you'd agree that the Chapter 10 - Pr ocesses, AppDomains, exts, name and Threads

C# using reduces keystrokes. thisAttr text, I willBased avoidPrthe use ofingfully qualified names (unless there Chapter 11 keyword - Type Reflection, Late Binding,Inand ibuteogramm isr ta Four definite to be resolved) Pa - Le ambiguity ve r a ging the .NET Libr a r ie sand

opt for the simplified approach of the C# using keyword. However, always remember that this technique is simply a shorthand notation for specifying a type's fully Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er qualified name, and each approach results in the exact same underlying CIL. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Referencing External Assemblies

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

In addition to specifying a namespace via the C# using keyword, you also need to tell the C# compiler the name of the assembly containing the actual CIL definition for the referenced type. As mentioned, many Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces core .NET namespaces live within mscorlib.dll. System.Drawing however, is contained in a separate binary Chapter 18 - ASP.NET Web Pages and Web Contr ols named System.Drawing.dll. By default, the system-supplied assemblies are located under : \ Chapter 19 - ASP.NET Web Applicat ions %windir%\ Microsoft.NET\ Framework\ , as seen in Figure 1-4. Chapter 17 - Data Access w ith ADO.NET

Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 1-4: The base class libraries Depending on the development tool you are using to build your .NET types, you will have various ways to inform the compiler which assemblies you wish to include during the compilation cycle. You examine how to do so in the next chapter, so I'll hold off on the details for now.

an d th e .N ET Plat f orm , Nomenclature Se con d Ed it ion Increasing C# Your Namespace ISBN:1590590554

by Andr ew Tr oelsen

If you are beginning to feel a tad overwhelmed at the thought of gaining mastery over every nuance of the Apr ess © 2003 (1200 pages) .NET universe, just remember that what makes This compr ehensiv e text star ts waithnamespace a brief ov er unique view of is thethat the types it defines are all somehow semantically related. Therefore, if you have no need for a user C# language and then quickly m oves to key technical and interface beyond a simple ar chitectur al forget issues all for about .NET developer s. console application, you can the System.Windows.Forms and System.Drawing namespaces (among others). If you are building a painting application, the database programming namespaces are most likely of little concern. Like any new set of prefabricated code, you learn as you go. Ta ble o f Con t en t s

Over you are exposed to numerous aspects of the .NET platform and related C# andthe t hechapters .NET Plat that for m,follow, Second Edition namespaces. As it would be impractical to detail every type contained in every namespace in a single I ntr oduction book (honestly, there area many ofmtypes Pa r t One - I nt r oduci ng C# nd the thousands .NET P la tf or

in .NET version 1.0 and even more with the release of

version11.1), youPhilosophy should beofaware Chapter - The .NET of the following techniques that can be used to learn more about the .NET libraries: Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

.NET SDK online documentation (MSDN)

Chapter 3

- C# Language Fundamentals

Chapter 4 ildasm.exe - Obj ect -Orutility iented Pr ogr am ming w ith C# The Chapter 5 - Exceptions and Obj ect Lifetim e

The Viewer WebCollections application Chapter 6 Class - I nter faces and Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

The wincv.exe desktop application

Pa r t Thre - Pr ogrStudio am m i ng w i thintegrated .N ET Assem bl ie s Thee Visual .NET Object

Chapter 9

Browser

- Under standing .NET Assem blies

I think it's to assume you know Cont whatexts, to doand with the supplied online Help (remember, F1 is your friend), Chapter 10 safe - Pr ocesses, AppDomains, Threads however 2 points outLate some strategies used when navigating MSDN. In addition, it is important that Chapter 11Chapter - Type Reflection, Binding, and Attr ibuteBased Pr ogramm ing you understand Pa r t Four - Le ve r a how ging to thework .NETwith Librthe a r ieildasm.exe, s

the Class Viewer Web application, and wincv.exe utilities, each of which is shipped with the .NET SDK (the VS .NET Object Browser is examined in Chapter 2). Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Using ildasm.exe

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Recall that at one time in the evolution of .NET, CIL was simply named IL. Given this, the first tool under examination in this chapter is not named cildasm.exe, but ildasm.exe. The Intermediate Language Chapter 17 - Data Access w ith ADO.NET Dissasembler utility (ildasm.exe) allows you to load up any .NET assembly and investigate its contents Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces (including the associated manifest, CIL instruction set and type metadata) using a friendly GUI. The Chapter 18 - ASP.NET Web Pages and Web Contr ols ildasm.exe is most likely found in :\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin. Chapter 19 - ASP.NET Web Applicat ions Once you launch this tool, proceed to the "File | Open" menu command and navigate to the assembly you Chapter 20 - XML Web Ser vices wish to explore. For the time being, open up mscorlib.dll (Figure 1-5). Note the path of the opened I ndex assembly is documented in the caption of the ildasm.exe utility. Chapter 16 - The Sy stem .I O Nam espace

List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Figure YourPaint newingbest friend, Chapter 14 - 1-5: A Better Fr amew or kildasm.exe ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter The Sy stem .I O Nam As you 16 can- see, the structure ofespace an assembly is presented in a familiar tree view format. While exploring a Chapter 17 Data Access w ith ADO.NET given type, notice that the members for a given type (methods, properties, nested classes, and so forth) Pa r t Fi ve - W e bby Appl ica ti ons icon. and XTable ML W e1-5 b Selists r vi ces are identified a specific some

of the more common iconic symbols and text dump

Chapter 18 - ASP.NET Web Pages and Web Contr ols abbreviations. Chapter 19 - ASP.NET Web Applicat ions Chapter Table 1-5: 20 - ildasm.exe XML Web Ser Tree vicesView Icons I ndex

ildasm.exe TreeView Icon

List of Figur es

Text Dump Abbreviation

Meaning in Life

(dot)

This icon signifies that additional information is available for a given type. Also marks the assembly manifest.

[NSP]

Represents a namespace.

[CLS]

Signifies a class type.

List of Tables

Be aware that nested types are marked with the dollar sign notation (for example, $). [VCL]

Represents a structure type.

[INT]

Represents an interface type.

[MET]

Represents a method of a given type.

[STM] a static method of a given type C# an d th e .N ET Plat f orm , Se con Represents d Ed it ion (note the "s" marker). ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) [FLD]

Represents a field (e.g., public data) defined by

This compr ehensiv e text star ts w ith a a given brief ov er view of the type. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. [STF] Represents a static field defined by a given type

(again note the "s" marker). Ta ble o f Con t en t s

[PTY]

Signifies a property supported by the type.

C# and t he .NET Plat for m, Second Edition I ntr oduction Beyond allowing you to explore the types (and members of a specific type) contained in a given assembly, Pa r t One - I ntalso r oduci ng C#you a ndtothe .NET la tf or m ildasm.exe allows view thePunderlying

CIL instructions for a given member. To illustrate, locate

Chapter 1 - The Philosophy .NET and double-click the defaultofconstructor icon for the System.IO.BinaryWriter class. This launches a Chapter separate 2 window, - Building displaying C# Applications the CIL shown in Figure 1-6. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Figure 1-6: Viewing the underlying CIL

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Dumping Namespace Information

to File

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

The next of interest regard to ildasm.exe Chapter 18 point - ASP.NET Web with Pages and Web Contr ols is the very useful ability to dump the relational hierarchy of an assembly into aWeb textApplicat file. In this Chapter 19 - ASP.NET ionsway, you can make hard copies of your favorite assemblies to read at your neighborhood coffeehouse (or brew pub). To do so, select "File | Dump TreeView" and provide a Chapter 20 - XML Web Ser vices name for the resulting *.txt file. As you look over the dump, notice that the identifying icons have been I ndex replacedwith their corresponding textual abbreviations (see the previous table). For example, ponder Figure 1-7.

List of Figur es List of Tables

Figure 1-7: Dumping namespace information to file

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Dumping CILbyInstructions to File Andr ew Tr oelsen

ISBN:1590590554

Apr ess © 2003 (1200 pages)

On a related note, you are also able to dump the CIL instructions for a given assembly to file, using the This compr ehensiv e text star ts w ith a brief ov er view of the "File | Dump" menu option. Once you configure your dump options, you are asked to specify a location for C# language and then quickly m oves to key technical and the *.IL file. Assuming you have dumped the developer contents s. of mscorlib.dll to file you can view its contents using ar chitectur al issues for .NET notepad. For example, Figure 1-8 shows the CIL for a method you will come to know (and love) in Chapter 11, GetType(). Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure Dumping file blies Chapter 9 - 1-8: Under standing CIL .NETtoAssem Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Ildasm.exe has additional options that can be discovered from the supplied online Help. Although I assume you will investigate these options on your own, as I mentioned earlier, one item of interest is the Chapter 12keystroke. - Obj ect Ser and.NET-aware the .NET Remoting Lay er "Ctrl+M" Asialization you recall, compilers emit CIL and metadata that is used by the CLR Chapter 13 Building a Bet ter Win dow ( Int roducin g Window For ildasm.exe, ms) to interact with a given type. Once you load an assemblysinto press Ctrl+M to view the Chapter 14 -type A Better Paint ing amewaorpreview k ( GDI +of ) things to come, Figure 1-9 shows the metadata for the generated metadata. ToFroffer Chapter 15 - Prassembly ogr am ming with s Contr TestApp.exe you willWindows create inForm Chapter 2.ols Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 1-9: Viewing type metadata via ildasm.exe

Viewing Assembly Metadata Finally, if you are interested in viewing the contents of the assembly's manifest (and I know you are), simply double click the MANIFEST icon (Figure 1-10).

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Figure 1-10: Double click here to view the assembly manifest. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

If you have not realized it by now, ildasm.exe is in many ways the .NET equivalent of the OLE/COM Object - Building C# Applications Viewer utility. Oleview.exe is the tool of choice to learn about classic COM servers and examine the Pa r t Tw o - The C# Pr ogr am m ing La ngua ge underlying IDL and registry settings behind a given binary. Ildasm.exe is the tool of choice to examine .NET Chapter 3 - C# Language Fundamentals assemblies, the underlying CIL and related metadata. Chapter 2

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

The Class Viewer Web Application - I nter faces and Collections

Chapter 6 Chapter 7

I nter faces, Delegates, and Ev ents In addition-toCallback ildasm.exe, the Class Viewer Web application (shipped with the .NET SDK sample Chapter 8 - Advanced C# Type ructionthe Techniques applications) is yet another wayConst to explore .NET namespaces. Once you have configured the samples Pa r t Thre e with - Pr ogr m i ngSDK w i th(via .N ET Assem provided theam .NET the Startbl| ie Alls Programs | Microsoft .NET Framework SDK v1.1 | Samples Chapter 9 - Under standingmenu .NET item), Assem blies and QuickStart Tutorials launch your browser of choice and navigate to Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads http://localhost/quickstart/aspplus/samples/classbrowser/vb/classbrowser.aspx Chapter 11that - Type Reflection, LateofBinding, andapplication Attr ibute- Based Pr ogramm ing (do note the exact location this Web may change in future releases of the .NET SDK). Pa r t Four - Le veyou r a ging the .NET the Librrelationship a r ie s This enables to examine of various types in a more Web-savvy manner (Figure 1-11). Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 1-11: Viewing types using the ClassViewer Web application

The wincv.exe Desktop Application The final tool to be aware of is wincv.exe (Windows Class Viewer). Again, by default this tool is installed in the same directory as ildasm.exe (most likely in :\Program Files\ Microsoft Visual Studio .NET 2003\SDK\V1.1\Bin directory). This Windows-based application allows you to browse the underlying C# type definition in the base class libraries. The use of this tool is quite simple: Type in the name of the item

you wish to explore, and the underlying C# source code definitions are displayed on the right side. Figure C# an d th e .N ET Plat f orm , Se con d Ed it ion 1-12 shows the member set for the System.Windows.Forms.ToolTip class. by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections Figure Working with wincv.exe Chapter 7 - 1-12: Callback I nter faces, Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Cool! Now that you have a number of strategies that you can use to explore the entirety of the .NET universe, you are just about ready to examine how to build some C# applications. But first, let me Chapter 9 - Under standing .NET Assem blies comment on one final "minor" (read: "not-so-minor") detail. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an.NET d th e .NRuntime ET Plat f orm , Se con d Ed it ion Deploying the ISBN:1590590554

by Andr ew Tr oelsen

As you have mostApr likely ess ©surmised, 2003 (1200 .NET pages) assemblies can only be loaded and executed on a machine that has been configured to host the .NET runtime. As individual whoofbuilds This compr ehensiv e text star ts w ithan a brief ov er view the .NET software, this should never be an issue, as your development machine will be properly configured at the time you install the C# language and then quickly m oves to key technical and ar chitectur issues However, for .NET developer .NET SDK (or Visual Studioal.NET). assume s.you have just created a fantastic .NET application and wish to copy it to a brand new machine. Of course, this *.exe will fail to run if the target computer does not have .NET installed. Ta ble o f Con t en t s

Rather than opting form,overkill and installing the full .NET SDK on each and every machine that may run C# and t he .NET Plat for Second Edition your application, Microsoft has created a specific redistribution package named Dotnetfx.exe that can be I ntr oduction freely andng installed withP your Pa r t Oneshipped - I nt r oduci C# a nd along the .NET la tf orcustom m

software. This installation program is included with the

.NET SDK .NET), however, Chapter 1 - (or TheVS Philosophy of .NET it is also freely downloadable (simply do a search on http://www.microsoft.com). Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Dotnetfx.exe will correctly configure a "virgin machine" to execute .NET assemblies, as long as said - C# Language Fundamentals machine is one of the following flavors of Microsoft Windows (of course, future versions of the Windows Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# OS will have native .NET support): Chapter 3 Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter Microsoft 6 - I nter Windows faces and 98Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Microsoft Windows NT 4.0 (SP 6a or greater) Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Microsoft Windows Millennium Edition (aka Windows Me)

Chapter 9

- Under standing .NET Assem blies

Chapter Microsoft 10 - Pr ocesses, WindowsAppDomains, 2000 (SP2 or Cont greater) exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Microsoft Home Pa r t Four - Le veWindows r a ging theXP .NET Libr a/ rProfessional ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Once installed, the target machine will now host the necessary base class libraries, mscoree.dll, and

Chapter 13 -.NET Building a Bet ter Win dow as ( Intthe roducin g Window s ForCache). ms) additional infrastructure (such Global Assembly Do understand however, that if you Chapter 14 - Aa Better Paint ing Fr amew k ( GDI +) are building Web application usingor.NET technologies, the end user's machine does not need to be Chapter 15 - with Pr ogr am.NET ming redistribution with Windows kit Form Contr ols configured the (ass the browser will simply display generic HTML). Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Running .NET on Non-Microsoft Operating Systems

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Webplaces Pages and Web Contr ols As mentioned at various in this chapter, the .NET platform is already being ported to other Chapter 19 systems. - ASP.NETThe Webkey Applicat ions operating that makes this possible is yet another .NET specification termed the Chapter 20 Language - XML Web Infrastructure Ser vices Common (CLI, which previously went under the code name "rotor"). Simply put, I ndex the CLI is the ECMA standard that describes the core libraries of the .NET universe. Microsoft has List released of Figuran es open-source implementation of the CLI (The Shared Source CLI) which can be compiled on

Windows XP, FreeBSD Unix as well as the Macintosh (OS X and higher). List of Tables Note For more information regarding the Shared Source CLI, do a search for "Shared Source Common Language Infrastructure" on http://www.microsoft.com. Although the role of this book is to confine the creation, deployment and execution of .NET applications to the Windows family of operating systems, Table 1-6 provides a few helpful links you may find interesting (understand the exact URL may change in the future). Table 1-6: Select Links to the Platform-Agnostic Nature of .NET

.NET-Centric C# Web an d Link th e .N ET Plat f orm , Se con dMeaning Ed it ion in Life by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

http://msdn.microsoft.com/net/ecma

ISBN:1590590554

Details the standardization of C# and the .NET platform

This compr ehensiv e text star ts w ith a brief ov er view of the

C# language and then quickly m ovesHomepage to key technical andMono project, which is a http://www.go-mono.com for the ar chitectur al issues for .NET developer s. porting of C# and .NET to various flavors of Linux Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Summary

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

The point of this chapter laypages) out the conceptual framework necessary for the remainder of this Apr ess ©was 2003 to (1200 book. We began This by examining a number of limitations andov complexities compr ehensiv e text star ts w ith a brief er view of thefound within the technologies prior to .NET, and followed up with an overview of how .NET and C# attempt C# language and then quickly m oves to key technical and to simplify the current state of ar chitectur al issues for .NET developer s. affairs. .NET basically boils down to a runtime execution engine (mscoree.dll) and base class library (mscorlib.dll Taand ble o associates). f Con t en t s The common language runtime (CLR) is able to host any .NET binary (aka "assembly")

that abides by the managed code. As you have seen, assemblies contain CIL instructions (in C# and t he .NET Platrules for m, of Second Edition addition to type metadata and the assembly manifest) that are compiled to platform-specific instructions I ntr oduction using a just-in-time (JIT) In addition, Pa r t One - I nt r oduci ng C# acompiler. nd the .NET P la tf or m

you explored the role of the Common Language

Specification (CLS) and Common Chapter 1 - The Philosophy of .NET Type System (CTS) and examined a number of tools that allow you to check out types within a given .NET namespace. We wrapped up with a brief examination of the Chapter 2 -the Building C# Applications process configuring a given Pa r t Tw o -of The C# Pr ogr am m ing machine La ngua geto host

the .NET runtime. With this necessary preamble complete, you can now begin to build .NET assemblies using C#. Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

d th e .N ET Plat f orm , Se con d Ed it ion Chapter C# 2:anBuilding C# Applications ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) C# is one of many possible languages which may be hosted by Visual Studio .NET (VS .NET). Unlike This compr ehensiv text star ts Development w ith a brief ov er view of the previous editions of Microsoft IDEs e(Integrated Environments), the professional and C# language and then quickly m oves to key technical and enterprise versions of VS .NET may be used to build C#, J#, VB .NET and MC++ project types (including ar chitectur al issues for .NET developer s. unmanaged frameworks such as MFC and ATL 4.0). Furthermore, if you download or purchase additional .NET-aware languages (such as COBOL .NET, Eiffel .NET and so forth), the chances are quite good that 'snap-in' Tathey ble owill f Con t en t s to the existing VS .NET IDE out of the box. C# and t he .NET Plat for m, Second Edition

This chapter offers a grand tour of the key features of the VS .NET IDE within the context of C#. Along the

I ntr oduction way, you will examine some common configuration options, preview various design time tools, examine the Pa r t One - I nt r oduci ng C# documentation, a nd the .NET P la tf or mexamine use of XML-based code and

various "preprocessor" directives. We wrap up by

Chapter 1 -aThe Philosophy .NET examining small subset ofoffreeware .NET-related tools. To open this discussion however, we begin with Chapter 2 Building C# Applications an examination of the raw C# compiler itself—csc.exe. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals The Role of the Command Line Compiler (csc.exe) - Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 4

Chapter 5 -a Exceptions Obj ect Lifetim e There are number ofand techniques you may use to compile C# source code. In addition to VS .NET proper Chapter 6 I nter faces and Collections (as well as various third party .NET IDEs), you are also able to compile your .NET assemblies using the Chapter 7 - Callback I nter faces, (as Delegates, entsgather, "csc" is short for C Sharp Compiler). This tool stand-alone compiler, csc.exe I'm sureand youEvcan is included in the freely downloadable Microsoft .NET Chapter 8 - Advanced C# Type Const ruction Techniques SDK (http://msdn.microsoft.com/net). Pa Now, r t Thre while e - Pr it ogr is true am m that i ng you w i thmay .N ETnever Assem decide bl ie s

to build an entire application using the raw C# compiler, it is

important understand the basics of blies how to compile your *.cs files by hand. I can think of two reasons you Chapter 9 to - Under standing .NET Assem should 10 get- aPrgrip on theAppDomains, process: Cont exts, and Threads Chapter ocesses, Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

The most obvious reason is the simple fact that you might not have a full copy of Visual Studio .NET (but do have the free .NET SDK). If this is the case, you will need to make use of csc.exe as you move Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er throughout this text. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Chapter 14 - Areason Better Paint Fr amew or k ( GDI + )Design time editors, code Wizards, and configuration Another is thisingvery important fact: Chapter 15 - Pr am more ming with s Contr dialogs doogr little thanWindows save youForm typing time.ols The more you understand what happens "under the Chapter hood" 16 -the Thestronger Sy stem .Iyour O Nam programming espace muscle becomes. As you use VS .NET to build applications,

you17are ultimately the raw C# compiler how to manipulate your *.cs input files. In this light, Chapter - Data Accessinstructing w ith ADO.NET to see takes place the Pa r t Fiit's ve edifying - W e b Appl ica tiwhat ons and X ML W e b behind Se r vi ces

scenes.

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Another nice by-product of working with csc.exe in the raw, is that you become that much more comfortable manipulating other command line tools included with the .NET SDK. As you will see Chapter 20 - XML Web Ser vices throughout this book, a number of important utilities are only accessible from the command prompt. Chapter 19 - ASP.NET Web Applicat ions I ndex

List of Figur es

Configuring the C# Compiler

List of Tables

Before you can begin to make use of the C# command line compiler, you need to ensure that your development machine recognizes the existence of csc.exe. Ideally, csc.exe is configured correctly at the time you install the .NET SDK. However, in my experiences teaching various .NET classes, I have found out the hard way (typically during the first code demo) this is not always the case. If csc.exe is not configured correctly, you are forced to change to the directory containing csc.exe before you can compile your programs (which is a massive pain in the neck, given that you must type in the full path name to the *.cs files to be compiled). To equip your development machine to compile *.cs files from any subdirectory, follow these steps (which assume a Windows XP installation; WinNT/Win2000 steps will slightly differ): Right-click the My Computer icon and select Properties from the pop-up menu. Select the Advanced tab and click the Environment Variables button. Double click the Path variable from the System Variables list box.

Add the following C# anline d thtoe the .N ET end Plat offthe ormcurrent , Se convalue d Ed it(note ion each value in the Path variable is separated by a semicolon, as shown in Figure 2-1): ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the :\%windir%\Microsoft.NET\Framework\v1.1.4322 C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 5

- Exceptions and Obj ect Lifetim e

2-1: theming pathwto Chapter 4 Figure - Obj ect -OrEstablishing iented Pr ogr am ithcsc.exe C# Chapter 6 - the I nter facespath and name Collections Of course, exact may need to be adjusted based on your current version and location of Chapter 7 Callback I nter faces, and Ev ents the .NET SDK (so be sure to doDelegates, a sanity check). Once you have added the correct Path setting, you may Chapter take a test 8 - run Advanced by closing C# Type any command Const ruction windows Techniques open in the background (to commit the settings), then Pa open r t Thre a new e - Prcommand ogr am m i ng window w i th .Nand ET Assem enter:bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads csc -? Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

If you set upSer correctly, seeRemoting a displayLay of er each option supported by the raw C# compiler. Chapter 12 things - Obj ect ializationyou andshould the .NET Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Configuring Additional .NET Command Line Tools

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Now, before we Sy begin investigate manipulating csc.exe, add the following additional Path variable to the Chapter 16 - The stemto .I O Nam espace System17Variables list boxw ith (again, performing a sanity check to ensure path settings): Chapter - Data Access ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

:\Program Files\Microsoft Studio .NET\FrameworkSDK\Bin Chapter 18 - ASP.NET Web Pages and Web ContrVisual ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

As you will see later in this text, this path contains additional command line tools (such as sn.exe, al.exe, wsdl.exe and so forth) that are commonly used during .NET development. With these two path settings List of Figur es established, you should now be able to run any .NET utility directly from the command line. If you wish to List of Tables confirm this new setting, close any open command window, open a new command window and enter the following command to view the flags for the assembly linker utility, al.exe: I ndex

al -?

Note Now that you have seen how to manually configure your .NET command line tools, I'll let you in on a shortcut. If you own a copy of VS .NET 2003, navigate to the Microsoft Visual Studio .NET 2003 | Visual Studio .NET Tools menu using the Window's Start button. There you will find a preconfigured command prompt (Visual Studio 2003 Command Prompt) that can be used to run .NET command line tools without the need to manually set your Path settings.

C# an d th e .N ET Plat f orm , Se con d Ed it ion Building a C# Application Using csc.exe ISBN:1590590554

by Andr ew Tr oelsen

Now that your development machine recognizes csc.exe, the next goal of this chapter is to build a simple Apr ess © 2003 (1200 pages) single file assembly named TestApp.exe using the C#ov compiler. This compr ehensiv e text star ts w ith raw a brief er view ofFirst, the you need some source code. Open a text editorC#(notepad.exe is fine), and enter the following: language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

// The first C# app of the book... using System; Ta ble o f Con t en t s class TestApp C# and t he .NET Plat for m, Second Edition { I ntr oduction public static void Main() Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m { Chapter 1 - The Philosophy of .NET Console.WriteLine("Testing! 1, 2, 3"); Chapter}2 - Building C# Applications Pa }r t Tw o - The C# Pr ogr am m ing La ngua ge Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# Once you finished, save file (in ea convenient location) as TestApp.cs. Now, let's get to know the Chapter 5 -have Exceptions and Obj the ect Lifetim

core options of the C#and compiler. The first point of interest is to understand how to specify the name and Chapter 6 - I nter faces Collections type of 7output file youI nter arefaces, interested in obtaining (e.g., a console application named MyShell.exe, a code Chapter - Callback Delegates, and Ev ents

library named HelperTypes.dll, a Windows application named MyRadWnd.exe, and so forth). Each Chapter 8 - Advanced C# Type Const ruction Forms Techniques possibility byi tha .N specific flagblpassed Pa r t Thre e -isPrrepresented ogr am m i ng w ET Assem ie s Chapter 9

into csc.exe as a command line parameter (Table 2-1).

- Under standing .NET Assem blies

Table 2-1: Output Options of the C# Compiler

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing File11Output Meaning in Life Pa rOption t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

/out 13 - Building a Used specify theroducin namegofWindow the output file (e.g., MyAssembly.dll, Chapter Bet ter to Win dow ( Int s For ms)

WordProcessingApp.exe, etc.) to be created. By default, the name of the output file is the same as the name of the input *.cs file containing the Chapter 15 - Pr ogr am ming with Windows Form s Contr ols program's specified entry point (the static Main() method). Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 16 - The Sy stem .I O Nam espace

Chapter /target:exe 17 - Data Access This w ith option ADO.NET builds an *.exe console application. This is the default file output Pa r t Fi ve - W e b Appl ica titype, ons and andXthus ML Wmay e b Se ber viomitted ces

when building this application type.

Chapter 18 - ASP.NET Web Pages and Web Contr ols

/target:library

This option builds a single file *.dll assembly.

Chapter 19 - ASP.NET Web Applicat ions

/target:module This option builds a "module." Modules are elements of multifile assemblies Chapter 20 - XML Web Ser vices I ndex

(as seen later in Chapter 9).

List of Figur es

Although you are free to build Windows-based applications using the /target:exe flag, the /target:winexe flag prevents an annoying console window from appearing in the background.

/target:winexe

List of Tables

Given these options, to compile TestApp.cs into a console application named TextApp.exe, you would use the following command set (note that the /target flag must come before the name of the C# file, not after): csc /target:exe TestApp.cs

Also be aware that most of the C# compiler flags support an abbreviated version, such as "/t" rather than "/target" (you can view all abbreviations by entering csc -? at the command prompt): csc /t:exe TestApp.cs

Furthermore, given that the /t:exe flag is the default output used by the C# compiler, you could also

compile TestApp.cs simply by saying:

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

csc TestApp.cs

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and To try things for yourself, open a command window and change to the directory containing your ar chitectur al issues for .NET developer s.

TestApp.cs file. Then, enter the previous command and hit return. This builds TestApp.exe, which can now be run from the command line (see Figure 2-2). Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Figure 2-2: The TestApp in action

Chapter 6 thing - I nter faces and strike Collections The first that should you is the fact that you have just created a console application using C#! Chapter 7 Callback I nter faces, Delegates, and Ev ents The reason I point this out is due to a common misconception (especially among management) that .NET Chapter 8 - Advanced C# development Type Const ruction Techniques is only useful during the of Internet applications. Nothing could be further from the truth. As Pa r t Thre - Prover ogr am i ng w i thof.Nthis ET Assem bl ie sprovides you will esee themcourse text, .NET

support for developing any type of application you

Chapter 9 - Under standing .NET Assem blies might envision (Web-based or otherwise). Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

While console applications less sexy a Windows-based or ing HTML-based front end, they can Chapter 11 - Type Reflection, are Latefar Binding, and than Attr ibuteBased Pr ogramm prove useful when you need build Pa r t Four - Le ve r a ging the .NETto Libr a r ieas program

that requires a minimal graphical user interface.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Note Given their simplicity, the initial chapters of this text make use of simple command window applications to ensure that you are able to focus on the syntax of C# rather than focusing on the Chapter 14 complexities - A Better Paint Fr amew or k using ( GDI +Windows ) of ing building GUIs Forms or ASP.NET technologies. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Referencing External Assemblies

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Next up, let's examine how to build an application that makes use of types defined in a separate .NET

Chapter 18 -Speaking ASP.NET Web Pagesjust andinWeb assembly. of which, caseContr you ols are wondering how the C# compiler understood your Chapter 19 -toASP.NET Web Applicat ions reference the System.Console type, realize that mscorlib.dll is automatically referenced during the Chapter 20 - XML Web (if Ser vices compilation process for some strange reason you wish to disable this behavior, you may specify the I ndex /nostdlib flag). List of Figur es

To ofillustrate List Tables the process of referencing external assemblies, let's update the TestApp application to display a Windows Forms message box. Thus, open your TestApp.cs file and modify it as follows: using System; // Add this! using System.Windows.Forms; class TestApp { public static void Main() { Console.WriteLine("Testing! 1, 2, 3"); // Add this! MessageBox.Show("Hello..."); } }

Notice the reference to the System.Windows.Forms namespace (via the C# "using" directive introduced in C# an d th e .N ET Plat f orm , Se con d Ed it ion Chapter 1). Recall that when you explicitly list the namespaces used within a given *.cs file, you avoid the ISBN:1590590554 by Andr ew Tr oelsen need to make use of fully qualified names (which can lead to hand cramps). Apr ess © 2003 (1200 pages)

This ehensiv e text you star ts w ithalso a brief ov ercsc.exe view of the In addition to using thecompr "using" keyword, must inform which assembly contains the C# language m oves to of key technical and referenced namespace. Givenand thatthen we quickly have made use the System.Windows.FormsMessageBox class, ar chitectur al issues for .NET developer s. you must specify the System.Windows.Forms.dll assembly using the /reference flag (which can be abbreviated to /r): Ta ble o f Con t en t s

csc testapp.cs C# and/r:System.Windows.Forms.dll t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

If you now rerun your application, you should see what appears in Figure 2-3.

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure- 2-3: Your first Windows Forms application Under standing .NET Assem blies

Chapter 9

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Compiling Multiple Source Files

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

The current incarnation of the TestApp.exe application was created using a single *.cs source code file (as well as a single external assembly). While it is perfectly permissible to have all of your .NET types defined Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) in a single *.cs file, most projects are composed of multiple *.cs files to keep your code base a bit more Chapter Pr ogr am ming with you Windows s Contr flexible.15To- illustrate, assume have Form authored anols additional class contained in a new file named Chapter 16 The Sy stem .I O Nam espace HelloMsg.cs. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

// The HelloMessage Class using System; Chapter - ASP.NET Web Applicat ions using19System.Windows.Forms; Chapter 20 - XML Web Ser vices class HelloMessage I ndex { List of Figur es public void Speak() List of Tables { MessageBox.Show("Hello..."); } } Chapter 18 - ASP.NET Web Pages and Web Contr ols

Now, update your initial TestApp class to make use of this new type, and comment out the previous Windows Forms logic: using System; // Don't need this anymore. // using System.Windows.Forms; class TestApp { public static void Main() { Console.WriteLine("Testing! 1, 2, 3"); // Don't need this anymore either.

// MessageBox.Show("Hello..."); C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew the Tr oelsen // Exercise HelloMessage class! ISBN:1590590554 Apr ess © 2003 (1200 pages) HelloMessage(); HelloMessage h = new This compr ehensiv e text star ts w ith a brief ov er view of the h.Speak(); C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

} } Ta ble o f Con t en t s

You can compile this multifile application by listing each *.cs file explicitly:

C# and t he .NET Plat for m, Second Edition I ntr oduction

csc /r:System.Windows.Forms.dll testapp.cs hellomsg.cs

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t an Tw o - The C# Prthe ogrC# am compiler m ing La ngua ge As alternative, allows

you to make use of the wildcard character (*) to inform csc.exe

Chapter 3 -allC# Language Fundamentals to include *.cs files contained in the project directory as part of the current build. When you use this Chapter Obj ect -Or iented ogrspecify am mingthe w ith C# of the output file (/out) as well, to directly control the option, 4you- will typically wantPrto name Chapter 5 the - Exceptions and Obj ect Lifetim e name of resulting assembly: Chapter 6 - I nter faces and Collections Chapter 7 - Callback I nter faces, Delegates, and Ev ents csc /r:System.Windows.Forms.dll /out:TestApp.exe *.cs Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

When you thestanding program.NET again, theblies output is identical. The only difference between the two applications Chapter 9 -run Under Assem is the fact the current logic has been split and among multiple files. Chapter 10 -that Pr ocesses, AppDomains, Cont exts, Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Referencing Multiple External Assemblies

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Now, what you need to ter reference assemblies? Simply list each assembly using a Chapter 13 - ifBuilding a Bet Win downumerous ( Int roducinexternal g Window s For ms) semicolon-delimited list (annoyingly, the compiler [vbc.exe] uses a comma delimited list, so be Chapter 14 - A Better Paint ing Fr amew or k ( VB GDI .NET +) mindful15when using multiple compilers). You don't Chapter - Pr ogr am ming with.NET Windows Form s Contr ols need to specify multiple external assemblies for the current but some sample usage follows: Chapter 16 - example, The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

csc /r:System.Windows.Forms.dll;System.Drawing.dll Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

/out:TestApp.exe *.cs

C# an d th e .N ET Response Plat f orm , Se conFiles d Ed it ion Working with Csc.exe ISBN:1590590554

by Andr ew Tr oelsen

As you might guess, if you were to pages) build a complex C# application at the command prompt, your life would Apr ess © 2003 (1200 be full of pain as This you type in the flags thatstar specify compr ehensiv e text ts w ithnumerous a brief ov referenced er view of theassemblies and *.cs input files. To help lessen your C# typing burden, the C# compiler honors the use of "response files." language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

C# response files contain all the instructions to be used during the compilation of your current build. By convention, these files end in a *.rsp (response) extension and can be used as an alternative to pounding Taout ble lines o f Con and t enlines t s of flags manually at the command prompt. To illustrate, assume that you have created a response file Plat named that contains the following arguments (as you can see, comments are C# and t he .NET for m,TestApp.rsp Second Edition denoted with the "#" character): I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 is - The Philosophy of .NET # This the response file Chapter # for2 the - Building TestApp.exe C# Applications app Pa #r t of Tw oChapter - The C# Pr 2. ogr am m ing La ngua ge

# External references. Chapter 3 - C# assembly Language Fundamentals /r:System.Windows.Forms.dll Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# # output and files compile Chapter 5 - Exceptions and to Obj ect Lifetim e (using wildcard syntax). /target:exe /out:TestApp.exe *.cs Chapter 6 - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Now, assuming this file is saved in the same directory as the C# source code files to be compiled, you are able to build your entire application as follows (note the use of the @ symbol):

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

[email protected]

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 -output Building Betcompiler ter Win dow ( Int roducin g Window s For ms) Again, the of athe is identical. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

If the need arise, also able tos specify Chapter 15 - should Pr ogr am ming you withare Windows Form Contr olsmultiple *.rsp files as input (for example: csc @FirstFile.rsp @ThirdFile.rsp). If you take this approach, do be aware that the compiler Chapter 16 - [email protected] Sy stem .I O Nam espace

processes command as they are encountered! Therefore, command line arguments in a later Chapter 17 - the Data Access w options ith ADO.NET *.rsp file- can options previous Pa r t Fi ve W e boverride Appl ica ti ons andinXaML W e b Se rresponse vi ces

file.

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Also note that any flags listed explicitly on the command line will be overridden by the options in a given

Chapter 19 file. - ASP.NET response Thus, ifWeb youApplicat were toions enter: Chapter 20 - XML Web Ser vices I ndex

csc/out:Foo.exe @TestApp.rsp

List of Figur es List of Tables

the name of the assembly would still be TestApp.exe (rather than Foo.exe), given the /out:TestApp.exe flag listed in the TestApp.rsp response file.

The Default Response File (csc.rsp) The final point to be made regarding response files is that the C# compiler has an associated default response file (csc.rsp), which is located in the same directory as csc.exe itself. If you were to open this file using Notepad, you will find that numerous .NET assemblies have already been specified using the /r: flag (Figure 2-4).

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter Figure 6 - 2-4: I nterBehold, faces andthe Collections default response file Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

When you are building your C# programs using csc.exe, this file will be automatically referenced, even when you supply a custom *.rsp file (be aware that Visual Studio .NET does not make use of response Chapter 9 - Under standing .NET Assem blies files whatsoever, custom or csc.rsp). Given the presence of the default response file, it should be clear Chapter - Pr ocesses, AppDomains, Cont exts, and Threadsa reference to the that the10current TestApp.exe application (which contains Chapter 11 Type Reflection, Late Binding, and Attr ibutePr ogramm ing System.Windows.Forms.MessageBox class) could be Based successfully compiled using the following command Pa r t Four Le ve r a ging the .NET Libr a r ie s line (note that I did not specify /r:System.Windows.Forms.dll as this reference will be added via csc.rsp): Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

csc /out:TestApp.exe *.cs

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter Finally,16 in the - The event Sy stem that.Iyou O Nam wish espace to disable the automatic reading of csc.rsp, you can specify the /noconfig

flag: 17 - Data Access w ith ADO.NET Chapter Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols csc @TestApp.rsp /noconfig Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion GeneratingC#Bug Reports by Andr ew Tr oelsen

ISBN:1590590554

The raw C# compiler provides a helpful Apr ess © 2003 (1200 pages) flag named /bugreport. As you can gather by its name, this flag allows you to specify a file that will betext populated (byacsc.exe) This compr ehensiv e star ts w ith brief ov erwith viewvarious of the statistics regarding your current build; including any errors encountered during the compilation process. C# language and then quickly m oves to key technical andIts use is self-explanatory: ar chitectur al issues for .NET developer s.

csc/bugreport:bugs.txt *.cs Ta ble o f Con t en t s C# and tyou he .NET Plat/bugreport, for m, Second Edition When specify you will be prompted to enter corrective information for the possible error(s) I ntr oduction at hand, which will be saved (along with other details) into the file you specify. To illustrate, let's inject a Pa r t One I nt rTestApp oduci ng C# a nd the .NET P la tf or m bug into- the class:

Chapter 1

- The Philosophy of .NET

Chapter 2 static - Buildingvoid C# Applications public Main() Pa {r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 ...

- C# Language Fundamentals

Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# HelloMessage h = new HelloMessage(); Chapter - Exceptions and semicolon Obj ect Lifetim e //5 Note lack of below! Chapter 6 - I nter faces h.Speak() //and

Chapter/// 9 - Assigning f2 to f1\n"); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er FOO f2 = f1; Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) // Here is F1. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Console.WriteLine("F1.x = {0}", f1.x); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Console.WriteLine("F1.y = {0}", f1.y); Chapter 16 - The stem .I O espace //SyHere isNam F2. Chapter 17 - Data Access w ith ADO.NET Console.WriteLine("F2.x = {0}", f2.x); Pa r t Fi ve - W e b Console.WriteLine("F2.y Appl ica ti ons and X ML W e b Se r vi ces = {0}", f2.y); Chapter 18 - ASP.NET Web Pages and This Web Contr ols NOT change f1.x. // Change f2.x. will Chapter 19 - ASP.NET Web Applicat ions Console.WriteLine("-> Changing f2.x to 900"); Chapter 20 - XML Web =Ser900; vices f2.x I ndex // Print again. List of Figur es Console.WriteLine("-> Here are the X's again..."); List of Tables Console.WriteLine("F2.x = {0}", f2.x); Console.WriteLine("F1.x = {0}\n", f1.x); return 0; } }

Here you have created a structure of type FOO (named f1) that is then assigned to another FOO structure (f2). Because FOO is a value type, you have two copies of the FOO type on the stack, each of which can be independently manipulated. Therefore, when you change the value of f2.x, the value of f1.x is unaffected (just like the behavior seen in the previous integer example). In stark contrast, reference types (classes) are allocated on the garbage-collected heap. These entities stay in memory until the .NET garbage collector destroys them. By default, assignment of reference types results in a new reference to the same object in memory. To illustrate, let's change the definition of the FOO type from a C# structure to a C# class:

C# an d th e .N ET Plat f orm , Se con d Ed it ion // Classes are always reference types. ISBN:1590590554 ew a Tr oelsen class FOO // by I ndex Console.WriteLine("-> List of Figur es Console.WriteLine("-> List of Tables Console.WriteLine("->

Chapter 19 - ASP.NET Web Applicat ions

Values after change:"); valWithRef.refType.x is {0}", valWithRef.refType.x); valWithRef2.refType.x is {0}", valWithRef2.refType.x); valWithRef.structData is {0}", valWithRef.structData); valWithRef2.structData is {0}", valWithRef2.structData);

As you can see, the state of the internal reference type (refType) was not fully copied into the new InnerRef variable. By default, when a value type contains other reference types, assignment results in a copy of the references. In this way, you have two independent structures, each of which contains a reference pointing to the same object in memory (i.e., a "shallow copy"). When you want to perform a "deep copy," where the state of internal references is fully copied into a new object, you need to implement the ICloneable interface (as you do in Chapter 6).

Value and Reference Types: Final Details To wrap up our examination of value types and reference types, ponder the information in Table 3-2 that illustrates how each stands up against a number of intriguing questions (many of which are examined in greater detail throughout this text).

Table 3-2: Value Types and Reference Types Side by Side C# an d th e .N ET Plat f orm , Se con d Ed it ion

Intriguing by Andr ew Tr Value oelsen Type Question Apr ess © 2003 (1200 pages)

Reference ISBN:1590590554

Type

This compr ehensiv e text star ts w ith a brief ov er view of the

Where is this type Allocated on the stack. Allocated on the managed heap. C# language and then quickly m oves to key technical and allocated? ar chitectur al issues for .NET developer s. How is a variable represented?

Ta ble o f Con t en t s

Value type variables are local copies.

C# and t he .NET Plat for m, Second Edition

is the base type? I ntrWhat oduction

Must directly derive from

Can derive from any other type (except System.ValueType) as long as that type is not "sealed"... more later.

Pa r t One - I nt r oduci ng C# a ndSystem.ValueType. the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Can this type function

No. Value types are always

Chapter 3 - to C#other Language Fundamentals as a base sealed and cannot be extended. Chapter 4 Obj ect -Or iented Pr ogr am ming w ith C# types? Chapter 5

- Exceptions and Obj ect Lifetim e Default Variables are passed by value Chapter 6 parameter - I nter faces and Collections

passing behavior? (i.e., a copy of the variable is Chapter 7 - Callback I nter faces, Delegates, and Ev ents passed into the called function). Chapter 8

- Advanced C# Type Const ruction Techniques

Pa rAble t Thre - Pr ogr am m i ng w i th .N ET Assem bl ie are s toe override No. Value types never

Reference type variables are pointing to the memory occupied by the allocated instance.

placed

Chapter 9 - Under standing .NET blies and therefore do Object.Finalize()? ontoAssem the heap Chapter 10 - Pr ocesses, AppDomains, not needCont to be exts, finalized. and Threads

Yes. If the type is not sealed, it may function as a base to other types. Variables are passed by reference (e.g., the address of the variable is passed into the called function). Yes...indirectly (more details in Chapter 4).

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Can I define Yes, but the default constructor is But, of course! constructors for this reserved (i.e., your custom Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er type? constructors must all have Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) arguments). Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

When15 do- variables of with When it falls out sofContr the defining Chapter Pr ogr am ming Windows Form ols this type scope. Chapter 16 -die? The Sy stem .I O Nam espace

When the managed heap is garbage collected.

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Despite their differences, value types and reference types both have the ability to implement interfaces, and may support any number of fields, methods, overloaded operators, constants, properties, and events.

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 - XML Web The Ser vices SOURCE ValAndRef project is located under the Chapter 3 subdirectory. I ndex CODE List of Figur es List of Tables

an d th eSystem.Object .N ET Plat f orm , Se con d Ed it ion The MasterC#Node: ISBN:1590590554

by Andr ew Tr oelsen

In C#, every dataApr type reference ess(value © 2003or (1200 pages) based) is ultimately derived from a common base class: System.Object. The Object class defines a common This compr ehensiv e text star ts w ith a polymorphic brief ov er viewbehavior of the for every type in the .NET universe. In the previous HelloClass type definition, you did not explicitly C# language and then quickly m oves to key technical and indicate that Object was the base ar chitecturifalyou issues for say .NETotherwise: developer s. class, but this is assumed do not // Implicitly deriving from System.Object. class HelloClass {...}

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntr oduction

Pa t One - I nt ng C# a ndSystem.Object the .NET P la tf oras m Ifryou wish tor oduci explicitly state

your base class, you are free to define your class definitions

Chapter 1 - The Philosophy .NET using either of the followingofnotations: Chapter 2

- Building C# Applications

Pa r t Tw o - The Pr ogr am m ing La ngua ge // Here weC#are explicitly deriving

from System.Object.

Chapter - C# Language class3 HelloClass : Fundamentals System.Object {...} Chapter 4 - story Obj ect -Or iented Pr ogr am ming w ith C# // Same here... Chapter - Exceptions and Obj ect Lifetim e class5 HelloClass : object {...} Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Like most classes, defines a set of instance-level and class-level (static) members. Chapter 8 -.NET Advanced C# System.Object Type Const ruction Techniques Note that some of these items are declared "virtual," and can therefore be overridden by a derived class: Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

// The class in the .NET world: System.Object Chapter 10 topmost - Pr ocesses, AppDomains, Cont exts, and Threads namespace System Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing {r t Four - Le ve r a ging the .NET Libr a r ie s Pa Object Chapter 12public - Obj ect class Ser ialization and the .NET Remoting Lay er Chapter { 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

public Object(); public virtual Boolean Equals(Object obj); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols public virtual Int32 GetHashCode(); Chapter 16 - The Sy stem .I O Nam espace public Type GetType(); Chapter 17 - Data Access w ith ADO.NET public virtual String ToString(); Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces protected virtual void Finalize(); Chapter 18 - ASP.NET Web Pages and Web Contr ols protected Object MemberwiseClone(); Chapter 19 - ASP.NET Web Applicat ions public static bool Equals(object objA, object objB); Chapter 20 - XML Web Ser vices public static bool ReferenceEquals(object objA, object objB); I ndex } List } of Figur es Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

List of Tables

Table 3-3 offers a rundown of the functionality provided by each instance-level method. Table 3-3: Core Members of System.Object

Instance Method C# an d th eMeaning .N ET Plat fin ormLife , Se con d Ed it ion of Object Class by Andr ew Tr oelsen

ISBN:1590590554

Apr ess © 2003 (1200 pages)

Equals()

By default this method returns true only if the items being compared

This compr ehensiv e text star ts w ith a brief ov er view of the refer to the exact same item in memory. Thus, Equals() is used to C# language and then quickly m oves to key technical and references, ar chitectur alcompare issues forobject .NET developer s. not the state of the object.

Typically, this method is overridden to return "true" only if the objects being compared have the same internal state values (that is, valueTa ble o f Con t en t s based semantics). Be aware that if you override Equals(), you should C# and t he .NET Plat for m, Second alsoEdition override GetHashCode(). I ntr oduction

Pa rGetHashCode() t One - I nt r oduci ng C# a ndReturns the .NETan P lainteger tf or m

that identifies a specific object instance. If you intend your custom types to be contained in a Chapter 1 - The Philosophy of .NET System.Collections.Hashtable type, you are well advised to override Chapter 2 - Building C# Applications the default implementation of this member. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - C# Language Fundamentals GetType() This method returns a System.Type object that fully describes details Chapter 4 - Obj ect -Or iented Pr ofogr theam type ming you w ith areC#currently referencing. In short, this is a Runtime Chapter 5

Type Identification (RTTI) method available to all objects (discussed in - Exceptions and Obj ect Lifetim e

Chapter 6

greater detail in Chapter 11). - I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents ToString() Returns a string representation of a given object, using the Chapter 8 - Advanced C# Type Const ruction Techniques " double.NegativeInfinity: {0}", double.NegativeInfinity); C# language and then quickly m oves to key technical and Console.WriteLine("-> double.MaxValue: {0}", double.MaxValue); ar chitectur al issues for .NET developer s. Console.WriteLine("-> double.MinValue: {0}",double.MinValue); Ta ble o f Con t en t s

Members of System.Boolean

C# and t he .NET Plat for m, Second Edition I ntr oduction

Pa r t One - I nt r oduci C# a nd the .NET P la tf or m Next, consider the ng System.Boolean data type.

Unlike C(++), the only valid assignment a C# bool can take is

Chapter 1 set - The Philosophy of .NET from the {true | false}. You cannot assign makeshift values (e.g., -1, 0, 1) to a C# bool, which (to most Chapter programmers) 2 - Building is a welcome C# Applications change. Given this point, it should be clear that System.Boolean does not support Pa arMinValue/MaxValue t Tw o - The C# Pr ogr am property m ing La set, ngua butgerather

Chapter 3

TrueString/FalseString:

- C# Language Fundamentals

Chapter - Obj ad-hoc ect -Or iented Pr ogr am ming w ithin C# C#! // No4 more Boolean types Chapter 5 =- Exceptions and // Obj ect Lifetim e bool b 0; Illegal! Chapter bool b2 6 - =I nter -1; faces and // Collections Also illegal!

bool b3 true;I nter faces, // No problem. Chapter 7 - =Callback Delegates, and Ev ents bool b4 false;C# Type // No problem. Chapter 8 - =Advanced Const ruction Techniques Console.WriteLine("-> bool.FalseString: Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

{0}", bool.FalseString); Console.WriteLine("-> bool.TrueString: {0}", bool.TrueString); Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Members of System.Char

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

It is important to notePaint thating C#Frtextual data is represented by the intrinsic C# string and char data types. Thus, Chapter 14 - A Better amew or k ( GDI +) no more char*, wchar_t*, LPSTR,Form LPCSTR, or OLECHAR string types! I am sure you agree with Chapter 15nasty - Pr ogr am ming with Windows s ContrBSTR ols me that16string manipulation in the COM and Win32 universe was horrifying. Utterly and completely horrifying. Chapter - The Sy stem .I O Nam espace

On a happy note, .NET offers a very simplified view of string management, as all .NET-aware languages map textual data to the same underlying types (System.String and System.Char), both of which are Unicode under Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces the hood. Chapter 17 - Data Access w ith ADO.NET

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Chapter 19 - ASP.NET Web Applicat ionsby the C# "char" keyword) provides you with a great deal of functionality The System.Char type (represented Chapter XML Web Ser vices beyond20 the- ability to hold a single point of character data (which must be placed between single tick marks). I ndex More interestingly, using the static methods of System.Char, you are able to determine if a given character is List of Figur esalphabetical, a point of punctuation, or whatnot. To illustrate, check out the following: numerical, List of Tables

// Test the truth or falsity of the following statements... Console.WriteLine("-> char.IsDigit('K'): {0}", char.IsDigit('K')); Console.WriteLine("-> char.IsDigit('9'): {0}", char.IsDigit('9')); Console.WriteLine("-> char.IsLetter('10', 1): {0}", char.IsLetter("10", 1)); Console.WriteLine("-> char.IsLetter('p'): {0}", char.IsLetter('p')); Console.WriteLine("-> char.IsWhiteSpace('Hello There', 5): {0}", char.IsWhiteSpace("Hello There", 5)); Console.WriteLine("-> char.IsWhiteSpace('Hello There', 6): {0}", char.IsWhiteSpace("Hello There", 6)); Console.WriteLine("-> char.IsLetterOrDigit('?'): {0}", char.IsLetterOrDigit('?')); Console.WriteLine("-> char.IsPunctuation('!'): {0}", char.IsPunctuation('!')); Console.WriteLine("-> char.IsPunctuation('>'): {0}", char.IsPunctuation('>'));

Console.WriteLine("-> char.IsPunctuation(','): {0}", C# an d th e .N ET Plat f orm , Se con d Ed it ion char.IsPunctuation(',')); by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

As you can see, each of these static members ofith System.Char has of twothe calling conventions: a single character This compr ehensiv e text star ts w a brief ov er view language and that thenspecified quickly mthe oves to key of technical and or a string with a C# numerical index position the character to test. ar chitectur al issues for .NET developer s.

Parsing Values from String Data Ta ble o f Con t en t s

Finally, also understand that the .NET data types provide the ability to generate a variable of their underlying type given a textual equivalent (e.g., parsing). This technique can be extremely helpful when you wish to I ntr oduction convert a bit of user input data (such as a listbox selection) into a numerical value. Ponder the following Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m parsing logic: C# and t he .NET Plat for m, Second Edition

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

bool bool.Parse("True"); Pa r t Tw omyBool - The C# = Pr ogr am m ing La ngua ge Console.WriteLine("-> Value of myBool: {0}", myBool); - C# Language Fundamentals double myDbl = double.Parse("99.884"); Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Console.WriteLine("-> Value of myDbl: {0}", myDbl); Chapter 5 - Exceptions and Obj ect Lifetim e int myInt = int.Parse("8"); Chapter 6 - I nter faces and Collections Console.WriteLine("-> Value of myInt: {0}", myInt); Chapter 7 - Callback I nter faces, Delegates, and Ev ents char myChar = char.Parse("w"); Chapter 8 - Advanced C# Type Value Const ruction Techniques{0}\n", myChar); Console.WriteLine("-> of myChar: Chapter 3

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

SOURCE The DataTypes project located underPrthe Chapter Chapter 11 - Type Reflection, Late Binding, and is Attr ibute- Based ogramm ing 3 subdirectory. CODE Pa r t Four - Le ve r a ging the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con dand Ed it ion ConvertingC#Between Value Types Reference Types: Boxing and ISBN:1590590554 by Andr ew Tr oelsen Unboxing Apr ess © 2003 (1200 pages) This compr text star ts of w ith a brief ov er view ofand thereference-based), you may Given that .NET defines twoehensiv broad ecategories types (value-based C# language and then quickly m oves to key technical and occasionally need to represent a variable of one category as a variable of the other category. C# provides a ar chitectur al issues for .NET developer s. very simple mechanism to convert between value types and reference types, termed boxing. To illustrate, assume that you have created a simple value data type of type short: Ta ble o f Con t en t s

//and Make a simple C# t he .NET Plat for m,value Second data Edition point. short s = 25; I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

If, during the course of your application, you wish to represent this value type as a reference type, you would - Building C# Applications "box" the value as follows:

Chapter 2

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

// Box the value into an object reference. - Obj ect -Or iented Pr ogr am ming w ith C# object objShort = s;

Chapter 4 Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter Callback I nter faces, Delegates, and Ev Boxing 7can- be formally defined as the process ofents explicitly converting a value type into a corresponding Chapter 8 -type. Advanced ruction Techniques reference WhenC# youType box Const a value, essentially all you are doing is allocating a new object on the heap and Pa r t Thre ethe - Printernal ogr am mvalue i ng w (in i th this .N ETcase Assem ie s copying 25)blinto

that instance. What is returned to you is a true-blue reference to

Chapter 9 allocated - Under standing Assem the newly object..NET Using this blies technique, .NET developers have no need to make use of a set of Chapter 10classes - Pr ocesses, exts, and Threads wrapper used AppDomains, to temporarilyCont treat intrinsic data as heap-allocated objects (as is the case in Java). Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

The opposite alsoLibr permitted Pa r t Four - Le veoperation r a ging theis.NET a r ie s through

unboxing. Unboxing is the term given to the process of converting the value held in the object reference back intoera corresponding value type on the stack. The Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay unboxing operation begins by verifying that the receiving data type is equivalent to the boxed type, and if so, Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) copying the value out of the box into a local stack based variable. For example, the following unboxing operation Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) works successfully, given that the underlying type of the objShort is indeed a "short": Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

// Now, unbox the reference back into a corresponding short. short anotherShort = (short)objShort; Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 17 - Data Access w ith ADO.NET

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20is -critical XML Web vices Again, it thatSer you unbox into an appropriate data type. Thus, the following unboxing logic generates an I ndex InvalidCastException exception (you examine casting and exception handling in detail in the next chapter, so List of tight Figurfor es now): hold List of Tables

// Bad unboxing! public static int Main(string[] args) { ... try { // The type contained in the box is NOT a string, but a short! string str = (string)objShort; } catch(InvalidCastException e) { Console.WriteLine("OOPS!\n{0} ", e.ToString()); } }

Some Practical C# (Un)boxing an d th e .N ET Plat Examples f orm , Se con d

Ed it ion

ISBN:1590590554 by Andr ew Tr oelsen So, you may be thinking, would you really need to manually box (or unbox) a data type? The previous Apr ess © when 2003 (1200 pages)

example was purely illustrative in nature, as there was no good reason to box (and then unbox) the short data This compr ehensiv e text star ts w ith a brief ov er view of the point. The truth ofC#thelanguage matter isand that youquickly will seldom to technical manuallyand box data types, if ever. Much of the time, then m ovesneed to key the C# compiler automatically ar chitectur al issues boxesfor variables .NET developer when appropriate. s. For example, if you pass a value type into a method requiring an object parameter, boxing occurs behind the curtains. However, Ta ble o f Con t en t s if you wish to invoke members of the underlying value type, you will be required to perform an explicit unboxing operation. illustrate, ponder the following: C# and t he .NET Plat for m, SecondTo Edition I ntr oduction Pa class r t One -Boxer I nt r oduci ng C# a nd the .NET P la tf or m

{ Chapter 1

- The Philosophy of .NET to illustrate automatic boxing. Chapter// 2 Helper - Buildingf(x) C# Applications

UseThisObject(object Pa r t Twpublic o - The C#static Pr ogr amvoid m ing La ngua ge

o) { Chapter 3 - C# Language Fundamentals Chapter 4 - Console.WriteLine(o.GetType()); Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Console.WriteLine(o.ToString()); Exceptions and Obj ect Lifetim e Console.WriteLine("Value of o is: {0}", o); Chapter 6 - I nter faces and Collections // Need to explicitly unbox to get at members of Chapter 7 - Callback I nter faces, Delegates, and Ev ents // System.Int32. (GetTypeCode() returns a value Chapter 8 - Advanced C# Type Const ruction Techniques // representing the underlying "type of intrinsic type". Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Console.WriteLine(((int)o).GetTypeCode()); Chapter 9 - Under standing .NET Assem blies } Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads static void Main(string[] args) Chapter{11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Leint ve r a ging .NET Libr a r ie s x = the 99; Chapter 12 - UseThisObject(x); Obj ect Ser ialization and the// .NET Remoting Lay er Automatic boxing. Chapter}13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Inr taddition automatic boxing when Pa Fi ve - Wto e bthe Appl ica ti ons and X MLperformed W e b Se r vi ces

calling custom functions, boxing implicitly occurs when interacting with numerous types of the .NET base class libraries. For example, the System.Collections Chapter 18 - ASP.NET Web Pages and Web Contr ols namespace (further examined in Chapter 6) defines a type named ArrayList. Like most collection types, Chapter 19 - ASP.NET Web Applicat ions ArrayList provides members that allow you to insert, index, and remove items. If you were to check the formal Chapter 20 - XML Web Ser vices class definition using wincv.exe, you would find prototypes such as: I ndex

List of Figur es

public class System.Collections.ArrayList : object, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable, ICloneable { ... public virtual int Add(object value); public virtual void Insert(int index, object value); public virtual void Remove(object obj); }

List of Tables

As you can see, these members take generic System.Object types as parameters. Given that everything ultimately derives from this common base class, the following code is perfectly legal:

ArrayList myInts = new ArrayList(); C# an d th e .N ET Plat f orm , Se con d Ed it ion myInts.Add(88); by Andr ew Tr oelsen myInts.Add(3); Apr ess © 2003 (1200 pages) myInts.Add(9764);

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer However, given your understanding of value types ands.reference types, you might wonder exactly what was

placed into the ArrayList type (references, copies of references, (copies of) structures, etc). Just like the previous Foo() method, it should be clear that each of the System.Int32 data types were indeed boxed before Ta ble o f Con t en t s being stored into the ArrayList type. As well, just like the Foo() helper method, if you wish to interact with the C# and t he .NET Plat for m, Second Edition members of the boxed type, you are required to unbox accordingly. Thus, assume the following static helper I ntr oduction method: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

public static void BoxAndUnboxInts() - Building C# Applications { Pa r t Tw o - The C# Pr ogr am m ing La ngua ge // Box ints into ArrayList. Chapter 3 - C# Language Fundamentals ArrayList myInts = new ArrayList(); ChaptermyInts.Add(88); 4 - Obj ect -Or iented Pr ogr am ming w ith C# ChaptermyInts.Add(3); 5 - Exceptions and Obj ect Lifetim e ChaptermyInts.Add(9764); 6 - I nter faces and Collections Chapter// 7 Unbox - Callback I nter faces, Delegates, and Ev ents first item. Chapterint 8 - firstItem Advanced C# = Type Const ruction Techniques (int)myInts[0]; Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assemitem bl ie s is {0}", firstItem); Console.WriteLine("First Chapter } 9 - Under standing .NET Assem blies Chapter 2

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

(Un)Boxing Under the Hood

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter If you examine 14 - A Better the underlying Paint ing FrCIL amew using or k (ildasm.exe GDI + ) for the BoxAndUnboxInts() method, you can clearly see

exactly15 when System.Int32 types are copied from Chapter - Prthe ogr am ming with Windows Form s Contr olsthe heap to the stack (and vice versa): Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - public Data Access w ith ADO.NET .method hidebysig static void BoxAndUnboxInts() cil managed Pa {r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter // Code 18 - ASP.NET size Web Pages 81and (0x51) Web Contr ols

.maxstack 3 Web Applicat ions Chapter 19 - ASP.NET .locals init class [mscorlib]System.Collections.ArrayList myInts, Chapter 20 - XML Web ([0] Ser vices [1] int32 firstItem) IL_0000: newobj List of Figur es instance void [mscorlib]System.Collections.ArrayList::.ctor() List of Tables IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.s 88 IL_0009: box [mscorlib]System.Int32 IL_000e: callvirt instance int32 [mscorlib]System.Collections.ArrayList::Add(object) IL_0013: pop IL_0014: ldloc.0 IL_0015: ldc.i4.3 IL_0016: box [mscorlib]System.Int32 IL_001b: callvirt instance int32 [mscorlib]System.Collections.ArrayList::Add(object) IL_0020: pop IL_0021: ldloc.0 IL_0022: ldc.i4 0x2624 I ndex

IL_0027: box [mscorlib]System.Int32 C# an d th e .N ET Plat f orm , Se con d Ed it ion IL_002c: callvirt ISBN:1590590554 Andr ew [mscorlib]System.Collections.ArrayList::Add(object) Tr oelsen instanceby int32 Apr ess © 2003 (1200 pages) IL_0031: pop This compr ehensiv e text star ts w ith a brief ov er view of the IL_0032: ldloc.0 C# language and then quickly m oves to key technical and IL_0033: ldc.i4.0 ar chitectur al issues for .NET developer s. IL_0034: callvirt instance object [mscorlib]System.Collections.ArrayList::get_Item(int32) IL_0039: unbox [mscorlib]System.Int32 Ta ble o f Con t en t s IL_003e: ldind.i4 C# and t he .NET Plat for m, Second Edition IL_003f: stloc.1 I ntr oduction IL_0040: ldstr "First item is {0}" Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m IL_0045: ldloc.1 Chapter 1 - The Philosophy of .NET IL_0046: box [mscorlib]System.Int32 Chapter 2 - Building C# Applications IL_004b: call void [mscorlib]System.Console::WriteLine(string, object) Pa r t Tw o - The C# Pr ogr am m ing La ngua ge IL_0050: ret Chapter 3 - C# Language Fundamentals } Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e Here, we indirectly triggered a fourth CIL box operation at the point of printing out the value of the first item Chapter 6 have - I nter faces and Collections

help in 7the- ArrayList. reason? System.Console.WriteLine() does not supply an overloaded variation that Chapter Callback I The nter faces, Delegates, and Ev ents operates raw System.Int32 types!ruction Techniques Chapter 8 on - Advanced C# Type Const Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

To be sure, boxing and unboxing types takes some processing time, and if used without restraint, could hurt the - Under standing .NET Assem blies performance of your application. However, given this .NET technique, you are able to symmetrically operate on Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads value-based and reference-based types. Without such a mechanism, we would be forced to be painfully aware Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing of the underlying type of a given variable (which would also result in extraneous code, as we see in C and C++). Pa r t Four - Le ve r a ging the .NET Libr a r ie s In this light, I'd place my vote that (un)boxing is a positive trait of a mature runtime. Chapter 9

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter On a final 13 -boxing-related Building a Bet ter note, Winunderstand dow ( Int roducin that gif Window you were s For to pass ms) custom structures or enumerations into a

method14taking generic System.Object you would also be required to unbox the parameter to Chapter - A Better Paint ing Fr amew or kparameters, ( GDI + ) interact15 with the of the structure Chapter - Pr ogrspecific am mingmembers with Windows Form s Contr(or ols enum). This topic will be revisited later in this chapter when you examine theespace C# structure. Chapter 16 -formally The Sy stem .I O Nam Chapter 17 - Data Access w ith ADO.NET

SOURCE CODE

The Boxing project is included under the Chapter 3 subdirectory.

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th eConstants .N ET Plat f orm , Se con d Ed it ion Defining Program by Andr ew Tr oelsen

ISBN:1590590554

Now that you canApr create transform) ess ©(and 2003 (1200 pages) value-based and reference-based variables, you need to examine the logical opposite: Constants. C# offers thestar "const" keyword, toerdefine with a fixed, unalterable value. This compr ehensiv e text ts w ith a brief ov view ofvariables the Unlike C++, the C# "const" keyword cannot be used to qualify parameters or return values. Furthermore, it is C# language and then quickly m oves to key technical and ar chitectur al the issues for of .NET developer s. of data is computed at compile time, and therefore a important to understand that value a constant point constant member cannot be assigned to an object reference (whose value is computed at runtime). Although it is possible to define local constants within a method scope, a more beneficial use of const is to create classTalevel ble oconstant f Con t en tdefinitions. s For example: C# and t he .NET Plat for m, Second Edition I ntr oduction

// Some const data. using System; Chapter - The Philosophy of .NET class1 MyConstants Chapter 2 - Building C# Applications { Pa r t Tw o// - The C# Praccessed ogr am m ing by La ngua ge When another type, these constants Chapter // 3 - must C# Language Fundamentals be referenced via the fully qualified name. Chapter public 4 - Obj ect -Or iented Pr ogr am ming w ith = C# 5; const int myIntConst Chapter public 5 - Exceptions Obj ect Lifetim e constand string myStringConst = "I'm a const"; Chapter public 6 - I nter static faces and void Collections Main() Chapter { 7 - Callback I nter faces, Delegates, and Ev ents // Scoped constant. Chapter 8 - Advanced C# Type Const ruction Techniques const string localConst Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s = "I am a rock, I am an island"; // Use const data. Chapter 9 - Under standing .NET Assem blies = {0}\nmyStringConst = {1}", Chapter 10 - Pr Console.WriteLine("myIntConst ocesses, AppDomains, Cont exts, and Threads myIntConst, myStringConst); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Console.WriteLine("Local constant: {0}", localConst); Pa r t Four - Le ve r a ging the .NET Libr a r ie s } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Praogr am ming s Contr If you create utility classwith thatWindows containsForm nothing but ols constant data, you may wish to define a private constructor. Chapter 16 The Sy stem .I O Nam espace In this way, you ensure the object user cannot make an instance of your class (which would be desirable given Chapter - Data w ith ADO.NET that the17class hasAccess no real implementation): Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols creation of a given type. // Private constructors prevent the Chapter - ASP.NET Web Applicat ions class19MyConstants Chapter 20 - XML Web Ser vices { I ndex

public const int myIntConst = 5;

List of Figur es public const string myStringConst = "I'm a const"; List of Tables // Don't let the user make this class,

// as its only purpose is to define constant values. private MyConstants(){ } }

The same result can be achieved by marking your "constant-only class" as an abstract type. You examine the use of this keyword in the next chapter, but here is the updated MyConstants definition: // Abstract definition also prevents the creation of a given type. abstract class MyConstants { public const int myIntConst = 5; public const string myStringConst = "I'm a const"; }

In either case, if another object attempts to create an instance of MyConstants, a compiler error is generated. C# an d th e .N ET Plat f orm , Se con d Ed it ion These techniques can be quite helpful given that C# does not allow you to define global level constants. ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Referencing Across Types ThisConstant compr ehensiv eData text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

Given that we have ar chitectur moved al ourissues constant for .NET points developer of datas.into a new class definition, how are they accessed from within another type? If you attempt to simply reference them by their unqualified name (myIntConstant, myStringConstant) you will be issued a compiler error. Again, the reason has to do with the fact that under C#, Taglobal ble o f points Con t en oft sdata are not allowed. Thus, any time you wish to access a constant defined outside of the C# and t he .NET you Plat for m, Second Edition defining class, must make use of the fully-qualified name. On the other hand, if a given class wishes to I ntr access oduction a constant it directly defined, you are able to directly refer to the item at hand: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 static - The Philosophy of .NET public void Main() Chapter 2 Building C# Applications { Pa r t Tw oconst - The C#string Pr ogr amlocalConst m ing La ngua ge =

"I am a rock, I am an island";

Chapter // 3 - Use C# Language Fundamentals const data. Chapter Console.WriteLine("myIntConst 4 - Obj ect -Or iented Pr ogr am ming w ith C# = {0}\nmyStringConst = {1}\nLocalConst = {2}",

localConst); Chapter MyConstants.myIntConst, 5 - Exceptions and Obj ect Lifetim MyConstants.myStringConst, e } Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

SOURCE The Constants project is located under the Chapter 3 subdirectory. - Under standing .NET Assem blies CODE

Chapter 9

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion C# IterationC#Constructs by Andr ew Tr oelsen

ISBN:1590590554

Consider the nextApr few pages mid-chapter reprieve from the complexities of value/reference types, ess © 2003a(1200 pages) overriding members of System.Object, and boxing heap This compr ehensiv e text star ts w ith types a briefon ovthe er view of (in theother words, the next few sections are boring, but necessary to cover). As you are well aware, all programming languages provide ways to C# language and then quickly m oves to key technical and ar chitectur al terminating issues for .NET developer repeat blocks of code until a condition hass.been met. Regardless of which language you are coming from, the C# iteration statements should pose no raised eyebrows and require little explanation. In a nutshell, C# provides the following four iteration constructs: Ta ble o f Con t en t s

fort he loop C# and .NET Plat for m, Second Edition I ntr oduction

foreach/in loop

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 loop - The Philosophy of .NET while Chapter 2

- Building C# Applications

Pa r t Tw do/while o - The loop C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

C, C++, and Java programmers will no doubt be familiar with the "for," "while," and "do/while" loops, but - Obj ect -Or iented Pr ogr am ming w ith C# may be unfamiliar with the "foreach" statement. Visual Basic programmers on the other hand, are in the Chapter 5 - Exceptions and Obj ect Lifetim e fortunate position to be well aware of all four C# iteration statements, as VB already supports "For Each" Chapter 6 - I nter faces and Collections syntax. Let's quickly examine each looping construct in turn. Chapter 4

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

The for Loop

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

When you need to iterate over a block of code a fixed number of times, the "for" statement is the construct of champions. In essence, you are able to specify how many times a block of code repeats itself, as well as Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing the terminating condition. Without belaboring the point, here is a sample of the syntax: Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

// A basic for loop. public static int Main(string[] args) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) { Chapter 15 - Pr ogr am ming with Windows Form s Contr ols // Note! 'i' is only visible within the scope of the for loop. Chapter 16 - The Sy stem .I O Nam espace for(int i = 0; i < 10; i++) Chapter { 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Console.WriteLine("Number Appl ica ti ons and X ML W e b Se r vi ces is: {0} ", i); Chapter } 18 - ASP.NET Web Pages and Web Contr ols Chapter // 19 - 'i' ASP.NET ions here. is Web not Applicat visible Chapter return 20 - XML Web 0; Ser vices I ndex } Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

List of Figur es List of Tables

All of your old C, C++, and Java tricks still hold when building a C# for statement. You can create complex terminating conditions, build endless loops, and make use of the "goto," "continue," and "break" keywords. I'll assume that you will bend this iteration construct as you see fit.

The foreach/in Loop Visual Basic programmers have long seen the benefits of the For Each construct. The C# equivalent allows you to iterate over all items within an array. Here is a simple example using foreach to traverse an array of strings that represent possible titles for forthcoming publications. Once this array has been filled, you iterate over the contents looking for a pattern match (COM or .NET) using String.IndexOf(): // Digging into an array using foreach. public static int Main(string[] args) { string[] arrBookTitles = new string[] {

"Complex Algorithms",

"COM for the Fearful Programmer", C# an d th e .N ET Plat f orm , Se con d Ed it ion "Do you Remember Classic COM?", ISBN:1590590554 by Andr ew Tr oelsen "C# and the .NET Platform", Apr ess © 2003 (1200 pages) "COM for the Angry Engineer" } ; compr ehensiv e text star ts w ith a brief ov er view of the int COM This = 0, NET = 0; C# language and then quickly mfor oves books to key technical // Assume we are not looking on COMand interop. ar chitectur al issues for .NET developer s. foreach (string s in arrBookTitles) { if (-1 != s.IndexOf("COM")) Ta ble o f Con t en t s COM++; C# and t he .NET Plat for m, Second Edition else if(-1 != s.IndexOf(".NET")) I ntr oduction NET++; Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m } Chapter 1 - The Philosophy of .NET Console.WriteLine("Found {0} COM references and {1} .NET references.", Chapter 2 - Building C# Applications COM, NET); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge return 0; Chapter 3 - C# Language Fundamentals } Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e In addition iterating simple arrays, foreach is also able to iterate over system-supplied or userChapter 6 - toI nter faces over and Collections

defined7 collections. hold off on the details Chapter 6, as this aspect of the "foreach" keyword entails Chapter - Callback I'll I nter faces, Delegates, anduntil Ev ents an understanding of interface-based programming and the system-supplied IEnumerator and IEnumerable Chapter 8 - Advanced C# Type Const ruction Techniques interfaces. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

The while and do/while Looping Constructs

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

You have- Le already seen the fora rstatement Pa r t Four ve r a ging thethat .NET Libr ie s

is typically used when you have some foreknowledge of the

number12of- iterations you wish toand perform (e.g., loop until Chapter Obj ect Ser ialization the .NET Remoting Layjer> 20). The while statement on the other hand is useful for times when are uncertain long its might Chapter 13 those - Building a Bet ter you Win dow ( Int roducinhow g Window For ms)take for a terminating condition to be met. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

To illustrate the while loop, here is a brief look at C# file manipulation (which is fully detailed in Chapter 16). The StreamReader class, defined within the System.IO namespace, encapsulates the details of reading Chapter - The stem .Ithat O Nam from a 16 given file.SyNotice youespace are obtaining an instance of the StreamReader type as a return value from Chapter 17 Data Access w ith ADO.NET the static File.OpenText() method. Once you have opened the boot.ini file, you are able to iterate over each Pa r t Fiinvethe - W e b using Appl ica ti ons and X ML W e b Se r vi ces line file StreamReader.ReadLine(): Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

try

// Just in case we can't find the correct file...

Chapter 20 - XML Web Ser vices { I ndex // Open the file named 'boot.ini'. List of Figur es StreamReader strReader = File.OpenText("C:\\boot.ini"); List of Tables

// Read the next line and dump to the console. string strLine; while(null != (strLine = strReader.ReadLine())) { Console.WriteLine(strLine); } // Close the file. strReader.Close(); } catch(FileNotFoundException e) { Console.WriteLine(e.Message); }

Closely related to the while loop is the do/while statement. Like a simple while loop, do/while is used when C# an d th e .N ET Plat f orm , Se con d Ed it ion you need to perform some action for an undetermined number of times. The difference is that do/while ISBN:1590590554 by Andr Tr oelsen loops are guaranteed to ew execute the corresponding block of code at least once (in contrast, it is possible Apr ess © 2003 (1200 pages) that a simple while loop may never execute if the terminating condition is false from the onset). This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and // The do/while statement ar chitectur al issues for .NET developer s.

string ans; do Ta{ble o f Con t en t s you done? [yes] [no] : "); C# and tConsole.Write("Are he .NET Plat for m, Second Edition ans = Console.ReadLine(); I ntr oduction }while(ans != ng "yes"); Pa r t One - I nt r oduci C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

SOURCE The Iterations project is located under the Chapter 3 subdirectory. - C# Language Fundamentals CODE

Chapter 3 Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion C# ControlC# Flow Constructs ISBN:1590590554

by Andr ew Tr oelsen

Now that you canApr iterate a block of code, the next related concept is how to control the flow of program ess ©over 2003 (1200 pages) execution. C# defines two simple constructs to w alter flow yourofprogram, based on various contingencies. F This compr ehensiv e text star ts ith athe brief ov of er view the you have our good friend, the "if/else" statement. Unlike C and C++ however, the if/else statement only operates C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer Boolean expressions (not ad-hoc values such as -1, 0s.and so on). Given this, if/else statements typically involve use of the following C# operators (Table 3-5). TaTable ble o f 3-5: Con tC# en tRelational s and Equality Operators C# and t he .NET Plat for m, Second Edition

Equality/Relational I ntrC# oduction Pa rOperator t One - I nt r oduci ng

C# a nd the .NET

Chapter 1

==

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Example P la tf or mUsage if(age = = 30)

Meaning in Life Returns true only if each expression is the same.

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

!= Chapter 3

- C# Language Fundamentals

if("Foo" != Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith myStr) C#

Returns true only if each expression is different.

Chapter 5
2000)

is less than, greater than, less

Chapter =

- Under standing .NET Assem blies

if(bonus >= 2000)

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

than or equal to expression B.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

C and C++ programmers need to be aware that the old tricks of testing a condition for a value "not equal to zero will not work in C#. Let's say you want to see if the string you are working with is greater than zero. You may be Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) tempted to write: Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

// This is illegal, given that Length returns an int, not a bool. string thoughtOfTheDay = "You CAN teach an old dog new tricks"; Chapter 17 - Data Access w ith ADO.NET if(thoughtOfTheDay.Length) // Error! Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces { Chapter 18 - ASP.NET Web Pages and Web Contr ols // Stuff... Chapter 19 - ASP.NET Web Applicat ions } Chapter 16 - The Sy stem .I O Nam espace

Chapter 20 - XML Web Ser vices I ndex List of Figur es

If you wish to make use of the String.Length property to determine if you have an empty string, you need to mod List of Tables your conditional expression as follows: // No problem. if(0!= thoughtOfTheDay.Length) { // Stuff... }

// Better! This resolves to {true | false}.

An "if" statement may be composed of complex expressions as well. As you would expect, if conditionals can containelse statements to perform more complex testing. The syntax is identical to C(++) and Java (and not too removed from Visual Basic). To build such a beast, C# offers an expected set of conditional operators (Table 3Table 3-6: C# Conditional Operators

C# Conditional C# anOperator d th e .N ET Plat Example f orm , Se con d Ed it ion ISBN:1590590554 by Andr ew Tr oelsen if((age = = 30) && (name = = "Fred")) Apr ess © 2003 (1200 pages)

&& ||

This compr ehensiv e text if((age star ts=w=ith 30) a brief || (name ov er = view = "Fred")) of the C# language and then quickly m oves to key technical and ar chitectur al issues for if(!myBool) .NET developer s.

!

Meaning in Life Conditional AND operator Conditional OR operator Conditional NOT operator

The other simple selection construct offered by C# is the switch statement. As I am sure you are aware, switch Tastatements ble o f Con t allow en t s you to handle program flow based on a predefined set of choices. For example, the following C# and t he .NET Plat forthe m, user Second application prompts for Edition one of three possible values. Based on the user input, act accordingly: I ntr oduction Pa r t One nt r oduci ng C# a nd the statement. .NET P la tf or m // The- Igood ol' switch

Chapter - The Philosophy of .NET class1 Selections Chapter 2 {

- Building C# Applications

Pa r t Tw opublic - The C# static Pr ogr am mint ing La ngua ge Main(string[]

args)

Chapter { 3 Chapter 4

- C# Language Fundamentals

Chapter 5

Console.WriteLine("1 - Exceptions and Obj ect Lifetim e = C#\n2 = Managed C++ (MC++)\n3 = VB.NET\n");

Chapter 6

Console.Write("Please select your implementation language:"); - I nter faces and Collections

Chapter 7

string s faces, = Console.ReadLine(); - Callback I nter Delegates, and Ev ents

Chapter 8

int n C# = int.Parse(s); - Advanced Type Const ruction Techniques

- Obj Console.WriteLine("Welcome ect -Or iented Pr ogr am ming w ith C# to the world of .NET");

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

switch(n) - Under standing .NET Assem blies {

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

// C# demands that each case (including 'default') which // contains executable statements, must have Pa r t Four - Le ve r a ging the .NET Libr a r ie s // a terminating 'break' or 'goto' to avoid fall through. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er case 1: Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Console.WriteLine("Good choice! C# is all about managed code." Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) break; Chapter 15 - Pr ogr am ming casewith 2:Windows Form s Contr ols Chapter 16 - The Sy stem .I O Console.WriteLine("Let Nam espace me guess, maintaining a legacy system?" Chapter 17 - Data Access w ith ADO.NET break; Pa r t Fi ve - W e b Appl icacase ti ons and 3: X ML W e b Se r vi ces Chapter 18 - ASP.NET Web Pages and Web Contr ols Console.WriteLine("VB .NET: It is not just for kids anymore... Chapter 19 - ASP.NET Web Applicat ions break; Chapter 20 - XML Web default: Ser vices Console.WriteLine("Well...good luck with that!"); I ndex break; List of Figur es List of Tables } return 0; } } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Note It is worth pointing out that the C# also supports switching on character data as well (it even supports a "null" case for empty strings). SOURCE CODE

The Selections project is located under the Chapter 3 subdirectory.

C# anSet d th eof .N ET Plat f orm , Se con d Ed it ion The Complete C# Operators ISBN:1590590554

by Andr ew Tr oelsen

C# defines a number of ©operators addition to those you have previously examined. By and large, these Apr ess 2003 (1200 in pages) operators behaveThis likecompr their C(++) and Java 3-7 of lists ehensiv e text starcounterparts. ts w ith a briefTable ov er view thethe set of C# operators in order of precedence. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Table 3-7: The Full Set of C# Operators Operator Ta ble o f Con t enCategory ts C# and t he .NET Plat for m, Second Edition

Unary

I ntr oduction

Operators + - ! ~ ++x x++ --x x--

Pa rMultiplicative t One - I nt r oduci ng C# a nd the .NET P la tf * or /% m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Additive

Pa rShift t Tw o - The C# Pr ogr am m ing La ngua ge

+>

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Relational

< > = is as

Equality Chapter 5 - Exceptions and Obj ect Lifetim e= = ! = Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Logical AND

&

Logical ^ Techniques Chapter 8 XOR - Advanced C# Type Const ruction Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Logical OR

Chapter 9

|

- Under standing .NET Assem blies

Conditional && and Threads Chapter 10 - PrAND ocesses, AppDomains, Cont exts, Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Conditional OR

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

||

Conditional ?: Remoting Lay er Chapter 12 - Obj ect Ser ialization and the .NET Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Indirection / Address

* -> &

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Assignment = *=s /= %=ols += -= = &= ^= |= Chapter 15 - Pr ogr am ming with Windows Form Contr Chapter 16 - The Sy stem .I O Nam espace

The only that you not be familiar with are the is and as operators. The is operator is used to Chapter 17 operators - Data Access w ith may ADO.NET verify at -runtime if an is compatible a given Pa r t Fi ve W e b Appl ica object ti ons and X ML W e b Sewith r vi ces

type. One common use for this operator is to determine if a given object supports a particular interface, as you discover in Chapter 6. The as operator Chapter 18 - ASP.NET Web Pages and Web Contr ols allows you to downcast between types (seen briefly in this chapter and formally in Chapter 4) or Chapter 19 - ASP.NET Web Applicat ions implemented interface. Chapter 20 - XML Web Ser vices

I ndex Also note that the C# language does support the use of classic C(++) pointer manipulations, via the *, -> List es andof &Figur operators. If you choose to make use of these operators, you are bypassing the runtime memory List of Tables management scheme and writing code in "unsafe mode." You learn about these operators in Chapter 8.

As for the remaining operators, I will make the assumption that many (if not all) of them are old hat to you. If you need additional information regarding the C# looping and decision constructs, consult the C# Language Reference using MSDN.

C# an d thClass e .N ET Plat f orm , Se con d Ed it ion Defining Custom Methods ISBN:1590590554

by Andr ew Tr oelsen

Now that we haveApr concluded reprieve, let's move on to more interesting topics and ess © 2003 our (1200mid-chapter pages) examine the details of defining custom methods for aa brief C# class. Firstofunderstand that, like points of data, This compr ehensiv e text star ts w ith ov er view the every method youC#implement must be a member of a class or struct (global methods are not allowed in language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. C#). As you know, a method exists to allow the type to perform a unit of work. Like Main(), your custom Tamethods ble o f Con may t enor t s may not take parameters, may or may not return values (of any intrinsic or user defined

types). Also custom may be declared nonstatic (instance-level) or static (class-level) entities. C# and t he .NET Plat formethods m, Second Edition I ntr oduction

Method Access Modifiers

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter A method 2 -must Building specify C# its Applications level of accessibility (see Table 3-8). C# offers the following method access Pa modifiers r t Tw o - The (youC#examine Pr ogr am the m ing useLaofngua protected ge

and internal methods in the next chapter during the

discussion hierarchies): Chapter 3 - of C#class Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Table 3-8: Accessibility Chapter 5 - C# Exceptions and ObjKeywords ect Lifetim e Chapter 6

- I nter faces and Collections C# Access Meaning in Life

Chapter 7 - Callback I nter faces, Delegates, and Ev ents Modifier Chapter 8

- Advanced C# Type Const ruction Techniques

Marks asblaccessible Pa rpublic t Thre e - Pr ogr am m i ng w i th a .Nmethod ET Assem ie s Chapter 9

private

from an object instance, or any subclass.

- Under standing .NET Assem blies

Marks a method as accessible only by the class that has defined the method. If you don't say otherwise, private is assumed (it is the default Chapter 11 - Type Reflection, Latelevel). Binding, and Attr ibute- Based Pr ogramm ing visibility Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Pa r t Four - Le ve r a ging the .NET Libr a r ie s

protected Marks a and method as usable by the class, as well as any child class, Chapter 12 - Obj ect Ser ialization the .NET Remoting Lay defining er butteris Win private as the outsidesworld is concerned. Chapter 13 - Building a Bet dow as ( Intfar roducin g Window For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI ) publicly accessible by all types in an assembly (but internal Defines a method that+ is Chapter 15 - Pr ogr am ming s Contr ols notwith fromWindows outsideForm the assembly). Chapter 16 - The Sy stem .I O Nam espace

protected internal

Defines a method whose access is limited to the current assembly or types derived from the defining class in the current assembly. Appl ica ti ons and X ML W e b Se r vi ces

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Here are the implications of each accessibility keyword:

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

// Visibility options. I ndex class SomeClass { List of Tables // Accessible anywhere. public void MethodA(){} // Accessible only from SomeClass types. private void MethodB(){} // Accessible from SomeClass and any descendent. protected void MethodC(){} // Accessible from within the same assembly. internal void MethodD(){} // Assembly-protected access. protected internal void MethodE(){} // Unmarked members are private by default in C#. void MethodF(){} } List of Figur es

As you may already know, methods that are declared public are directly accessible from an object C# an d th e .N ET Plat f orm , Se con d Ed it ion instance via the dot operator. Private methods cannot be accessed by an object reference, but instead are ISBN:1590590554 by the Andr ew Tr to oelsen called internally by object help the instance get its work done (that is, private helper functions). To Apr ess © 2003 (1200 pages) illustrate, the Teenager class shown next defines two public methods, Complain() and BeAgreeable(), This compr ehensiv star ts w ith a brief ov er view of the make use of a private helper each of which returns a string to thee text object user. Internally, both methods C# language and then quickly m oves to key technical and method named GetRandomNumber(), which manipulates a private member variable of type ar chitectur al issues for .NET developer s. System.Random: public methods, each using an internal helper function. Ta// ble Two o f Con t en t s using System; C# and t he .NET Plat for m, Second Edition class Teenager I ntr oduction {r t One - I nt r oduci ng C# a nd the .NET P la tf or m Pa System.Random Chapter // 1 - The The Philosophy of .NET type generates random numbers. Random r = new Random(); Chapter private 2 - Building C# Applications Pa r t Tw opublic - The C# string Pr ogr am mComplain() ing La ngua ge

{ - C# Language Fundamentals string[] messages = new string[5]{ "Do I have to?", Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# "He started it!", "I'm too tired...", Chapter 5 - Exceptions and Obj ect Lifetim e "I hate school!", "You are sooo wrong." } ; Chapter 6 - I nter faces and Collections return messages[GetRandomNumber(5)]; Chapter 7 - Callback I nter faces, Delegates, and Ev ents } Chapter public 8 - Advanced C# Type Const ruction Techniques string BeAgreeable() Pa r t Thre{e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9 - Under standing messages .NET Assem blies string[] = new string[3]{ "Sure! No problem!", Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads "Uh uh.", "I guess so." } ; Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing return messages[GetRandomNumber(3)]; Pa r t Four} - Le ve r a ging the .NET Libr a r ie s Chapter private 12 - Obj ect int Ser ialization and the .NET Remoting Lay er GetRandomNumber(short upperLimit) Chapter { 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Random.Next() Chapter 14 - A // Better Paint ing Fr amew orreturns k ( GDI + ) a random integer // between 0 and upperLimit. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols return Chapter 16 - The Sy stem .Ir.Next(upperLimit); O Nam espace } Chapter 17 - Data Access w ith ADO.NET static Main(string[] args) Pa r t Fi vepublic - W e b Appl ica ti ons void and X ML W e b Se r vi ces { Chapter 18 - ASP.NET Web Pages and Web Contr ols // Let mike do his thing. Chapter 19 - ASP.NET Web Applicat ions Console.WriteLine("Grumpy Mike says:"); Chapter 20 - XML Web Ser vices Teenager mike = new Teenager(); I ndex for(int i = 0; i < 10; i++) List of Figur es Console.WriteLine("-> {0}", mike.Complain()); List of Tables // Now be agreeable. Console.WriteLine("\nHappy Mike says:"); Console.WriteLine("-> {0}", mike.BeAgreeable()); } } Chapter 3

Obviously the benefit of defining GetRandomNumber() as a private helper method is that various parts of the Teenager class can make use of its functionality. The only alternative would be to duplicate the random number logic within the Complain() and BeAgreeable() methods (which in this case would not be too traumatic, but assume GetRandomNumber() contains 20 or 30 lines of code). Figure 3-14 shows a possible test run.

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - 3-14: C# Language Figure RandomFundamentals teenager chatter Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C#

Note System.Random is used to generate and manipulate random numbers. Chapter 5 The - Exceptions and Obj ecttype Lifetim e

returns a number between 0 and the specified upper limit. As you would Chapter 6 Random.Next() - I nter faces and method Collections Chapter 7 Chapter 8

guess, the Random type provides additional members, all of which are documented within - Callback I nter faces, Delegates, and Ev ents MSDN. - Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am mThe i ng wTeenager i th .N ET Assem bl ie s SOURCE application

is located under the Chapter 3 subdirectory.

Chapter 9 - Under standing .NET Assem blies CODE Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dStatic th e .N ETMethods Plat f orm , Se con d Ed it ion Understanding by Andr ew Tr oelsen

ISBN:1590590554

As you have seen, methods can bepages) declared "static." But, what exactly does it mean to be a static method? Apr ess © 2003 (1200 When a method is marked with the "static" keyword, mayovbe from the class level, and does This compr ehensiv e text star ts w ith a itbrief er called view of directly the not require an object variable. For this very reason, Main() is declared static to allow the runtime to invoke this C# language and then quickly m oves to key technical and ar chitectur issues for .NET developer function without needing to al allocate a new instance of s.the defining class. This is a good thing of course, or else you would need to create an object to create an object to create an object to (...). TaYou ble oshould f Con t en also t s consider our good friend System.Console. As you have seen, you do not invoke the

WriteLine() method from an object instance: C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One nt r oduci ng C# a nd theinstance .NET P la tf or m // No!- IWriteLine() not level...

Chapter 1 - cThe of .NET Console = Philosophy new Console(); Chapter c.WriteLine("I 2 - Building C# can't Applications be printed..."); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals but instead prefix thePr type name static WriteLine() member. Chapter 4 - simply Obj ect -Or iented ogr am mingtowthe ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

// Yes! is static... Chapter 6 - WriteLine() I nter faces and Collections Console.WriteLine("Thanks..."); Chapter 7 - Callback I nter faces, Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Simply put, static members are methods that are deemed (by the class designer) to be so commonplace that - Under standing .NET Assem blies there is no need to create an instance of the type. When you are designing your custom class types, you are Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads also able to define any number of static and/or instance level members. To illustrate custom static methods, Chapter - Type Reflection, Late Binding, and and Attr ibuteBased Pr ogramm ing of the Teenager class as follows: assume11I have reconfigured the Complain() BeAgreeable() methods Chapter 9

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

// Teenagers complain so often, there is no need to create an initial object... publicstatic string Complain() Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) { Chapter string[] 15 - Pr ogr ammessages ming with Windows s Contr ols "Do I have to?", = new Form string[5]{ Chapter 16 - The Sy stem .I O Nam espace "He started it!", "I'm too tired...", Chapter 17 - Data ith ADO.NET "You are sooo wrong." } ; "I Access hate wschool!", Pa r t Fi vereturn - W e b Appl ica ti ons and X ML W e b Se r vi ces messages[GetRandomNumber(5)]; Chapter 18 ASP.NET Web Pages and Web Contr ols } Chapter 19static - ASP.NET Web Applicat ions public string BeAgreeable() Chapter { 20 - XML Web Ser vices I ndex string[] messages = new string[3]{ "Sure! No problem!", "Uh uh.", "I guess so." }; List of Figur es return messages[GetRandomNumber(3)]; List of Tables } Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

This update also assumes that the System.Random and GetRandomNumber() helper function method have also been declared as static members of the Teenager class, given the rule that static members can only operate on other static members: class Teenager { private static Random r = new Random(); private static int GetRandomNumber(short upperLimit) { return r.Next(upperLimit); } ... }

These assumptions aside, the process of calling a static method is simple. Just append the member to the C# an d th e .N ET Plat f orm , Se con d Ed it ion name of the defining class: ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

// Call the static Complain method of the Teenager class. This compr ehensiv e text star ts w ith a brief ov er view of the public staticC#void Main(string[] args) language and then quickly m oves to key technical and { ar chitectur al issues for .NET developer s. for(int i = 0; i < 40; i++) Console.WriteLine("-> {0}", Teenager.Complain()); } Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Again, by contrast, nonstatic (instance) methods are scoped at the object level. Thus, if Complain() was not - The Philosophy of .NET marked static, you would need to create an instance of the Teenager class before you could hear about the Chapter 2 - Building C# Applications gripe of the day: Chapter 1

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

// Must - make an instance of Teenager class to call instance methods. Obj ect -Or iented Pr ogr am ming w ith C# Teenager joe = new Teenager(); Chapter 5 - Exceptions and Obj ect Lifetim e joe.Complain(); Chapter 4 Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am mThe i ng wStaticTeenager i th .N ET Assem bl ie s SOURCE application

is located under the Chapter 3 subdirectory.

Chapter 9 - Under standing .NET Assem blies CODE Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Defining Static Data

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - toObj ect Ser ializationa and the .NET Lay er In addition static methods, C# class mayRemoting also define static data (such as the previous Random member Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms)a set of nonstatic state data. This simply variable from the Teenager example). Typically, a class defines Chapter - each A Better Paintinstance ing Fr amew or k ( GDIa+private ) means14 that object maintains copy of the underlying values. Thus, if you have a class Chapter defined15as- follows: Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter - Data Access w ith ADO.NET // We17all love Foo. Pa r t Fi ve -Foo W e b Appl ica ti ons and X ML W e b Se r vi ces class

Chapter 18 - ASP.NET Web Pages and Web Contr ols { Chapter public 19 - ASP.NET intWeb intFoo; Applicat ions

} Chapter 20 - XML Web Ser vices I ndex List of Figur es

you can create any number of objects of type Foo and assign the intFoo field to a value to each instance:

List of Tables

// Each Foo reference maintains a copy of the intFoo field. Foo f1 = new Foo(); f1.intFoo = 100; Foo f2 = new Foo(); f2.intFoo = 993; Foo f3 = new Foo(); f3.intFoo = 6;

Static data, on the other hand, is shared among all object instances of the same type. Rather than each object holding a copy of a given field, a point of static data is allocated exactly once for all instances of the type. Assume you have a class named Airplane that contains a single point of static data. In the constructor of the Airplane class you increment this data point. Here is the initial definition:

// Note the use of static keyword. C# an d th e .N ET Plat f orm , Se con d Ed it ion class Airplane ISBN:1590590554 by Andr ew Tr oelsen { Apr ess © 2003 (1200 pages) // This static data member is shared by all Airplane objects. compr ehensiv e text star ts w ith a brief ov er view of the privateThis static int NumberInTheAir = 0; C# language and then quickly m oves to key technical and public Airplane() ar chitectur al issues for .NET developer s. { NumberInTheAir++; } Ta ble o f Con t en t s // Get value from an object instance. C# and t he .NET Plat for m, Second Edition public int GetNumberFromObject() { return NumberInTheAir; } I ntr oduction // Get value from class level. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public static int GetNumber() { returnNumberInTheAir; } Chapter 1 - The Philosophy of .NET } Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter C# Airplane Languageclass Fundamentals Notice 3that- the defines two methods. The static GetNumber() returns the current number of Chapter 4 objects - Obj ect -Orhave ientedbeen Pr ograllocated am ming wby iththe C# application. GetNumberFromObject() also returns the value airplane that Chapter of the static 5 - Exceptions NumberInTheAir and Objinteger, ect Lifetim however e given that this method has not been defined as static, the

object user call this from an instance of Airplane. To illustrate, observe the following usage: Chapter 6 - must I nter faces andmethod Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8 - some Advanced C# Type Const Techniques // Make airplanes are ruction examine the static members. Pa r t Thre eStaticApp - Pr ogr am m i ng w i th .N ET Assem bl ie s class

Chapter { 9

- Under standing .NET Assem blies static int Main(string[] args) Chapter public 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter { 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Make planes. Pa r t Four - Le ve// r a ging the some .NET Libr a r ie s Console.WriteLine("Created two types"); Chapter 12 - Obj ect Ser ialization and the .NET Remoting LayAirplane er Airplane a1Win = dow new( IntAirplane(); Chapter 13 - Building a Bet ter roducin g Window s For ms) a2Fr = new Chapter 14 - A Airplane Better Paint ing amew or kAirplane(); ( GDI + ) // How many are in flight? Console.WriteLine("Number of planes: {0} ", Chapter 16 - The Sy stem .I O Nam espace a1.GetNumberFromObject()); Chapter 17 - Data Access w ith ADO.NET Console.WriteLine("Number of planes: {0} ", Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Airplane.GetNumber()); Chapter 18 - ASP.NET Web Pages and Web Contr ols // More planes! Chapter 19 - ASP.NET Web Applicat ions Console.WriteLine("\nCreated two more Airplane types"); Chapter 20 - XML Web Ser vices Airplane a3 = new Airplane(); I ndex Airplane a4 = new Airplane(); List of Figur es // Now how many? List of Tables Console.WriteLine("Number of planes: {0} ", a3.GetNumberFromObject()); Console.WriteLine("Number of planes: {0} ", Airplane.GetNumber()); return 0; } } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure 3-15 shows the output.

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble Figure o f Con t 3-15: en t s Static data is shared among like objects. C# and t he .NET Plat for m, Second Edition I ntr oduction

As you can see, all instances of the Airplane class are sharing (i.e., viewing) the same integer. If one object changes the value (using either static or instance level members) all types 'see' the change. That's the point Chapter 1 - The Philosophy of .NET of static data: To allow all objects to share a given value at the class (rather than at the object) level. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge SOURCE The StaticData project

is located under the Chapter 3 subdirectory.

Chapter 3 - C# Language Fundamentals CODE Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Method Parameter Modifiers by Andr ew Tr oelsen

ISBN:1590590554

Methods tend to take parameters. you have a COM background, you are certainly familiar with the use of Apr ess © 2003 (1200 If pages) the [in], [out], andThis [in, compr out] IDL attributes. objects ehensiv e text Classic star ts wCOM ith a brief ov eruse viewthese of theattributes to clearly identify the direction of travelC# (and memory allocation rules) for a given interface method parameter. While IDL is not language and then quickly m oves to key technical and chitectur there al issues for .NET developer s. with the set of C# parameter modifiers shown in used in the .NET ar universe, is analogous behavior Table 3-9. TaTable ble o f 3-9: Con tC# en tParameter s Modifiers C# and t he .NET Plat for m, Second Edition I ntrParameter oduction Pa rModifier t One - I nt r oduci ng

Meaning in Life C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C#anApplications input parameter passed by value. This is analogous to the IDL [in]

(none)

If a parameter is not marked with a parameter modifier, it is assumed to be

Pa r t Tw o - The C# Pr ograttribute. am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

out 4 Chapter

This isPranalogous an IDL - Obj ect -Or iented ogr am mingtow ith C# [out] parameter. Output parameters are assigned

Chapter 5 Chapter ref 6

theObj called member. - Exceptionsby and ect Lifetim e

Chapter 7

- I nter faces Analogous and Collections to the IDL [in, out] attribute. The value is assigned by the caller, - Callback I nter Delegates, and within Ev entsthe scope of the method call. butfaces, may be reassigned

Chapter 8

- Advanced C# Type Const ruction Techniques

params

This parameter modifier allows you to send in a variable number of parameters as a single parameter. A given method can only have a single Chapter 9 - Under standing .NET Assem blies params modifier, and must be the final parameter of the method. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

The Default Parameter Passing Behavior

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

The default manner in which a parameter is sent into a function is by value. Simply put, if you do not mark an argument with a parameter-centric keyword, a copy of the data is passed into the function (the story Chapter 15 - Pr ogr am ming with Windows Form s Contr ols changes slightly when passing reference types by value, as you will see in just a bit). You have already Chapter 16 - The Sy stem .I O Nam espace been making use of by-value parameter passing, however, here is a simple example (with implications): Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

// Default param passing is by value. public static int Add(int x, int y) Chapter 19 - ASP.NET Web Applicat ions { Chapter 20 - XML Web Ser vices int ans = x + y; I ndex // Caller will not see these changes. List of Figur x = es99999; List of Tables y = 88888; return ans; } Chapter 18 - ASP.NET Web Pages and Web Contr ols

Here, the two value type parameters have been sent by value into the Add() method. Therefore, if we change the values of the parameters within the scope of the member, the caller is blissfully unaware, given that we are changing the values of copies of the caller's System.Int32 data types: // Call Add() using input params. Console.WriteLine("***** Adding 2 ints *****"); int x = 9, y = 10; Console.WriteLine("X: {0}, Y: {1}", x, y); Console.WriteLine("Answer is: {0}", Add(x, y)); Console.WriteLine("X: {0}, Y: {1}", x, y);

As you would expect, the values of Plat x and y remain C# an d th e .N ET f orm , Se conidentical d Ed it ionbefore and after the call to Add(). ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) The C# "out" Keyword

This compr ehensiv e text star ts w ith a brief ov er view of the language andparameters. then quicklyHere m oves to key technicalversion and Next, we have theC#use of output is an alternative of the Add() method that ar chitectur al issues .NET s. returns the sum of two integers usingforthe C#developer "out" keyword (note the physical return value of this method is now void): Ta ble o f Con t en t s

// Output parameters are allocated by the callee. public static void Add(int x, int y, out int ans) I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m ans = x + y; Chapter 1 - The Philosophy of .NET } C# and t he .NET Plat for m, Second Edition

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter - C# Language Fundamentals Calling3a method with output parameters also requires the use of the "out" keyword. Recall that when you Chapter 4 output - Obj ectvariables -Or ientedare Pr ogr ming w ith C# assigned before use (if you do so, the value is forgotten are local, notam required to be Chapter after the 5 call). - Exceptions For example: and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Chapter - Callback I nter faces, Delegates, Ev ents // No7 need to assign before useandwhen a variable is used ala out. Chapter 8 - Advanced C# Type Const ruction Techniques int ans; Pa r t Thre e - Pr ogr am i ng wkeyword i th .N ET Assem ie s // Note use ofmout in bl calling

syntax.

Chapter Add(90, 9 - 90, Underout standing ans); .NET Assem blies

Console.WriteLine("90 + 90Cont = {0} ", Threads ans); Chapter 10 - Pr ocesses, AppDomains, exts, and Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Now in this case, we really have no good reason to return the value of our summation using an output parameter. However, the C# "out" keyword does serve a very useful purpose: It allows the caller to obtain Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) multiple return values from a single method invocation. For example, assume we have the following Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) member: Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

// Returning multiple output parameters. public static void FillTheseValues(out int a, out string b, out bool c) Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces { Chapter 18 - ASP.NET Web Pages and Web Contr ols a = 9; Chapter 19 - ASP.NET Web Applicat ions b = "Enjoy your string..."; Chapter 20 - XML Web Ser vices c = true; I ndex } Chapter 17 - Data Access w ith ADO.NET

List of Figur es List of Tables

The caller would be able to invoke the following method: // Method with multiple output params. Console.WriteLine("Calling method with multiple output params"); int i; string str; bool b; FillTheseValues(out i, out str, out b); Console.WriteLine("Int is: {0}", i); Console.WriteLine("String is: {0}", str); Console.WriteLine("Boolean is: {0}", b);

The C# "ref" Keyword

Now consider the use of the C# ref parameter modifier. Reference parameters are necessary when you C# an d th e .N ET Plat f orm , Se con d Ed it ion wish to allow a method to operate on (and usually change the values of) various data points declared in Andr as ew aTrsort oelsen the caller's scopeby(such routine). Note the distinction ISBN:1590590554 between output and reference parameters: Apr ess © 2003 (1200 pages)

Output parameters do not need to bestar initialized they areofsent This compr ehensiv e text ts w ith abefore brief ov er view theto the callee. Reason? It is language m oves to key technical and assumed theC# method fills and the then valuequickly on your behalf. ar chitectur al issues for .NET developer s.

Reference parameters must be initialized before being sent to the callee. Reason? You are passing a reference to an existing type. If you don't assign it to an initial value, that would be the equivalent to Ta ble o f Con t enon t s a NULL pointer! operating C# and t he .NET Plat for m, Second Edition

Let's check out the use of the "ref" keyword: I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter // Reference 1 - The Philosophy parameter. of .NET

public UpperCaseThisString(ref string s) Chapter 2 static - Buildingvoid C# Applications {r t Tw o - The C# Pr ogr am m ing La ngua ge Pa the Fundamentals uppercase version of the string. Chapter // 3 - Return C# Language s.ToUpper(); Chapter s 4 =- Obj ect -Or iented Pr ogr am ming w ith C# } Chapter 5

- Exceptions and Obj ect Lifetim e public void Chapter 6 static - I nter faces and Main() Collections

{

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

... Chapter 8 - Advanced C# Type Const ruction Techniques // Use 'ref'. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s string s = "Can you really have sonic hearing for $19.00?"; Chapter 9 - Under standing .NET Assem blies Console.WriteLine("Before: {0} ", s); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads UpperCaseThisString(ref s); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Console.WriteLine("After: {0} ", s); Pa r t Four - Le ve r a ging the .NET Libr a r ie s } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter Here, the 14 caller - A Better has Paint assigned ing Fran amew initial or kvalue ( GDI +to) a local string named "s." Once the call to

UpperCaseThisString() the caller will Chapter 15 - Pr ogr am mingreturns, with Windows Form s find Contr"s" olshas been converted into uppercase, given the use of the "ref" Chapter 16keyword. - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

The C# "params" Keyword

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

The final is the "params" keyword, which is somewhat odd (but convenient) given that Chapter 19 parameter - ASP.NET modifier Web Applicat ions it allows20you to send varied Chapter - XML Web aSer vices number of arguments as a singleparameter. Yes, this can be confusing. To clear the air, assume I have written a simple method defined as follows: I ndex List of Figur es

//ofThis List Tablesmethod has two physical parameters. public static void DisplayArrayOfInts(string msg, params int[] list) { Console.WriteLine(msg); for ( int i = 0 ; i < list.Length ; i++) Console.WriteLine(list[i]); }

This method has been defined to take two physical parameters: one of type string, and one as a parameterized array of integers. What this method is in fact saying is, "Send me a string as the first parameter and any number of integers as the second." Given this, you can call ArrayOfInts() in any of the following ways: // Use 'params' keyword. int[] intArray = new int[3] {10,11,12} ;

DisplayArrayOfInts ("Here is an array of ints", intArray); C# an d th("Enjoy e .N ET Plat f orm , Se d Ed it ion DisplayArrayOfInts these 3 con ints", 1, 2, 3); by Andr ew Tr oelsen DisplayArrayOfInts ("Take some more!", 55, 4,ISBN:1590590554 983, 10432, 98, 33); Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language quickly oves to keyitems technical Looking at the previous code, and you then can see thatmthe bolded in a and given invocation correspond to the ar chitectur al of issues for .NET developer s. second parameter (the array integers).

Of course, you do not have to make use of simple numeric value types when using the params keyword. TaAssume ble o f Con t s yet another variation of the Person class, now defined as follows: wet en have C# and t he .NET Plat for m, Second Edition I ntr //oduction Yet another person class. Pa r t One -Person I nt r oduci ng C# a nd the .NET P la tf or m class

Chapter 1 {

- The Philosophy of .NET

Chapter private 2 - Building C# Applications string fullName; Pa r t Tw oprivate - The C# Prbyte ogr amage; m ing La ngua ge

Chapter public 3 - C# Language Fundamentals Person(string n, byte a) Chapter { 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions fullName and =Objn; ect Lifetim e

Chapter 6

age = a; - I nter faces and Collections

Chapter } 7

- Callback I nter faces, Delegates, and Ev ents

voidC#PrintInfo() Chapter public 8 - Advanced Type Const ruction Techniques { Console.WriteLine("{0} is Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s{1} years old", fullName, age); } } Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Now assume a new method that leverages the "params" keyword. This time however, you specify an array of objects, which boils down to any number of anything. With the method implementation, you can test for Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er an incoming Person type using the C# "is" keyword. If your current item is of type Person, call the Chapter 13 -method. BuildingIfa you Bet ter roducin gtype, Window For ms) PrintInfo() do Win not dow have( Int a Person justsdump the textual information of the type to the Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) console: Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

// This method takes any number of any type.

Chapter 17 static - Data Access ADO.NET public voidw ith DisplayArrayOfObjects(params object[] list) Pa {r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter for 18 - ASP.NET Web and CurrSpeed = {0}", currSpeed); } } } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

At this point, you have two independent classes. Obviously, it would be rather odd to establish an "is-a" relationship between the two entities. However, it should be clear that some sort of relationship between the two could be established. In short, you would like to express the idea that the Car "has-a" Radio. In OO parlance, a class that wishes to contain another class is termed the containing class. The inner class is often

termed a contained class. To begin, you can update the Car class definition as follows: C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

// A Car has-a Radio. Apr ess © 2003 (1200 pages) public class Car This compr ehensiv e text star ts w ith a brief ov er view of the { C# language and then quickly m oves to key technical and ... ar chitectur al issues for .NET developer s. // The contained Radio. private Radio theMusicBox; } Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction

Notice how the outer Car class has declared the Radio object as private. This, of course, is typically a good thing, as you have preserved encapsulation. However, the next obvious question is: How can the outside Chapter 1 - The Philosophy of .NET world interact with contained objects? It should be clear that it is the responsibility of the outer Car class to Chapter 2 - Building C# Applications create the contained Radio class. Although the containing class may create any child objects whenever it Pa r t Tw o - The C# Pr ogr am m ing La ngua ge sees fit, one common place to do so is in the type's constructor set: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

// Containing classes are responsible for creating any child objects. - Exceptions and Obj ect Lifetim e public class Car Chapter 6 - I nter faces and Collections { Chapter 7 - Callback I nter faces, Delegates, and Ev ents ... Chapter 8 - Advanced C# Type Const ruction Techniques private Radio theMusicBox; Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s public Car() Chapter{9 - Under standing .NET Assem blies Chapter 10 - maxSpeed Pr ocesses, AppDomains, Cont exts, and Threads = 100; Chapter 11 - theMusicBox Type Reflection, = Late Binding, and Attr ibute- Based Pr ogramm ing new Radio(); Pa r t Four Le ve r a ging the .NET Libr a r ie s } Chapterpublic 12 - Obj Car(string ect Ser ialization name, and the int .NET Remoting Lay curr) er max, int Chapter{13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - currSpeed A Better Paint = ingcurr; Fr amew or k ( GDI + ) = with max; Chapter 15 - maxSpeed Pr ogr am ming Windows Form s Contr ols name; Chapter 16 - petName The Sy stem=.I O Nam espace new Radio(); Chapter 17 - theMusicBox Data Access w ith=ADO.NET } - W e b Appl ica ti ons and X ML W e b Se r vi ces Pa r t Fi ve } Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 5

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

Alternatively, rather than duplicate the same code in each custom constructor, you could make use of the C# initializer syntax (see Chapter 3) as follows:

I ndex

List of Figur es List of Tables

// A Car has-a Radio. public class Car { private Radio theMusicBox = new Radio(); ... }

At this point, you have successfully contained another object. However, to expose the functionality of the inner class to the outside world requires delegation. Delegation is simply the act of adding members to the containing class that make use of the contained classes' functionality. For example: // Containing classes extend their public interface to provide access to // the contained classes. public class Car {

... C# anCrankTunes(bool d th e .N ET Plat f orm ,state) Se con d Ed it ion public void ISBN:1590590554 by Andr ew Tr oelsen { Apr ess © 2003 (1200 pages) // Delegate request to inner object. This compr ehensiv e text star ts w ith a brief ov er view of the theMusicBox.TurnOn(state); C# language and then quickly m oves to key technical and } ar chitectur al issues for .NET developer s.

} Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

In the following code, notice how the object user is able to interact with the hidden inner object indirectly, and

I ntr oduction is totally unaware of the fact that the Car class is making use of a private Radio instance: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

// Take this car for a test drive. - Building C# Applications public class CarApp Pa r t Tw o - The C# Pr ogr am m ing La ngua ge { Chapter 3 - C# Language Fundamentals public static int Main(string[] args) Chapter{4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions Obj ect Lifetim e makes the radio). // Make and a car (which Chapter 6 - ICar nter faces and Collections c1; Chapter 7 - Callback I nterCar("SlugBug", faces, Delegates, and 100, Ev ents 10); c1 = new Chapter 8 - Advanced Typetunes Const ruction Techniques // Jam C# some (which makes use of the radio). Pa r t Thre e - Prc1.CrankTunes(true); ogr am m i ng w i th .N ET Assem bl ie s Chapter 9 - Under // Speed standingup .NET (and Assem watch blies engine die...) for(int i = 0; i Cont < 10; Chapter 10 - Pr ocesses, AppDomains, exts,i++) and Threads c1.SpeedUp(20); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing //r a ging Shutthedown (which Pa r t Four - Le ve .NET Libr a r ie s again makes use of the radio). c1.CrankTunes(false); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er returna Bet 0; ter Win dow ( Int roducin g Window s For ms) Chapter 13 - Building } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 2

Chapter 16 - The Sy stem .I O Nam espace Chapter - Data Access w ith ADO.NET Figure 17 4-11 shows the output. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 4-11: The contained Radio in action SOURCE CODE

The Containment project is included under the Chapter 4 subdirectory.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# Definitions an d th e .N ET Plat f orm , Se con d Ed it ion Nested Type by Andr ew Tr oelsen

ISBN:1590590554

Before examiningApr theess final pillar of pages) OOP (polymorphism), let's explore a programming technique termed © 2003 (1200 nested types. In C#, it is possible to a ts type (enum, interface, This compr ehensiv e define text star w ith a briefclass, ov er view of the struct, delegate) directly within the scope of class. When you have done so, the nested type is considered a member of the nesting class, C# language and then quickly m oves to key technical and chitectur al issues formanipulated .NET developer and in the eyes ofarthe runtime can be likes.any "normal" member (fields, properties, methods, events, etc.). The syntax used to nest a type is quite straightforward: Ta ble o f Con t en t s

// C# allows classes to nest others. publicclass MyClass I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // Members of outer class. Chapter ... 1 - The Philosophy of .NET Chapter public 2 - Building C# Applications class MyNestedClass Pa r t Tw o{- The C# Pr ogr am m ing La ngua ge Chapter 3 - C#// Language Fundamentals Members of inner class. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# ... Chapter } 5 - Exceptions and Obj ect Lifetim e Chapter } 6 - I nter faces and Collections C# and t he .NET Plat for m, Second Edition

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Although syntax clean, Pa r t Thre e -the Pr ogr am misi ng w i th understanding .N ET Assem bl iewhy s

you might do this is not readily apparent. Typically, a nested type is regarded only as a helper type of the nesting type, and is not intended for use by the outside Chapter 9 - Under standing .NET Assem blies world. This is slightly along the lines of the "has-a" relationship; however, in the case of nested types, you Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads are in greater control of the inner type's visibility. In this light, nested types also help enforce encapsulation Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing services. In general, when you are attempting to model the fact that type B makes no sense outside of the Pa r t Four - Le ve r a ging the .NET Libr a r ie s context of type A, nested classes do the trick. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 Be - Building a Betwhen ter Win dow ( Intover roducin Window s For ms)(including online help samples) you may Note aware that you read theg .NET literature Chapter 14 find - A Better Paint ing Fr amew or k are ( GDI +) that nested relationships denoted in text using the dollar sign token ($). Thus, if you Chapter 15 come - Pr ogracross am ming Car$Radio, with Windows youForm are able s Contr to ols interpret this as "the Radio class is nested within the

class." As.I you willespace see during your examination of Windows Forms, the pattern of nesting Chapter 16 Car - The Sy stem O Nam other is commonplace, so make a mental note of the $ token! Chapter 17 types - Datawithin Access w ithtypes ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

To illustrate how to nest types, let's redesign your current Car application by representing the Radio as a private nested type. By doing so, you are assuming the outside world does not need to directly create a Chapter 19 - ASP.NET Web Applicat ions Radio. In other words, you are attempting to programmatically capture the idea that a Radio type makes Chapter 20 - XML Web Ser vices no sense outside of the Car to which it belongs. Here is the update: Chapter 18 - ASP.NET Web Pages and Web Contr ols

I ndex

List of Figur es

// The Car is nesting the Radio. Everything else is as before. public class Car { ... // A nested, private radio that // cannot be created by the outside world. private class Radio { public void TurnOn(bool on) { if(on) Console.WriteLine("Jamming..."); else Console.WriteLine("Quiet time..."); } } // The outer class can make instances of nested types.

List of Tables

private Radio theMusicBox = new Radio(); C# an d th e .N ET Plat f orm , Se con d Ed it ion

}

ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Notice that the Car type is able to create nested This compr ehensiv e text object star ts winstances ith a brief of ov any er view of theitem. Also notice that this class C#alanguage and then quickly m oves key be technical andprivate as well as public. Recall, has been declared private type. In C#, nested typestomay declared ar chitectur al issues for within .NET developer s. however, that classes that are directly a namespace (e.g., nonnested types) cannot be defined as private. As far as the object user is concerned, the Car type works as before. Because of the private, nested nature of the Radio, the following is now illegal:

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

// Can't do it outside the scope of the Car class! Radio r = new Radio();

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2 the - Building C#able Applications However, caller is to interact with the nested Radio type indirectly as follows: Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Car c1= new Car("SlugBug", 100, 10); - Obj ect -Or iented Pr ogr am ming w ith C# // Jam some tunes. Chapter 5 - Exceptions and Obj ect Lifetim e c1.CrankTunes(true); Chapter 4 Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

SOURCE under Pa r t Thre e - Pr ogr am mThe i ng wNested i th .N ETproject Assemis bl included ie s

the Chapter 4 subdirectory.

CODE Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ETPolymorphic Plat f orm , Se con d Ed it ion The Third Pillar: C#'s Support by Andr ew Tr oelsen

ISBN:1590590554

Switching back toApr theess employees let's now examine the final pillar of OOP: polymorphism. Assume © 2003 (1200hierarchy, pages) that the Employee base class now defines a method GiveBonus() This compr ehensiv e text star ts w ith a named brief ov er view of the as follows: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. // Employee defines a new method that gives a bonus to a given employee. public class Employee { Ta ble o f Con t en t s ... C# and t he .NET Plat for m, Second Edition public void GiveBonus(float amount) I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m currPay += amount; Chapter}1 - The Philosophy of .NET Chapter 2 - Building C# Applications } Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals Because method has been public, Chapter 4 this - Obj ect -Or iented Pr ogrdefined am mingas w ith C# you can now give bonuses to sales-persons and managers

(see Figure for output): Chapter 5 - 4-12 Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Chapter // Give 7 - each Callback child I nter faces, class Delegates, a bonus. and Ev ents

Manager Chapter 8 - chucky Advanced=C#new TypeManager("Chucky", Const ruction Techniques92, 100000, "333-23-2322", 9000); chucky.GiveBonus(300); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s chucky.DisplayStats(); Chapter 9 - Under standing .NET Assem blies SalesPerson fran AppDomains, = new SalesPerson("Fran", Chapter 10 - Pr ocesses, Cont exts, and Threads 93, 3000, "932-32-3232", 31); fran.GiveBonus(200); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing fran.DisplayStats(); Pa r t Four - Le ve r a ging the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List ofFigure Tables 4-12: The current employee hierarchy does not honor polymorphism.

The problem with the current design is that the inherited GiveBonus() method operates identically for each subclass. Ideally, the bonus of a salesperson should take into account the number of sales. Perhaps managers should gain additional stock options in conjunction with a monetary bump in salary. Given this, you are suddenly faced with an interesting question: "How can related objects respond differently to the same request?" Polymorphism is the final pillar of OOP, and it provides a way for a subclass to redefine how it responds to a method defined by its base class. To retrofit your current design, you need to revisit the use of the C# "virtual" and "override" keywords. When a base class wishes to define a method that may be overridden by a subclass, it must specify the method as virtual: public class Employee { // GiveBonus() has a default implementation, however

// child classes are free to override this behavior. C# an d th evoid .N ET GiveBonus(float Plat f orm , Se con d Ed itamount) ion public virtual ISBN:1590590554 by Andr ew Tr oelsen { currPay += amount; } ... }

Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

If a subclass wishes to redefine a virtual method, it is required to reimplement the method in question using the "override" keyword. For example:

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

public class SalesPerson : Employee { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // A salesperson's bonus is influenced by the number of sales. Chapter 1 - The Philosophy of .NET public override void GiveBonus(float amount) Chapter 2 - Building C# Applications { Pa r t Tw o - The C# Pr ogr am m ing La ngua ge int salesBonus = 0; Chapter 3 - C# Language Fundamentals if(numberOfSales >= 0 && numberOfSales = 101 && numberOfSales :-) and Web Contr ols everyone Chapter public 19 - ASP.NET Web Applicat static void ions FireThisPerson(Employee e) Chapter { 20 - XML Web Ser vices

if(eis SalesPerson)

I ndex

List of Figur es { List of Tables

Console.WriteLine("Lost a sales person named {0}", e.GetFullName() Console.WriteLine("{0} made {1} sales...", e.GetFullName(), ((SalesPerson)e).NumbSales); } if(eis Manager) { Console.WriteLine("Lost a suit named {0}", e.GetFullName()); Console.WriteLine("{0} had {1} stock options...", e.GetFullName(), ((Manager)e).NumbOpts); }

} }

Here, you make use of the "is" keyword to dynamically determine the type of employee. To gain access to the NumbSales and NumbOpts properties, you make use of an explicit cast. As an alternative, you could make use the "as" keyword to obtain a reference to the more derived type (if the types are incompatible, the reference is s

to null):

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

SalesPerson p = e as SalesPerson; Apr ess © 2003 (1200 pages) if(p != null) This compr ehensiv e text star ts w ith a brief ov er view of the Console.WriteLine("# of sales: {0}", p.NumbSales); C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

As you Ta ble Note o f Con t en t s will see in Chapter 6, these same techniques (explicit cast, "is", and "as") can be used to obtain interface reference from an implementing type. C# and t he an .NET Plat for m, Second Edition I ntr oduction

Numerical Casts

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET In addition castingC# between objects, be aware that numerical conversions follow more or less the same rules. Chapter 2 - toBuilding Applications

you are to cast "larger" numerical Pa r t Tw o -attempting The C# Pr ogr am maing La ngua ge

type to a "smaller" type (such as an integer to a byte), you must also make an explicit cast that informs the compiler you are willing to accept any possible data loss: Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

int x5 = - 30000; Chapter Exceptions and Obj ect Lifetim e byte b Chapter 6 =- I(byte)x; nter faces and Collections

// Loss of information here...

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

However, when you are storing a "smaller" numerical type into a "larger" type (such as a byte to an integer), the - Under standing .NET Assem blies type is implicitly cast on your behalf, as there is no loss of data:

Chapter 9

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

byte b = 30; int x = b;

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

// No loss of information...

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - concludes A Better Paint Fr amew or kof( GDI Cool! This ouring examination how+ )C# contends with the famed pillars of OOP. To close this chapter, Chapter 15 to - Pr ogr am with Windows Contr ols allow me point outming a few select tools Form of VSs .NET that aid in the construction of custom types. Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th eDefinitions .N ET Plat f orm , Se con d EdVisual it ion GeneratingC#Class Using Studio .NET ISBN:1590590554

by Andr ew Tr oelsen

Over the course of youpages) have seen how the C# programming language contends with the Aprthis ess chapter, © 2003 (1200 three pillars of OOP, by making use the "Keyboard Wizard" This compr ehensiv e of text star ts w ith a brief ov er (read: view oftyping the everything in by hand using a text editor). WhileC# you are always free to do this very thing, it is worth pointing out that Visual Studio .NET language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. to build initial class definitions using various GUI does provide a number of integrated tools that allow you input dialog boxes. TaTo bleillustrate o f Con t en how t s to leverage VS .NET, assume you have created a brand new console application (named

whatever mine ClassWithWizards) and wish to insert a new class definition to the C# and t he you .NETchoose-I Plat for m,called Second Edition project. Your first task is to select the Class View tab of the Solution Explorer window. From here, simply I ntr oduction right-click solution icon and | Class Pa r t One - I the nt r oduci ng C# a nd theselect .NET PAdd la tf or m Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

(Figure 4-18).

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Figure Adding a new viaroducin VS .NET Chapter 13 - 4-18: Building a Bet ter Win class dow ( Int g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr dialog ogr am ming withallow Windows Form Contr The resulting box will you to set sup the ols initial class definition. As you can see from Figure 4-19, Chapter 16 The Sy stem .I O Nam espace the Class Options link of the wizard allows you to define whether the class is sealed or abstract, public or Chapter 17and - Data w ith ADO.NET internal, any Access optional XML code documentation (see Chapter 2). Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 4-19: The Add Class Wizard The Base Class link allows you to select the name of the new type's base class. Do note that the choice of base classes will depend on the set of classes defined in the currently selected namespace (Figure 4-20).

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Chapter 3

- C# Language Fundamentals

Figure 4-20: Specifying theLabase class Pa r t Tw o - The C# Pr ogr am m ing ngua ge Finally, the (rather poorly named) Inheritance link (Figure 4-21) allows you to choose the set of interfaces Obj ect -Or iented Pr ogr am ming w ith C# (if any) the- type will implement (not inherit).

Chapter 4 Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Figure 4-21: Implementing (not inheriting) select interfaces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Once you Chapter 20 -have XMLdefined Web Seryour vicesnew class using this integrated wizard, you will find your new type is now part of your current project and is a member of the current default namespace. I ndex List of Figur es

Adding Members to Types Using Visual Studio .NET

List of Tables

VS .NET also supports the ability to add members to existing types using the Class View tab of the Solutions Explorer. To do so, simply right-click a type, and using the add menu, pick the member of your choice (field, property, method, or indexer, which will be defined in Chapter 8). Each possible option of the Add context menu will result in a unique dialog box. While I will assume you will check things out as you see fit, Figure 4-22 illustrates the result of electing to add a new method to an existing class. Do note that you are able to add any number of parameters to the member as well as configure a versioned, abstract, virtual, or static member. Of course, if your type is not defined as abstract, you cannot add an abstract member. Also, if your member is private, you cannot declare it using the "virtual" keyword.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Chapter 3

- C# Language Fundamentals

Figure 4-22: The Wizard Pa r t Tw o - The C# Pr ogr Add am mMember ing La ngua ge Chapter 4 -point Obj ect -Orshould iented have Pr ogr am mingunderstanding w ith C# So, at this you a solid of C#'s handling of the pillars of OOP (as well as Chapter 5 - Exceptions and ect Lifetim e in the process of defining custom types). The next chapter will some insights as to how VSObj .NET can aid Chapter build upon 6 - this I nter foundation faces and Collections by examining how to handle runtime anomalies using structured exception

handling showing how the CLR manages anents object's lifetime. Chapter 7 and - Callback I nter faces, Delegates, and Ev Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Summary

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

If you already come to the universe of .NET from another object-oriented language, this chapter may have Apr ess © 2003 (1200 pages) been more of a quick compare and between yourov current of choice and C#. On the This compr ehensiv e contrast text star ts w ith a brief er view language of the other hand, thoseC#of language you who are exploring OOP for the first time may have found many of the concepts and then quickly m oves to key technical and chitectur al issuesRegardless for .NET developer presented here aarbit confounding. of your s.background, rest assured that the information presented here is the foundation for any .NET application, and will be reiterated over the course of this text. Ta ble o f Con t en t s

This began with reviewEdition of the pillars of OOP: encapsulation, inheritance, and polymorphism. As C# andchapter t he .NET Plat for m, a Second youoduction have seen, C# provides full support for each aspect of object orientation. Encapsulation services can I ntr be for using accessor/ mutator Pa r t accounted One - I nt r oduci ng C# traditional a nd the .NET P la tf or m

methods, type properties, or read-only public fields.

Inheritance C# couldofnot be any simpler, given that the language does not provide a specific Chapter 1 - under The Philosophy .NET keyword, rather makes use of the simple colon operator. Last but not least, you have polymorphism, Chapter 2 but - Building C# Applications which is -supported via am them"abstract", Pa r t Tw o The C# Pr ogr ing La ngua"virtual", ge

and "new" keywords (as you recall, "new" can be applied to

members well!). Chapter 3 -asC# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# The chapter closed by illustrating some built-in tools of VS .NET that can be used to lessen reliance on the

Chapter 5 -wizard." Exceptions and the Obj mission ect Lifetim "keyboard Again, ofethis text is not to examine every aspect of VS .NET; however, you Chapter 6 I nter faces and Collections will find numerous examples throughout the remainder of the book. Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

d th e .N ET Plat f orm , Se con d Ed it ion Chapter C# 5:anExceptions and Object Lifetime ISBN:1590590554 by Andr ew Tr oelsen Apr ess ©you 2003 (1200 pages) In the previous chapter, dug into the details of how C# supports encapsulation services, reuse of code This compr ehensiv e text star ts related w ith a brief ov er view of theof this chapter is twofold. First, (inheritance), and polymorphic activity among classes. The point C# language and then quickly m oves to key technical and you will come to understand how to handle runtime anomalies in your code base through the use of ar chitectur al issues for .NET developer s. structured exception handling. Not only will you learn about the C# keywords that allow you to handle such problems ("try", "catch", "throw", "finally"), but you will also come to understand the distinction between application-level Ta ble o f Con t en t s and system-level exceptions. This discussion will also provide a lead-in to the topic of building custom exception types, as well as how to leverage the built-in exception handling functionality of C# and t he .NET Plat for m, Second Edition Visual Studio .NET. I ntr oduction

Pa r t One - I nt rhalf oduci C#chapter a nd thewill .NET P la tf or m The second ofngthe examine the process

of object lifetime management as handled by the

Chapter 1 you - The of .NET CLR. As willPhilosophy see, the .NET runtime destroys objects in a rather nondeterministic nature. Thus, you Chapter 2 Building C# Applications typically do not know when a given object will be deallocated from the managed heap, only that it will Pa r t Tw o - Thecome C# Prto ogr am m On ing La ngua ge you (eventually) pass. this note,

will come to understand how the System.Object.Finalize()

Chapter - C# Language interface Fundamentals method3 and IDisposable can be used to interact with an object's lifetime management. Finally, Chapter 4 up - Obj iented Pr ogrof amthe ming w ith C# type, and illustrate a number of ways you are able to we wrap withectan-Or examination System.GC Chapter "get involved" 5 - Exceptions with the garbage and Obj ect collection Lifetim e process. Chapter 6

- I nter faces and Collections

Callback I nter faces, Delegates, and Ev ents Ode to- Errors, Bugs, and Exceptions

Chapter 7 Chapter 8

- Advanced C# Type Const ruction Techniques

Pa Despite r t Thre ewhat - Pr ogr ouram (often m i nginflated) w i th .N ET egos Assem may bl ie tell s

us, no programmer is perfect. Writing software is a complex

undertaking, and given this.NET complexity, it is quite common for even the best software to ship with various Chapter 9 - Under standing Assem blies "problems." Sometimes the problemCont is caused byThreads "bad code" (such as overflowing the bounds of an Chapter 10 - Pr ocesses, AppDomains, exts, and array). 11 Other times, a problem caused and by bogus user inputPrthat has not Chapter - Type Reflection, LateisBinding, Attr ibuteBased ogramm ing been accounted for in the application's code base phone Pa r t Four - Le ve r a ging the (e.g., .NET a Libr a r ie s number

field assigned "Chucky"). Now, regardless of the cause of

said problem, result is that your.NET application does not work as expected. To help frame the Chapter 12 - Objthe ect end Ser ialization and the Remoting Lay er

upcoming handling, allow Chapter 13 -discussion Building a of Betstructured ter Win dowexception ( Int roducin g Window s Forme ms)to provide definitions for three common anomaly-centric terms:

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 -This Pr ogr ming with Windows Form Controfols Bugs: is,am simply put, an error on thes part the programmer. For example, assume you are Chapter 16 The Sy stem .I O Nam espace programming with unmanaged C++. If you make calls on a NULL pointer, overflow the bounds of an Chapter 17 -orData Access w ith ADO.NET array, fail to delete allocated memory (resulting in a memory leak), you have a bug. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Errors: bugs, caused by the end user of the application, rather than by those Chapter 18 - Unlike ASP.NET Web errors Pages are and typically Web Contr ols who saidWeb application. For example, an end user who enters a malformed string into a text box Chapter 19created - ASP.NET Applicat ions that a Social Security number could very well generate an error if you fail to trap this faulty Chapter 20requires - XML Web Ser vices I ndex input in your code base. List of Figur es

Exceptions: Exceptions are typically regarded as runtime anomalies that are difficult, if not impossible,

List ofto Tables prevent. Possible exceptions include attempting to connect to a database that no longer exists,

opening a corrupted file, or contacting a machine that is currently offline. In each of these cases, the programmer (and end user) has little control over these "exceptional" circumstances. Given the previous definitions, it should be clear that .NET structured exception handling is a technique best suited to deal with runtime exceptions. However, as for the bugs and errors that have escaped your view, do be aware that the CLR will generate a corresponding exception that identifies the problem at hand. As you will see, the .NET base class libraries define exceptions such as OutOfMemoryException, IndexOutOfRangeException, FileNotFoundException, ArgumentOutOfRangeException, and so forth. Before we get too far ahead of ourselves, let's formalize the role of structured exception handling and check out how it differs from traditional error handling techniques.

an d thException e .N ET Plat f ormHandling , Se con d Ed it ion The Role ofC#.NET ISBN:1590590554

by Andr ew Tr oelsen

Error handling among developers has grown into a confused mishmash of techniques over the Apr essWindows © 2003 (1200 pages) years. Many programmers roll their own error logic within context of a given application. For This compr ehensiv e text star ts handling w ith a brief ov er view the of the example, a development team may define a set of numerical constants C# language and then quickly m oves to key technical and that represent known error ar chitectur al them issuesas formethod .NET developer s. conditions, and make use of return values. For example, ponder the following C code: /* A very C-style error trapping mechanism. */ #defineE_FILENOTFOUND 1000

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntr oduction

int SomeFunction() { Chapter// 1 Assume - The Philosophy of .NEThappens in this f(x) something Chapter// 2 which - Building C# Applications causes the following return value. Pa r t Twreturn o - The C#E_FILENOTFOUND; Pr ogr am m ing La ngua ge Chapter 3 - C# Language Fundamentals } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - Exceptions and Obj ect Lifetim e void Main() Chapter { 6 - I nter faces and Collections

SomeFunction(); Chapterint 7 - retVal Callback I=nter faces, Delegates, and Ev ents ==C#E_FILENOTFOUND) Chapterif(retVal 8 - Advanced Type Const ruction Techniques { eprintf("Can not find file...");} Pa r t Thre - Pr ogr am m i ng w i th .N ET Assem bl ie s } Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

This approach is less than ideal, given the fact that the constant E_FILENOTFOUND is little more than a raw numerical value, and is far from being a self-describing agent. Ideally, you would like to encapsulate Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er the name, message, and other helpful information regarding this error condition into a single, well-defined Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) package (which is exactly what happens under structured exception handling). Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter In addition 15 - toPrthis ogr am ad ming hoc technique, with Windows theForm Windows s Contr API olsdefines hundreds of error codes that come by way of

#defines, far too many variations on the simple Boolean (bool, BOOL, VARIANT_BOOL, Chapter 16 HRESULTs, - The Sy stemand .I O Nam espace and so 17 on). many C++ developers (and indirectly, many VB 6.0 COM developers) have made Chapter - Also, Data Access w ith COM ADO.NET use set of interfaces (e.g., Pa r t Fiof vea -small W e b Appl icastandard ti ons and COM X ML W e b Se r vi ces

ISupportErrorInfo, IErrorInfo, ICreateErrorInfo) to

return meaningful error a COM client using a COM error object. Chapter 18 - ASP.NET Webinformation Pages and to Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

The obvious problem with these previous techniques is the tremendous lack of symmetry. Each approach is more or less tailored to a given technology, a given language, and perhaps even a given project. In I ndex order to put an end to this madness, the .NET platform provides exactly one technique to send and trap List of Figur es runtime errors: structured exception handling (SEH). Chapter 20 - XML Web Ser vices

List of Tables

The beauty of this approach is that developers now have a well-defined approach to error handling, which is common to all languages targeting the .NET universe. Therefore, the way in which a C# programmer handles errors is conceptually similar to that of a VB .NET programmer, and a C++ programmer using managed extensions (MC++). As an added bonus, the syntax used to throw and catch exceptions across assemblies, AppDomains (defined in Chapter 10), and machine boundaries is identical. Another bonus of .NET exceptions is the fact that rather than receiving a cryptic numerical value that identifies the problem at hand, exceptions are objects that contain a human-readable description of the problem, as well as a detailed snapshot of the call stack that eventually triggered the exception in the first place. Furthermore, you are able to provide the end user with help link information that points the user to a URL that provides detailed information regarding the error at hand.

The Atoms of .NET Exception Handling Programming with structured exception handling involves the use of four key (and interrelated) elements:

A type that represents the details of the exceptional circumstance C# an d th e .N ET Plat f orm , Se con d Ed it ion

bythrows Andr ewthe Tr oelsen A method that exception to the caller

ISBN:1590590554

Apr ess © 2003 (1200 pages)

A block of code willehensiv invokeethe method Thisthat compr textexception-ready star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

A block of code that willalprocess (or.NET catch) the exception (should it occur) ar chitectur issues for developer s. As you will see, the C# programming language offers four keywords ("try", "catch", "throw", and "finally") allow Tathat ble o f Conyou t en ttos throw and handle exceptions. The type that represents the problem at hand is a class derived from System.Exception a descendent thereof). Given this fact, let's check out the role of this C# and t he .NET Plat for m, Second (or Edition exception-centric base class. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm ,Class Se con d Ed it ion The System.Exception Base ISBN:1590590554

by Andr ew Tr oelsen

All system-supplied exceptions ultimately derive from the System.Exception base class (which Apr and ess ©custom 2003 (1200 pages) in turn derives from System.Object). As you C# definition of this type, This compr ehensiv e text starcan ts w see ith a from brief the ov erfollowing view of the System.ExceptionC#also implements a standard interface named ISerializable; however, ignore this fact for language and then quickly m oves to key technical and ar chitectur al issues for .NET developer the time being (given that this interface has more to dos.with .NET Remoting than SEH). public class Exception : object, ISerializable C# and t he .NET Plat for m, Second Edition { I ntr oduction public Exception(); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public Exception(string message); Chapter 1 - The Philosophy of .NET public Exception(string message, Exception innerException); Chapter 2 Building C# HelpLink Applications { virtual get; virtual set; } public string Pa r t Tw o - The C# Pr ogr am m ing La ngua ge public Exception InnerException { get; } Chapter 3 - C#string Language Fundamentals public Message { virtual get; } Chapter 4 - Obj ect -Or iented Pr ogr am w ith C# public string Source { ming virtual get; virtual set; } Chapter 5 - Exceptions Obj ect Lifetim public string and StackTrace {e virtual get; } Chapter public 6 - I nter MethodBase faces and Collections TargetSite { get; } public virtual Equals(object obj); Chapter 7 - Callback I nterbool faces, Delegates, and Ev ents public virtual Exception GetBaseException(); Chapter 8 - Advanced C# Type Const ruction Techniques public virtual int GetHashCode(); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s public virtual void Chapter 9 - Under standing .NET Assem blies info, StreamingContext context); Chapter 10 GetObjectData(SerializationInfo - Pr ocesses, AppDomains, Cont exts, and Threads public Type GetType(); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing public Pa r t Four - Le vevirtual r a ging the string .NET Libr aToString(); r ie s } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Ta ble o f Con t en t s

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter A Better Paint amew or k defined ( GDI + ) by System.Exception are read-only in nature. This is due to As you 14 can- see, many of ing the Fr members Chapter 15 Pr ogr am ming with Windows Form s Contr olsdefault values for each property (for example, the the simple fact that derived types will typically supply Chapter - The Syofstem O Nam espace default 16 message the .IIndexOutOfRangeException type is "Index was outside the bounds of the array"). Chapter 17 Data Access w ith default ADO.NET As you would expect, these values can be altered and extended with custom information via Pa r t Fi ve - W eparameters. b Appl ica ti ons and X MLdescribes W e b Se r vithe ces core constructor Table 5-1

members of System.Exception.

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - Core ASP.NET Web Applicat Table 5-1: Members of theions System.Exception Type Chapter 20 - XML Web Ser vices

System.Exception Property

I ndex

Meaning in Life

List of Figur es ListHelpLink of Tables

This property returns a URL to a help file describing the error in gory detail.

InnerException

This read-only property can be used to obtain information about the previous exceptions that caused the current exception to occur. The previous exceptions are documented by passing them into the constructor of the most current exception.

Message

This read-only property returns the textual description of a given error. The error message itself is set as a constructor parameter.

Source

This property returns the name of the assembly that threw the exception.

StackTrace

This read-only property contains a string that identifies the sequence of calls that triggered the exception. As you might guess, this property is very useful during debugging.

TargetSite

read-only property returns C# an d th e .NThis ET Plat f orm , Se con d Ed it ion a MethodBase type, which describes numerous details about the method that threw the exception ISBN:1590590554 by Andr ew Tr oelsen (ToString() will identify the method by name). Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .NException ET Plat f orm , Se con d Ed it ion Throwing aC#Generic by Andr ew Tr oelsen

ISBN:1590590554

To illustrate the simplest System.Exception, let's revisit the Car class defined in Chapter 4, in Apr ess ©use 2003of (1200 pages) particular, the SpeedUp() method. Here is current implementation: This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and al issues for .NET developer s. // Currently,ar chitectur SpeedUp() reports errors using console IO. public void SpeedUp(int delta) { Ta ble o f Con t en t s // If the car is dead, just say so... C# and t he .NET Plat for m, Second Edition if(carIsDead) I ntr oduction Console.WriteLine("{0} is out of order....", petName); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m else // Not dead, speed up. Chapter { 1 - The Philosophy of .NET Chapter 2 - Building C# Applications currSpeed += delta; Pa r t Tw o - The C# Pr ogr am m ing La ngua ge if(currSpeed >= maxSpeed) Chapter 3 - C#{ Language Fundamentals Chapter 4 - Obj ect -OrConsole.WriteLine("{0} iented Pr ogr am ming w ith C# has overheated...", petName); Chapter 5 - Exceptions and Obj ect Lifetim e carIsDead = true; Chapter 6 - I nter } faces and Collections else I nter faces, Delegates, and Ev ents Chapter 7 - Callback CurrSpeed = {0}", currSpeed); Chapter 8 - AdvancedConsole.WriteLine("=> C# Type Const ruction Techniques } Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s } Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Now, let's retrofit SpeedUp() to throw an exception if the user attempts to speed up the automobile after it has met its maker (carIsDead == true). First, you want to create and configure a new instance of the Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er System.Exception class, setting the value of the read-only Message property via the class constructor. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) When you wish to send the error object back to the caller, make use of the C# "throw" keyword. Here is Chapter 14 - Acode Better Paint ing Fr amew or k ( GDI + ) the relevant update: Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

// This time, throw an exception if the user speeds up a trashed automobile. public void SpeedUp(int delta) Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces { Chapter if(carIsDead) 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET ions throwWeb newApplicat Exception("This car is already dead..."); Chapter else 20 - XML Web Ser vices I ndex { ... } List } of Figur es Chapter 17 - Data Access w ith ADO.NET

List of Tables

Before examining how to catch this exception, a few points of interest. First of all, when you are building a custom type, it is always up to you to decide exactly what constitutes an exception, and when it should be thrown. Here, you are making the assumption that if the program attempts to increase the speed of a car that has expired, a System.Exception type should be thrown to indicate the SpeedUp() method cannot continue (which may or may not be a valid assumption). Alternatively, you could implement SpeedUp() to recover automatically without needing to throw an exception in the first place. By and large, exceptions should be thrown only when a more terminal condition has been met (for example, the inability to allocate a block of unmanaged memory, not finding a necessary file, failing to connect to a database, and whatnot). Deciding exactly what constitutes throwing an exception is a design issue you must always contend with. For our current purposes, assume that asking a doomed automobile to increase its speed justifies a cause for an exception.

C# an d th e .N ET Plat f orm , Se con d Ed it ion Catching Exceptions by Andr ew Tr oelsen

ISBN:1590590554

Because the SpeedUp() now throws an exception, you need to be ready to handle the exception Apr ess ©method 2003 (1200 pages) should it occur (you'll see what happens you anerexception This compr ehensiv e text if star ts fail w ithtoa catch brief ov view of thea bit later in this chapter). When you are calling a C# method that may throw an exception, you make useand of a try/catch block. Once you have language and then quickly m oves to key technical ar chitectur al issues for .NET developer s. members of the System.Exception type. What you caught the exception type, you are able to invoke of the do with this information is largely up to you. You may wish to log this information to a given file, write the error to the Windows event log, or display the message to the end user. Here, you will simply dump the Tacontents ble o f Con en t s totthe console window: C# and t he .NET Plat for m, Second Edition I ntr oduction

// Speed up the car safely... public static int Main(string[] args) Chapter 1 - The Philosophy of .NET { Chapter // 2 - Make Building Applications a C# car. Pa r t Tw oCar - Thebuddha C# Pr ogr= amnew m ing Car("Buddha", La ngua ge 100, 20); Chapter // 3 - Speed C# Language Fundamentals up past the car's max speed to Chapter // 4 - trigger Obj ect -Or iented Pr ogr am ming w ith C# the exception. Chapter try 5 - Exceptions and Obj ect Lifetim e Chapter { 6 - I nter faces and Collections for(int = 0; i < 10; Chapter 7 - Callback I nter i faces, Delegates, and i++) Ev ents buddha.SpeedUp(10); Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre}e - Pr ogr am m i ng w i th .N ET Assem bl ie s e)Assem blies Chapter catch(Exception 9 - Under standing .NET { Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Console.WriteLine("\n*** ***"); Chapter 11 - Type Reflection, Late Binding, and Attr Error! ibute- Based Pr ogramm ing Console.WriteLine("Method: {0}", e.TargetSite); Pa r t Four - Le ve r a ging the .NET Libr a r ie s Console.WriteLine("Message: {0}", e.Message); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Console.WriteLine("Source: {0}", e.Source); Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) // The error has been handled, continue on with the flow of this app... Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Console.WriteLine("\n***** Out of exception logic *****"); Chapter 16 - The Sy stem .I O Nam espace return 0; Chapter 17 - Data Access w ith ADO.NET } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter In essence, 19 - ASP.NET a try block Web is aApplicat section ions of code that is on the lookout for any exception that may be

encountered during scope. Chapter 20 - XML Webits Ser vices If an exception is detected, the flow of program execution is sent to the appropriate catch block. On the other hand, if the code within a try block does not trigger an exception, the I ndex catch block List of Figur es is skipped entirely, and all is right with the world. Figure 5-1 shows a test run of the handled error. List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Figure 5-1: Dealing with the error using structured exception handling

Chapter 3

- C# Language Fundamentals

Chapter Obj ect -Or iented Pr ogr amhas mingbeen w ith handled, C# As you 4can- see, once an exception the application is free to continue on from the point Chapter 5 Exceptions and Obj ect Lifetim e after the catch block. In some circumstances, a given exception may be critical enough to warrant the Chapter 6 - of I nter and Collections termination thefaces application. However, in a good number of cases, the logic within the exception handler Chapter 7 Callback I nter Delegates, and Ev ents will ensure the applicationfaces, will be able to continue on its merry way (although it may be slightly less Chapter 8 - such Advanced Type ruction Techniques functional, as theC#case ofConst not being able to connect to a remote data source). Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies The TargetSite Property

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ingyou to determine the name of the As you 11 have just seen, the System.Exception.TargetSite property allows Pa r t Four that - Le ve r a ging .NET Libr a r ie s method threw thethe current exception.

Understand, however, that TargetSite does not simply return a

Chapter 12 - Obj ect Ser ialization and the .NETSystem.Reflection.MethodBase Remoting Lay er vanilla-flavored string, but a strongly typed class. This abstract type can be Chapter used to13 gather - Building numerous a Bet ter details Win dow regarding ( Int roducin the offending g Window smethod For ms) as well as the class that defines the

offending illustrate, assume catch logic has been updated as follows: Chapter 14 method. - A BetterTo Paint ing Fr amew or k ( the GDI previous +) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy steme) .I O Nam espace catch(Exception Chapter { 17 - Data Access w ith ADO.NET Pa r t Fi veConsole.WriteLine("\n*** - W e b Appl ica ti ons and X ML W e b Se Error! r vi ces

***");

defining member: {0}", Chapter Console.WriteLine("Class 18 - ASP.NET Web Pages and Web Contr ols e.TargetSite.DeclaringType); Chapter 19 - ASP.NET Web Applicat ions type: {0}", e.TargetSite.MemberType); Chapter Console.WriteLine("Member 20 - XML Web Ser vices Console.WriteLine("Member name: {0}", e.TargetSite); Console.WriteLine("Message: {0}", e.Message); List of Figur es Console.WriteLine("Source: {0}", e.Source); List of Tables } I ndex

This time, you make use of the MethodBase.DeclaringType property to determine the fully qualified name of the class that threw the error (SimpleException.Car in this case) as well as the MethodBase.MemberType property to identify the type of member (such as a property versus a method) where this exception originated. Figure 5-2 shows the updated output.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter Figure 4 - 5-2: Obj ect Obtaining -Or ienteddetailed Pr ogr amerror ming information w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

As you may be aware, the ability to discover information regarding the structure of a type is a form of RTTI - Callback I nter faces, Delegates, and Ev ents (runtime type identification). The .NET base class library supplies an entire namespace devoted to the Chapter - Advanced C# Type Const ruction topic of8RTTI named System.Reflection (in Techniques fact, MethodBase is defined within System.Reflection). Chapter Pa r t will Threexamine e - Pr ogrthe am m i ng w iof th .NET .N ET Assem bl ie sservices. For the time being, simply understand that the 11 details reflection Chapter 9 - Under standing .NET Assem blies System.Exception.TargetSite property allows you to discover a number of details about the method that Chapter 10 the - Prexception ocesses, AppDomains, Cont exts, and Threads triggered at hand. Chapter 7

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

The StackTrace Property

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - toBuilding a Betthe ter type Win dow Int roducinthat g Window ms)exception via TargetSite, the In addition identifying and (member threw sa For given Chapter 14 - A Better Paint ing Fr amew or k allows ( GDI + ) you to identify the series of calls that resulted in the System.Exception.StackTrace property Chapter 15 -To Pr ogr am mingassume with Windows Form s Contr ols updated your catch logic: exception. illustrate, you have once again Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access catch(Exception e)w ith ADO.NET Pa {r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter ... 18 - ASP.NET Web Pages and Web Contr ols Chapter Console.WriteLine("Stack: 19 - ASP.NET Web Applicat ions {0}", e.StackTrace); Chapter 20 - XML Web Ser vices } I ndex List of Figur es

If you were to run the program, you would find the following line printed to the console (assuming the List of Tables application is located under the C:\MyApps\Exception directory):

Stack: at SimpleException.Car.SpeedUp(Int32 delta) in c:\myapps\exceptions\car.cs:line 65 at Exceptions.App.Main() in c:\myapps\exceptions\app.cs:line 21

As you can see, the System.String returned from StackTrace documents the sequence of calls that resulted in the throwing of this exception. Notice how the bottommost line number of this string identifies the first call in the sequence, while the topmost line number identifies the exact location of the offending member. Clearly, this information can be quite helpful during the debugging of a given application, as you are able to "follow the flow" of the error's origin.

The HelpLink Property

While the TargetSite and StackTrace allow programmers to gain an understanding of a given C# an d th e .N ET Platproperties f orm , Se con d Ed it ion exception, this information is of little use to the end user. As you have already seen, the ISBN:1590590554 by Andr ew Tr oelsen System.Exception.Message property can be used to obtain human-readable information that may be Apr ess © 2003 (1200 pages) displayed to the current user. In addition, the HelpLink property can be set to point the user to a given URL This compr ehensiv e text star ts w ith a brief ov er view of the or standard Win32 file that moremdetailed information. C#help language andcontains then quickly oves to key technical and ar chitectur al issues for .NET developer s.

By default, the value managed by the HelpLink property is an empty string. If you wish to fill this property with a relevant value, you will need to do so before throwing the System.Exception type. Here is the update Tarelevant ble o f Con t en t sto the SpeedUp() method: C# and t he .NET Plat for m, Second Edition

if(carIsDead) I ntr oduction {r t One - I nt r oduci ng C# a nd the .NET P la tf or m Pa ex = ofnew Chapter Exception 1 - The Philosophy .NETException("Error information can be found at:"); "http://www.CarsRUs.com"; Chapter ex.HelpLink 2 - Building C# = Applications Pa r t Tw othrow - The C#ex; Pr ogr am m ing La ngua ge

} Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

Exceptions and Obj ect Lifetim e The catch -logic, of course, would print out this help link information as follows:

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

catch(Exception e) Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s ... Chapter 9 - Under standing .NET Assem blies Console.WriteLine("Help Link: {0}", e.HelpLink); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

SOURCE SimpleException project is included under the Chapter 5 subdirectory. Chapter 13 - Building aThe Bet ter Win dow ( Int roducin g Window s For ms) CODE Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se (System.SystemException) con d Ed it ion CLR System-Level Exceptions ISBN:1590590554

by Andr ew Tr oelsen

As mentioned, the .NET classpages) libraries already define a number of exception classes. For example, Apr ess ©base 2003 (1200 the System namespace defines numerous general such This compr ehensiv e text star ts w ith exception a brief ov ertypes view of the as ArgumentOutOfRangeException, IndexOutOfRangeException, StackOverflowException, and so forth. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. Other namespaces define additional exceptions that reflect the behavior of that namespace (e.g., System.Drawing.Printing defines printing exceptions, System.IO defines IO-based exceptions, System.Data defines data-centric exceptions, and so forth). Ta ble o f Con t en t s

Exceptions thatPlat arefor thrown by methods C# and t he .NET m, Second Edition in the base class libraries are (appropriately) called system exceptions. I ntr oduction System exceptions generally (but sadly not always) derive directly from a base class named System.SystemException, which in turn Pa r t One - I nt r oduci ng C# a nd the .NET P laderives tf or m

from System.Exception (which of course derives from

System.Object): Chapter 1 - The Philosophy of .NET Chapter 2

- Building C# Applications

Pa public r t Tw o - The class C# PrSystemException ogr am m ing La ngua ge :

Exception, ISerializable Chapter 3 - C# Language Fundamentals { Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# SystemException(); Chapterpublic 5 - Exceptions and Obj ect Lifetim e public SystemException(string message); Chapter 6 - I nter faces and Collections public SystemException(string message, Exception innerException); Chapter 7 - Callback I nter faces, Delegates, and Ev ents public string HelpLink { virtual get; virtual set; } Chapter 8 - Advanced C# Type Const ruction Techniques public Exception InnerException { get; } Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s public string Message { virtual get; } Chapter 9 - Under standing .NET Assem blies public string Source { virtual get; virtual set; } Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads public string StackTrace { virtual get; } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing public MethodBase TargetSite { get; } Pa r t Four - Le ve r a ging the .NET Libr a r ie s public virtual bool Equals(object obj); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er public virtual Exception GetBaseException(); Chapterpublic 13 - Building a Bet ter Win GetHashCode(); dow ( Int roducin g Window s For ms) virtual int Chapterpublic 14 - A Better Paint ing Fr amew or k ( GDI + ) virtual void Chapter 15 - GetObjectData(SerializationInfo Pr ogr am ming with Windows Form s Contr ols info, StreamingContext context); Chapterpublic 16 - TheType Sy stemGetType(); .I O Nam espace Chapterpublic 17 - Data Access w ith ADO.NET virtual string ToString(); Pa }r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Given that System.SystemException type does not add any additional functionality beyond that of Chapter 20 -the XML Web Ser vices

System.Exception, you might wonder why SystemException exists in the first place. The idea is that when an exception type derives from System.SystemException, you are able to determine that the .NET runtime List of Figur es is the entity that has thrown the exception, rather than the custom code base of the executing application. List of Tables As you will see in just a bit, however, there is a lack of consistency within the .NET base class libraries regarding this pattern. I ndex

Locating System Exceptions While it is nice to know that System.SystemException provides a way to identify the underlying source of the error, the next logical question would be "How do I know which exceptions may be thrown by a given base class library method?" The ultimate answer to that question is simple: Use online help. For example, if you were to look up the File.Open() method, you would find a table that describes the set of possible system exceptions that may be thrown should an error occur (Figure 5-3).

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le5-3: ve r a ging the .NET a r ie s Figure Identifying theLibr exceptions

thrown from a given method

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

For those to Paint .NETing from a Java Chapter 14 coming - A Better Fr amew or k mindset, ( GDI + ) understand that a method is not prototyped with the set of exceptions it may emit. Therefore you are not required to handle each and every possible exception that may be thrown from a given member. As you will see in just a bit, if you fail to handle a raised exception, Chapter 16 - The Sy stem .I O Nam espace the operating system will trigger a "last chance exception." Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Custom Application-Level Exceptions (System.ApplicationException) by Andr ew Tr oelsen

ISBN:1590590554

Now that you understand the proposed Apr ess © 2003 (1200 pages)role of System.SystemException (to identify CLR exceptions), you may wonder if it isThis possible to buildecustom for use compr ehensiv text starexceptions ts w ith a brief ov erwithin view ofyour the proprietary applications. The answer is a resounding "yes." In fact, the .NET base class library defines C# language and then quickly m oves to key technical and another System.Exception derived ar chitecturenough) al issues for .NET developer s. type named (appropriately System.ApplicationException: public class ApplicationException : Exception, ISerializable C# and t he .NET Plat for m, Second Edition { I ntr oduction public ApplicationException(); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public ApplicationException(string message); Chapterpublic 1 - TheApplicationException(string Philosophy of .NET message, Exception innerException); Chapterpublic 2 - Building C# Applications string HelpLink { virtual get; virtual set; } Pa r t Twpublic o - The C#Exception Pr ogr am m ing La ngua ge InnerException { get; } Chapterpublic 3 - C# string Language Message Fundamentals { virtual get; } Chapterpublic 4 - Obj string ect -Or iented Pr ogr am{ming w ith C# get; virtual set; } Source virtual Chapterpublic 5 - Exceptions Obj ect Lifetim { e virtual get; } stringand StackTrace Chapterpublic 6 - I nter MethodBase faces and Collections TargetSite { get; } virtual boolDelegates, Equals(object Chapterpublic 7 - Callback I nter faces, and Ev ents obj); public virtual Exception GetBaseException(); Chapter 8 - Advanced C# Type Const ruction Techniques public virtual GetHashCode(); Pa r t Thre e - Pr ogr am m i ng w int i th .N ET Assem bl ie s public virtual void Chapter 9 - Under standing .NET Assem blies info, StreamingContext context); Chapter 10 - GetObjectData(SerializationInfo Pr ocesses, AppDomains, Cont exts, and Threads public Type GetType(); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing public virtual string ToString(); Pa r t Four - Le ve r a ging the .NET Libr a r ie s } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Ta ble o f Con t en t s

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI +does ) Like SystemException, ApplicationException not add any additional functionality beyond the inherited Chapter 15 Pr ogr am ming with Windows Form s Contr members of System.Exception. Again, the only realols role of System.ApplicationException is to identify the Chapter 16 - source The Sy stem Nam When espaceyou handle an exception deriving from System.ApplicationException, underlying of the.I O error. Chapter 17 Data Access w ith ADO.NET you can (ideally) assume the exception was raised by the code base of the executing application, rather than Pa r t the Fi ve.NET - W e base b Applclass ica ti ons and X ML W e b Se r vi ces by libraries.

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Figure 19 5-4- illustrates the relationship Chapter ASP.NET Web Applicat ions between these key exception-centric base classes. Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Figure 5-4: Application and system exceptions

Pa Strictly r t Threspeaking, e - Pr ogr am when m i ngyou w i th create .N ET Assem your own bl ie custom s

.NET exception types, you are not required to derive

from System.ApplicationException. If you Chapter 9 - Under standing .NET Assem bliesso choose, you are able to simply derive from the more generic System.Exception (andAppDomains, if you really wanted to,and nothing would stop you from deriving from Chapter 10 - Pr ocesses, Cont exts, Threads System.SystemException . butBinding, don't doand so!Attr ). To understand the various Chapter 11 - Type Reflection,. .Late ibuteBased Pr ogramm ing possibilities, let's build a custom exception type. Pa r t Four - Le ve r a ging the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Building Custom Exceptions, Take One

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Although throw instances to signal a runtime error (as seen in the Chapter 15 you - Pr could ogr am simply ming with Windows Formof s System.Exception Contr ols previous it is .Isometimes advantageous to build a custom class that encapsulates the unique Chapter 16example), - The Sy stem O Nam espace

details 17 of your problem. For Chapter - Data Access w ith example, ADO.NET assume you wish to build a custom exception to represent the error of speeding upe ba Appl doomed automobile. Pa r t Fi ve - W ica ti ons and X ML W e b Se r vi ces Chapter 18 - ASP.NET Web Pages and Web Contr ols

The first approach we will look at involves defining a new class derived directly from System.Exception (by

Chapter 19 - ASP.NET Web types Applicat ions convention, all exception end with an "Exception" suffix). Like any class, you are free to include any Chapter 20 XML Web Ser vices custom properties, methods, or fields that can be used from within the catch block of the calling logic. You I ndex are also free to override any virtual members defined by your parent class: List of Figur es List Tablescustom exception describes the details of the car-is-dead condition. //ofThis

public class CarIsDeadException : System.Exception { // This custom exception maintains the name of the doomed car. private string carName; public CarIsDeadException(){ } public CarIsDeadException(string carName) { this.carName = carName; } // Override the Exception.Message property. public override string Message { get { string msg = base.Message;

if(carName != null)

} }

C# an d th emsg .N ET+= Plat f orm , Se con it ion carName + "d Ed has bought the farm..."; ISBN:1590590554 by Andr ew Tr oelsen return msg; Apr ess © 2003 (1200 pages) } This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Here, the CarIsDeadException type maintains a private data member that holds the pet name of the car that threw the exception. You have also added two constructors to the class, and overridden the virtual Message C# and t he .NET Plat for m, Second Edition property in order to include the pet name of the car in the description. Throwing this error from within I ntr oduction is straightforward: SpeedUp()

Ta ble o f Con t en t s

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

// Throw the custom CarIsDeadException. - Building C# Applications public void SpeedUp(int delta) Pa r t Tw o - The C# Pr ogr am m ing La ngua ge { Chapter 3 - C# Language Fundamentals // If the car is dead, just say so... Chapter if(carIsDead) 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter { 5 - Exceptions and Obj ect Lifetim e Chapter 6 - I nter and Collections //faces Throw 'car is dead' exception. Chapter 7 - Callback I nter faces, Delegates, and Ev ents throw new CarIsDeadException(this.petName); Chapter } 8 - Advanced C# Type Const ruction Techniques Pa r t Threelse e - Pr ogr am m w i th dead, .N ET Assem bl ie s up. //i ngNot speed Chapter { 9 ... - Under } standing .NET Assem blies } Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 2

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Catching the custom exception is just as easy:

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

try 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter {... } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols catch(CarIsDeadException e) { Chapter 17 - Data Access w ith ADO.NET Console.WriteLine("Method: {0}", e.TargetSite); Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Console.WriteLine("Message: {0}", e.Message); Chapter 18 - ASP.NET Web Pages and Web Contr ols } Chapter 16 - The Sy stem .I O Nam espace

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex

List Figur es you understand the basic process of defining a custom exception, you may wonder if you are So,ofnow that List required of Tables to do so. Typically, you only need to create custom exceptions when the error is tightly bound to the

class issuing the error (for example, a File class that throws a number of file-related errors, a Car class that throws a number of car-related errors, and so forth). In doing so, you provide the caller with the ability to handle numerous exceptions on a name-by-name basis (as seen in just a bit).

Building Custom Exceptions, Take Two Our current CarIsDeadException type has overridden the System.Exception.Message property in order to configure a custom error message. This class also has an overloaded constructor that accepts the pet name of the automobile that has currently met its maker. As you build custom exceptions, you are able to build the type as you see fit. However, the recommended approach is to build a relatively simple type that supplies three named constructors matching the following signature: public class CarIsDeadException : System.Exception { public CarIsDeadException(){ }

public CarIsDeadException(string message) C# an d th e .N ET Plat : base(message){ } f orm , Se con d Ed it ion ISBN:1590590554 by Andr ew Tr oelsen // Just in case the CarIsDeadException is generated by Apr ess © 2003 (1200 pages) // another exception, the previous exception can be passed in compr ehensiv parameter. e text star ts w ith a brief ov er view of the // as a This constructor C# language and then quickly m oves message, to key technical and public CarIsDeadException(string Exception innerEx) ar chitectur al issues for .NET developer s. : base(message, innerEx){ } } Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

Notice that this time you have not provided a private string to hold the pet name, and have not overridden the

I ntr oductionproperty. Rather, you are simply passing all the relevant information to your base class. When you Message Pa r t One - I nt r oduci ng C# a nd tf orwould m wish to throw an exception ofthe this.NET type,P la you

send in all necessary information as a constructor

Chapter 1 -(the Theoutput Philosophy .NET argument wouldofbe identical): Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

public void SpeedUp(int delta) - C# Language Fundamentals { Chapter ... 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter if(carIsDead) 5 - Exceptions and Obj ect Lifetim e Chapter { 6 - I nter faces and Collections Chapter 7 - Callback I nterpet faces,name Delegates, Ev ents as ctor argument. // Pass and and message Chapter 8 - Advanced Const ruction Techniques throw C# newType CarIsDeadException(this.petName + " has bought the farm!"); Pa r t Thre}e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter else 9 - Under standing // Not .NET dead, Assemspeed blies up. Chapter {... 10 - Pr } ocesses, AppDomains, Cont exts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Chapter 3

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Using this design, this custom exception is little more than a uniquely named class, devoid of any unnecessary member variables (or overrides). Don't be surprised if most (if not all) of your custom exception Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) classes follow this pattern. Many times, the role of a custom exception is not necessarily to provide additional Chapter 15 - Pr ogr am ming with Windows Form s Contr ols functionality beyond what is inherited from the base class, but to provide a strongly named type that clearly Chapter 16 - The Sy stem .I O Nam espace identifies the nature of the error. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Building Custom Exceptions, Take Three

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Recall the exceptions can be categorized as system-level or application-level types. If you wish to clearly mark the fact that the CarIsDeadException is a type thrown by the application itself (rather than the base I ndex class libraries), you are free to retrofit the type definition as follows: Chapter 20 - XML Web Ser vices List of Figur es List of Tables

public class CarIsDeadException : ApplicationException { // Constructors for this custom exception. public CarIsDeadException(){ } public CarIsDeadException(string message) : base(message){ } public CarIsDeadException(string message, Exception innerEx) : base(message, innerEx){ } }

Once you have done so, the logic that handles the CarIsDeadException is unchanged. Again, we'll look at the process of identifying the underlying nature of a generated exception in just a bit. Until then, let's check how to handle multiple exceptions.

C# an d th eExceptions .N ET Plat f orm , Se con d Ed it ion Handling Multiple by Andr ew Tr oelsen

ISBN:1590590554

In its simplest form, try©block haspages) a single corresponding catch block. In reality, you 23often run into a situation Apra ess 2003 (1200 where the code within a try block could For example, assume the car's This compr ehensiv e texttrigger star ts numerous w ith a briefpossible ov er viewexceptions. of the SpeedUp() method not only throws an exception when you attempt to speed up a doomed automobile, but throw C# language and then quickly m oves to key technical and ar chitectur al issues .NET developer s. a system-level exception if you sendfor in an invalid parameter (which for the sake of argument is any number less than zero): Ta ble o f Con t en t s

// Test for bad parameter. public void SpeedUp(int delta) I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // Bad param? Throw system supplied exception! Chapter if(delta 1 - The Philosophy < 0) of .NET Chapter 2 - Building Applications throw C# new ArgumentOutOfRangeException("Speed must be greater than zero!" Pa r t Tw oif(carIsDead) - The C# Pr ogr am m ing La ngua ge Chapter { 3 - C# Language Fundamentals Chapter 4 - Obj ect Throw -Or iented'Car Pr ogr am w ith application C# // isming dead' exception. Chapter 5 - Exceptions and Obj ect Lifetim e throw new CarIsDeadException(this.petName + " has bought the farm!"); Chapter } 6 - I nter faces and Collections Chapter ... 7 - Callback I nter faces, Delegates, and Ev ents } Chapter 8 - Advanced C# Type Const ruction Techniques C# and t he .NET Plat for m, Second Edition

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

The calling logic would look like this:

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

// Here, weect are on the and lookout multiple Chapter 12 - Obj Ser ialization the .NETfor Remoting Lay er exceptions. try {

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

for(int i = 0; i < 10; i++) buddha.SpeedUp(10);

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

} catch(CarIsDeadException e) Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces { Chapter Console.WriteLine("Method: 18 - ASP.NET Web Pages and Web Contr ols {0}", e.TargetSite); Chapter Console.WriteLine("Message: 19 - ASP.NET Web Applicat ions {0}", e.Message); Chapter 20 - XML Web Ser vices } I ndex catch(ArgumentOutOfRangeException e) List { of Figur es List of Tables Console.WriteLine("Method: {0}", e.TargetSite); Console.WriteLine("Message: {0}", e.Message); } Chapter 17 - Data Access w ith ADO.NET

When you are constructing multiple catch blocks for a single try block, you must be aware that when an exceptio is thrown, it will be processed by the "nearest available" catch. To illustrate exactly what the "nearest available" catch means, assume you retrofitted the previous catch logic as follows: // This code will not compile! try { for(int i = 0; i < 10; i++) buddha.SpeedUp(10); } catch(Exception e)

{...} C# an d th e .N ET e) Plat f orm , Se con d Ed it ion catch(CarIsDeadException ISBN:1590590554 by Andr ew Tr oelsen {...} Apr ess © 2003 (1200 pages) catch(ArgumentOutOfRangeException e) This compr ehensiv e text star ts w ith a brief ov er view of the {...} C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

This exception handling logic generates compile-time errors. The problem is due to the fact that the first catch block can handle anything derived from System.Exception (given the "is-a" relationship), including the Ta ble o f Con t en t s CarIsDeadException and ArgumentOutOfRangeException types. Therefore, the final two catch blocks are C# and t he .NET Plat for m, Second Edition unreachable! I ntr oduction Pa r t One I ntthumb r oduci ng C# a nd .NET tf or msure The rule- of to keep in the mind is toP la make

your catch blocks are structured such that the very first catch

Chapter the most 1 specific - The Philosophy exceptionof(i.e., .NET the most derived type in a given exception inheritance chain) while the final catc

is the most the base class of a given exception inheritance chain, in this case System.Exception). Chapter 2 - general Building (i.e., C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Therefore,- ifC# youLanguage wish to provide a catch statement that will handle any errors beyond CarIsDeadException and Fundamentals ArgumentOutOfRangeException, you would write the following:

Chapter 3 Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

// Better. Chapter 6 - I nter faces and Collections try {

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

for(int i = 0; i < 10; i++) buddha.SpeedUp(10);

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

} catch(CarIsDeadException e) Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing {...} Pa r t Four - Le ve r a ging the .NET Libr a r ie s catch(ArgumentOutOfRangeException e) Chapter {...}12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet Win This dow ( Int roducin g Windowany s Forother ms) catch(Exception e) ter // will handle exception. Chapter {...}14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Again, notice howAccess this catch explicitly specifies the exception type it is willing to catch. Given that you Chapter 17 - Data w ith block ADO.NET construct your finalica catch toML handle System.Exception, Pa r t Fi ve - W e b Appl ti onslogic and X W e b Se r vi ces

you write an exception handling routine that can (in

effect) 18 work with any Web type Pages deriving (given that all types defined in a catch block must der Chapter - ASP.NET andfrom WebSystem.Exception Contr ols from this class).Web Applicat ions Chapter 19 base - ASP.NET Chapter 20 - XML Web Ser vices

Generic Catch Statements

I ndex

List of Figur es

C#of(as well as numerous other languages targeting the .NET platform) also supports a generic catch block that List Tables does not explicitly define the type of exception. Thus, you could implement a catch block as follows: // I handle any possible error thrown from a try block. catch { Console.WriteLine("Something bad happened..."); }

Obviously, this is not the most descriptive manner in which to handle runtime exceptions, given that you have no way to obtain meaningful information about the error that occurred (such as the method name, call stack, or custom message). Nevertheless, C# does allow for such a construct.

Rethrowing Exceptions

Also, beware that it is permissible to "rethrow" an error up the call stack to the previous caller. To do so, simply C# an d th e .N ET Plat f orm , Se con d Ed it ion make use of the "throw" keyword within a catch block. This passes the exception up the chain of calling logic: try {

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and // Speed arup car allogic... chitectur issues for .NET developer s.

} catch(CarIsDeadException e) Ta{ble o f Con t en t s Do any of this error and pass the buck. C# and t// he .NET Plat forpartial m, Second processing Edition // Here, we are rethrowing the CarIsDeadException type. I ntr oduction // HOWEVER, you are also free to throw a different exception if need be. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m throw e; Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion The Finally C#Block by Andr ew Tr oelsen

ISBN:1590590554

Your try/catch logic augmented with an optional finally block. The idea behind a finally block Aprmay ess ©also 2003 be (1200 pages) is to ensure that aThis block of code will always execute, if an exception compr ehensiv e text star ts w ith a even brief ov er view of the (of any type) interferes with the normal flow of execution. For example, assume you wish to always C# language and then quickly m oves to key technicalpower and down the car's radio before ar chitectur issues for .NET developer s. exiting Main(), regardless ofalany possible exception: // Provide a manner to clean up. public static int Main(string[] args) C# and t he .NET Plat for m, Second Edition { I ntr oduction ... Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // Try to rev the engine hard! Chapter try 1 - The Philosophy of .NET Chapter { 2 - Building C# Applications Pa r t Tw o - The C# ogr am mup ing car La ngua ge // PrSpeed logic ... Chapter } 3 - C# Language Fundamentals Chapter catch(CarIsDeadException 4 - Obj ect -Or iented Pr ogr am ming w ith C# e) Chapter {...} 5 - Exceptions and Obj ect Lifetim e Chapter catch(ArgumentOutOfRangeException 6 - I nter faces and Collections e) Chapter {...} 7 - Callback I nter faces, Delegates, and Ev ents Chapter finally 8 - Advanced C# Type Const ruction Techniques Pa r t Thre{e - Pr ogr am m i ng w i th .N ET Assem bl ie s // standing This will always Chapter 9 - Under .NET Assem bliesoccur. Exception or not. buddha.CrankTunes(false); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter } 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing 0; the .NET Libr a r ie s Pa r t Fourreturn - Le ve r a ging } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Ta ble o f Con t en t s

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 include - A Better Paint ing Fr amew or k ( GDI + ) not be turned off if an exception is caught (which may or If you did a finally block, the radio would Chapter 15 Pr ogr am ming with Windows Form s ols if you need to clean up any allocated memory, may not be problematic). In a more real-worldContr scenario, Chapter 16 - a The Syor stem .I O Nam espace close down file, detach from a data source (or whatever), you must add that code within a finally block Chapter 17 Data Access w ith ADO.NET to ensure proper cleanup. To this end, it is important to realize that the code contained within a finally Pa r t Fi ve - W e b Appl ica titime, ons and X ML W elogic b Se r vi ces block executes all the even if the within

your try clause does not generate an exception. This is

Chapter 18 -helpful ASP.NET Pages and Web Contr ols especially if aWeb given exception requires the termination of the current application. Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d thException e .N ET Plat f orm , Se con d Ed it ion The Last Chance by Andr ew Tr oelsen

ISBN:1590590554

Unlike ad hoc error Aprhandling ess © 2003techniques, (1200 pages) .NET exceptions cannot be ignored. One obvious question that may be on your mind is what would an of exception thrown your direction. For This compr ehensiv e happen text stariftsyou w ithdo a not briefhandle ov er view the example, assumeC#that the logic in Main() that increases the speed of the Car object has no error handling language and then quickly m oves to key technical and ar chitectur issues for .NET developer logic. The result of ignoringalthe generated error woulds.be highly obstructive to the end user of your application, as the following "last chance exception" dialog box is displayed (Figure 5-5). Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - 5-5: Building Bet ter Win dow ( Intno-man's roducin g land. Window s For ms) Figure Youahave just entered Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Now that theming inherent goodness of catching an exception programmatically, you may wonder what Chapter 15 you - Prsee ogr am with Windows Form s Contr ols to do with exception you have trapped it. Again, this is a design issue based on your current Chapter 16 -the The Sy stem .Ionce O Nam espace project.17In -your Carw ith example, you simply dumped your custom message and call stack to the Chapter Datatrivial Access ADO.NET console. realistic freeing Pa r t Fi ve - A W more e b Appl ica ti onsscenario and X MLmay W e binclude Se r vi ces

up acquired resources or writing to a log file. The exception-handling schema is simply a pattern to follow when sending, receiving, and processing runtime Chapter 18 - ASP.NET Web Pages and Web Contr ols anomalies. How you do so is largely up to you. Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 - XML Web The Ser vices SOURCE CustomException project is included under the Chapter 5 subdirectory. I ndex CODE List of Figur es List of Tables

C# Identifying an d th e .N ET Plat f orm , Se con d Ed itand ion System-Level Exceptions Dynamically ApplicationISBN:1590590554

by Andr ew Tr oelsen

In the previous example, to handle each exception by its specific class name. As an Apr ess ©you 2003 saw (1200how pages) illustrative alternative, assume you wish generalize yourov catch blocks This compr ehensiv e text to star ts w ith a brief er view of thein such a way that all applicationlevel exceptions are handled apart from possible system-level exceptions: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

// This time, make things a bit more general. try Ta ble o f Con t en t s { C# and t he .NET Plat for m, Second Edition for(int i = 0; i < 10; i++) I ntr oduction buddha.SpeedUp(10); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m } Chapter 1

- The Philosophy of .NET

Chapter 2 type - Building C# Applications // Any derived from System.ApplicationException Pa r t Tw o - The C#here. Pr ogr am m ing La ngua ge // handled

Chapter 3 - C# Language Fundamentals catch(ApplicationException e) Chapter 4 {

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter Console.WriteLine("Caught 5 - Exceptions and Obj ect Lifetim e an app exception!"); Chapter Console.WriteLine("Method: 6 - I nter faces and Collections {0}", e.TargetSite); Chapter Console.WriteLine("Message: 7 - Callback I nter faces, Delegates, and {0}", Ev ents e.Message);

} Chapter 8

- Advanced C# Type Const ruction Techniques

// Anye -type derived from Pa r t Thre Pr ogr am m i ng w i th .N ET System.SystemException Assem bl ie s // handled here. Chapter 9 - Under standing .NET Assem blies catch(SystemException e) Cont exts, and Threads Chapter 10 - Pr ocesses, AppDomains, { Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t FourConsole.WriteLine("Caught - Le ve r a ging the .NET Libr a r ie s

a system-level exception"); Console.WriteLine("Method: {0}", e.TargetSite); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Console.WriteLine("Message: {0}", e.Message); Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 the - The Sy stem .I O Nam espace Although ability to discover at runtime the underlying source of an exception might sound intriguing, Chapter 17 Data Access w ith ADO.NET you really gain nothing by doing so. Sadly, if you spend time digging through the .NET base class libraries, Pa r t Fiwill ve find - W ethat b Appl ica tibase ons and X ML W e b Se r vi ces you some class library methods

that should ideally throw a type derived from

Chapter 18 - ASP.NET Web Pages Contr ols System.ApplicationException or even the more generic System.SystemException are in and factWeb derived from Chapter System.Exception! 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

Thus, although the proposed idea issued by Microsoft was noble, you cannot always use the previous technique to universally determine the source of the exception. In your applications, you will do well to List of Figur es simply handle each possible exception on a name-by-name basis. However, if you are building a custom List of Tables exception class, best practice dictates deriving directly from System.ApplicationException. I ndex

an d th e .NExceptions ET Plat f orm , Se con d Ed it ion DebuggingC#System Using VS .NET by Andr ew Tr oelsen

ISBN:1590590554

Visual Studio .NET number of helpful tools that you can use to debug the exceptions that may Aprprovides ess © 2003a (1200 pages) be thrown by a given member during the development cycle. default, This compr ehensiv e text star ts w ith a brief ov erBy view of thewhen an exception is caught during a debugging session, the IDE will not automatically stop at the offending line of code. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

To illustrate this default behavior, begin to debug your current CustomExceptions project without setting any breakpoints. You will find that the only visible display of the CarIsDeadException is the information Taprinted ble o f Con to the t enconsole ts (via your catch block), which disappears so quickly you cannot see the error. Of course, you arePlat free any number C# and t he .NET forto m,set Second Edition of manual breakpoints by hand; however, there is a better way. I ntr oduction

VS .NET may be configured to automatically break whenever an exception occurs, without requiring you to set dozens of manual breakpoints at various catch blocks. When you wish to enable such support, begin Chapter 1 - The Philosophy of .NET by launching the Exceptions dialog box, using the Debug | Exceptions menu selection (Figure 5-6). Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex

Figure 5-6: Preparing to enable VS .NET exception handling

List of Figur es List Tables As ofyou can see, VS .NET is able to interact with various types of exceptions; the only category of interest is

the common language runtime exceptions. If you open up the CLR Exceptions node, you will find a list of all of the System.Exception-derived types that Visual Studio .NET is aware of. For example, if you open up the System node, you will find a list of all exception types listed in this namespace (Figure 5-7).

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Figure 5-7: Them CLR set bl ie s Pa r t Thre e - Pr ogr am i ng w exception i th .N ET Assem Chapter 9

- Under standing .NET Assem blies

To enable automatic breaking for a specific exception, simply select the exceptions of interest. For example, to instruct VS .NET to automatically break when an ArgumentOutOfRange exception occurs, Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing check the "Break into the debugger" option (Figure 5-8). Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 5-8: Specifying VS .NET exception support for a given exception

Handling Custom Exceptions Using VS .NET In addition to handling system-level exceptions, you are also able to configure Visual Studio .NET to

handle your custom application exceptions (such as the CarIsDeadException). To do so, first select the C# an d th e .N ET Plat f orm , Se con d Ed it ion CLR Exceptions node and click the Add button. At this point, type in the fully qualified name of your custom ISBN:1590590554 by Andr ew Tr oelsen exception type (Figure 5-9). Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET for m, Second Edition application exceptions via VS .NET Figure 5-9:Plat Enabling your custom I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

At this point you are able to configure the custom exception as if it were a standard exception (Figure 5- The Philosophy of .NET 10).

Chapter 1 Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t FiFigure ve - W e5-10: b Appl Handling ica ti ons and yourXcustom ML W e b application Se r vi ces

exceptions via VS .NET

Chapter 18 - ASP.NET Web Pages and Web Contr ols

With this, are now able to debug Chapter 19 you - ASP.NET Web Applicat ions your application, and automatically step into the debugger when a given exception is raised.

Chapter 20 - XML Web Ser vices I ndex So then, this wraps up the first topic of the chapter. As you read over the remainder of this text, you will be List of Figur esto numerous other system-level exceptions. Next up, we will turn our attention to the topic of introduced List of Tables object lifetime.

Note To make the code examples used in this text as clean as possible, I will not catch every possible exception that may be thrown by a CLR type. Do be aware that your production-level projects should, of course, make liberal use of try/catch/finally blocks.

C# an dObject th e .N ET Plat f orm , Se con d Ed it ion Understanding Lifetime by Andr ew Tr oelsen

ISBN:1590590554

To close this chapter, we will switch topics completely and address garbage collection. Recall that unlike Apr ess © 2003 (1200 pages) C++, C# programmers (and .NET programmers in general) This compr ehensiv e text star ts w ith a brief ovnever er view directly of the deallocate an object from memory (therefore there is no "delete" keyword in the C# language). Rather, .NET objects are allocated C# language and then quickly m oves to key technical and ar chitectur al issues .NET developer s. onto a region of memory termed thefor managed heap, where they will be automatically deallocated by the runtime at "some time in the future." TaAs bleyou o f Con are tbuilding en t s your C# applications, you are correct to assume that the managed heap will take care

of and itselft he without yourfordirect intervention. C# .NET Plat m, Second Edition In fact, the golden rule of .NET memory management is simple. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Rule: The Zen of .NET memory management says this: Allocate an object onto the managed heap

Chapter 1 -the The Philosophy of .NET using "new" keyword and forget about it. Chapter 2 - Building C# Applications Pa Once r t Tw "new-ed," o - The C# the Pr ogr CLR am m removes ing La ngua thege object

when it is no longer needed. Next question: How does the runtime determine when an object is "no longer needed"? The short (i.e., incomplete) answer is that the Chapter 3 - C# Language Fundamentals runtime removes an object from the heap when Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C#it is unreachable by the current application. To illustrate, assume5 you have a new application thatemakes use of the Car type as follows: Chapter - Exceptions and Obj ect Lifetim Chapter 6

- I nter faces and Collections

// Create a local Chapter 7 - Callback I nterCar faces,object. Delegates, and Ev ents public int args) Chapter 8 static - Advanced C# Main(string[] Type Const ruction Techniques {r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Pa an object ontoblies the managed heap. Chapter // 9 - Place Under standing .NET Assem c ocesses, = new AppDomains, Car("Viper", 200, Chapter Car 10 - Pr Cont exts, and100); Threads Chapter ... 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

}r t Four // - If is the only Pa Le vecr a ging the .NET Librreference a r ie s

to the Car object, // it may be destroyed when Main() exits. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter A Better Paint ing (c) Fr amew or k ( GDI +) Notice 14 that- the Car variable has been created within the scope of Main(). Thus, once the application Chapter 15 Pr ogr am ming with Windows Form s Contr ols shuts down, this reference is no longer valid, and therefore is a candidate for garbage collection. Chapter 16 - The Sy stemthat .I O Nam Understand, however, you espace cannot guarantee that this object will be reclaimed from memory when Chapter 17 Data Access w ith ADO.NET Main() has completed. All you can assume at this point in the game is that when the CLR performs the Pa r t Figarbage ve - W e b collection, Appl ica ti ons X ML W r vi ces next "c"and is ready toe bbeSedestroyed.

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion The CIL of "new" by Andr ew Tr oelsen

ISBN:1590590554

Under the hood, when C# (1200 compiler Apr essthe © 2003 pages)encounters the "new" keyword, it will emit a CIL "newobj" instruction to the This codecompr module. Thus, if you to aopen the previous ehensiv e text starwere ts w ith briefup ov er view of the assembly using ildasm.exe, you would find the following CIL: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

.method public hidebysig static int32 Main(string[] args) cil managed { Ta ble o f Con t en t s .entrypoint C# and t he .NET Plat for m, Second Edition // Code size 24 (0x18) I ntr oduction .maxstack 4 Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m .locals init ([0] class GC.Car c, Chapter 1 - The[1] Philosophy .NET int32of CS$00000003$00000000) Chapter 2 Building C# Applications IL_0000: ldstr "Viper" Pa r t IL_0005: Tw o - The C# ldc.i4 Pr ogr am m ing La ngua ge 0xc8 Chapter 3 - C# Language Fundamentals IL_000a: ldc.i4.s 100 Chapter 4 - Obj ect -Or ientedinstance Pr ogr am ming w ith GC.Car::.ctor C# IL_000c: newobj void Chapter(string, 5 - Exceptions and Obj ect Lifetim e int32, int32) Chapter IL_0011: 6 - I nter stloc.0 faces and Collections IL_0012: ldc.i4.0 Chapter 7 - Callback I nter faces, Delegates, and Ev ents IL_0013: stloc.1 Chapter 8 - Advanced C# Type Const ruction Techniques br.s IL_0016 Pa r t IL_0014: Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s IL_0016: ldloc.1 Chapter 9 - Under standing .NET Assem blies IL_0017: ret AppDomains, Cont exts, and Threads Chapter 10 - Pr ocesses, } // end of Chapter 11 - Type method Reflection,GCApp::Main Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Before we examine the exact rules that determine when an object is removed from the managed heap, let's check out the role of the CIL newobj instruction in a bit more detail. First, understand that the Chapter 14 heap - A Better Paintthan ing Fr amew or k chunk ( GDI + )of memory accessed by the CLR. The .NET garbage managed is more just a raw Chapter 15 Pr ogr am ming with Windows Form s Contr olscompact empty blocks of memory (when necessary) collector is quite a tidy housekeeper, given that it will Chapter 16 The Sy stem .I O Nam espace for purposes of optimization. To aid in this endeavor, the managed heap maintains a pointer (commonly Chapter Data w ith ADO.NET referred17to- as theAccess new object pointer) that identifies exactly where the next object will be placed on the Pa r t Fi ve W e b Appl ica ti ons and X ML Wthe e b newobj Se r vi cesinstruction informs the CLR to perform the following heap itself. These things being said, Chapter 18 ASP.NET Web Pages and Web Contr ols sequence of events: Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Chapter 19 - ASP.NET Web Applicat ions

Calculate theWeb total amount Chapter 20 - XML Ser vices of memory required for the object about to be allocated. As you would

expect, if this object contains other internal objects (i.e., the "has-a" relationship as well as nested type members), they are also factored into the equation. As well, the memory required for each base class List of Figur es is also taken into account (i.e., the "is-a" relationship). I ndex

List of Tables

The CLR then examines the managed heap to ensure that there is indeed enough room to host the object to be allocated. If so, the type's constructor is called, and the caller is returned a reference to the type in memory, which just happens to be identical to the last position of the new object pointer. Finally, before returning the reference to the caller, the CLR will advance the new object pointer to point to the next available slot on the managed heap. This process is illustrated in Figure 5-11.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s

Figure 5-11: Reference types are allocated on the managed heap.

C# and t he .NET Plat for m, Second Edition I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

d th e .N ET Plat f orm , Se con d Ed it ion The BasicsC#ofanGarbage Collection ISBN:1590590554

by Andr ew Tr oelsen

As you are busy creating managed heap may eventually become full. When the newobj Apr ess © objects, 2003 (1200the pages) instruction is being processed, if the CLR determines that the heap does not have sufficient This compr ehensiv e text star ts w ith a brief ov ermanaged view of the memory to allocate the requested type, it will perform a garbage collection in an attempt to free up C# language and then quickly m oves to key technical and ar chitectur issues for .NET developer s. memory. Thus, the next ruleal of garbage collection is quite simple. Rule: thet smanaged heap does not have sufficient memory to allocate a new object, a garbage Ta ble o f ConIft en collection C# and t he .NETwill Platoccur. for m, Second Edition I ntr oduction

Now, assuming that the CLR performs a garbage collection, we need to return to the question regarding how the runtime is able to determine an object on the heap is "no longer needed." To understand the Chapter of .NET details,1you- The needPhilosophy to be aware of the notion of application roots. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 2

- Building C# Applications

Pa Simply r t Tw o put, - The a C# rootPrisogr a am storage m ing location La ngua ge containing

a reference to an object on the heap. Put even more succinctly, a root can be understood as a variable in your application that points to some area of memory Chapter 3 - C# Language Fundamentals on the managed heap. Strictly speaking, however, Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# a root can fall into any of the following categories: Chapter 5

- Exceptions and Obj ect Lifetim e

References to global objects (while not allowed in C#, raw CIL does permit allocation of global - I nter faces and Collections objects)

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8 - Advanced C# objects Type Const ruction Techniques References to static Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

References local objects withinblies a given method Chapter 9 - Undertostanding .NET Assem Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

References to object parameters passed into a method

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four Le ve register r a ging the Libr a r ie sa local Any -CPU that.NET references

object

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

When a13garbage collection investigate all objects on the managed heap to Chapter - Building a Bet ter occurs, Win dowthe ( Intruntime roducin gwill Window s For ms) determine is still in useing(aka "rooted") in the Chapter 14 -if Ait Better Paint Fr amew or k ( GDI + ) application. To do so, the CLR will build an object graph, which represents each object the heap that is still Chapter 15 - Pr ogr am ming with on Windows Form s Contr olsreachable. We will explore object graphs in more

detail later during our examination of object serialization (see Chapter 12). For the time being, simply understand that the CLR will ensure that all related objects are accounted for before a possible garbage Chapter 17 - Data Access w ith ADO.NET collection through the construction of an object graph that documents all codependencies for the current Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces object. One nice feature of this process is the fact that the runtime will never graph the same object twice, Chapter 18 - ASP.NET Web Pages and Web Contr ols thus avoiding the nasty circular reference count found in classic COM programming. Chapter 16 - The Sy stem .I O Nam espace

Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 -once XML the Webgarbage Ser vices collector determines that a given root is no longer used by a given Now then, I ndex application, the object is marked for termination. When the entire heap has been searched for "severed List roots," of Figur thees underlying memory is reclaimed for each unreachable object. After the objects have been

swept from memory, the memory on the heap is compacted, which in turn will cause the CLR to modify List of Tables the set of application roots to refer to the correct memory location (this is done automatically and transparently). Finally, the new object pointer is readjusted to point to the next available slot. Note Be aware that the garbage collection process happens on a unique thread of execution (more on threading in Chapter 10).

an d th e .N ET Plat f orm , Se con d Ed it ion Finalizing aC#Type ISBN:1590590554

by Andr ew Tr oelsen

As you might have gathered previous discussion, the .NET garbage collection scheme is rather Apr ess © 2003from (1200the pages) nondeterministic This in nature. In other words, you exactly when an object compr ehensiv e text star ts are w ith typically a brief ovunable er view to of determine the will be deallocated from memory. Although this approach to memory management can simplify your C# language and then quickly m oves to key technical and ar chitectur al issues forleft .NET developer s. coding efforts at some levels, you are with the unappealing byproduct of your objects possibly holding onto unmanagedresources (raw HWNDs, raw Win32 file handles, etc.) longer than necessary. When you build .NET types that interact with unmanaged resources (a common task when working with platform Tainvocation ble o f Conand t en tCOM s interoperability), you will most likely wish to ensure that this resource is released in a C# and tmanner he .NET rather Plat for m, Second timely than at theEdition whim of the .NET garbage collector. I ntr oduction

To such choice you Pa r t account One - I ntfor r oduci ng situations, C# a nd theone .NET P la tf or m

have as a C# class designer is to override the virtual

System.Object.Finalize() Chapter 1 - The Philosophymethod of .NET(the default implementation does nothing). Believe it or not, most of the time you not need support a custom implementation of the Finalize() method. In fact, the only Chapter 2 will - Building C#toApplications reason will to do so is ge if your Pa r t Tw o you - The C#be Prrequired ogr am m ing La ngua

custom C# classes make use of unmanaged resources that are typically obtained by directly calling into the Win32 API. On the other hand, if your C# types do not Chapter 3 - C# Language Fundamentals make use of unmanaged resources but only make use of managed types, you are not required to Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# implement a custom Finalize() method at all. Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6 - I nter faces and Nevertheless, assume youCollections have a type that has acquired various unmanaged resources and wish to Chapter 7 Callback I nter Delegates, and Ev ents to ensure proper cleanup of the internal unmanaged support a custom versionfaces, of System.Object.Finalize() Chapter 8 - While Advanced C#allType ructionthe Techniques resources. this is wellConst and good, odd thing is that the C# language does not allow you to Pa r t Thre override e - Pr ogr am i ng w i th .N ET Assem bl ie standard s directly themFinalize() method using

Chapter 9

C# syntax:

- Under standing .NET Assem blies

Chapter 10 class - Pr ocesses, AppDomains, Cont exts, and Threads public FinalizedCar Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing { Pa r t Four// - LeCompile ve r a ging the .NETerror! Libr a r ie s time

Chapter protected 12 - Obj ect Ser ialization and the .NET Remoting Lay } er override void Finalize(){ Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Rather,16when you your custom C# class types to override the Finalize() method, you Chapter - The Sy wish stem .ItoOconfigure Nam espace make use of the following (C++-like) destructor syntax to achieve the same effect:

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

// This overrides Chapter 18 - Car ASP.NET Web PagesSystem.Object.Finalize(). and Web Contr ols class19FinalizedCar Chapter - ASP.NET Web Applicat ions { Chapter 20 - XML Web Ser vices I ndex

~FinalizedCar() {Console.WriteLine("=> Finalizing car..."); }

List of Figur es

}

List of Tables

The C# destructor-style syntax can be understood as a shorthand notation for the following code: protected override void Finalize() { try { Console.WriteLine("=> Finalizing car..."); } finally { base.Finalize(); } }

In fact, if you were to check out the CIL that is generated for classes supporting the C# destructor method (via ildasm.exe), you will find that an override is indeed made for the virtual System.Object.Finalize() method. Also notice that the CIL code will automatically call the base class Finalize() method on your

behalf:

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

.method family hidebysig virtual instance void Apr ess © 2003 (1200 pages) Finalize() cil managed This compr ehensiv e text star ts w ith a brief ov er view of the { C# language and then quickly m oves to key technical and // Code size (0x14) ar chitectur al 20 issues for .NET developer s. .maxstack 1 .try { Ta ble o f Con t en t s "=> Finalizing car..." C# andIL_0000: t he .NET Platldstr for m, Second Edition IL_0005: call void [mscorlib]System.Console::WriteLine(string) I ntr oduction IL_000a: leave.s IL_0013 Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m } // .try Chapter 1 - end The Philosophy of .NET .finally Chapter 2 - Building C# Applications Pa r t {Tw o - The C# Pr ogr am m ing La ngua ge IL_000c: ldarg.0 Chapter 3 - C# Language Fundamentals IL_000d: call instance void [mscorlib]System.Object::Finalize() Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# IL_0012: endfinally Chapter 5 - Exceptions and Obj ect Lifetim e } // end handler Chapter 6 - I nter faces and Collections IL_0013: ret Chapter 7 - Callback I nter faces, Delegates, and Ev ents } Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

(Indirectly) Invoking System.Object.Finalize()

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

As mentioned, the .NET runtime will trigger a garbage collection when it requires more memory than is currently available on the managed heap. Therefore, if you have created an application that is intended to Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er run for lengthy periods of time (such as a background service), garbage collections may occur few and far Chapter 13over - Building a Bet ter Winapplication's dow ( Int roducin g Window s For ms) between the course of the lifetime. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

It is important to note thatwith finalization will automatically Chapter 15 - Pr ogr am ming Windows Form s Contr ols take place when an application domain is unloaded by the CLR. Application (or simply AppDomains) will be examined in greater detail later in this Chapter 16 - The Sy stem .Idomains O Nam espace text. For time Access being, w simply assume that an AppDomain is the application itself. Thus, you can rest Chapter 17the - Data ith ADO.NET assured finalizable will Whave itsr vicleanup Pa r t Fi ve -that W e baAppl ica ti onsobject and X ML e b Se ces

logic triggered upon application shutdown. This

brings us the next rule garbage collection. Chapter 18 to - ASP.NET Web of Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 -When XML Web Ser vices Rule: an AppDomain is unloaded, the Finalize() method is invoked for all finalizable objects. I ndex

To ofillustrate, List Figur es ponder the following illustrative example: List of Tables

namespace SimpleFinalize { class FinalizedCar { ~FinalizedCar() { Console.WriteLine("=> Finalizing car..."); } } class FinalizeApp { static void Main(string[] args) { Console.WriteLine("***** Making object *****"); FinalizedCar fc = new FinalizedCar(); Console.WriteLine("***** Exiting main *****"); }

} C# an d th e .N ET Plat f orm , Se con d Ed it ion

}

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

The output of thisThis program be eseen Figure Notice that the finalization message is compr can ehensiv text in star ts w ith5-12. a brief ov er view of the C# language and then quickly m oves to exits. key technical anda proper finalizer would free up automatically printed to the console once the program Of course, ar chitectur al issues for developer s. has been made. some set of unmanaged resources, but.NET I think the point Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Figure 5-12: Finalizers are called automatically upon application shutdown.

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion The Finalization Process ISBN:1590590554

by Andr ew Tr oelsen

Given that finalization is ©guaranteed to take place when your application exits, you may be tempted to Apr ess 2003 (1200 pages) support C#-style This destructors on all of yourstar types. Buta don't. First of all, always remember that the role of a compr ehensiv e text ts w ith brief ov er view of the finalizer is to ensure that a .NET object can clean up unmanaged resources. Thus, if you are building a C# language and then quickly m oves to key technical and chitectur al of issues for .NET developer s. type that does notarmake use unmanaged entities, finalization is of little use. However, there is a more practical reason to avoid supporting a finalize method: Finalization takes time. TaWhen ble o f you Conplace t en t s an object onto the managed heap using the new operator, the runtime automatically

determines if your supports a custom Finalize() method. If so, the object is marked as finalizable, C# and t he .NET Plat object for m, Second Edition and a pointer to this object is stored on an internal queue named (of course) the finalization queue. Simply I ntr oduction put, the -finalization queue is athe table maintained Pa r t One I nt r oduci ng C# a nd .NET P la tf or m

by the CLR that points to each and every object that must

be finalized before it is removed from the heap. Chapter 1 - The Philosophy of .NET Chapter 2

- Building C# Applications

When the garbage collector determines it is time to free an object from memory, it examines each entry cataloged on the finalization queue, and copies the object off the heap to yet another CLR-managed Chapter 3 - C# Language Fundamentals structure termed the finalization reachable table (often abbreviated as freachable, and pronounced "FChapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# reachable"). At this point, a separate thread is spawned to invoke the Finalize() method for each object on Chapter 5 - Exceptions Lifetim ecollection. the freachable table at and the Obj nextectgarbage Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 6

- I nter faces and Collections The bottom line is that when you build a custom Chapter 7 - Callback I nter faces, Delegates, and Ev type ents that overrides the System.Object.Finalize() method,

the .NET will ensure thisruction member is called once your object is removed from the managed Chapter 8 runtime - Advanced C# Typethat Const Techniques heap. However, thismcomes at.Na ET cost in terms Pa r t Thre e - Pr ogr am i ng w i th Assem bl ie s of Chapter 9

application performance.

- Under standing .NET Assem blies

SOURCE CODE

The SimpleFinalize project is included under the Chapter 5 subdirectory.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an dHoc th e .NDestruction ET Plat f orm , Se con d Ed it ion Building anC#Ad Method ISBN:1590590554

by Andr ew Tr oelsen

As you have seen, the of finalizing an object is quite time consuming. Ideally, you should design Apr essprocess © 2003 (1200 pages) your objects in such a way so they do not need finalizable This compr ehensiv e text star ts wtoithbea marked brief ov eras view of the in the first place. However, when a type manipulates unmanaged resources, you do need to ensure C# language and then quickly m oves to key technical and they are released in a timely and ar chitectur al issues .NET developer s. predictable manner. While you couldforsupport a C# destructor (and incur the overhead of being finalized), there are better ways. TaOne ble oalternative f Con t en t sis to define a custom ad hoc method that you can assume all objects in your system

implement. Let's call methodEdition Dispose(). The assumption is that when the object user is finished using C# and t he .NET Plat for this m, Second your type, it manually calls Dispose() before allowing the object reference to drop out of scope. In this way, I ntr oduction your objects perform amount cleanup necessary of Pa r t One - I nt rcan oduci ng C# a any nd the .NET Pof la tf or m

unmanaged resources without incurring the

hit of being on the finalization queue and without waiting for the garbage collector to trigger the Chapter 1 - placed The Philosophy of .NET class' finalization logic: Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

// Equipping our class with an ad hoc destruction method. Chapter 3 - C# Language Fundamentals public Chapter 4 Car - Obj ect -Or iented Pr ogr am ming w ith C# { Chapter 5

- Exceptions and Obj ect Lifetim e

... 6 Chapter

- I nter faces and Collections isI nter a custom methodandweEv expect the object user to call manually. Chapter // 7 - This Callback faces, Delegates, ents

public void Dispose() - Advanced C# Type Const ruction Techniques { /* Clean up your internal unmanaged resources. */} Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 8 Pa r t

}

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - the Type Reflection, Binding, and Attr ibutePr ogramm ing Of course, name of this Late method is completely up toBased you. While Dispose() is a very common name, if Pa r t Four - Le ve r a ging the that .NETmanipulates Libr a r ie s you are building a class

a physical file, you may opt to call this member Close().

Chapter 12 any - Objname ect Ser ialization and the .NET Remoting Lay er However, will do (ShutDown(), Kill(), DestroyMeNow(), and so forth). Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Note that unmanaged Chapter 14 To - Aensure Better Paint ing Fr amew orresources k ( GDI + ) are always cleaned up appropriately, the implementation a ogr Dispose() shouldForm be safely multiple times without throwing an exception. Chapter 15 of - Pr am mingmethod with Windows s Contrcallable ols Chapter 16 - The Sy stem .I O Nam espace

The IDisposable Interface

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

In order18to-provide symmetry among all objects Chapter ASP.NET Web Pages and Web Contr olsthat support an explicit destruction routine, the .NET class libraries19define an interface named IDisposable that (surprise, surprise) supports a single member named Chapter - ASP.NET Web Applicat ions Dispose(): Chapter 20 - XML Web Ser vices I ndex

public IDisposable List of Figurinterface es { of Tables List public void Dispose(); }

Now, rest assured that the concepts behind interface-based programming are fully detailed in Chapter 6. Until then, understand that the recommended design pattern to follow is to implement the IDisposable interface for all types that wish to support an explicit form of resource deallocation. Thus, you may update the Car type as follows: // Implementing IDisposable. public Car : IDisposable { ... // This is still a custom method we expect the object user to call

// manually. C# an dDispose() th e .N ET Plat f orm , Se con d Ed it ion public void ISBN:1590590554 by Andr ew Tr oelsen { Apr ess © 2003 (1200 pages) // Clean up your internal unmanaged resources. This compr ehensiv e text star ts w ith a brief ov er view of the } }

C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Again, using this approach, you provide the object user with a way to manually dispose of acquired resources as soon as possible, and avoid the overhead of being placed on the finalization queue. The C# and t he .NET Plat for m, Second Edition calling logic is straightforward:

Ta ble o f Con t en t s I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

namespace DisposeMe - The Philosophy of .NET { Chapter 2 - Building C# Applications public class App Pa r t Tw o - The C# Pr ogr am m ing La ngua ge { Chapter 3 - C# Language Fundamentals public static int Main(string[] args) Chapter 4 - Obj {ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and c1 Obj ect Lifetim e Car = new Car("Car one", 40, 10); Chapter 6 - I nter facesc1.Dispose(); and Collections Chapter 7 - Callback Ireturn nter faces,0; Delegates, and Ev ents Chapter 8 - Advanced C# is Typestill Const ruction Techniques } // C1 on the heap and may be collected at this point. Pa r t Thre}e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter } 9 - Under standing .NET Assem blies Chapter 1

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

This example yet.NET another Pa r t Four - Le ve exposes r a ging the Libr a rrule ie s

of working with garbage collected types.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 -Always Building a Bet ter Win dow ( Int roducin g Window s Forallocate ms) Rule: call Dispose() for any object you manually to the heap. The assumption you Chapter should 14 - make A Better is that Paintifing theFrclass amewdesigner or k ( GDI +chose ) to support the Dispose() method (or a named

alternative such as Close()), the type has someols cleanup to perform. Chapter 15 - Pr ogr am ming with Windows Form s Contr Chapter 16 - The Sy stem .I O Nam espace

As you may be guessing, it is possible for a single class to support a C#-style destructor as well as implement the IDisposable interface. You see this technique in just a moment.

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Reusing the C# "using" Keyword

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

When you are handling a managed object that implements IDisposable, it will be quite common to make use of structured exception handling to ensure the type's Dispose() method is called in the event of a List of Figur es runtime exception: I ndex

List of Tables

public void SomeMethod() { Car c = new Car(); try {// Use the car. } catch { // Catch any exceptions here. } finally { // Always call Dispose(), error or not. c.Dispose(); } }

While this is a fine example of defensive programming, the truth of the matter is that few developers are C# an d th e .N ET Plat f orm , Se con d Ed it ion thrilled by the prospects of wrapping each and every type within a try/catch/finally block just to ensure the by Andr ew Tr oelsen type's Dispose() method is called. To achieve the same result ISBN:1590590554 in a much less obtrusive manner, C# Apr ess © 2003 (1200 supports a special bit of syntax thatpages) looks like this: This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and public void SomeMethod() ar chitectur al issues for .NET developer s.

{ using(Car c = new Car()) { Ta ble o f Con t en t s // Use car. Edition C# and t he .NET Plat forthe m, Second // Dispose() is called automatically when the I ntr oduction // using block Pa r t One - I nt r oduci ng C# a nd theexits. .NET P la tf or m Chapter}1 - The Philosophy of .NET } Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Unfortunately, the "using" keyword now has a double meaning (specifying namespaces and triggering a Obj ect -Or iented Pr ogr am ming w ith C# Dispose() -method). Nevertheless, when you are working with .NET types that support the IDisposable Chapter 5 Exceptions and Obj ect Lifetim e interface, this syntactical construct will ensure that the object "being used" will automatically have its Chapter 6 I nter faces and Collections Dispose() method called once the using block has exited. On the other hand, if you specify a type that Chapter 7 implement - Callback IIDisposable nter faces, Delegates, Ev ents does not within theand using declaration, you are issued a compile time error. Chapter 4

Chapter 8

- Advanced C# Type Const ruction Techniques

SOURCE Pa r t Thre e - Pr ogr am mThe i ng wDisposableCar i th .N ET Assem project bl ie s

is included under the Chapter 5 subdirectory.

CODE Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .NOptimizations ET Plat f orm , Se con d Ed it ion Garbage Collection ISBN:1590590554

by Andr ew Tr oelsen

Now that you have Aprseen ess ©two 2003approaches (1200 pages) that may be used to ensure the proper cleanup of your custom types, let's dig a bit deeper into the efunctionality .NETovgarbage and check out the topic of This compr ehensiv text star ts wof iththe a brief er view ofcollector the objectgenerations. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

When the CLR is attempting to locate unreachable objects, is does not literally walk over each and every object placed on the managed heap looking for orphaned roots. Doing so would involve considerable Tatime, ble o especially f Con t en t sin larger (i.e., real-world) applications. C# and t he .NET Plat for m, Second Edition

To help optimize the collection process, each object on the heap is assigned to a given "generation." The idea behind generations is simple: The longer an object has existed on the heap, the more likely it is to Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m stay there (for example, the object implementing an application's Main() method). Conversely, objects that Chapter 1 - The Philosophy of .NET have been recently placed on the heap are more likely to be dereferenced by the application rather quickly Chapter 2 - Building C# Applications (such as an object created within a method scope). Given these assumptions, each object belongs to one Pa r t Tw o - The C# Pr ogr am m ing La ngua ge of the following generations (as of .NET version 1.1): I ntr oduction

Chapter 3

- C# Language Fundamentals

Chapter 4 - Obj ect iented Pr am ming w ith C# Generation 0: -Or Identifies a ogr newly allocated object that has never been marked for collection. Chapter 5 - Exceptions and Obj ect Lifetim e

Generation Identifies an object that has survived a garbage collection sweep (i.e., it was marked for Chapter 6 - I nter1: faces and Collections collection, but was not removed due to theEvfact Chapter 7 - Callback I nter faces, Delegates, and entsthat the heap had enough free space). Chapter 8

- Advanced C# Type Const ruction Techniques Generation 2: Identifies an object that has survived more than one sweep of the garbage collector.

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - a Under standing .NET Assem blies Now, when collection occurs, the GC marks and sweeps all generation 0 objects first. If this results in the Chapter required 10amount - Pr ocesses, of memory, AppDomains, the remaining Cont exts,objects and Threads are promoted to the next available generation. If all

generation objects have been from the heap, but Pr more memory Chapter 11 - 0Type Reflection, Late removed Binding, and Attr ibuteBased ogramm ing is still necessary, generation 1 objects followed Pa r t Four are - Lemarked ve r a gingand the swept, .NET Libr a r ie s

(if necessary) by generation 2 objects. In this way, the newer

objects12 (i.e., local areand removed quickly whileLay anerolder object (i.e., the object defining the Main() Chapter - Obj ect variables) Ser ialization the .NET Remoting method) beterinWin use. In a nutshell, GC issable to quickly free heap space using the Chapter 13is- assumed Building ato Bet dow ( Int roducin gthe Window For ms) generation a baseline. Chapter 14 - as A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d Type th e .N ET Plat f orm , Se con d Ed it ion The System.GC by Andr ew Tr oelsen

ISBN:1590590554

Like everything inApr theess .NET universe, you are able to interact with the garbage collector using a base class © 2003 (1200 pages) library type, whichThis in this case is System.GC. allows with the garbage collector compr ehensiv e text star tsThis w ithtype a brief ov eryou viewtoofinteract the using a small set C# of static members. Table 5-2 gives a rundown of some of the more interesting items. language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Table 5-2: Select Members of the System.GC Type System.GC Ta ble o f Con t en t Member s

Meaning in Life

C# and t he .NET Plat for m, Second Edition

Collect()

I ntr oduction Pa r t One - I nt r oduci ng C# a nd

Chapter 1

Forces the GC to call the Finalize() method for every object on the managed heap. You can also (if you choose) specify the generation to the .NET P la tf or m sweep .

- The Philosophy of .NET GetGeneration() Returns the generation to which an object currently belongs. Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

MaxGeneration

Chapter 3

This property returns the maximum of generations supported on the target system.

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# ReRegisterForFinalize() a flag eindicating that a suppressed object should be reregistered Chapter 5 - Exceptions and ObjSets ect Lifetim Chapter 6 Chapter 7

as finalizable. This (of course) assumes the object was marked as - I nter faces and Collections nonfinalizable using SuppressFinalize(). - Callback I nter faces, Delegates, and Ev ents

Chapter 8 - Advanced C# TypeSets Const Techniques SuppressFinalize() a ruction flag indicating that a given object should not have its Finalize() Pa r t Thre e - Pr ogr am m i ng w i th method .N ET Assem bl ie s called.

Chapter 9

- Under standing .NET Assem blies

GetTotalMemory()

Returns the estimated amount of memory (in bytes) currently being used by all objects in the heap, including objects that are soon to be Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing destroyed. This method takes a Boolean parameter that is used to Pa r t Four - Le ve r a ging the .NET Libr a r ie s specify if a garbage collection should occur during the method Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er invocation. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Building Finalizable and Disposable Types

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

To illustrate programmatic interaction with the .NET garbage collector, let's retrofit the automobile's destruction logic to support both an overridden Finalize() method as well as the IDisposable interface:

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

// Memory clean up. public class Car : IDisposable I ndex { List of Figur es ... List of Tables ~Car() { // Clean up any internal unmanaged resouces. } public void Dispose() { // Clean up any internal resources. ... // No need to finalize if user called Dispose(), // so suppress finalization. GC.SuppressFinalize(this); } } Chapter 20 - XML Web Ser vices

Notice that this iteration of the Car class supports both a C#-style destructor as well as the IDisposable interface. Here, your Dispose() method has been altered to call GC.SuppressFinalize(), which informs the system that it should no longer call the destructor for the specified object, as the end user has called

Dispose() manually (and has therefore cleaned up any internal resources of the Car type). C# an d th e .N ET Plat f orm , Se con d Ed it ion

ISBN:1590590554 by Andr ew Tr oelsen To illustrate the interplay between explicit and implicit object deallocation, assume the following updated Apr ess © 2003 pages) Main() method. Given that two(1200 of the Car types have been manually disposed by the object user, these types do not haveThis their destructor due theovcall to GC.SuppressFinalize(): compr ehensivlogic e texttriggered star ts w ith a to brief er view of the

C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

// Interacting with the GC. public class GCApp Ta{ble o f Con t en t s public static int Main(string[] args) C# and t he .NET Plat for m, Second Edition { I ntr oduction // Add these cars to the managed heap. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Car c1, c2, c3, c4; Chapter 1 - The Philosophy of .NET c1 = new Car("Car one", 40, 10); Chapter 2 - Building C# Applications c2 = new Car("Car two", 70, 5); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge c3 = new Car("Car three", 200, 100); Chapter 3 - C# Language Fundamentals c4 = new Car("Car four", 140, 80); Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 Chapter 6

- Exceptions and Obj ect Lifetim e some objects. // Manually dispose - I nter faces and Collections c1.Dispose();

Chapter 7

- Callback I nter faces, Delegates, and Ev ents c3.Dispose();

Chapter 8

- Advanced returnC#0;Type Const ruction Techniques

Pa r t Thre}e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter } 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

The output seen Figure Pa r t Four - Lecan ve r abe ging the in .NET Libr a5-13. r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

Figure 5-13: The interplay of finalization and disposal

I ndex List ofSOURCE Figur es

The FinalizedAndDisposedType project is included under the Chapter 5 subdirectory.

List ofCODE Tables

Forcing a Garbage Collection Recall that the CLR will automatically trigger a garbage collection when the managed heap is full, which will happen "whenever." If you so choose, you are able to programmatically force the runtime to perform a garbage collection using the static GC.Collect() method. Now, understand that you should seldom (if ever) do so, given that the whole purpose of the managed heap is that it is maintained by forces outside of your control. Nevertheless, assume you have an object-hungry application that is designed to run for a lengthy amount of time. To trigger a garbage collection, you could write the following: // Force a garbage collection, and wait for // each object to be finalized. GC.Collect();

GC.WaitForPendingFinalizers(); C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

ess © 2003 (1200 pages) Note that you callApr GC.WaitForPendingFinalizers() after forcing a garbage collection cycle. In this way, you can rest assured This that compr all finalizable hada a chance to perform ehensiv eobjects text starhave ts w ith brief ov er view of the any necessary cleanup before C# Do language andthis then quickly m oves tothe key technical and during the process (which is a continuing forward. note that call will suspend current thread ar chitectur al don't issuesinvoke for .NET developer good thing, as it ensures you methods ons.a type that is currently being destroyed! ).

Programmatically Interacting with Generations

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

To close this chapter, let's revisit the topic of an object's generation. Programmatically speaking, you are able to investigate the generation an object currently belongs to using GC.GetGeneration(). Furthermore, Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m GC.Collect() does allow you to specify which generation should be checked for valid application roots. Chapter 1 - The Philosophy of .NET Consider the following: I ntr oduction

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

// Just - how old are you? C# Language Fundamentals public static int Main(string[] args) Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# { Chapter 5 - Exceptions and Obj ect Lifetim e // Add these cars to the managed heap. Chapter 6 - I nter faces and Collections Car c1, c2, c3, c4; Chapter 7 - Callback I nter faces, Delegates, and Ev ents c1 = new Car("Car one", 40, 10); Chapter c2 8 - =Advanced C# Type Const ruction new Car("Car two", 70,Techniques 5); Pa r t Threc3 e - Pr am m i ng w i th .N ET Assem bl ie s = ogr new Car("Car three", 200, 100); Chapter c4 9 - =Under .NET Assem blies140, 80); newstanding Car("Car four", Chapter 3

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter // 11 - Display Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing generations. Pa r t FourConsole.WriteLine("C1 - Le ve r a ging the .NET Libr a r ieis s

gen {0} ", GC.GetGeneration(c1));

Chapter Console.WriteLine("C2 12 - Obj ect Ser ialization and theis .NET Remoting LayGC.GetGeneration(c2)); er gen {0} ", Chapter Console.WriteLine("C3 13 - Building a Bet ter Win dow ( is Int roducin gen {0} g Window ", sGC.GetGeneration(c3)); For ms)

gen Chapter Console.WriteLine("C4 14 - A Better Paint ing Fr amew oris k ( GDI + ) {0} ", GC.GetGeneration(c4)); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

cars manually. Chapter // 16 - Dispose The Sy stemsome .I O Nam espace Chapter c1.Dispose(); 17 - Data Access w ith ADO.NET Pa r t Fi vec3.Dispose(); - W e b Appl ica ti ons and X ML W e b Se r vi ces

allPages genand 0 objects? Chapter // 18 - Collect ASP.NET Web Web Contr ols GC.Collect(0);

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

// Display generations again Console.WriteLine("C1 is gen List of Figur es Console.WriteLine("C2 is gen List of Tables Console.WriteLine("C3 is gen Console.WriteLine("C4 is gen return 0; } I ndex

The output is shown in Figure 5-14.

(each will be promoted). {0} ", GC.GetGeneration(c1)); {0} ", GC.GetGeneration(c2)); {0} ", GC.GetGeneration(c3)); {0} ", GC.GetGeneration(c4));

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - 5-14: Obj ectInfluencing Ser ializationanand the .NET Remoting Lay er Figure object's current generation Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Notice that when you request a collection of generation 0, each object is promoted to generation 1, given that these objects did not need to be removed from memory (as the heap was not exhausted). Also note Chapter 16 - The Sy stem .I O Nam espace that if you request a collection of generation 2 objects, the objects that have survived the current garbage Chapter 17 - Data Access w ith ADO.NET collection remain at generation 2 (there is no generation greater than 2 as of .NET version 1.1). Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 considered, - ASP.NET Web Pages and that Webyour Contrinteractions ols All things keep in mind with the System.GC type should be slim to none. Chapter 19 - point ASP.NET Web Applicat ions heap is to move the responsibility of memory management from The whole of having a managed Chapter your hands 20 - into XMLthe Webhands Ser vices of the runtime. I ndex

SOURCE CODE

List of Figur es List of Tables

The Generations project is included under the Chapter 5 subdirectory.

Summary

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

This chapter examined OOP-centric Apr ess two © 2003 (1200 pages) topics. First, you were shown how the .NET runtime makes use of structured exception handling to contend withtsruntime problems. Using a small set of keywords ("try", This compr ehensiv e text star w ith a brief ov er view of the "catch", "throw", "finally"), C# programmers are able to raise and handle C# language and then quickly m oves to key technical and system-level and applicationlevel exceptions. ar chitectur al issues for .NET developer s. Next, you were exposed to various aspects of object lifetime. Given that the CLR makes use of runtime Tagarbage ble o f Con collections, t en t s the basic rule of thumb is to assume that the runtime will destroy an object when it is

"noand longer needed." your C# types make use of unmanaged resources that need to be freed C# t he .NET Plat forHowever, m, Secondif Edition in aoduction timely and predictable manner, you are free to override the virtual System.Object.Finalize() method I ntr and/or IDisposable interface. Finally, Pa r t One implement - I nt r oduci the ng C# a nd the .NET P la tf or m

you were exposed to the role of the System.GC type

and checked outPhilosophy a subset of functionality. Chapter 1 - The of its .NET Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

d th e .N ET Plat f orm , Se con d Ed it ion Chapter C# 6:anInterfaces and Collections ISBN:1590590554 by Andr ew Tr oelsen Apron essyour © 2003 (1200 pages) This chapter builds current understanding of object-oriented development by introducing the topic This compr ehensiv e textyou starlearn ts w ith a brief ov er view of the and implement custom of interface-based programming. Here how to use C# to define C# language and then quickly m oves to key technical and interfaces, and come to understand the benefits of building types that support multiple behaviors. Along ar chitectur al issues for .NET developer s. the way, a number of related topics are also discussed, such as obtaining interface references, explicit interface implementation, and the construction of interface hierarchies. Ta ble o f Con t en t s

The remainder of this chapter is spent examining some of the standard interfaces defined within the .NET base class libraries. As you will see, your custom types are free to implement these predefined interfaces I ntr to oduction support a number of advanced behaviors such as object cloning, object enumeration, and object Pa r t One -To I ntwrap r oduci ng C#up, a nd thewill .NET P la tfout or mthe numerous predefined interfaces that are implemented by sorting. things you check Chapter 1 The Philosophy of .NET various collection classes (ArrayList, Stack, etc.) defined by the System.Collections namespace. C# and t he .NET Plat for m, Second Edition

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Defining Interfaces Using C# - C# Language Fundamentals

Chapter 3

Chapter 4 - Obj ect -Orhave iented Pr ogr amdied mingby w ith COM programmers lived and theC# notion of interface-based programming for years. In fact, Chapter 5 Exceptions and Obj ect Lifetim e one of the central tenets of COM is that the only way a client can communicate with a COM class is via an Chapter 6 pointer - I nter faces Collections interface (not aand direct object reference). Although the .NET universe still honors the use of Chapter 7 Callback I nter faces, Ev ents interfaces, they are not the onlyDelegates, means byand which two binaries can communicate (as the CLR supports true Chapter object references). 8 - Advanced BeC#aware, Type however, Const ruction thatTechniques this does not in any way imply that interfaces are obsolete! Pa These r t Thresyntactic e - Pr ogrentities am m i ngare w i th still .N the ET Assem most elegant bl ie s

manner by which you can safely extend the functionality

of a custom type without existing Chapter 9 - Under standingbreaking .NET Assem blies code. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

First, a formal definition: An interface is nothing more than a named collection of semantically related abstract members. The exact number of members defined by a given interface always depends on the Pa r t Four - Le ve r a ging the .NET Libr a r ie s exact behavior you are attempting to model. Yes, it's true. An interface expresses a behavior that a given Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er class may support. At a syntactic level, an interface is defined using the C# "interface" keyword. Unlike Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) other .NET types, interfaces never specify a base class (not even System.Object) and contain members Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) that do not take an access modifier (given that interface methods are implicitly public, in order to allow the Chapter 15 - type Pr ogr ming with the Windows Form s To Contr supporting toam implement members). getols the ball rolling, here is a custom interface definition: Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

// This interface defines the behavior of 'having points'. // Interfaces don't have base classes! Chapter 18 - ASP.NET Web Pages and Web Contr ols public interface IPointy Chapter 19 - ASP.NET Web Applicat ions { Chapter byte 20 - XML Web Ser vices GetNumberOfPoints(); // Implicitly public and abstract. I ndex } Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

List of Figur es List of Tables

.NET interfaces (C# or otherwise) are also able to define any number of properties. For example, you could modify the IPointy interface to use a read/write property: // The pointy behavior as a read / write property. public interface IPointy { // Remove 'get' or 'set' to build read/write only property. byte Points{ get; set;} }

In either case, IPointy is an interface that expresses the behavior of "having points." As you can tell, this behavior might be useful in the shapes hierarchy developed in Chapter 4. The idea is simple: Some objects in the Shapes application have points (such as the Hexagon and Triangle) while others (such as the Circle) do not. If you configure the Hexagon and Triangle to support the IPointy interface, you can

safely assume that each class supports a common behavior, and therefore a common set of methods. C# an d th e .N ET Plat f orm , Se con d Ed it ion

by Andr ewmay Tr oelsen Note .NET interfaces also contain event and indexer ISBN:1590590554 method definitions. Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the Implementing an Interface Using C# C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

When a C# class (or structure) chooses to extend its functionality by supporting a given interface, it does so using a comma-delimited list in the type definition. Be aware that the direct base class must be listed Tafirst. ble oWhen f Con tyour en t sclass type derives directly from System.Object, you are free to simply list the interface(s) supported by the class, as the C# compiler will extend your types from System.Object if you do not say C# and t he .NET Plat for m, Second Edition otherwise. On a related note, given that structures always derive from System.ValueType, simply list each I ntr oduction interface directly after the structure definition: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET // This from System.Object and Chapter 2 - class Buildingderives C# Applications

// implements a single interface. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge public class SomeClass : ISomeInterface - C# Language Fundamentals {...}

Chapter 3 Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

// This class derives from a specific base class - I nter faces and Collections // and implements a single interface. Chapter 7 - Callback I nter faces, Delegates, and Ev ents public class AnotherClass : MyBaseClass, ISomeInterface Chapter {...}8 - Advanced C# Type Const ruction Techniques Chapter 6

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - struct Under standing .NET Assem // This derives from blies System.ValueType and Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads // implements a single interface. Chapter 11 struct - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing public SomeStruct : ISomeInterface Pa r t Four - Le ve r a ging the .NET Libr a r ie s {...}

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Understand implementing an interface Chapter 14 - Athat Better Paint ing Fr amew or k ( GDIis+ an ) all-or-nothing proposition. The supporting class is not able to 15 selectively choose which members implement. Given that the IPointy interface defines a Chapter - Pr ogr am ming with Windows Formitswill Contr ols

single method, this is not too much of a burden. However, if you are implementing an interface that defines ten members, the type is now responsible for fleshing out the details of the ten abstract entities.

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Pa r t FiNote ve - W e b Appl ica ti ons and X ML e b Se r vi ces Abstract base classes areWpermitted to support

interfaces without implementing the interface

Chapter 18 members - ASP.NET so Web Pages and explicitly Web Contrdefine ols long as they them as abstract. By doing so, derived types will be Chapter 19 responsible - ASP.NET Web Applicat ions each member and thus become compatible with the interface in for implementing Chapter 20 question. - XML Web Ser vices I ndex

Here is theesimplementation of the updated shapes hierarchy: List of Figur List of Tables

// A given class may implement as many interfaces as necessary, // but may have exactly 1 base class. public class Hexagon : Shape, IPointy { public Hexagon(){ } public Hexagon(string name) : base(name){ } public override void Draw() { // Recall the Shape class defined the PetName property. Console.WriteLine("Drawing {0} the Hexagon", PetName); } // IPointy Implementation. public byte GetNumberOfPoints() { return 6; } }

public class Triangle : Shape, IPointy C# an d th e .N ET Plat f orm , Se con d Ed it ion { ISBN:1590590554 by Andr ew Tr oelsen public Triangle() { } Apr ess © 2003 (1200 pages) public Triangle(string name) : base(name) { } This compr ehensiv text star ts w ith a brief ov er view of the public override void e Draw() C# language and then quickly m{0} oves the to keyTriangle", technical and PetName); } { Console.WriteLine("Drawing ar chitectur al issues for .NET developer s. // IPointy Implementation. public byte GetNumberOfPoints() { return 3; } Ta ble o f Con t en t s } C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I ntnow r oduci ng C# the a ndnumber the .NETofP points la tf or mto Each class returns

the outside world when asked to do so. To sum up the

Chapter - The Philosophydiagram of .NET illustrates IPointy-compatible objects using the popular COM lollipop story so1 far, the following Chapter 2 Building C# Applications notation. For those coming from a non-Microsoft view of the world, COM objects are graphically Pa r t Tw o - Theusing C# Pra ogr am m ing La ngua represented lollipop (aka jack)gefor

each interface supported by a given class. For those who are

Chapter - C# Fundamentals familiar3with theLanguage COM lifestyle, notice that the Hexagon and Triangle classes (see Figure 6-1) do not Chapter 4 - IUnknown Obj ect -Or iented Pr ogr am ming w ith C# base class (again illustrating the stark differences implement and derive from a common Chapter between 5 COM - Exceptions and .NET). and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - 6-1: ASP.NET Applicat ions hierarchy Figure The Web updated shapes Chapter 20 - XML Web Ser vices I ndex

Contrasting Interfaces to Abstract Base Classes

List of Figur es List of Tables

Given your work in Chapter 4, you may be wondering why you need the "interface" keyword in the first place. After all, C# allows you to build base classes containing abstract methods. Like an interface, when a child class derives from an abstract base class, it is also under obligation to flesh out the details of the abstract methods. However, abstract base classes typically do far more than define a group of abstract methods. They are free to define public, private, and protected state data, as well as any number of concrete methods that can be accessed by the subclasses. Interfaces on the other hand, are pure protocol. Interfaces never define data types, and never provide a default implementation of the methods. Every member of an interface (whether it is a property or method) is automatically abstract. Furthermore, given that C# (and .NET-aware languages in general) only supports single inheritance, the interface-based protocol allows a given type to support numerous behaviors, while avoiding the issues that arise when deriving from multiple base classes. In a nutshell, interface-based programming provides yet another way to inject polymorphic behavior into a system: If multiple classes (or structures) implement the same interface in their unique ways, you have the power to treat each type in the same manner. As you will see a bit later in this chapter, interfaces are

extremely polymorphic, given that types that are not related via classical inheritance can support identical C# an d th e .N ET Plat f orm , Se con d Ed it ion behaviors. by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e Members .N ET Plat f orm ,at Se the con d Ed it ion Invoking Interface Object Level ISBN:1590590554

by Andr ew Tr oelsen

Now that you have set©of2003 types that support the IPointy interface, the next question is how you interact Apraess (1200 pages) with the defined members. The most straightforward This compr ehensiv e text star ts w ith a way brief to ovinteract er view ofwith thefunctionality supplied by a given interface is to invoke the methods directly from the object level. For example: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Hexagon hex = new Hexagon(); Console.WriteLine("Points: {0}", hex.GetNumberOfPoints());

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntr oduction This approach works fine in this case, given that you are well aware that the Hexagon type has Pa r t One - I nt r oduci ng C# a nd .NET P la tf or mtimes, implemented the interface in the question. Many

however, you will not be able to determine at compile

Chapter 1 - interfaces The Philosophy of .NET by a given type. For example, assume you have a collection time which are supported Chapter 2 Building C# Applications containing some number of types. Ideally, you would like to determine which interfaces are supported by a Pa r t Tw - The C#toPrtrigger ogr am the m ing La ngua ge type atoruntime functionality

Chapter 3

on the fly.

- C# Language Fundamentals

Furthermore, inect a -Or number Chapter 4 - Obj ientedofPrcircumstances ogr am ming w ith(as C#seen over the course of this chapter) you will be required to obtain a- valid interface reference directly before you are able to trigger said functionality. Given these Exceptions and Obj ect Lifetim e two scenarios, let's check out a number of techniques that can be used to test for interface support and Chapter 6 - I nter faces and Collections see how to obtain a stand-alone interface reference from an implementing type. Chapter 5 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Obtaining Interface References: Explicit Casting

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Assume you have created an instance of the Hexagon class, and wish to dynamically discover if it supports the pointy behavior. One approach is to make use of an explicit cast (as described in Chapter 4) Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing in order to obtain an interface reference: Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

// Cast for the interface reference. Hexagon hex = new Hexagon("Bill"); Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) IPointy itfPt = (IPointy)hex; Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Console.WriteLine(itfPt.GetNumberOfPoints());

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Pa t Fi ve W e brequire Appl icaatistand-alone ons and X MLinterface W e b Se r vi ces Ifryou do- not reference,

you could shorten the previous code into a single

Chapter - ASP.NET Web Pages and Web Contr ols step as18 follows: Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - end XML Web Ser vices // Same result, less code. I ndex Hexagon hex = new Hexagon("Bill"); List of Figur es Console.WriteLine(((IPointy)hex).GetNumberOfPoints()); List of Tables

In each of these cases, you are explicitly asking the Hexagon instance for access to the IPointy interface. If the object does support this interface, you are then able to exercise the behavior accordingly. However, what if you were to create an instance of Circle? Given that the Circle class does not support the IPointy interface, you are issued a runtime error if you attempt to invoke GetNumberOfPoints()! When you attempt to access an interface not supported by a given class using a direct cast, the runtime throws an InvalidCastException. To safely recover from this possibility, simply catch the exception: // Safely cast for interface reference. Circle c = new Circle("Lisa"); IPointy itfPt; try { itfPt = (IPointy)c; Console.WriteLine(itfPt.GetNumberOfPoints());

} C# an d th e .N ET Plat f orm , Se con d Ed it ion catch(InvalidCastException e) by Andr ew Tr oelsen { Console.WriteLine("OOPS! Not pointy..."); }ISBN:1590590554 Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Obtaining Interface References: The "as" Keyword The second way you can test for interface support (as well as obtain an interface from an object tot smake use of the "as" keyword, which was first introduced in Chapter 4 during our Tareference) ble o f Con is t en examination of casting For example: C# and t he .NET explicit Plat for m, Secondoperations. Edition I ntr oduction Pa r t One - I nt r oduci a nd the .NET P lainterface: tf or m // Second way ng toC#test for an

Chapter Hexagon 1 - hex2 The Philosophy = new Hexagon("Peter"); of .NET

IPointy Chapter 2 - itfPt2; Building C# Applications itfPt2 = hex2 as am IPointy; Pa r t Tw o - The C# Pr ogr m ing La ngua ge if(itfPt2 null) Fundamentals Chapter 3 - C#!= Language Chapter Console.WriteLine(itfPt2.GetNumberOfPoints()); 4 - Obj ect -Or iented Pr ogr am ming w ith C#

else 5 Chapter

- Exceptions and Obj ect Lifetim e Not pointy..."); Chapter Console.WriteLine("OOPS! 6 - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

Advanced C# Type Const ruction Techniques As you can- see, the "as" syntax sets the interface variable to null if a given interface is not supported by the object (notice that you check your IPointy reference for null before continuing) rather than throwing an Chapter 9 - Under standing .NET Assem blies exception. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Obtaining Interface References: The "is" Keyword

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Finally, you may also obtain an interface from an object using the "is" keyword. If the object in question is

Chapter 13 - compatible, Building a Bet tercondition Win dow (fails: Int roducin g Window s For ms) not IPointy the Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

// Third way to test for an interface. Triangle t = new Triangle(); Chapter 17 IPointy) - Data Access w ith ADO.NET if(tis Pa r t Fi veConsole.WriteLine(t.GetNumberOfPoints()); - W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter else 18 - ASP.NET Web Pages and Web Contr ols Chapter Console.WriteLine("OOPS! 19 - ASP.NET Web Applicat ions Not pointy..."); Chapter 16 - The Sy stem .I O Nam espace

Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

th e .N ET Plat f orm , Se con d Ed it ion Exercising C# thean dShapes Hierarchy by Andr ew Tr oelsen

ISBN:1590590554

In these examples, havepages) avoided checking the outcome of asking for the IPointy reference, given that Apryou ess could © 2003 (1200 you knew ahead This of time which shapes were However, compr ehensiv e text star IPointy ts w ith acompatible. brief ov er view of the what if you were to create an array of generic Shape references, each of which has been assigned to a given C# language and then quickly m oves to key technical andsubclass? You may make use of any of ar chitectur al issues at for runtime .NET developer s. the previous techniques to discover which items in the array support this behavior: // Let's discover which shapes are pointy at runtime... Shape[] s = { new Hexagon(), new Circle(), new Triangle("Joe"), C# and t he .NET Plat for m, Second Edition new Circle("JoJo")} ; I ntr oduction for(int i = 0; i < s.Length; i++) Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m { Chapter // 1 - Recall The Philosophy of .NET base class defines an abstract Draw() member, the Shape Chapter // 2 - so Building C# Applications all shapes know how to draw themselves. Pa r t Tw os[i].Draw(); - The C# Pr ogr am m ing La ngua ge Chapter // 3 - Who's C# Language Fundamentals pointy? Chapter if(s[i] 4 - Obj ect is -Or iented Pr ogr am ming w ith C# IPointy) Chapter 5 - Exceptions and Obj ect Lifetim e Points: {0} ", ((IPointy)s[i]).GetNumberOfPoints() Console.WriteLine("-> Chapter else 6 - I nter faces and Collections Console.WriteLine("-> {0}\'s Chapter 7 - Callback I nter faces, Delegates, and Ev ents not pointy!", s[i].PetName); } Chapter 8 - Advanced C# Type Const ruction Techniques

Ta ble o f Con t en t s

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

The output follows in Figure 6-2.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Figure 6-2: Dynamically determining implemented interfaces

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Interfaces As Parameters

Chapter 20 - XML Web Ser vices

I ndex Given that interfaces are strongly typed entities, you may construct methods that take interfaces as parameters List of as Figur es well method return values. To illustrate, assume you have defined another interface named IDraw3D as List of Tables follows:

// The 3D drawing behavior. public interface IDraw3D { void Draw3D(); }

Next, assume that two of your three shapes (Circle and Hexagon) have been configured to support this new behavior: // Circle supports IDraw3D. public class Circle : Shape, IDraw3D { ...

public void Draw3D() C# an d th e .N ET Plat f orm , Se con d Ed it ion { Console.WriteLine("Drawing Circle in 3D!"); } ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

}

This compr ehensiv multiple e text star ts w ith a brief ov er view of the tack them // If your types support interfaces, simply C# language and then quickly m oves to key technical and // to the end of the class definition. ar chitectur al issues for .NET developer s. public class Hexagon : Shape, IPointy, IDraw3D { ... Ta ble o f Con t en t s public void Draw3D() C# and t he .NET Plat for m, Second Edition { Console.WriteLine("Drawing Hexagon in 3D!"); } I ntr oduction } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2 -define Building C# Applications If you now a method taking an IDraw3D interface as a parameter, you are able to effectively send in any Pa r t Tw osupporting - The C# PrIDraw3D. ogr am m ing La ngua the ge object Consider

Chapter 3

following:

- C# Language Fundamentals

Chapter 4 - some Obj ect shapes. -Or iented PrIf ogr am mingcan w ith be C# rendered in 3D, do it! // Make they Chapter 5 Exceptions and Obj ect Lifetim e public class ShapesApp Chapter 6 {

- I nter faces and Collections

Chapter // 7 - I'll Callback I nteranyone faces, Delegates, and Ev ents draw supporting IDraw3D! Chapter public 8 - Advanced C# Type Const ruction Techniques static void DrawThisShapeIn3D(IDraw3D itf3d) Pa r t Thre{e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under Console.WriteLine("-> standing .NET Assem blies Drawing IDraw3D compatible type");

Chapter 10 - Pr itf3d.Draw3D(); ocesses, AppDomains, Cont exts, and Threads Chapter } 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

static intLibr Main(string[] Pa r t Fourpublic - Le ve r a ging the .NET a r ie s

args)

Chapter { 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Shape[] { dow new( IntHexagon(), new Circle(), Chapter 13 - Building a Bet s ter =Win roducin g Window s For ms) new new Circle("JoJo")} ; Chapter 14 - A Better Paint ing Fr amew or kTriangle(), ( GDI + ) for(int i = 0; i < s.Length; i++) { Chapter 16 - The Sy stem .I O Nam espace ... Chapter 17 - Data Access w ith ADO.NET // Can I draw you in 3D? Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces if(s[i] is IDraw3D) Chapter 18 - ASP.NET Web Pages and Web Contr ols DrawThisShapeIn3D((IDraw3D)s[i]); Chapter 19 - ASP.NET Web Applicat ions } Chapter 20 - XML Web Ser0; vices return I ndex } List } of Figur es Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

List of Tables

Notice that the triangle is never drawn, as it is not IDraw3D compatible (Figure 6-3).

Figure 6-3: Interfaces as parameters

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dExplicit th e .N ET Plat f orm , Se conImplementation d Ed it ion Understanding Interface by Andr ew Tr oelsen

ISBN:1590590554

In our previous definition IDraw3D, you were forced to name your method Draw3D() in order to avoid Apr ess ©of 2003 (1200 pages) clashing with the This abstract Draw() method defined Shapes base compr ehensiv e text star ts w ithinathe brief ov er view of class: the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. // The 3D drawing behavior. public interface IDraw3D { void Draw3D(); }

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntr oduction While there is nothing horribly wrong with this interface definition, a more natural method name would Pa r t One be - I nt r oduci ng C# a nd the .NET P la tf or m simply Draw():

Chapter 1

- The Philosophy of .NET

Chapter 2 3D - Building C# Applications // The drawing behavior. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge public interface IDraw3D

Chapter 3 - Draw(); C# Language { void } Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e If you were create newCollections class that derives from Shape and implements IDraw3D, you would be in for Chapter 6 - to I nter facesaand

some problematic Before seeingand theEv problem firsthand, assume you have defined the following Chapter 7 - Callbackbehavior. I nter faces, Delegates, ents new class Line: Chapter 8 -named Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

// Problems... Chapter 9 - Under standing .NET Assem blies public LineAppDomains, : Shape,Cont IDraw3D Chapter 10 class - Pr ocesses, exts, and Threads // Both define a Draw() method! { Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing public override void Pa r t Four - Le ve r a ging the .NET Libr aDraw() r ie s Chapter{12 - Obj ect Ser ialization and the .NET Remoting Lay er

Console.WriteLine("Drawing a line..."); Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) }

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

}

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 class - Data Access wwithout ith ADO.NET The Line compiles a hitch. But, consider the following object user code: Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

// Calls Line.Draw() Line myLine = new Line(); Chapter 20 - XML Web Ser vices myLine.Draw();

Chapter 19 - ASP.NET Web Applicat ions I ndex List Figur es //ofAlso calls Line.Draw(). List of Tables IDraw3D itfDraw3d= (IDraw3D) myLine;

itfDraw3d.Draw();

Given what you already know about the Shapes base class and IDraw3D interface, it looks as if you have acquired two abstract methods named Draw(). However, as the Line class offers a concrete implementation, the compiler is happy to call the same implementation from an interface or object reference. This is problematic in that you would like to have the IDraw3D.Draw() method render a type in stunning 3-D, while the overridden Shape.Draw() method draws in boring 2-D. Now consider a related problem. What if you wish to ensure that the methods defined by a given interface are only accessible from an interface reference rather than an object reference? Currently, the members defined by the IPointy interface can be accessed using either an object reference or an IPointy reference. The answer to both questions comes by way of explicit interface implementation. Using this technique, you are able to ensure that the object user can only access methods defined by a given interface using the correct interface reference, as well as circumvent possible name clashes. To illustrate, here is the

updated Line class:

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

// Using explicit method implementation we are able Apr ess © 2003 (1200 pages) // to provide distinct Draw() implementations. This compr ehensiv e text star ts w ith a brief ov er view of the public class C# Line : Shape, IDraw3D language and then quickly m oves to key technical and { ar chitectur al issues for .NET developer s. // You can only call this method using an IDraw3D interface reference. void IDraw3D.Draw() Console.WriteLine("Drawing a 3D line..."); } Ta ble o { f Con t en t s C# and t he .NET Plat for m, Second Edition

// You can only call this using a Line (or base class) reference. I ntr oduction public override Draw() Pa r t One - I nt r oduci ng C# a ndvoid the .NET P la tf or m a line..."); } Chapter{1 Console.WriteLine("Drawing - The Philosophy of .NET } Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

There are a few odds and ends to be aware of when using explicit interface implementation. First and - Obj ect -Or iented Pr ogr am ming w ith C# foremost, you cannot make use of an access modifier when using this technique. For example, the Chapter 5 Exceptions and Obj ect Lifetim e following is- illegal syntax: Chapter 4 Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

// Nope! Illegal. Chapter 8 - Advanced C# Type Const ruction Techniques public class Line : Shape, IDraw3D Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s { Chapterpublic 9 - Under standing .NET Assem blies // = maxSpeed) I ndex carIsDead = true; List of Figur es else List of Tables Console.WriteLine("\tCurrSpeed = {0} ", currSpeed); } } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

To wrap things up all nice and tidy, here is some client-side code, now making use of a callback interface to listen to the Car events: // Make a car and listen to the events. public class CarApp { public static int Main(string[] args) { Car c1 = new Car("SlugBug", 100, 10); // Make sink object. CarEventSink sink = new CarEventSink();

// Pass the Car a reference to the sink. C# an d th e .N ET Plat f orm , Se con d Ed it ion c1.Advise(sink); ISBN:1590590554 by Andrup ew (this Tr oelsen will generate the events). // Speed Apr ess © 2003 (1200 pages) for(int i = 0; i < 6; i++) This compr ehensiv e text star ts w ith a brief ov er view of the c1.SpeedUp(20); C# language then quickly m oves to key technical and // Detach fromand events. ar chitectur al issues for .NET developer s. c1.Unadvise(sink); return 0; }

Ta ble o f Con t en t s

}

C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter The Philosophy of .NET Figure 17-1- shows the end result of this interface-based event protocol. Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8 - 7-1: Advanced C# Type Const ruction Techniques Figure An interface-based event protocol Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter - Under standing .NET Assemcan blies Do note9 that the Unadvise() method be very helpful in that it allows the caller to selectively detach Chapter from events 10 - Pr atocesses, will. Here, AppDomains, you call Unadvise() Cont exts, before and Threads exiting Main(), although this is not technically

necessary. assume that the application nowBased wishesPrto register Chapter 11 - However, Type Reflection, Late Binding, and Attr ibuteogramm ingtwo sinks, dynamically remove a particular sink the .NET flow of execution, Pa r t Four - Le ve rduring a ging the Libr a r ie s

and continue processing the program at large:

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 static - Buildingint a Bet Main(string[] ter Win dow ( Int roducin g Window s For ms) public args) Chapter { 14 - A Better Paint ing Fr amew or k ( GDI + )

a ming car with as Windows usual. Form s Contr ols Chapter // 15 - Make Pr ogr am c1 Sy = stem new.I O Car("SlugBug", 100, 10); Chapter Car 16 - The Nam espace sink wobjects. Chapter // 17 - Make Data Access ith ADO.NET Creating Pa r t Fi veConsole.WriteLine("***** - W e b Appl ica ti ons and X ML W e b Se r vi ces

sinks *****");

sink"); Chapter CarEventSink 18 - ASP.NET Web sink Pages = andnew Web CarEventSink("First Contr ols = new CarEventSink("Other sink"); Chapter CarEventSink 19 - ASP.NET Web myOtherSink Applicat ions // Hand sinks to Car. Console.WriteLine("\n***** Sending 2 sinks into Car *****"); I ndex c1.Advise(sink); List of Figur es c1.Advise(myOtherSink); List of Tables // Speed up (this will generate the events.) Console.WriteLine("\n***** Speeding up *****"); for(int i = 0; i < 6; i++) c1.SpeedUp(20); // Detach first sink from events. Console.WriteLine("\n***** Removing first sink *****"); c1.Unadvise(sink); // Speed up again (only 'other sink' will be called.) Console.WriteLine("\n***** Speeding up again *****"); for(int i = 0; i < 6; i++) c1.SpeedUp(20); // Detach other sink from events. Console.WriteLine("\n***** Removing second sink *****"); c1.Unadvise(myOtherSink); return 0; } Chapter 20 - XML Web Ser vices

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

Event interfaces will always have place under any programming architecture. However, as you may Apr ess © 2003 (1200their pages) be suspecting, the .NET platform supplies native support enabling communications. To This compr ehensiv e text star ts w ith a brieffor ov er view of bidirectional the understand this intrinsic event protocol, we begin by examining the role of the delegate type. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

SOURCE CODE

The EventInterface project is located under the Chapter 7 subdirectory.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET PlatDelegate f orm , Se con dType Ed it ion Understanding .NET ISBN:1590590554

by Andr ew Tr oelsen

Before formally defining delegates, Apr ess ©.NET 2003 (1200 pages) let's gain a bit of perspective. Historically speaking, the Windows API makes frequent use of C-style create callback functions or simply This compr ehensiv efunction text starpointers ts w ith atobrief ov erentities view of termed the callbacks. Using C# callbacks, programmers were able to configure one function to report back to (call back) language and then quickly m oves to key technical and ar chitectur al issuesUnderstand for .NET developer s. another function in the application. that C-style callback functions have nothing to do with traditional COM connection points or event interfaces (however, in many ways the same end result was achieved). Ta ble o f Con t en t s

The problem with C-style callback functions is that they represent little more than a raw address C# and t he .NET Platstandard for m, Second Edition in memory. I ntr oduction Ideally, callbacks could be configured to include additional type-safe information such as the number (and types of)aparameters and Pa r t One -of I nt r oduci ng C# nd the .NET P la tf the or m return

value (if any) of the method pointed to. Sadly, this is

not the1case in traditional Chapter - The Philosophycallback of .NET functions, and, as you may suspect, can therefore be a frequent source of bugs, crashes, other runtime disasters. Chapter 2 hard - Building C# and Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Nevertheless, callbacks are useful entities. In the .NET Framework, callbacks are still possible, and their - C# Language Fundamentals functionality is accomplished in a much safer and more object-oriented manner using delegates. In Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# essence, a delegate is an object that points to another method in the application. Specifically speaking, a Chapter 5 maintains - Exceptions andimportant Obj ect Lifetim e of information: delegate three pieces Chapter 3

Chapter 6

- I nter faces and Collections

The of the Imethod onDelegates, which it makes Chapter 7 name - Callback nter faces, and Evcalls ents Chapter 8

- Advanced C# Type Const ruction Techniques

Thearguments (if any) of this method

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 return - Under standing .NET Assem blies The value (if any) of this method Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Once a11 delegate has been created and provided the aforementioned it may dynamically Chapter - Type Reflection, Late Binding, and Attr ibuteBased Pr ogramminformation, ing invoke method it represents ataruntime. Pa r t Fourthe - Le ve r a ging the .NET Libr r ie s

As you will see, the .NET Framework automatically supports

the use12 of -synchronous and asynchronous Chapter Obj ect Ser ialization and the .NETdelegates Remoting (both Lay er of which are seen over the course of this chapter). Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Defining a Delegate in C#

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

When you createw ith a delegate Chapter 17 -want Datato Access ADO.NETin C#, you make use of (surprise, surprise) the "delegate" keyword. Under the expands Pa r t Fi vethe - Whood, e b Appl icadelegate ti ons andkeyword X ML W e b Se r vi cesto

a sealed class type deriving from

System.MulticastDelegate. For example, if youols write the following C# delegate definition: Chapter 18 - ASP.NET Web Pages and Web Contr Chapter 19 - ASP.NET Web Applicat ions

public PlayAcidHouse(Person theDJ, int volume); Chapter 20delegate - XML Web void Ser vices I ndex List of Figur es

the C# compiler dynamically produces a new sealed class named PlayAcidHouse deriving from System.MulticastDelegate. This class is only capable of calling a method that takes two parameters (of type Person and System.Int32) and returns nothing. If you check out how this class type is represented in metadata format using ildasm.exe (Figure 7-2), you would see that the PlayAcidHouse type indeed derives from System.MulticastDelegate.

List of Tables

Figure 7-2: The C# "delegate" keyword represents a sealed type deriving from

System.MulticastDelegate.

C# an d th e .N ET Plat f orm , Se con d Ed it ion

ISBN:1590590554 by Andr ew Tr oelsen class has been automatically As you can see, the PlayAcidHouse endowed (thanks to the C# compiler) Apr ess © 2003 (1200 pages) with three public methods. Invoke() is perhaps the core method, and it may be called to inform the delegate it is timeThis to call compr theehensiv method e text it is currently star ts w ithpointing a brief ov to.erNotice view ofthat the the parameters that are sent into C# language and then quickly m oves to key technical and BeginInvoke() and EndInvoke() Invoke() are identical to the declaration of the PlayAcidHouse delegate. issues for .NET developer s. provide the abilityartochitectur call thealcurrent method asynchronously (Invoke(), on the other hand, makes synchronous method calls). Strangely enough, the synchronous Invoke() method is not directly callable from C#. As you will see in just a bit, Invoke() is called behind the scenes when you make use of the Ta ble o f Con t en t s appropriate C# syntax.

C# and t he .NET Plat for m, Second Edition

I ntr oduction Now, how exactly does the compiler know how to prototype the Invoke(), BeginInvoke(), and EndInvoke() Pa r t One - I nt ng C# a nd .NET P here la tf or is m methods? Tor oduci understand thethe process,

the crux of the generated PlayAcidHouse class type (the

Chapter - The Philosophy .NET items in1 bold represent theofauto-generated items): Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua:ge System.MulticastDelegate sealed class PlayAcidHouse

Chapter 3 {

- C# Language Fundamentals

Chapter public 4 - Obj ect -Or iented Pr ogr am ming w ith target, C# PlayAcidHouse(object uint functionAddress); Chapter public 5 - Exceptions Obj ect Lifetim e theDJ, int volume); void and Invoke(Person Chapter public 6 - I nter faces IAsyncResult and Collections BeginInvoke(Person theDJ, int volume,

AsyncCallback cb, object state); - Callback I nter faces, Delegates, and Ev ents public void EndInvoke(IAsyncResult Chapter 8 - Advanced C# Type Const ruction Techniques result); }r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Pa Chapter 7

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

First, notice that the parameters that are defined for the Invoke() and BeginInvoke() members (in addition to the mandatory AsyncCallback and System.Object parameters of the BeginInvoke() method) are the Pa r t Four - Le ve r a ging the .NET Libr a r ie s same number of, and type of, the original C# delegate declaration. Likewise, the return value of Invoke() Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er and EndInvoke() is identical to the original C# delegate declaration. And obviously, the name of the Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) constructor is based on the name of the original C# delegate declaration. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter Now assume 15 - Pr you ogr am have ming defined with Windows anotherForm C# delegate s Contr olstype that represents a method returning a string and

taking three Booleans: Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica tistring ons and XTakeSomeBools(bool ML W e b Se r vi ces public delegate

a, bool b, bool c);

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

This time, auto-generated Chapter 20 -the XML Web Ser vices class breaks down as follows: I ndex

sealed TakeSomeBools : System.MulticastDelegate List of Figurclass es { of Tables List public TakeSomeBools(object target, uint functionAddress); public string Invoke(bool a, bool b, bool c); public IAsyncResult BeginInvoke(bool a, bool b, bool c, AsyncCallback cb, object state); public string EndInvoke(IAsyncResult result); }

Finally, understand that delegates can also "point to" methods that contain out and ref parameters: public delegate string TakeSomeBoolsByRefAndAsOut (out bool a, out bool b, ref bool c);

In this case, the signatures of the Invoke() and BeginInvoke() methods look as you would expect; however, check out the EndInvoke() method, which now pads the first set of parameters with the set of out/ref

arguments from the delegate:

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

sealed class TakeSomeBoolsByRefAndAsOut : System.MulticastDelegate Apr ess © 2003 (1200 pages) { This compr ehensiv e text star ts w ith a brief ov er view of the public TakeSomeBoolsByRefAndAsOut (object target, uint functionAddress); C# language and then quickly m oves to key technical and public arstring Invoke(out bool a, out bool b, ref bool c); chitectur al issues for .NET developer s. public IAsyncResult BeginInvoke(out bool a, out bool b, ref bool c, AsyncCallback cb, object state); public Ta ble o f Con t en t s string EndInvoke(out bool a, out bool b, bool c, IAsyncResult result); C# and t he .NETref Plat for m, Second Edition } I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

I think you can see the general pattern: A C# delegate definition results in a sealed class with three autogenerated methods whose parameter and return types are based on the delegate's declaration. We will Chapter 3 - C# Language Fundamentals see exactly how we interact with Invoke(), BeginInvoke(), and EndInvoke() in just a bit, but first let's check Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# out the System.MulticastDelegate base class. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Members ofC#System.MulticastDelegate by Andr ew Tr oelsen

ISBN:1590590554

So then, when you type(1200 using the C# "delegate" keyword, you indirectly declare a type that derives Aprbuild ess ©a2003 pages) from System.MulticastDelegate. The MulticastDelegate type inview turn of derives This compr ehensiv e text star ts w ith a brief ov er the from System.Delegate (as well as implements two standard interfaces). Here is the formal definition of MulticastDelegate: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

public abstract class MulticastDelegate : Delegate, ICloneable, ISerializable Ta ble o f Con t en t s { C# and t he .NET Plat for m, Second Edition public MethodInfo Method { get; } I ntr oduction public object Target { get; } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public virtual object Clone(); Chapter 1 - The Philosophy of .NET public object DynamicInvoke(object[] args); Chapter 2 Building C# Applications public virtual bool Equals(object obj); Pa r t Tw o - The C# Pr ogr amint m ing GetHashCode(); La ngua ge public virtual Chapter 3 - C#virtual Language Delegate[] Fundamentals GetInvocationList(); public Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# public virtual void Chapter 5 GetObjectData(SerializationInfo - Exceptions and Obj ect Lifetim e info, StreamingContext context); Chapter public 6 - I nter Type facesGetType(); and Collections public virtual ToString(); Chapter 7 - Callback I nterstring faces, Delegates, and Ev ents } Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

And here is the definition of System.Delegate:

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

public class Delegate Pa r t Four - abstract Le ve r a ging the .NET Libr a r ie s

: object, ICloneable, ISerializable Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er { Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) public MethodInfo Method { get; } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) public object Target { get; } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols public virtual object Clone(); Chapter 16 - The Sy stem .I O Nam espace public static Delegate Combine(Delegate a, Delegate b); Chapter 17 - Data Access w ith ADO.NET public static Delegate Combine(Delegate[] delegates); Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces public static Delegate Chapter 18 CreateDelegate(Type - ASP.NET Web Pages and Web ContrSystem.Reflection.MethodInfo ols type, method); Chapter 19 - ASP.NET Web Applicat ions public static Delegate Chapter 20 CreateDelegate(Type - XML Web Ser vices type, object target, string method); I ndex public static Delegate CreateDelegate(Type type, Type target, string method); List ofpublic Figur es static Delegate CreateDelegate(Type type, List of Tables object target, string method, bool ignoreCase); public object DynamicInvoke(object[] args); public virtual bool Equals(object obj); public virtual int GetHashCode(); public virtual Delegate[] GetInvocationList(); public virtual void GetObjectData(SerializationInfo info, StreamingContext context); public Type GetType(); public static Delegate Remove(Delegate source, Delegate value); public virtual string ToString(); }

Together, these two base classes provide the necessary infrastructure for the derived type to wrap and invoke a method on the fly. Table 7-1 documents the key members to be aware of.

Table 7-1: Select Members of System.MultcastDelegate/System.Delegate C# an d th e .N ET Plat f orm , Se con d Ed it ion

Inherited Member

Meaning by Andr ew Tr oelsen in Life Apr ess © 2003 (1200 pages)

Method

This compr ehensiv e text star ts w ith a brief ov er view of the This property returns the name of a static method that is maintained by the C# language and then quickly m oves to key technical and delegate. ar chitectur al issues for .NET developer s.

ISBN:1590590554

Target

If the method to be called is defined at the object level (rather than a static method), Target returns the name of the method maintained by the delegate. Ta ble o f Con t en t s If the value returned from Target equals null, the method to be called is a C# and t he .NET Plat for m, Second Edition static member. I ntr oduction

static method Pa rCombine() t One - I nt r oduci ng C# aThis nd the .NET P la tf oradds m

a method to the list maintained by the delegate. In

Chapter 1

C#, - The Philosophy of you .NETtrigger this method using the overloaded += operator as a shorthand

Chapter 2

notation. - Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

GetInvocationList()

Chapter 3 Chapter 4

This method returns an array of System.Delegate types, each representing a

- C# Language particular Fundamentals method that may be invoked. - Obj ect -Or iented Pr ogr am ming w ith C#

Remove() This method Chapter 5 - Exceptions and Objstatic ect Lifetim e removes a delegate from the list methods to call. In C#, Chapter 6

trigger this method using the overloaded -= operator as a shorthand - I nter faces andyou Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

notation.

As you may be able to infer from Table 7-1, delegates are capable of pointing to multiple methods. Under the hood, the System.Delegate type defines a linked list that is used to hold onto each method maintained by a Chapter 9 - Under standing .NET Assem blies given delegate. Additional methods can be added to this internal list using the static Combine() method (or Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads using the C# overloaded += operator). To remove a method from the internal list, call the static Remove() Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing method (or the C# overloaded -= operator). As you may know, the ability for a delegate to call multiple Pa r t Four - Le ve r a ging the .NET Libr a r ie s functions is termed multicasting . You see this technique action a bit later in this chapter. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion The Simplest Possible Delegate Example ISBN:1590590554

by Andr ew Tr oelsen

Delegates can tend great deal of confusion when encountered for the first time. Thus, to get Apr to esscause © 2003a(1200 pages) the ball rolling, let's take a look at a very is the code, with analysis to This compr ehensiv e text simple star ts wexample. ith a brief Here ov er view of complete the follow: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

namespace SimpleDelegate { Ta ble o f Con t en t s class DelegateApp C# and t he .NET Plat for m, Second Edition { I ntr oduction // This is the method that will be called Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // by the delegate. Chapter 1 - The Philosophy of .NETvoid PlainPrint(string msg) public static Chapter 2 - Building C# Applications { Console.WriteLine("Msg is: {0}", msg); } Pa r t Tw o - The C# ogr am m ing La ngua ge // PrDefine a delegate type. Chapter 3 - C#public Language Fundamentals delegate void AnyMethodTakingAString(string s); Chapter 4 - Obj ect -Or iented Pr ogr am mingMain() w ith C# public static void Chapter 5 - Exceptions and Obj ect Lifetim e { Chapter 6 - I nter faces //and Make Collections the delegate. del; Chapter 7 - CallbackAnyMethodTakingAString I nter faces, Delegates, and Ev ents del = new AnyMethodTakingAString(PlainPrint); Chapter 8 - Advanced C# Type Const ruction Techniques //i ngAnyMethodTakingAString.Invoke() called here! Pa r t Thre e - Pr ogr am m w i th .N ET Assem bl ie s del("Hello there..."); Chapter 9 - Under standing .NET Assem blies // AppDomains, Dump infoCont about theThreads delegate. Chapter 10 - Pr ocesses, exts, and Console.WriteLine("I just called: {0}", Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing del.Method); } Pa r t Four - Le ve r a ging the .NET Libr a r ie s } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er } Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 -begin Pr ogrby amdeclaring ming with aWindows Form s Contr Here, you .NET delegate type ols using the C# "delegate" keyword. The Chapter 16 The Sy stem .I O Nam espace AnyMethodTakingAString delegate represents an object that maintains a reference to some method that Chapter - Data Access w ith ADO.NET takes a17 single string parameter and returns nothing. When you want to assign the target (i.e., the method Pa Fi ve of - W b Appldelegate, ica ti ons and X MLpass W e b in Sethe r vi ces tor tcall) a egiven simply name

of the method to the delegate's constructor. At this

Chapter 18 -are ASP.NET Pages invoke and Web ols using a syntax that looks like a direct function point, you able toWeb indirectly theContr member Chapter invocation: 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex // Make the delegate. List of Figur es AnyMethodTakingAString del; List del of Tables = new AnyMethodTakingAString(PlainPrint);

del("Hello there..."); // Dump info about the delegate. Console.WriteLine("I just called: {0}", del.Method);

Notice that when you print out the method maintained by the delegate (using the Method property), you see that each parameter is automatically mapped to the corresponding .NET system type (when you run this example, notice the presence of the System.Void type, which is a language-neutral way to denote a method with no return value). Now recall that a delegate object could care less about the actual name of the method it is responsible for invoking. If you want, you could dynamically change the target method as follows: class DelegateApp {

public static void PlainPrint(string msg) C# an d th e .N ET Plat f orm con d Ed it ion } { Console.WriteLine("Msg is:, Se {0}", msg); by Andr ew Tr oelsen public static void UpperCasePrint(string ISBN:1590590554 msg) Apr ess © 2003 (1200 pages) is: {0}", msg.ToUpper()); } { Console.WriteLine("Msg This compr ehensiv e text star ts w ith a brief ov er view of themsg) public static void XXXXYYYYZZZZ888777aaa(string C# language and then m oves tomsg); key technical and { Console.WriteLine("Msgquickly is: {0}", } ar chitectur al issues for .NET developer s. public delegate void AnyMethodTakingAString(string s); public static void Main() { Ta ble o f Con t en t s AnyMethodTakingAString del; C# and t he .NET Plat for m, Second Edition del = new AnyMethodTakingAString(PlainPrint); I ntr oduction del("Hello there..."); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Console.WriteLine("->I just called: {0}\n", del.Method); Chapter 1 - The Philosophy of .NET // Reassign and invoke delegate. Chapter 2 - Building C# Applications del= new AnyMethodTakingAString(UpperCasePrint); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge del("Hello there..."); Chapter 3 - C# Language Fundamentals Console.WriteLine("->I just called: {0}\n", del.Method); Chapter 4 - Obj ect -Or iented Prand ogr aminvoke ming w ithdelegate. C# // Reassign Chapter 5 - Exceptions and Obj ect Lifetim e del= new AnyMethodTakingAString(XXXXYYYYZZZZ888777aaa); Chapter 6 - Idel("Hello nter faces and Collections there..."); Chapter 7 - Callback I nter faces, Delegates, and Ev ents Console.WriteLine("->I just called: {0}\n", del.Method); Chapter}8 - Advanced C# Type Const ruction Techniques Pa }r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

The final output can be seen in Figure 7-3.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Figure 7-3: Dynamically "pointing to" various methods

Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 - XML Serthe vices If you attempt to Web assign address of a method that did not match the delegate's declaration: I ndex List Figurtarget! es //ofBad List of Tables public void BadTargetForDelegate(int x, System.AppDomain y)

{ // Stuff... } ... // This is not a valid target! Error! del = new AnyMethodTakingAString(BadTargetForDelegate); del("Huh?!?");

you are (thankfully) issued the following compile time error (note the bold text that highlights the crux of the error): C:\Books\C# Book Second Edition\Code\Chapter 7\SimpleDelegate\SimpleDel.cs(53): Method 'SimpleDelegate.DelegateApp.BadTargetForDelegate(int, System.AppDomain)'

does not match delegate 'void C# an d th e .N ET Plat f orm , Se con d Ed it ion SimpleDelegate.DelegateApp.AnyMethodTakingAString(string)' by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the

Multicasting .NET Delegates C# with language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

The final point to be made with this simple delegate example is the fact that a single delegate object may be configured to point to numerous methods. When you wish to insert multiple methods into the invocation Talist blemaintained o f Con t en tby s the System.Delegate base class, you are able to make use of the overloaded += operator. The topic ofm, operator will be examined in detail in the next chapter, but for the time C# and t he .NET Plat for Secondoverloading Edition being simply understand that when you apply the += operator to a type derived from I ntr oduction System.MulticastDelegate, the hidden Combine() method is triggered automatically (so be sure to check Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m out the CIL via ildasm.exe). Chapter 1 - The Philosophy of .NET Chapter 2

- Building C# Applications

// Now some Pa r t Tw o - The C# multicasting. Pr ogr am m ing La ngua ge AnyMethodTakingAString myMultiCaster; Chapter 3 - C# Language Fundamentals myMultiCaster = iented new AnyMethodTakingAString(PlainPrint); Chapter 4 - Obj ect -Or Pr ogr am ming w ith C# myMultiCaster += and newObjAnyMethodTakingAString(UpperCasePrint); Chapter 5 - Exceptions ect Lifetim e myMultiCaster +=and new AnyMethodTakingAString(XXXXYYYYZZZZ888777aaa); Chapter 6 - I nter faces Collections myMultiCaster("Here is a string"); - Callback I nter faces, Delegates, and Ev ents

Chapter 7 Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - Under standing .NET Assem blies project is located under the Chapter 7 subdirectory. SOURCE The SimpleDelegate Chapter 10 Pr ocesses, AppDomains, Cont exts, and Threads CODE Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d Elaborate th e .N ET Plat f orm , Se con d EdExample it ion Building a More Delegate by Andr ew Tr oelsen

ISBN:1590590554

To illustrate a more use pages) of delegates, let's begin by updating the Car class to include two new Boolea Apr advanced ess © 2003 (1200 member variables. The first is used determine if your automobile is due This compr ehensiv e to text star ts w ith a brief ov er view of the for a wash (isDirty); the other represents if the car in question is in need of a tire rotation (shouldRotate). To enable the object user to interact C# language and then quickly m oves to key technical and ar data, chitectur issues for .NET developer s. with this new state Caralalso defines some additional properties and an updated constructor. Here is the story so far: Ta ble o f Con t en t s

// Another updated Car class. public class Car I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m ... Chapter // 1 - NEW! The Philosophy Are we ofin.NET need of a wash? Need to rotate tires? Chapter private 2 - Building C# Applications bool isDirty; Pa r t Tw oprivate - The C# Prbool ogr amshouldRotate; m ing La ngua ge C# and t he .NET Plat for m, Second Edition

Chapter 3

- C# Language Fundamentals

Chapter // 4 - Extra Obj ect -Or iented Prto ogr am ming w ith C# params set bools. Chapter public 5 - Exceptions and Obj ect Lifetim e Car(string name, int max, int curr, bool dirty, bool rotate) Chapter { 6 - I nter faces and Collections Chapter 7

... - Callback I nter faces, Delegates, and Ev ents

Chapter 8

isDirtyC#= Type dirty; - Advanced Const ruction Techniques

=ETrotate; Pa r t Thre e - PrshouldRotate ogr am m i ng w i th .N Assem bl ie s Chapter } 9

- Under standing .NET Assem blies boolAppDomains, Dirty //and Get and set isDirty. Chapter 10public - Pr ocesses, Cont exts, Threads Chapter { 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

get{ return Pa r t Four - Le ve r a ging the .NETisDirty; Libr a r ie s Chapter Chapter Chapter Chapter Chapter Chapter

} set{ isDirty = value; } 12 - Obj ect Ser ialization and the .NET Remoting Lay er } 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) public bool Rotate // Get and set shouldRotate. 14 - A Better Paint ing Fr amew or k ( GDI + ) { 15 - Pr ogr am ming with Windows Form s Contr ols get{ return shouldRotate; } 16 - The Sy stem .I O Nam espace set{ shouldRotate = value; } 17 - Data Access w ith ADO.NET }

Pa }r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Now, assume you have the following delegate (which, again, is nothing more than an object-oriented Chapter 20 - XML Web Serdeclared vices wrapper around a function pointer) within your current namespace: I ndex List of Figur es List //ofThis Tablesdelegate is actually a class encapsulating a function pointer

// to 'some method', taking a Car as a parameter, and returning void. public delegate void CarDelegate(Car c);

Here, you have created a delegate named CarDelegate. The CarDelegate type represents "some function" taking a Car as a parameter and returning void.

Delegates As Nested Types Currently, your delegate is decoupled from its logically related Car type (given that you have simply declared the CarDelegate type within the defining namespace). While there is nothing horribly wrong with this approach, a more enlightened alternative would be to define the CarDelegate directly within the Car class: // This time, define the delegate as part of the class definition. public class Car

{ d th e .N ET Plat in f ormCIL , Se con // This C# isanrepresented as d Ed it ion ISBN:1590590554 by Andr ew Tr oelsen // Car$CarDelegate (i.e., a nested type). Apr ess © 2003 (1200 pages) public delegate void CarDelegate(Car c); This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

... }

Given that the "delegate" keyword produces a new class deriving from System.MulticastDelegate, the CarDelegate is in fact a nested type definition! If you check ildasm.exe (see Figure 7-4), you will see the truth of C# and t he .NET Plat for m, Second Edition the matter.

Ta ble o f Con t en t s I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Figure 7-4: Remember! C# delegate types alias System.MulticastDelegate

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Using the CarDelegate

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 you - A have BetteraPaint Frpoints amew or ( GDI + )function" taking a Car parameter and returning nothing, you can Now that typeing that tok "some Chapter 15 Pr ogr am ming with Windows Form Contr ols create other functions that take this delegates as a parameter. To illustrate, assume you have a new class named Chapter 16This - The Sy stem .I O Nam espace Garage. type maintains a collection of Car types contained in an ArrayList. Upon creation, the ArrayList is Chapter 17 Data Access w ith ADO.NET filled with some initial Car types. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

More importantly, theWeb Garage class a public ProcessCars() method, which takes a single argument of Chapter 18 - ASP.NET Pages and defines Web Contr ols type Car.CarDelegate. In Applicat the implementation of ProcessCars(), you pass each Car in your collection as a Chapter 19 - ASP.NET Web ions parameter theWeb "function pointed to" by the delegate. Chapter 20 - to XML Ser vices I ndex

To help keep your wits about you, ProcessCars() also makes use of two members defined by the

List of Figur es System.MulticastDelegate class (Target and Method) to determine exactly which function the delegate is List of Tables currently pointing to. Here, then, is the complete definition of the Garage class:

// The Garage class has a method that makes use of the CarDelegate. Using System.Collections; ... public class Garage { // A list of all cars in the garage. ArrayList theCars = new ArrayList(); // Create the cars in the garage. public Garage() { // Recall, we updated the ctor to set isDirty and shouldRotate. theCars.Add(new Car("Viper", 100, 0, true, false)); theCars.Add(new Car("Fred", 100, 0, false, false)); theCars.Add(new Car("BillyBob", 100, 0, false, true));

theCars.Add(new Car("Bart", 100, 0, true, true)); C# an d th e .N ET Plat f orm , Se con d100, Ed it ion theCars.Add(new Car("Stan", 0, false, true)); ISBN:1590590554 by Andr ew Tr oelsen } Apr ess © 2003 (1200 pages) // This method takes a Car.CarDelegate as a parameter. This compr ehensiv is e text star ts w ithmore a briefthan ov er view of the // Therefore 'proc' nothing a function pointer! C# language and then quickly m oves to key technical public void ProcessCars(Car.CarDelegate proc)and ar chitectur al issues for .NET developer s. { // Diagnostics: Where are we forwarding the call? Console.WriteLine("***** Calling: {0} *****", Ta ble o f Con t en t s d.Method.ToString()); C# and t he .NET Plat for m, Second Edition // Diagnostics: Are we calling an instance method or a static method? I ntr oduction if(proc.Target != null) Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Console.WriteLine("->Target: {0} ", proc.Target.ToString()); Chapter 1 - The Philosophy of .NET else Chapter 2 - Building C# Applications Console.WriteLine("->Target is a static method"); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge // Real Work: Now call the method, passing in each car. Chapter 3 - C#foreach(Car Language Fundamentals c in theCars) Chapter 4 - Obj ect -Orproc(c); iented Pr ogr am ming w ith C# Chapter } 5 - Exceptions and Obj ect Lifetim e Chapter 6 - I nter faces and Collections }

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

When the user calls ProcessCars(), it swill Pa r t Thre e - object Pr ogr am m i ng w i th .N ET Assem bl ie

send in the name of the method that should handle this reques For the sake of argument, assume these are static members named WashCar() and RotateTires(). Consider th Chapter 9 - Under standing .NET Assem blies following usage: Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

// The - garage delegates Pa r t Four Le ve r a ging the .NET Librall a r ie s work

orders to these static functions

// (finding a Ser good mechanic problem...) Chapter 12 - Obj ect ialization and the is .NETalways RemotingaLay er public CarApp Chapter 13 class - Building a Bet ter Win dow ( Int roducin g Window s For ms) { Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) // A target for the delegate. public static void WashCar(Car c) Chapter 16 - The Sy stem .I O Nam espace { Chapter 17 - Data Access w ith ADO.NET if(c.Dirty) Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Console.WriteLine("Cleaning a car"); Chapter 18 - ASP.NET Web Pages and Web Contr ols else Chapter 19 - ASP.NET Web Applicat ions Console.WriteLine("This car is already clean..."); Chapter } 20 - XML Web Ser vices I ndex // Another target for the delegate. List of Figur es public static void RotateTires(Car c) List of Tables { if(c.Rotate) Console.WriteLine("Tires have been rotated"); else Console.WriteLine("Don't need to be rotated..."); } public static int Main(string[] args) { // Make the garage. Garage g = new Garage(); // Wash all dirty cars. g.ProcessCars(new Car.CarDelegate(WashCar)); // Rotate the tires. g.ProcessCars(new Car.CarDelegate(RotateTires)); return 0; } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

} C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

essthe © 2003 pages) Notice (of course)Apr that two(1200 static methods are an exact match to the delegate type (void return value and a single Car argument). Also,ehensiv recall that when you pass in the This compr e text star ts w ith a brief ov name er view of of your the function as a constructor parameter, C# item language then quickly m oves to key technical and you are adding this to theand internal linked list maintained by System.MulticastDelegate. Figure 7-5 shows the chitectur al issues for .NET developer s. output of this testarrun. (Notice the output messages supplied by the Target and Method properties.)

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6 - 7-5: I nterPassing faces andthe Collections Figure buck Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Analyzing the Delegation Code

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter As you 10 can- see, Pr ocesses, the Main() AppDomains, method begins Cont exts, by and creating Threads an instance of the Garage type. This class has been

configured delegate all work other named Now, when Chapter 11 - to Type Reflection, Lateto Binding, and Attrstatic ibute-functions. Based Pr ogramm ing you write the following: Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - all Obj ect Ser ialization // Wash dirty cars.and the .NET Remoting Lay er Chapter 13 - Building a Bet Car.CarDelegate(WashCar)); ter Win dow ( Int roducin g Window s For ms) g.ProcessCars(new Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

what you effectively is "Add a pointer to the WashCar() function to the CarDelegate type, and pass th Chapter 16 are - The Sy stem .Isaying O Nam espace delegate to Garage.ProcessCars()." Like most real-world garages, the real work is delegated to another part of the system (which explains why a 30-minute oil change takes 2 hours). Given this, you can assume that Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces ProcessCars()actually looks like the following under the hood: Chapter 17 - Data Access w ith ADO.NET

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

// CarDelegate Chapter 20 - XML Web points Ser vices to the WashCar function: public void ProcessCars(Car.CarDelegate proc) { List of Figur es ... List of Tables foreach(Car c in theCars) proc(c); // proc(c) => CarApp.WashCar(c) } I ndex

Likewise, if you say: // Rotate the tires. g.ProcessCars(new Car.CarDelegate(RotateTires));

ProcessCars() can be understood as: // CarDelegate points to the RotateTires function: public void ProcessCars(Car.CarDelegate proc)

{ C# an dc thin e .NtheCars) ET Plat f orm , Se con d Ed it ion foreach(Car ISBN:1590590554 by Andr ew Tr oelsen proc(c); // proc(c) => CarApp.RotateTires(c) Apr ess © 2003 (1200 pages)

... }

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Also notice that when you are calling ProcessCars(), you must create a new instance of the custom delegate: Ta ble o f Con t en t s

// Wash all dirty cars. g.ProcessCars(newCar.CarDelegate(WashCar)); I ntr oduction // Rotate the tires. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m g.ProcessCars(newCar.CarDelegate(RotateTires)); C# and t he .NET Plat for m, Second Edition

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ograt amfirst, m ing La ngua This might seem odd given thatgea delegate

represents a function pointer. However, remember that this

Chapter - C# Language Fundamentals function3 pointer is represented by an instance of type System.MulticastDelegate, and therefore must be "newChapter ed." 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections Multicasting with the Car.CarDelegate

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter Type Const Recall 8that- aAdvanced multicastC#delegate is anruction objectTechniques that is capable of calling any number of functions. In the current Pa r t Thre e -you Pr ogr i ng w i th .Nof ET this Assem bl ie s example, doam notmmake use feature.

Rather, you make two calls to Garage.ProcessCars(), sending in

Chapter 9 - Under standing .NET Assem new instance of the CarDelegate eachblies time. However, assume you have updated Main() to look like the Chapter following: 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four Le ve r function a ging the .NET Libr a r ie s // Add - two pointers

to the internal linked list.

Chapter 12 static - Obj ect Ser ialization and the .NET Remoting public int Main(string[] args) Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) { Chapter // 14 - Make A Better the Paint garage. ing Fr amew or k ( GDI + )

newwith Garage(); Chapter Garage 15 - Pr ogrgam=ming Windows Form s Contr ols two delegates. Chapter // 16 - Create The Sy stem .I O new Nam espace wash = new Car.CarDelegate(WashCar); Chapter Car.CarDelegate 17 - Data Access w ith ADO.NET rotate new Car.CarDelegate(RotateTires); Pa r t Fi veCar.CarDelegate - W e b Appl ica ti ons and X ML W e= b Se r vi ces overloaded can be applied to multicast delegates. Chapter // 18 - The ASP.NET Web Pages + andoperator Web Contr ols result is a ions new delegate that maintains pointers to Chapter // 19 - The ASP.NET Web Applicat // both functions. g.ProcessCars(wash + rotate); return 0;

Chapter 20 - XML Web Ser vices I ndex

List of Figur es

}

List of Tables

Here, you begin by creating two new CarDelegate objects, each of which points to a given function. When you call ProcessCars(), you are actually passing in a new delegate that holds each function pointer within the interna linked list (crazy huh?). Do note that the + operator is simply a shorthand for calling the static Delegate.Combine() method. Thus, you could write the following equivalent (but uglier) code: // The + operator has the same effect as calling the Combine() method. g.ProcessCars((Car.CarDelegate)Delegate.Combine(wash, rotate));

Furthermore, if you wish to hang onto the new delegate for later use, you could write the following instead: // Create two new delegates. Car.CarDelegate wash = new Car.CarDelegate(WashCar); Car.CarDelegate rotate = new Car.CarDelegate(RotateTires);

// Store the new delegate for later use. C# an d d th e= .Nwash ET Plat , Se con d Ed it ion MulticastDelegate + f orm rotate; ISBN:1590590554 by Andr ew Tr oelsen // Send the new delegate into the ProcessCars() method. Apr ess © 2003 (1200 pages) g.ProcessCars((Car.CarDelegate)d); This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer Regardless of how you configure a multicast delegate,s.understand that when you call Combine() (or use the

overloaded + operator), you are adding a new function pointer to the internal list. If you wish to remove an item from this internal linked list, you can call the static Remove() method. The first parameter marks the delegate yo Ta ble o f Con t en t s wish to manipulate, while the second parameter marks the item to remove: C# and t he .NET Plat for m, Second Edition I ntr oduction

// The static Remove() method returns a Delegate type. Delegate washOnly = MulticastDelegate.Remove(d, rotate); Chapter 1 - The Philosophy of .NET g.ProcessCars((Car.CarDelegate)washOnly); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter C# Language Fundamentals Before 3you- view the output of this program, let's also update ProcessCars() to print out each function pointer Chapter 4 the - Obj ect -Or ogr am ming w ith C# stored in linked listiented usingPrDelegate.GetInvocationList(). This method returns an array of Delegate objects, Chapter 5 -iterate Exceptions and Obj ect Lifetim e which you over using foreach: Chapter 6

- I nter faces and Collections

Chapter 7 print - Callback I nter faces,member Delegates,in and Ev ents // Now out each the linked list. Chapter 8 void - Advanced C# Type Const ruction Techniques proc) public ProcessCars(Car.CarDelegate Pa {r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter // 9 - Where Under standing .NET Assem blies are we passing the call? Chapter 10foreach(Delegate - Pr ocesses, AppDomains, d in Cont proc.GetInvocationList()) exts, and Threads Chapter { 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Console.WriteLine("***** Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Calling: {0} *****",

Chapter 12 - Obj d.Method.ToString()); ect Ser ialization and the .NET Remoting Lay er Chapter } 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

... 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Instance Methods As Callbacks

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Currently, CarDelegate type isions storing pointers to static functions. This is not a requirement of the delegate Chapter 19 -the ASP.NET Web Applicat protocol callbacks, which require static members). It is also possible to delegate a call to a Chapter 20(unlike - XML C-based Web Ser vices

method defined on any object instance. To illustrate, assume that the WashCar() and RotateTires() methods have now been moved into a new class named ServiceDept:

I ndex

List of Figur es List of Tables

// We have now moved the static functions into a helper class. public class ServiceDept { // Not static! public void WashCar(Car c) { if(c.Dirty) Console.WriteLine("Cleaning a car"); else Console.WriteLine("This car is already clean..."); } // Still not static! public void RotateTires(Car c) { if(c.Rotate)

Console.WriteLine("Tires have been rotated"); C# an d th e .N ET Plat f orm , Se con d Ed it ion else by Andr ew Tr oelsen Console.WriteLine("Don't need ISBN:1590590554 to be rotated..."); }

Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

}

You could now update Main() as follows: Ta ble o f Con t en t s

// Delegate to instance methods of the ServiceDept type. public static int Main(string[] args) I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // Make the garage. Chapter 1 - The Philosophy of .NET Garage g = new Garage(); Chapter 2 - Building C# Applications // Make the service department. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge ServiceDept sd = new ServiceDept(); Chapter 3 - C# Language Fundamentals // The garage delegates the work to the service department. Chapter Car.CarDelegate 4 - Obj ect -Or iented Prwash ogr am ming w ithCar.CarDelegate(sd.WashCar); C# = new Chapter Car.CarDelegate 5 - Exceptions and Objrotate ect Lifetim e = new Car.CarDelegate(sd.RotateTires); Chapter MulticastDelegate 6 - I nter faces and Collections d = wash + rotate; Chapter // 7 - Tell Callback I nter faces, Delegates, and Ev work. ents the garage to do some Chapter g.ProcessCars((Car.CarDelegate)d); 8 - Advanced C# Type Const ruction Techniques Pa r t Threreturn e - Pr ogr am 0;m i ng w i th .N ET Assem bl ie s Chapter } 9 - Under standing .NET Assem blies C# and t he .NET Plat for m, Second Edition

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Figure the the final.NET fruits ofaour Pa r t Four7-6 - Leshows ve r a ging Libr r ie s labor.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 7-6: Passing the buck yet again SOURCE CODE

The CarDelegate project is located under the Chapter 7 subdirectory.

Understanding Asynchronous Delegates Now that you have some experience with the synchronous behavior of .NET delegate types, let's examine how t invoke methods asynchronously. First off, what exactly warrants an asynchronous method invocation? As you a fully aware, some programming operations take time. For example, if you build a word processing application that has the ability to print the current document, and that document happens to be 1000 pages in length, the computer's CPU has the potential to spin away for quite some time. Now assume that this application has all of its programming logic taking place within the Main() method using a

singlethread. Simply put, a thread is a path of execution within a .NET application. Single-threaded applications C# an d th e .N ET Plat f orm , Se con d Ed it ion are quite simple to program; however, in the case of the word processor application, the end user is far less tha ISBN:1590590554 by Andr pleased. The reason hasew to Tr dooelsen with the fact that while the application's single thread of execution is crunching ou Apr ess © 2003 (1200 pages) the 1000-page document, all other aspects of this program (such as menu activation, toolbar clicking, and Thisunresponsive. compr ehensiv e text star ts w ith a brief ov er view of the keyboard input) are C# language and then quickly m oves to key technical and

ar chitectur issues for .NET developer When programmers wish toalbuild applications that ares.able to simulate numerous tasks performing "at the same time," they will typically spawn additional threads to perform background tasks (e.g., printing documents) while the main thread is still able to respond to basic user-input needs.

Ta ble o f Con t en t s

C# and t hedoes .NET threading Plat for m, Second So, what have toEdition do with .NET delegates? Well, to illustrate the potential problem with I ntr oduction synchronous delegate invocations, ponder the following simple application: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter - The Philosophy of .NET using1 System; Chapter - Building C# Applications using2 System.Threading; Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - C#AsyncDelegate Language Fundamentals namespace Chapter 4 {

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter // 5 - AExceptions new delegate and Obj ect type. Lifetim e

string NewCarDelegate(Car carToDetail); Chapter public 6 - I nter delegate faces and Collections class Chapter public 7 - Callback I nterCar{...} faces, Delegates, and Ev ents App C# Type Const ruction Techniques Chapter class 8 - Advanced Pa r t Thre{e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

public static string - Under standing .NET Assem blies DetailCar(Car c)

Chapter 10 - Pr { ocesses, AppDomains, Cont exts, and Threads

// Detailing a car takes 10 seconds. Console.WriteLine("Detailing car on thread {0}", Pa r t Four - Le ve r a ging the .NET Libr a r ie s Thread.CurrentThread.GetHashCode()); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Thread.Sleep(10000); Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) return "Your car is ready!"; Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols static void Main(string[] args) Chapter 16 - The { Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Console.WriteLine("Main() is on thread {0}", Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Thread.CurrentThread.GetHashCode()); Chapter 18 - ASP.NET NewCarDelegate Web Pages and Web Contr d = ols new NewCarDelegate(DetailCar); Chapter 19 - ASP.NET Web Car Applicat myCarions = new Car(); Chapter 20 - XML Web Console.WriteLine(d(myCar)); Ser vices I ndex Console.WriteLine("Done invoking delegate"); List of Figur es } } List of Tables } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

First, notice that this example makes use of a new namespace named System.Threading. Chapter 10 will fully examine the details of multithreading within the .NET platform; however, to frame the use of asynchronous delegates, simply understand this namespace defines a type named Thread, which provides a static method named CurrentThread(). If you obtain the hash code for the current thread, you (in effect) obtain a unique identifier for the currently executing thread. Here, you print out the hash code of the current thread within Main(), and then synchronously invoke the NewCarDelegate type. Once the flow of execution passes into the DetailCar() helper function, you print out the hash code of the active thread once again and put it to sleep (which is to say, stop all activity on said thread) for 10 seconds. Given this, you will not see the final message of Main() print to the console until approximately 10 seconds after the delegate's invocation. When you run this example, note that the same hash code has been printed twice, signifying the fact that your

application is performing all work on a single thread of execution. Now, in many cases, this behavior may be C# an d th e .N ET Plat f orm , Se con d Ed it ion perfectly acceptable. However, given that the DetailCar() method takes 10 seconds to complete, your applicatio ISBN:1590590554 by Andr ew Tr oelsen appears to be hanging until the call has completed (just like the printing of the 1000-page document). Apr ess © 2003 (1200 pages)

The question therefore is: How caneyou to invoke a method This compr ehensiv texttell staratsdelegate w ith a brief ov er view of the on a separate thread of execution an C# main language andonce then the quickly m oves key technicalThe andgood news is that every .NET delegate "report back" to the thread method hastocompleted? ar chitectur al issues for .NET developer s. better news is that you are not required to directly dive type is automatically equipped with this ability. The even into the details of the System.Threading namespace to do so (although these entities can quite naturally work hand in hand).

Ta ble o f Con t en t s

C# and tfull he .NET Platoffor m, Second Edition Again, details multithreaded programming will be examined later in this text, but for the time being, let's I ntr oduction check out how System.MulticastDelegate provides automatic support for asynchronous method invocations. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET Invoking Methods Asynchronously

Chapter 2

- Building C# Applications

Pa r t you Tw o recall, - The C# Pr ogr m ing La nguaprocesses ge As when theamC# compiler

the "delegate" keyword, you dynamically receive two methods

Chapter - C# Language named3BeginInvoke() andFundamentals EndInvoke(). Thus, for the NewCarDelegate type, you are provided with the following Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# members: Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6 IAsyncResult - I nter faces and Collections public BeginInvoke(Car carToDetail, Chapter System.AsyncCallback 7 - Callback I nter faces, Delegates, and Ev ents callback, object state); Chapter 8 string - Advanced C# Type Const ruction Techniques public EndInvoke(IAsyncResult result); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies Note that returns an IAsyncResult Chapter 10 BeginInvoke() - Pr ocesses, AppDomains, Cont exts, and interface, Threads while EndInvoke() requires an IAsyncInvoke type as

parameter. (defined in the System namespace) Chapter 11 - This Type interface Reflection, Late Binding, and Attr ibuteBased Pr breaks ogrammdown ing as follows: Pa r t Four - Le ve r a ging the .NET Libr a r ie s

public IAsyncResult Chapter 12 interface - Obj ect Ser ialization and the .NET Remoting Lay er { Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) object {amew get; Chapter 14 - A AsyncState Better Paint ing Fr or k}( GDI + ) WaitHandle { sget; } Chapter 15 - Pr ogr amAsyncWaitHandle ming with Windows Form Contr ols bool CompletedSynchronously { get; } bool IsCompleted { get; }

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

}

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET ions In the simplest case, Web one Applicat is able to effectively ignore directly interacting with these members. All you have to do Chapter 20 -returned XML WebIAsyncResult Ser vices cache the type in a local variable in order to pass it to EndInvoke() when you are ready to I ndex obtain the result of the method invocation. Thus, to invoke DetailCar() asynchronously, you simply need to make List Figur es updates: theoffollowing List of Tables

static void Main(string[] args) { Console.WriteLine("Main() is on thread {0}", Thread.CurrentThread.GetHashCode()); NewCarDelegate d = new NewCarDelegate(DetailCar); Car myCar = new Car(); IAsyncResult itfAR = d.BeginInvoke(myCar, null, null); Console.WriteLine("Done invoking delegate"); // Do other work... string msg = d.EndInvoke(itfAR); // Get the result. Console.WriteLine(msg); }

Before viewing the output, a point must be made regarding Visual Studio .NET. As you were typing in the C# an d th e .N ET Plat f orm , Se con d Ed it ion previous code updates, you may have noticed that IntelliSense failed to show you the BeginInvoke() and by AndrThe ew Tr oelsen is due to the fact that theseISBN:1590590554 EndInvoke() members. reason methods don't exist until the current assembly Apr ess © 2003 (1200 has been compiled! Recall that thepages) C# compiler will autogenerate a type derived from System.MulticastDelegat This compr text star ts w ith a brief ov er view of thealways remember that you are smarter atcompile time. Thus, whenehensiv you aree invoking members asynchronously, C# language and then quickly m oves to key technical and than any IDE. As long as you are mindful of the parameters and return value of the member you are invoking, ar chitectur al issues for .NET developer s. you will be able to type in the code for BeginInvoke()/EndInvoke() accordingly. Now, check out Figure 7-7. Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2 - 7-7: Building C# Applications Figure Asynchronous invocations increase program responsiveness. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Here, you that two threads of execution are working to perform the work of the program (automatically) Chapter 3 -can C# see Language Fundamentals In addition the hash codes, you wwill Chapter 4 - toObj ectunique -Or iented Pr ogr am ming ith also C# be able to see upon running the application that the "Done

invoking message displays immediately, while the secondary thread is busy attending to its business ( Chapter 5 delegate" - Exceptions and Obj ect Lifetim e this case, sleeping on the job for 10 seconds). - I nter faces and Collections

Chapter 6

Chapter 7 - Callback IThe nter faces, Delegates, project and Ev ents SOURCE AsyncDelegate is located under the Chapter 7 subdirectory. Chapter 8 - Advanced C# Type Const ruction Techniques CODE Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Callbacks for Asynchronous Delegates

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter Type At Reflection, ibuteBased Pr via ogramm ing delegate and obtain the result at So far, 11 so -good. this point,Late youBinding, are ableand to Attr trigger a method a custom Pa r t Four - Leinvethe r a ging the(e.g., .NET when Libr a ryou ie s some time future

call the EndInvoke() method). While this is all well and good, there may

Chapter 12when - Obj you ect Ser ialization .NET Remoting Lay er be times would ratherand notthe manually call EndInvoke() to obtain the results of your invocation, but would Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s Forcompleted. ms) rather that the delegate call you when the method has been In many ways, this functionality is quite Chapter - A callback Better Paint ing Fr amew or k examined ( GDI + ) similar 14 to the interface pattern at the opening of this chapter. To understand the connection, Chapter 15 -down Pr ogr the am ming with Windows s Contr ols method generated for the NewCarDelegate type: let's break parameters to the Form BeginInvoke() Chapter 16 - The Sy stem .I O Nam espace Chapter 17 IAsyncResult - Data Access w ithBeginInvoke( ADO.NET public Pa r t FiCar ve - W e b Appl ica ti ons and X ML W e b Se r vi ces carToDetail,

// All delegate parameters are listed first // A standard delegate for the callback. Chapter - ASP.NET Web Applicat ions //19Allows the calling thread to pass information to the callback. Chapter object 20 - XML state Web Ser vices ); I ndex Chapter 18 - ASP.NET Web Pages and Web Contr ols System.AsyncCallback callback,

List of Figur es List of Tables

Note that the second parameter to BeginInvoke() is (get this) another delegate. In this case, System.AsyncCallback is a system-defined delegate that knows how to call methods that match the following prototype: void SomeCallBackFunction(IAsyncResult itfAR)

When you wish to inform the delegate to call you back when the asynchronous invocation is complete, pass in a instance of the AsyncCallback type as the second parameter to BeginInvoke() and build a static (or instancelevel) method to receive the call. Here is the complete code update, with analysis to follow (note the extra and required namespace reference): using System; using System.Threading; using System.Runtime.Remoting.Messaging;

namespace AsyncCallbackDelegate C# an d th e .N ET Plat f orm , Se con d Ed it ion { ISBN:1590590554 by Andr ew Tr oelsen // The delegate. Apr ess © 2003 (1200 pages) public delegate string NewCarDelegate(Car carToDetail); This compr ehensiv e text star ts w ith a brief ov er view of the public class Car{...} C# language and then quickly m oves to key technical and class App ar chitectur al issues for .NET developer s. { public static void DetailCarCallBack(IAsyncResult itfAR) Ta ble o f Con t en{t s on thread {0}", C# and t he .NET Plat forConsole.WriteLine("DetailCarCallBack m, Second Edition Thread.CurrentThread.GetHashCode()); I ntr oduction message DetailCar(). Pa r t One - I nt r oduci ng // C# aGet nd the .NET P la tffrom or m AsyncResult res = (AsyncResult)itfAR; Chapter 1 - The Philosophy of .NET NewCarDelegate d = (NewCarDelegate)res.AsyncDelegate; Chapter 2 - Building C# Applications Console.WriteLine(d.EndInvoke(itfAR)); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge } Chapter 3 - C# Language Fundamentals public static string DetailCar(Car c) Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# { Chapter 5 - Exceptions and Obj ect Lifetim e // Detail car for 10 seconds. Chapter 6 - I nter faces and Collections Console.WriteLine("Detailing car on thread {0}", Chapter 7 - Callback I nter faces, Delegates, and Ev ents Thread.CurrentThread.GetHashCode()); Chapter 8 - AdvancedThread.Sleep(10000); C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am mreturn i ng w i th .N ET Assem bl ieis s "Your car ready!"; Chapter 9 - Under } standing .NET Assem blies Chapter 10 - Pr static ocesses, AppDomains, Cont exts, and Threads void Main(string[] args) Chapter 11 - Type { Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging Console.WriteLine("Main() the .NET Libr a r ie s is on thread {0}", Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Thread.CurrentThread.GetHashCode()); Chapter 13 - Building aNewCarDelegate Bet ter Win dow ( Int roducin d = new g Window NewCarDelegate(DetailCar); s For ms) Car myCar = new Car(); Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) // Call asynchronously via callback. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols d.BeginInvoke(myCar, new AsyncCallback(DetailCarCallBack), null); Chapter 16 - The Sy stem .I O Nam espace Console.WriteLine("Done invoking delegate"); Chapter 17 - Data Access w ith ADO.NET // Keep console alive until call completes. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Console.ReadLine(); Chapter 18 - ASP.NET Web Pages and Web Contr ols } Chapter 19 - ASP.NET Web Applicat ions } Chapter 20 - XML Web Ser vices } I ndex

List of Figur es List of of Tables First all, notice that you now have a new helper function named DetailCarCallBack that will be invoked by the

delegate when the DetailCar() method has completed. As well, notice that this time you are not caching the IAsyncResult type returned from BeginInvoke(), given that Main() is no longer required to call EndInvoke()! Now, let's look at the implementation of DetailCarCallBack(). After printing out the hash code of the current thread (which logically should be the same number as the thread that is calling DetailCar()), you find the following lines of (technically optional) code: public static void DetailCarCallBack(IAsyncResult itfAR) { ... // Get message from DetailCar(). AsyncResult res = (AsyncResult)itfAR; NewCarDelegate d = (NewCarDelegate)res.AsyncDelegate; Console.WriteLine(d.EndInvoke(itfAR)); }

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Recall that the DetailCar() method returns a string message that informs the user that the operation has ISBN:1590590554 by Andr ew Tr oelsen completed. In theApr previous interaction of this example, Main() directly called EndInvoke() to obtain the return ess © 2003 (1200 pages) value of the "method pointed to" by the NewCarDelegate. However, now that the delegate will call This compr ehensiv e text star ts w ith a brief ov er view of the DetailCarCallBack() at some time in the future,m this needs toand be the entity in charge of this task. C# language and then quickly ovesmethod to key technical ar chitectur al issues for .NET developer s.

Here, you cast the incoming parameter into a System.Runtime.Remoting.Messaging.AsyncResult type and obtain the underlying delegate type (NewCarDelegate) via the AsyncDelegate property (this new namespace numerous Tadefines ble o f Con t en t s types used when leveraging the .NET Remoting layer, as you will see later in this text). Once you have a handle to m, theSecond delegate that is calling your callback method, you are able to indeed call EndInvoke() C# and t he .NET Plat for Edition obtain the textual message from DetailCar(). I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Cool! At this point you have dug into the details of synchronous and asynchronous delegate invocations. To be

Chapter 1 - are Theadditional Philosophytechniques of .NET sure, there that may be used when asynchronously invoking a member, and you will Chapter 2 Building C# Applications see further examples where necessary. As you will see over the remainder of this text, this same asynchronous Pa r t Tw o is - The Pr ogrinvoking am m ing file La ngua ge pattern usedC#when access

Chapter 3

methods, remote types, XML Web services, and whatnot.

- C# Language Fundamentals

SOURCE AsyncCallbackDelegate Chapter 4 - Obj ect -OrThe iented Pr ogr am ming w ith C# project is located under the Chapter 7 subdirectory. CODE Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d(and th e .N ET Plat f ormEvents , Se con d Ed it ion Understanding Using) by Andr ew Tr oelsen

ISBN:1590590554

Delegates are fairly constructs Apr interesting ess © 2003 (1200 pages) because you can resolve the name of a function to call at runtime, rather than at compile time. Admittedly, take a bit of getting used to. However, This compr ehensiv e textthis starsyntactic ts w ith a orchestration brief ov er view can of the because the ability for one object to call back to another object is such a C# language and then quickly m oves to key technical and helpful construct, C# provides the ar chitectur al issues forof.NET developer s. in the raw. "event" keyword to lessen the burden using delegates The most prevalent use of the "event" keyword would be found in GUI-based applications, in which Button, TaTextBox, ble o f Con and t enCalendar ts widgets all report back to the containing Form when a given action (such as clicking a

Button) has occurred. However, events are not limited to GUI-based applications. Indeed, they can be quite C# and t he .NET Plat for m, Second Edition helpful when creating non-GUI-based projects (as you will now see). I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Recall that the current implementation of Car.SpeedUp() (as of Chapter 4) throws an exception if the user - The Philosophy of .NET attempts to increase the speed of an automobile that has already been destroyed. This is a rather brute force Chapter 2 - Building C# Applications way to deal with the problem, given that the exception has the potential to halt the program's execution if the Pa r t Tw o - The C# Pr ogr am m ing La ngua ge error is not handled in an elegant manner. A better design would be to simply inform the object user when the Chapter 3 - C# Language Fundamentals car has died using a custom event, and allow the caller to act accordingly. Chapter 1

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - Exceptions andtoObj ect two Lifetim e Let's reconfigure the Car send events to those who happen to be listening. The first event Chapter (AboutToBlow) 6 - I nterwill faces be and sentCollections when the current speed is 10 miles below the maximum speed. The second event

(Exploded) be sent when the user attempts speed up a car that is already dead. Establishing an event is Chapter 7 - will Callback I nter faces, Delegates, and Evtoents a two-step you need defineTechniques a delegate, which will be used to hold onto the set of methods Chapter 8 - process. AdvancedFirst, C# Type Constto ruction that will ebe- Pr called when event Pa r t Thre ogr am m i ngthe w i th .N EToccurs. Assem blNext, ie s

you define the events themselves using the C# "event" keyword, which as you can see is defined in terms of the related delegate. Here are the initial updates: Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

// This 'talk back' toand the Chapter 11 - car Type can Reflection, Late Binding, Attr user. ibute- Based Pr ogramm ing public Carthe .NET Libr a r ie s Pa r t Four - class Le ve r a ging { Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er ... 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter the Paint car ing alive or Chapter // 14 - Is A Better Fr amew or kdead? ( GDI + ) bool Chapter private 15 - Pr ogr am ming carIsDead; with Windows Form s Contr ols // Holds the function(s) to call when the event occurs. public delegate void EngineHandler(string msg); Chapter 17 - Data Access w ith ADO.NET // This car can send these events. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces public static event EngineHandler Exploded; Chapter 18 - ASP.NET Web Pages and Web Contr ols public static event EngineHandler AboutToBlow; Chapter 19 - ASP.NET Web Applicat ions ... Chapter 20 - XML Web Ser vices } Chapter 16 - The Sy stem .I O Nam espace

I ndex List of Figur es List of Tables

Firing an event is as simple as specifying the event by name and sending out any specified parameters as defined by the related delegate. To illustrate, update the previous implementation of SpeedUp() to send each event accordingly (and remove the previous exception logic): // Fire the correct event based on our current state of affairs. public void SpeedUp(int delta) { // If the car is dead, send exploded event. if(carIsDead) { if(Exploded != null) Exploded("Sorry, this car is dead..."); } else {

currSpeed += delta; an d th edead? .N ET Plat f ormabout , Se conto d Edblow it ion event. // C# Almost Send ISBN:1590590554 by Andr ew Tr oelsen if(10 == maxSpeed - currSpeed) Apr ess © 2003 (1200 pages) if(AboutToBlow != null) This compr ehensiv e text star ts w ith a brief approaching ov er view of the terminal speed!"); AboutToBlow("Careful, C# language and then quickly m oves to key technical and // Still OK! Proceed as usual. ar chitectur al issues for .NET developer s. if(currSpeed >= maxSpeed) carIsDead = true; else Ta ble o f Con t en t s Console.WriteLine("\tCurrSpeed = {0} ", currSpeed); C# and t he .NET Plat for m, Second Edition } I ntr oduction } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2 you - Building C# Applications With this, have configured the car to send two custom events (under the correct conditions). You will see Pa r t Tw o - The C# Pr ograutomobile am m ing La ngua ge a the usage of this new in just

Chapter detail. 3

moment, but first, let's check the event architecture in a bit more

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# Note how you Chapter 5 Notice - Exceptions andare Objchecking ect Lifetimthe e event against a null object reference before firing. This is to ensure

if the caller not register to listen to a given event, it is not sent into sweet oblivion. Chapter 6 that - I nter faces and did Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Events- Under Advanced the C# Type Hood Const ruction Techniques

Chapter 8

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

A given9event actually expands into two hidden public functions, one having an "add_" prefix, the other having Chapter - Under standing .NET Assem blies a "remove_" ForAppDomains, example, theCont Exploded event expands to the following methods: Chapter 10 - Prprefix. ocesses, exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

// The - following expands Pa r t Four Le ve r a ging theevent .NET Libr a r ie s

in CIL code to:

// add_Exploded() Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er // remove_Exploded() Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) public Chapter 14 static - A Betterevent Paint ingEngineHandler Fr amew or k ( GDI + ) Exploded; Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - toData Access w ith ADO.NET In addition defining hidden add_XXX() and remove_XXX() methods, each event also actually maps to a Pa r t Fi ve class, - W e bwhich Appl ica ti ons and X MLcorresponding W e b Se r vi ces private associates the

delegate to a given event. In this way, when an event is

Chapter - ASP.NET Pages and Webdelegate Contr ols will be called. This is a convenient way to allow an object to raised, 18 each method Web maintained by the Chapter 19 -the ASP.NET Web Applicat ions sinks. To illustrate, check out Figure 7-8, which shows the Car type as broadcast event to multiple event Chapter 20 - XML seen through theWeb eyesSer ofvices ildasm.exe. I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter Figure 6 - 7-8: I nterAsynchronous faces and Collections invocations via callbacks Chapter 7

- Callback I nter faces, Delegates, and Ev ents

As you 8can- see, each C# event (Exploded and Techniques AboutToBlow) is internally represented as the following members: Chapter Advanced Type Const ruction Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

A private class

Chapter 9

- Under standing .NET Assem blies

Chapter - Pr ocesses, AppDomains, Cont exts, and Threads An10 add_XXX() method Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

A remove_XXX() method Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

If you were to check out the CIL instructions behind add_AboutToBlow(), you would find the following (note the call to Delegate.Combine() is handled on your behalf):

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

.method public hidebysig specialname static void add_AboutToBlow(class CarEvents.Car/EngineHandler 'value') Chapter 17 - Data Access w ith ADO.NET cil managed synchronized Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces { Chapter - ASP.NET and(0x16) Web Contr ols //18Code sizeWeb Pages22 Chapter 19 - ASP.NET2Web Applicat ions .maxstack Chapter 20 - XML Web Ser vices IL_0000: ldsfld class CarEvents.Car/EngineHandler CarEvents.Car::AboutToBlow I ndex IL_0005: ldarg.0 List ofIL_0006: Figur es call class [mscorlib]System.Delegate List of Tables [mscorlib]System.Delegate::Combine (class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000b: castclass CarEvents.Car/EngineHandler IL_0010: stsfld class CarEvents.Car/EngineHandler CarEvents.Car::AboutToBlow IL_0015: ret } // end of method Car::add_AboutToBlow Chapter 16 - The Sy stem .I O Nam espace

As you would expect, remove_AboutToBlow() will make the call to Delegate.Remove() automatically: .method public hidebysig specialname static void remove_AboutToBlow(class CarEvents.Car/EngineHandler 'value') cil managed synchronized { // Code size 22 (0x16)

.maxstack 2 C# an d thclass e .N ET CarEvents.Car/EngineHandler Plat f orm , Se con d Ed it ion IL_0000: ldsfld CarEvents.Car::AboutToBlow ISBN:1590590554 by Andr ew Tr oelsen IL_0005: ldarg.0 Apr ess class © 2003 (1200 pages) IL_0006: call [mscorlib]System.Delegate This compr ehensiv e text star ts w ith a brief ov er view of the [mscorlib]System.Delegate::Remove C# language and then quickly m oves to key[mscorlib]System.Delegate) technical and (class [mscorlib]System.Delegate, class ar chitectur al issues for .NET developer s. IL_000b: castclass CarEvents.Car/EngineHandler IL_0010: stsfld class CarEvents.Car/EngineHandler CarEvents.Car::AboutToBlow Ta ble o f Con t en t s IL_0015: ret C# and t he .NET Plat for m, Second Edition } // end of method Car::remove_AboutToBlow I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter - The Philosophy .NETitself make use of the [.addon] and [.removeon] directives to establish the The CIL1 instructions for theofevent Chapter 2 Building C# Applications correct add_XXX and remove_XXX methods (also note the private class is mentioned by name): Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals .event CarEvents.Car/EngineHandler AboutToBlow

Chapter 4 {

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - Exceptions and Obj ect Lifetim e .addon void CarEvents.Car::add_AboutToBlow(class CarEvents.Car/EngineHandler) Chapter 6 I nter faces and Collections .removeon void CarEvents.Car::remove_AboutToBlow Chapter (class 7 - Callback I nter faces, Delegates, and Ev ents CarEvents.Car/EngineHandler) Chapter 8 - Advanced C# Car::AboutToBlow Type Const ruction Techniques } // end of event Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies So, now understand how toCont buildexts, a class can send events, the next big question is how you can Chapter 10that - Pryou ocesses, AppDomains, and that Threads

configure object to receive these events. Chapter 11 an - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Listening to Incoming Events

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Assume now created an instance Chapter 14you - Ahave Better Paint ing Fr amew or k ( GDIof + )the Car class and wish to listen to the events it is capable of sending. isming to create a methodForm thatsrepresents Chapter 15The - Prgoal ogr am with Windows Contr ols the event sink that will be called by the related

delegate. To bind this method to the event, you need to call the correct add_XXX() method to ensure that your method is added to the list of function pointers maintained by the EngineHandler delegate. However, you Chapter 17 - Data Access w ith ADO.NET cannot call the CIL add_XXX() and remove_XXX() directly, but rather use the overloaded += and -= operators. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Thus, when you wish to listen to an event, follow the pattern shown here: Chapter 16 - The Sy stem .I O Nam espace

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

// I'm listening... // ObjectVariable.EventName += new ObjectVariable.DelegateName(functionToCall); I ndex Car.Exploded += new Car.EngineHandler(OnBlowUp); Chapter 20 - XML Web Ser vices List of Figur es List of Tables

When you wish to detach from a source of events, use the -= operator: // Shut up already! // ObjectVariable.EventName -= new ObjectVariable.DelegateName(functionToCall); Car.Exploded -= new Car.EngineHandler(OnBlowUp);

Here is the complete code: // Make a car and listen to the events. public class CarApp { public static int Main(string[] args) { Car c1 = new Car("SlugBug", 100, 10);

// Hook into events. C# an d th e .N ET f orm , Se con d Ed it ion Car.Exploded += Plat new Car.EngineHandler(OnBlowUp); ISBN:1590590554 by Andr ew Tr oelsen Car.AboutToBlow += new Car.EngineHandler(OnAboutToBlow); Apr ess © 2003 (1200 pages) // Speed up (this will generate the events.) This compr e text star tsi++) w ith a brief ov er view of the for(int i ehensiv = 0; i < 10; C# language and then quickly m oves to key technical and c1.SpeedUp(20); ar chitectur al issues for .NET developer s. // Detach from events. Car.Exploded -= new Car.EngineHandler(OnBlowUp); Car.Exploded -= new Car.EngineHandler(OnAboutToBlow); Ta ble o f Con t en t s // No response! C# and t he .NET Plat for m, Second Edition for(int i = 0; i < 10; i++) I ntr oduction c1.SpeedUp(20); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m return 0; Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications // OnBlowUp event sink. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge public static void OnBlowUp(string s) Chapter 3 - C# Language Fundamentals { Chapter Console.WriteLine("Message 4 - Obj ect -Or iented Pr ogr am ming w ithfrom C# car: {0} ", s); Chapter 5 Exceptions and Obj ect Lifetim e } Chapter // 6 - OnAboutToBlow I nter faces and Collections event sink. Chapter public 7 - Callback I nter faces, and Ev ents static voidDelegates, OnAboutToBlow(string s) Chapter { 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr Console.WriteLine("Message am m i ng w i th .N ET Assem bl ie s from car: {0} ", s); Chapter } 9 - Under standing .NET Assem blies } Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

If you wish to have multiple event sinks called by a given event, simply repeat the process:

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

// Multiple event Chapter 14 - A Better Paint sinks. ing Fr amew or k ( GDI + ) public class CarApp { Chapter 16 - The Sy stem .I O Nam espace public static int Main(string[] args) Chapter 17 - Data Access w ith ADO.NET { Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces // Make a car as usual. Chapter 18 - ASP.NET Web Pages and Web Contr ols Car c1 = new Car("SlugBug", 100, 10); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML vices events. // Web HookSerinto I ndex Car.Exploded += new Car.EngineHandler(OnBlowUp); List of Figur es Car.Exploded += new Car.EngineHandler(OnBlowUp2); List of Tables Car.AboutToBlow += new Car.EngineHandler(OnAboutToBlow);

// Speed up (this will generate the events.) for(int i = 0; i < 10; i++) c1.SpeedUp(20); ... // Detach from events when desired. Car.Exploded -= new Car.EngineHandler(OnBlowUp); Car.Exploded -= new Car.EngineHandler(OnBlowUp2); Car.Exploded -= new Car.EngineHandler(OnAboutToBlow); ... } // OnBlowUp event sink A. public static void OnBlowUp(string s) { Console.WriteLine("Message from car: {0} ", s); } // OnBlowUp event sink B.

public static void OnBlowUp2(string s) C# an d th e .N ET Plat f ormI, Se con d{0} Ed it ion { Console.WriteLine("AGAIN say: ", s); } ISBN:1590590554 by Andr ew Tr oelsen // OnAboutToBlow event sink. Apr ess © 2003 (1200 pages) public static void OnAboutToBlow(string s) This compr ehensiv e text star tsfrom w ith acar: brief ov{0} er view the } { Console.WriteLine("Message ",of s); C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

}

Now, when the Exploded event is sent, the associated delegate calls OnBlowUp() as well as OnBlowUp2(), as shown in Figure 7-9.

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure 7-9: Hooking into the engine events

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Note .NET 2003 further event When you apply Chapter 11 VS - Type Reflection, Late simplifies Binding, and Attrhandling. ibute- Based Pr ogramm ing the + syntax to an object's event, you use the TabLibr key Pa r t Four - Le vemay r a ging the .NET a rto ie sautomatically generate

the delegate target.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Objects As Event Sinks

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

At this point, you have thewith background build objects Chapter 15 - Pr ogr am ming Windows to Form s Contr ols that can participate in a two-way conversation. However, free to build a helper object to respond to an object's event set, much in the Chapter 16 understand - The Sy stemthat .I O you Namare espace same way you created helper class to be called by all delegates. For example, let's move your event Chapter 17 -that Data Access w ithaADO.NET sink the CarApp class a new class Pa r t Fimethods ve - W e b out Applofica ti ons and X ML W eand b Seinto r vi ces

named CarEventSink:

Chapter 18 - ASP.NET Web Pages and Web Contr ols

// Car sink Chapter 19 event - ASP.NET Web Applicat ions public CarEventSink Chapter 20 class - XML Web Ser vices { I ndex // OnBlowUp event handler. List of Figur es public void OnBlowUp(string s) List of Tables { Console.WriteLine("Message from car: {0} ", s); } // OnBlowUp event handler version 2. public void OnBlowUp2(string s) { Console.WriteLine("AGAIN I say: {0} ", s); } // OnAboutToBlow handler. public void OnAboutToBlow(string s) { Console.WriteLine("Message from car: {0} ", s); } }

The CarApp class is then a bit more self-contained, as the event sink methods have been pulled out of the CarApp definition and into their own custom type. Here is the update: // Note the creation and use of the CarEventSink. public class CarApp

{ C# an d thint e .N ET Plat f orm , Se conargs) d Ed it ion public static Main(string[] by Andr ew Tr oelsen {

ISBN:1590590554

Apr ess © 2003 (1200 pages) ehensiv e text star ts w ith a100, brief ov10); er view of the CarThis c1compr = new Car("SlugBug", C# language and then quickly m oves to key technical and // Make the sink object. ar chitectur al issues for .NET developer s. CarEventSink sink = new CarEventSink(); // Hook into events using sink object. Car.Exploded += new Car.EngineHandler(sink.OnBlowUp); Ta ble o f Con t en t s Car.Exploded += new Car.EngineHandler(sink.OnBlowUp2); C# and t he .NET Plat for m, Second Edition Car.AboutToBlow += new Car.EngineHandler(sink.OnAboutToBlow); I ntr oduction for(int i = 0; i < 10; i++) Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m c1.SpeedUp(20); Chapter 1 - The Philosophy of .NET // Detach from events using sink object. Chapter 2 - Building C# Applications Car.Exploded -= new Car.EngineHandler(sink.OnBlowUp); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Car.Exploded -= new Car.EngineHandler(sink.OnBlowUp2); Chapter 3 - C#Car.Exploded Language Fundamentals -= new Car.EngineHandler(sink.OnAboutToBlow); Chapter 4 - Obj ect -Or iented return 0; Pr ogr am ming w ith C# Chapter } 5 - Exceptions and Obj ect Lifetim e Chapter 6 - I nter faces and Collections } Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

The output is ogr (ofam course) identical. Pa r t Thre e - Pr m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

SOURCE CODE

The CarEvents project is located under the Chapter 7 subdirectory.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Summary

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

In this chapter, you a number of ways in which multiple objects can partake in a Aprhave ess ©examined 2003 (1200 pages) bidirectional conversation under .NET. First, examined the use of interfaces, which provide a This compr ehensiv e text star you ts w ith a brief ov er view of callback the way to have object B make calls on object A via an interface reference. Do understand that this design C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developerin s. any language or platform that honors the use of pattern is not specific to .NET, but may be employed interface types. TaNext, ble o fyou Conexamined t en t s the C# "delegate" keyword, which is used to indirectly construct a class derived from

System.MulticastDelegate. As you have seen, a delegate is simply an object that maintains a list of C# and t he .NET Plat for m, Second Edition methods to call when told to do so. These invocations may be made synchronously (using the Invoke() I ntr oduction method) BeginInvoke() Pa r t One - or I ntasynchronously r oduci ng C# a nd(via the the .NET P la tf or m Chapter 1

and EndInvoke() methods).

- The Philosophy of .NET

Finally, you examined the C# "event" keyword which, when used in conjunction with a delegate type, can - Building C# Applications simplify the process of sending your event notifications to awaiting callers. As seen via the resulting CIL, Pa r t Tw o - The C# Pr ogr am m ing La ngua ge the .NET event model maps to hidden calls on the System.Delegate/System.MulticastDelegate types. In Chapter 3 - C# Language Fundamentals this light, the C# "event" keyword is purely optional in that it simply saves you some typing time. Chapter 2

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

d th e .N ET Plat f orm , Se con d Ed it ion Chapter C# 8:anAdvanced C# Type Construction ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) Techniques This compr ehensiv e text star ts w ith a brief ov er view of the C# up language and then quickly to key technical and by examining a number of This chapter wraps our investigation of the m C#oves programming language ar chitectur al issues for .NET developer s. advanced (but extremely useful) syntactic constructs. To begin, we will examine a small set of C# keywords that we have not yet formally examined. For example, you will learn how to programmatically account for overflow/underflow conditions using the "checked"/"unchecked" keywords as well as how to Ta ble o f Con t en t s create an "unsafe" code context in order to directly manipulate pointer types using C#. C# and t he .NET Plat for m, Second Edition

I ntr oduction Next, you learn how to construct and use an indexer method. This C# mechanism enables you to build Pa r t One -types I nt r oduci C# a nd the .NET P la tf orusing m custom that ng expose internal subtypes

the familiar bracket operator (i.e., []). If you have a C++

Chapter 1 - The of .NET background, youPhilosophy will find that creating a C# indexer method is analogous to overloading the [] operator on Chapter 2 Building C# Applications a C++ class. Once you learn how to build an indexer method, you then examine how to overload various Pa r t Tw o - The C# , ogr am m La ngua operators (+, –, and soing forth) andgecreate

custom conversion functions (the C# equivalent to

Chapter overloading 3 - C# theLanguage () operator Fundamentals under C++) for a type. Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

- Exceptions and Obj ect Lifetimof e C# The Advanced Keywords

Chapter 5 Chapter 6

- I nter faces and Collections Over the of the previous seven chapters, you have seen a majority of the C# keywords in action. In Chapter 7 course - Callback I nter faces, Delegates, and Ev ents

addition8 to-those already C# does have a set of lesser used, but still intriguing, keywords, Chapter Advanced C# investigated, Type Const ruction Techniques specifically Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

"checked"/"unchecked"

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing "unsafe"/"stackalloc"/"fixed"/"volatile"/"sizeof" Pa r t Four - Le ve r a ging the .NET Libr a r ie s

"lock" Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

The "lock" keyword will be examined later in this text during our formal examination of multithreaded programming (see Chapter 10). The remaining members of the preceding list ("checked", "unchecked", Chapter 15 - Pr ogr am ming with Windows Form s Contr ols "unsafe", "stackalloc", "fixed", "volatile", and "sizeof") will be the focus of the first part of this chapter. To Chapter 16 - The Sy stem .I O Nam espace start, let's check out how C# provides automatic detection of arithmetic overflow (and underflow). Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

The "checked" Keyword

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

As you are well aware, each numerical data type has a fixed upper and lower limit (which may be obtained programmatically using the MaxValue/MinValue properties). Now, when you are performing arithmetic I ndex operations on a specific type, it is very possible that you may accidentally overflow the maximum storage List of Figur of the typees(assign a value that is greater than the maximum value) or underflow the minimum storage of List of Tables the type (assign a value that is less than the minimum value). To keep in step with the CLR, I will refer to both of these possibilities collectively as "overflow." (As you will see, both overflow and underflow conditions result in a System.OverflowException type. There is no System.UnderflowException type in the base class libraries.) Chapter 20 - XML Web Ser vices

To illustrate the issue, assume you have created two System.Byte types, each of which have been assigned a value that is safely below the maximum value (255). If you were to add the values of these types (casting the result as a byte) and print out the result, you would assume that the result would be the exact sum of each member: namespace CheckedUnchecked { class TheChecker { static void Main(string[] args) {

// Overflow the max value of a System.Byte. C# an d th e .N ET Plat f orm ,value Se con dof Ed itbyte ion Console.WriteLine("Max is {0}.", byte.MaxValue); by Andr ew Tr oelsen Console.WriteLine("Min value of byteISBN:1590590554 is {0}.", byte.MinValue); ess = © 2003 (1200 pages) byteAprb1 100; ehensiv e text star ts w ith a brief ov er view of the byteThis b2compr = 250; C# language and then quickly m oves to key technical and byte b3 = (byte)(b1 + b2); ar chitectur al issues for .NET developer s. // b3 should hold the value 350, however... Console.WriteLine("b3 = {0}", b3); }

Ta ble o f Con t en t s

}

C# and t he .NET Plat for m, Second Edition

}

I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - to The Philosophy of .NET If you were view the output of this application, you might be surprised to find that b3 contains the value Chapter 2 Building C# Applications 94 (rather than the expected 350). The reason is simple. Given that a System.Byte can only hold a value Pa r t Tw o - 0 The C#255 Pr ogr am m ing for La ngua ge between and (inclusive, a grand

total of 256 slots), b3 now contains the overflow value (350 –

Chapter 3 -As C#you Language Fundamentals 256 = 94). have just seen, if you take no corrective course of action, overflow occurs without Chapter 4 -At Obj ect -Or iented Pr ogr am ming may w ith cause C# exception. times, this hidden overflow no harm whatsoever in your project. Other times, this Chapter loss of 5data - Exceptions is completely andunacceptable. Obj ect Lifetim e Chapter 6

- I nter faces and Collections

To handle-overflow or underflow conditions in your application, you have two possibilities. Your first choice Callback I nter faces, Delegates, and Ev ents is to leverage your wits and programming skills to handle all overflow conditions manually. Assuming you Chapter 8 - Advanced C# Type Const ruction Techniques were indeed able to find each overflow condition in your program, you could resolve the previous overflow Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s error as follows: Chapter 7

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

// Store sum in an integer to prevent overflow. byte b1 = 100; Pa r t Four - Le ve r a ging the .NET Libr a r ie s byte b2 = 250; Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er int answer = b1 + b2;

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 16 - the Theproblem Sy stem .Iwith O Nam Of course, thisespace technique is the simple fact that we are humans, and even our best Chapter 17 may - Data Access w ith ADO.NET attempts result in errors that have escaped our eyes. Given this, C# provides the "checked" keyword. Pa r t Fi veyou - Wwrap e b Appl ica ti ons and ML W eof b Se r vi ces When a statement (orXblock statements)

within the scope of the "checked" keyword, the C#

Chapter compiler 18 will - ASP.NET emit specific Web Pages CIL instructions and Web Contr that ols test for overflow conditions that may result when adding,

multiplying, dividing two numerical data types. If an overflow has occurred, the runtime will Chapter 19 - subtracting, ASP.NET WeborApplicat ions throw a20 System.OverflowException type. To illustrate, observe the following update: Chapter - XML Web Ser vices I ndex List class of Figur TheChecker es

{ of Tables List static void Main(string[] args) { // Overflow the max value of a System.Byte. Console.WriteLine("Max value of byte is {0}.", byte.MaxValue); byte b1 = 100; byte b2 = 250; try { byte b3 = checked((byte)(b1 + b2)); Console.WriteLine("b3 = {0}", b3); } catch(OverflowException e) { Console.WriteLine(e.Message); } } }

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Here, you wrap the addition of b1 and b2 within the scope of the "checked" keyword. If you wish to force ISBN:1590590554 ew Tr oelsen overflow checkingbytoAndr occur over a block of code, you can interact with the "checked" keyword as follows: Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

try {

checked { Ta ble o f Con byte t en t s b3 = (byte)(b1 + b2); byte = 100, b6 = 200; C# and t he .NET Platb4, for m,b5 Second Edition I ntr oduction b4 = (byte)(b5 + b6); Console.WriteLine("b3 {0}", b3); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf=or m Chapter}1 - The Philosophy of .NET } Chapter 2 - Building C# Applications catch(OverflowException e) ge Pa r t Tw o - The C# Pr ogr am m ing La ngua { Chapter 3 - C# Language Fundamentals Console.WriteLine(e.Message); Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# } Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter - Callback I nterinfaces, Delegates, Ev ents for possible overflow conditions automatically, which In either7 case, the code question will beand evaluated Chapter 8 -an Advanced Type Const ruction Techniques will trigger overflowC#exception. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 -Project-Wide Under standing .NET Assem blies Setting Overflow Checking Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Now, if 11 you- are an application that never allow silent overflow to occur, you may find Chapter Typecreating Reflection, Late Binding, andshould Attr ibuteBased Pr ogramm ing yourself the numerous Pa r t Four -inLe ve rannoying a ging the position .NET Librofa rwrapping ie s

lines of code within the scope of the "checked" keyword. As an alternative, the C# compiler supports the /checked flag. When enabled, all of your Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er arithmetic will be evaluated for overflow without the need to make use of the C# "checked" keyword. If Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) overflow has been discovered, you will still receive a runtime exception. To enable this flag under VS Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) .NET, activate the Check for Arithmetic Overflow/Underflow option from the project's property page Chapter 15 - Pr ogr am ming with Windows Form s Contr ols (Figure 8-1). Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 8-1: Enabling VS .NET overflow checking As you may guess, this technique can be very helpful when creating a debug build. Once all of the overflow exceptions have been squashed out of the code base, you are free to disable the /checked flag for subsequent builds (which will increase the runtime execution of your application).

The "unchecked" Keyword

Now, assuming you have enabled this project-wide setting, what are you to do if you have a block of code C# an d th e .N ET Plat f orm , Se con d Ed it ion where silent overflow is acceptable? Given that the /checked flag will evaluate all arithmetic logic, the C# ISBN:1590590554 by the Andr ew Tr oelsen keyword to disable the throwing language provides "unchecked" of System.OverflowException on a Apr ess © 2003 (1200 pages) case-by-case basis. The use of this keyword is identical to the "checked" keyword in that you can specify a e text star ts example: w ith a brief ov er view of the single statement This or a compr block ehensiv of statements. For C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

// Assuming +checked is enabled, // this block will not trigger Ta// ble a o f runtime Con t en t s exception. unchecked C# and t he .NET Plat for m, Second Edition { oduction I ntr byte = ng (byte)(b1 + b2); Pa r t One - I nt rb3 oduci C# a nd the .NET P la tf or m Console.WriteLine("b3 Chapter 1 - The Philosophy of .NET = {0}", b3); } Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

So, to summarize the C# "checked" and "unchecked" keywords, recall that the default behavior of the - Obj ect -Or iented Pr ogr am ming w ith C# .NET runtime is to ignore arithmetic overflow. When you want to selectively handle discrete statements, Chapter 5 and Obj ect Lifetim e wish to trap overflow errors throughout your application, enable make use -ofExceptions the "checked" keyword. If you Chapter 6 I nter faces and Collections the +checked flag. Finally, the "unchecked" keyword may be used if you have a block of code where Chapter 7 is- acceptable Callback I nter faces, and Ev ents overflow (and thusDelegates, should not trigger a runtime exception). Chapter 4

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Regarding Underflow Conditions - Under standing .NET Assem blies

Chapter 9

Chapter - Pr ocesses, Cont exts, and Threads type within the .NET base class libraries. Finally,10 recall that thereAppDomains, is no System.UnderflowException Chapter 11 Type Reflection, Late Binding, and Attr ibuteBasedwill Pr ogramm ing an OverflowException: Rather, in the event of an underflow condition, the runtime again throw Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

// Underflow conditions also trigger an OverflowException!

Chapter try 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) { Chapterbyte 15 - Pr a ogr = am 9,ming b =with 9;Windows Form s Contr ols Chapterbyte 16 - The stem .I O Nam+espace c =Sy(byte)(a b + -100); // c is less than zero! Chapter 17 - Data Access w ith ADO.NET } Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces catch(OverflowException e){Console.WriteLine(e);}

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex

SOURCE CODE

The CheckedUnchecked project can be found under the Chapter 8 subdirectory.

List of Figur es List of Tables

Working with "Unsafe" Code Next up, we have three keywords that allow the C# programmer to bypass the CLR's memory management scheme in order to take matters into their own hands. In a nutshell, this allows C# programmers to make use of C(++) style pointers. Given this, C# does indeed provide additional operators specifically for this purpose (see Table 8-1). Table 8-1: Pointer-Centric C# Operators

C# Pointer- C# an d thMeaning in Life e .N ET Plat f orm , Se con d Ed it ion Centric by Andr ew Tr oelsen Operator Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the Used to create a pointer variable, a variable that represents a direct C# language and then quickly m oves to key technical and memory. Like C(++), this same operator is used to represent ar chitecturlocation al issuesinfor .NET developer s.

*

pointer indirection. &

Ta ble o f Con t en t s

Used to obtain the address of a pointer.

C# –> and t he .NET Plat for m, Second This operator Edition is used to access fields of a type that is represented by a I ntr oduction

pointer variable (the unsafe version of the C# dot operator).

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

[]

The [] operator (in an unsafe context) allows you to index the slot pointed to by a pointer variable (recall the interplay between a pointer variable Chapter 2 - Building C# Applications and the [] operator in C(++)! ). Chapter 1

- The Philosophy of .NET

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4 - Obj -Or iented ogr am let ming ith C#out the fact that you will seldom ifever need to make use Now, before weect dig into the Pr details, mewpoint Chapter of the techniques 5 - Exceptions we are andabout Obj ect to Lifetim examine. e Although C# does allow you to drop down to the level of

pointer6manipulations, understand that the .NET runtime has absolutely no clue of your intentions. Thus, if Chapter - I nter faces and Collections you mismanage a pointer, you are the oneand in charge Chapter 7 - Callback I nter faces, Delegates, Ev ents of dealing with the consequences. Given these warnings, exactly need to work with unsafe code (and therefore the operators seen in Chapter 8 -when Advanced C#would Type you Const ruction Techniques Table 8-1)? two situations: Pa r t Thre e - PrThere ogr amare m i ng w icommon th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

You are looking to optimize select parts of your application by bypassing the CLR. For example, you want to build a function that copies an array using pointer arithmetic.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four Le ve r a ging theto .NET Librthe a r ie functionality s You -are attempting trigger of

a C-based *.dll (such as the Win32 API or a custom

Chapter 12 - Obj ect Ser the pointer .NET Remoting Lay C-based *.dll) andialization need to and create variables toercall various methods. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Beyond14these two reasons, willornever Chapter - A Better Paint ing there Fr amew k ( GDIbe + ) a need to declare, dereference, or manipulate direct

pointers using C#. In the event that you decide to make use of this C# language feature, you will also be required to inform csc.exe of your intent! If you are making use of csc.exe in the raw, be sure you supply Chapter 16 - The Sy stem .I O Nam espace the /unsafe flag. From VS .NET, you will need to access your project's Property page and enable the Chapter 17 - Data Access w ith ADO.NET Allow Unsafe Code Blocks setting (Figure 8-2). Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 8-2: Enabling VS .NET unsafe compilation Now let's ponder the basics. In the examples that follow, I'm assuming that you do have some background in C(++) pointer manipulations. If this is not true in your case, don't sweat it. Again, writing unsafe code will not be a common task for a huge majority of .NET applications.

The "Unsafe"C#Keyword an d th e .N ET Plat f orm ,

Se con d Ed it ion

ISBN:1590590554 by Andr ew Tr oelsen When you wish to work with pointers in C#, you must specifically declare a block of "unsafe" code using Apr ess © 2003 (1200 pages)

the "unsafe" keyword (as you might guess, any code that is not marked with the "unsafe" keyword is This compr ehensiv e text star ts w ith a brief ov er view of the considered "safe"C#automatically, thus there is not a "safe" keyword in C#): language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

unsafe { Ta ble o // f Con t en t s with pointers here! Work C# } and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

In addition declaring a scope of unsafe code, you are able to build structures, classes, type members, Chapter 1 - toThe Philosophy of .NET and parameters thatC# areApplications "unsafe." Here are a few examples to gnaw on: Chapter 2 - Building Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

// This structure is 'unsafe' and can Chapter 3 - entire C# Language Fundamentals // only used in an unsafe Chapter 4 - be Obj ect -Or iented Pr ogr am mingcontext. w ith C# public struct Node Chapter 5 unsafe - Exceptions and Obj ect Lifetim e { Chapter 6

- I nter faces and Collections int IValue; Chapterpublic 7 - Callback nter faces, Delegates, and Ev ents

public Node* Left; - Advanced C# Type Const ruction Techniques public Node* Right; Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 8 Pa r t

} - Under standing .NET Assem blies // This struct is safe, but the Node* members Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads // are not. Technically, you may access 'Value' from Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing // outside a unsafe context, but not 'Left' and 'Right'. Pa r t Four - Le ve r a ging the .NET Libr a r ie s public struct Node Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er { Chapterpublic 13 - Building Bet ter Win dow ( Int roducin g Window s For ms) int aValue; Chapter// 14 These - A Better Paint ing Fr be amew or k ( GDI + ) in an unsafe context! can only accessed Chapterpublic 15 - Pr ogr am ming Node* with Windows unsafe Left;Form s Contr ols Chapterpublic 16 - Theunsafe Sy stem .I O Nam espace Node* Right; Chapter 17 - Data Access w ith ADO.NET } Chapter 9

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Methods or instance level) ions may be marked as unsafe as well. For example, assume that you know Chapter 19(static - ASP.NET Web Applicat

a given20 static method willvices make use of pointer logic. To ensure that this method can only be called from an Chapter - XML Web Ser unsafe context, you could define the method as follows:

I ndex

List of Figur es

unsafe public static void SomeUnsafeCode() List of Tables { // Work with pointers here! }

This configuration would demand that the caller invoke SomeUnsafeCode() as so: static void Main() { unsafe{SomeUnsafeCode();} }

Conversely, if you would rather not force the caller to wrap the invocation within an unsafe context, you could remove the "unsafe" keyword from the SomeUnsafeCode() method signature and opt for the following:

C# an d th e .N ET Plat f orm , Se con d Ed it ion

public static void SomeUnsafeCode() ISBN:1590590554 by Andr ew Tr oelsen { Apr ess © 2003 (1200 pages) unsafe This compr ehensiv e text star ts w ith a brief ov er view of the { C# language and then quickly m oves to key technical and // Work withal pointers here! ar chitectur issues for .NET developer s. } } Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction

which would simplify the call to:

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET static Main() Chapter 2 void - Building C# Applications

{r t Tw o - The C# Pr ogr am m ing La ngua ge Pa SomeUnsafeCode(); - C# Language Fundamentals

Chapter 3

}

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

I nter faces and Collections Working- with the * and & Operators

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8 -have Advanced C# Type ruction Techniques Once you established an Const unsafe context, you are then free to build pointers to data types using the * Pa r t Thre e as - Prwell ogr am i ng w the i th .N ET Assem ie s operator as m obtain address of bl said

pointer using the & operator. Using C#, the * operator is

Chapter Under standingtype .NETonly, Assem applied9to -the underlying notblies as a prefix to each pointer variable name. For example, the Chapter following 10 declares - Pr ocesses, two AppDomains, variables, both Cont of exts, type int* and (a Threads pointer to an integer). Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four Le ve r a ging the .NET Libr aunder r ie s // No! - This is incorrect

C#!

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er int *pi, *pj; Chapter 13 - This Building ter way Win dow Int roducin g Window s For ms) // Yes! isa Bet the of ( C#. Chapter int* pi, 14 - Apj; Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Given this, check out the following example:

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

unsafe Chapter 18 - ASP.NET Web Pages and Web Contr ols { Chapter 19 - ASP.NET Web Applicat ions myInt; Chapter int 20 - XML Web Ser vices // Define an int pointer, and // assign it the address of myInt. List of Figur es int* ptrToMyInt = &myInt; List of Tables // Assign value of myInt using pointer indirection. *ptrToMyInt = 123; // Print some stats. Console.WriteLine("Value of myInt {0}", myInt); Console.WriteLine("Address of myInt {0:X}", (int)ptrToMyInt); } I ndex

An Unsafe (and Safe) Swap Function Of course, declaring pointers to local variables simply to assign their value (as shown in the previous example) is never required. To illustrate a more useful example of unsafe code, assume you wish to build a swap function using pointer arithmetic: unsafe public static void UnsafeSwap(int* i, int* j) {

int temp = *i; *i = *j;C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen *j = temp;

ISBN:1590590554

Apr ess © 2003 (1200 pages)

}

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Very C-like, don't you think? However, given your work in Chapter 3, you should be aware that you could write the following safe version of your swap algorithm using the C# "ref" keyword:

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

public static void SafeSwap(ref int i, ref int j) { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m int temp = i; Chapter 1 - The Philosophy of .NET i = j; Chapter 2 - Building C# Applications j = temp; Pa r t Tw o - The C# Pr ogr am m ing La ngua ge } I ntr oduction

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - Exceptions andmethod Obj ect is Lifetim e The functionality of each identical, thus reinforcing the point that direct pointer manipulation is Chapter not a mandatory 6 - I nter faces task under and Collections C#. Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Field 8Access via C# Pointers (the –>Techniques Operator) Chapter - Advanced Type Const ruction Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Now assume that you have a Point structure and wish to declare a pointer to a Point type. Like C(++), - Under standing .NET Assem blies when you wish to invoke methods or trigger fields of a pointer type, you will need to make use of the Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads pointer-field access operator (–>). As mentioned in Table 8-1, this is the unsafe version of the standard Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing (safe) dot operator (.). In fact, using the pointer indirection operator (*), it is possible to dereference a Pa r t Four - Le ve r a ging the .NET Libr a r ie s pointer to (once again) apply the dot operator notation. Check out the following: Chapter 9

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

struct Point { Chapter 15 - Pr ogr am ming with Windows Form s Contr ols public int x; Chapter 16 - The Sy stem .I O Nam espace public int y; Chapter public 17 - Data override Access w ith ADO.NET string ToString() Pa r t Fi ve{- W e b Appl ti ons W e+ b Se return ica "(" + and x +X ML "," y r vi +ces ")"; } Chapter 18 ASP.NET Web Pages and Web Contr ols } Chapter 19 void - ASP.NET Web Applicat ionsargs) static Main(string[] Chapter 20 - XML Web Ser vices { I ndex // Access members via pointer. List of Figur unsafe es { List of Tables Point point; Point* p = &point; p->x = 100; p->y = 200; Console.WriteLine(p->ToString()); } // Access members via pointer indirection. unsafe { Point point; Point* p = &point; (*p).x = 100; (*p).y = 200; Console.WriteLine((*p).ToString()); } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

} C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) This compr ehensiv e text The "stackalloc" Keyword

star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues .NET developer In an unsafe context, you may need for to declare a locals.variable that allocates memory directly from the call

stack (and is therefore not subject to .NET garbage collection). To do so, C# provides the "stackalloc" keyword, which is the C# equivalent to the _alloca function of the C runtime library. Here is a simple Ta ble o f Con t en t s example: C# and t he .NET Plat for m, Second Edition I ntr oduction

unsafe {

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

char* p = stackalloc char[256]; - Building C# Applications for (int k = 0; k < 256; k++) Tw o - The C# Pr ogr am m ing La ngua ge p[k] = (char)k;

Chapter 2 Pa r t

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

}

Chapter 6 -aI nter faces andthe Collections Pinning Type via "fixed" Chapter 7

Keyword

- Callback I nter faces, Delegates, and Ev ents

As seen previous allocating a chunk of memory within an unsafe context may be facilitated Chapter 8 in- the Advanced C#example, Type Const ruction Techniques via the "stackalloc" keyword. theAssem very nature Pa r t Thre e - Pr ogr am m i ng w i th By .N ET bl ie s

of this operation, the allocated memory is cleaned up as soon as the allocating method has returned (as the memory is acquired from the stack). However, Chapter 9 - Under standing .NET Assem blies assume a more complex example. During our examination Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads of the –> operator, you created a value type named11 Point. LikeReflection, all value Late types, the allocated is popped off ing the stack once the executing scope Chapter - Type Binding, and Attrmemory ibute- Based Pr ogramm has terminated. For the sake of argument, assume Point was instead defined as a reference type: Pa r t Four - Le ve r a ging the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

class13Point // a are overloaded as a Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s set. The same holds true for the = operators. If the Car type you developed in Chapter 6 Chapter 9 - Under standing .NET Assem blies overloaded these comparison operators, the object user could now compare types as follows: Chapter 7

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

// Exercise the overloaded < operator for the Car class. public class CarApp Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er { Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) public static int Main(string[] args) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) { Chapter 15 - Pr ogr am ming with Windows Form s Contr ols // Make an array of Car types. Chapter 16 - The Sy stemmyAutos .I O Nam espace Car[] = new Car[5]; Chapter 17 - Data Access w ith ADO.NET myAutos[0] = new Car(123, "Rusty"); Pa r t Fi ve - W e b myAutos[1] Appl ica ti ons and ML WCar(6, e b Se r vi ces = Xnew "Mary"); Chapter 18 - ASP.NET Web Pages and Web Contr ols myAutos[2] = new Car(6, "Viper"); Chapter 19 - ASP.NET Web Applicat ions Car(13, "NoName"); myAutos[3] = new Chapter 20 - XML Web Ser vices= new Car(6, "Chucky"); myAutos[4] Pa r t Four - Le ve r a ging the .NET Libr a r ie s

I ndex List of Figur es // Is Rusty less than Chucky? List of Tables

if(myAutos[0] < myAutos[4]) Console.WriteLine("Rusty is less than Chucky!"); else Console.WriteLine("Chucky is less than Rusty!"); return 0;

} }

Assuming you have a Car type that implements IComparable, overloading the comparison operators is trivial. Here is the updated class definition: // This class is also comparable using the comparison operators. public class Car : IComparable { ...

public int CompareTo(object o) C# an d th e .N ET Plat f orm , Se con d Ed it ion { ISBN:1590590554 Andr ew=Tr(Car)o; oelsen Carby temp Apr ess © 2003 (1200 pages) if(this.CarID > temp.CarID) Thisreturn compr ehensiv 1; e text star ts w ith a brief ov er view of the C# language and quickly m oves to key technical and if(this.CarID (Car c1, Car c2) Chapter { 3 - C# Language Fundamentals Chapter 4 - Obj ect -Or iented Pr ogr am ming w C# IComparable itfComp =ith(IComparable)c1; Chapter 5 - Exceptions and Obj ect Lifetim e return (itfComp.CompareTo(c2) > 0); Chapter } 6 - I nter faces and Collections Chapter public 7 - Callback I nter faces, and = s For ms) } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t FiSOURCE ve - W e b Appl icaThe ti onsObjCompWithOps and X ML W e b Se r vi ces project

Chapter 18 - ASP.NET Web Pages and Web Contr ols CODE Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

is located under the Chapter 8 subdirectory.

an d th e .N ET Plat f orm ,of Se con d Ed it ion The InternalC#Representation Overloaded Operators by Andr ew Tr oelsen

ISBN:1590590554

Like any C# programming element, overloaded operators are represented using specific CIL instructions. To Apr ess © 2003 (1200 pages) begin examining what takes place behind thetsscenes, openovup yourofOverLoadOps.exe assembly (created This compr ehensiv e text star w ith a brief er view the previously) using C# ildasm.exe. As you can see from Figure 8-3, the +, -, = =, and != operators are internally language and then quickly m oves to key technical and ar chitectur al issues forin.NET expressed via hidden methods, which this developer case are s. named op_Addition(), op_Subtraction(), op_Equality(), and op_Inequality(). Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - 8-3: TypeInternal Reflection, Binding, andofAttr ibute- Based Pr ogramm ing Figure CILLate representation overloaded operators Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Now, if you were to examine the specific CIL instructions for the op_Addition method, you would find that the specialname flag has also been inserted by csc.exe:

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

.method public hidebysig specialname static valuetype OverLoadOps.Point op_Addition(valuetype OverLoadOps.Point p1, Chapter 17 - Data Access w ith ADO.NET valuetype OverLoadOps.Point p2) cil managed Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces { Chapter 18 - ASP.NET Web Pages and Web Contr ols ... Chapter 19 - ASP.NET Web Applicat ions } Chapter 16 - The Sy stem .I O Nam espace

Chapter 20 - XML Web Ser vices I ndex List of truth Figurof es the matter is that any operator that you may overload equates to a specially named method in The List terms of Tables of CIL. Table 8-3 documents the C#-operator-to-CIL mapping for the key C# operators.

Table 8-3: C#-Operator-to-CIL Special Name Roadmap Intrinsic C# Operator

CIL Representation

--

op_Decrement()

++

op_Increment()

Unary-

op_UnaryNegation()

Unary +

op_UnaryPlus()

!

op_LogicalNot()

True

op_True()

False

op_False()

~

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Binary +

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Binary -

This compr ehensiv e text star ts w ith a brief ov er view ofop_Subtraction() the C# language and then quickly m oves to key technical and op_Multiply() ar chitectur al issues for .NET developer s.

Binary *

op_OnesComplement() ISBN:1590590554

/

op_Addition()

op_Division()

% o f Con t en t s Ta ble C# and t he .NET Plat for m, Second Edition

^

I ntr oduction

op_Modulus() op_ExclusiveOr()

Pa rBinary t One -&I nt r oduci ng C# a nd the .NET P la tf or m

op_BitwiseAnd()

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

op_BitwiseOr()

|

Pa r&& t Tw o - The C# Pr ogr am m ing La ngua ge

op_LogicalAnd()

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

op_LogicalOr()

= Chapter 5

- Exceptions and Obj ect Lifetim e

op_Assign()

Chapter 6

- I nter faces and Collections

op_LeftShift()

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

>> 8 Chapter

- Advanced C# Type Const ruction Techniques

||

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

op_GreaterThan()

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogrammop_LessThan() ing < Pa r t Four - Le ve r a ging the .NET Libr a r ie s

!= Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

op_Inequality()

Chapter >= 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

op_GreaterThanOrEqual()

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

op_MemberSelection()

Chapter 17 - Data Access w ith ADO.NET

Pa r>>= t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

op_RightShiftAssignment()

Chapter *= 18 - ASP.NET Web Pages and Web Contr ols

op_MultiplicationAssignment()

Chapter 19 - ASP.NET Web Applicat ions

->* 20 - XML Web Ser vices Chapter

op_PointerToMemberSelection()

I ndex -=

op_SubtractionAssignment()

List of Figur es

^=

op_ExclusiveOrAssignment()

PID: {0}\tName: {1}", Pa r t One - I nt r oduci ng p.Id, C# a nd the .NET P la tf or m p.ProcessName); Chapter 1 - The Philosophy of .NET Console.WriteLine(info); Chapter } 2 - Building C# Applications Pa r t Tw oConsole.WriteLine("************************************\n"); - The C# Pr ogr am m ing La ngua ge } Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Notice how the static Process.GetProcesses() method returns an array of Process types that represent the - I nter faces and Collections running processes on the target machine (the dot notation seen here represents the local computer).

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8 -have Advanced C# the Typearray Const Techniques Once you obtained ofruction Process types, you are able to trigger any of the members seen in Pa r t Thre e - PrHere, ogr amsimply m i ng wdump i th .N ET bl ieidentifier s Table 10-2. theAssem process

(PID) and the name of each process. Assuming the

Chapter 9 - Under standing .NET Assem blies Main() method has been updated to call this helper function, you will see something like the output in Figure Chapter 10-3. 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List ofFigure Tables 10-3: Enumerating running processes

Investigating a Specific Process In addition to obtaining a full and complete list of all running processes on a given machine, the static Process.GetProcessById() method allows you to obtain a single Process type via the associated PID. As you would hope, if you request access to a nonexistent process ID, an ArgumentException exception is thrown: // If there is no process with the PID of 987, a // runtime exception will be thrown. int pID = 987; Process theProc; try { theProc = Process.GetProcessById(pID); }

catch // Generic catch for simplicitiy C# an d th e .N ETSorry...bad Plat f orm , Se con d Ed it ion } { Console.WriteLine("-> PID!"); by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Investigating a Process' Thread Set

Now that you understand how to gain access to a Process type, you are able to programmatically Tainvestigate ble o f Con tthe en tset s of all threads currently alive in the process at hand. This set of threads is represented by the strongly typed collection, which contains any number of individual C# and t he .NET PlatProcessThreadCollection for m, Second Edition ProcessThread types. To illustrate, assume the following additional static helper function has been added I ntr oduction to your current application: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET public EnumThreadsForPid(int pID) Chapter 2 static - Buildingvoid C# Applications

{r t Tw o - The C# Pr ogr am m ing La ngua ge Pa theProc; Chapter Process 3 - C# Language Fundamentals Chapter try 4 - Obj ect -Or iented Pr ogr am ming w ith C#

= and Process.GetProcessById(pID); } Chapter { 5 theProc - Exceptions Obj ect Lifetim e Chapter catch 6 - I nter faces and Collections

{ - Callback I nter faces, Delegates, and Ev ents Console.WriteLine("-> Sorry...bad PID!"); Chapter 8 - Advanced C# Type Const ruction Techniques Console.WriteLine("************************************\n"); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s return; Chapter 9 - Under standing .NET Assem blies } Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads // List out stats for each thread in the specified process. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Console.WriteLine("Here are the thread IDs for: {0}", Pa r t Four - Le ve r a ging the .NET Libr a r ie s theProc.ProcessName); Chapter ProcessThreadCollection 12 - Obj ect Ser ialization and the .NET Remoting Lay theThreads = ertheProc.Threads; Chapter foreach(ProcessThread 13 - Building a Bet ter Win dow ( pt Int roducin g Window s For ms) in theThreads) Chapter { 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr string ogr am ming with Windows Form s Contr ols info = Chapter 16 - The Sy stem .I O Nam espace string.Format("-> Thread ID: {0}\tStart Time {1}\tPriority {2}", Chapter 17 - Data Access pt.Id w ith ADO.NET , pt.StartTime.ToShortTimeString(), pt.PriorityLevel); Pa r t Fi ve - W e b Appl Console.WriteLine(info); ica ti ons and X ML W e b Se r vi ces Chapter } 18 - ASP.NET Web Pages and Web Contr ols Chapter Console.WriteLine("************************************\n"); 19 - ASP.NET Web Applicat ions } Chapter 20 - XML Web Ser vices Chapter 7

I ndex List of Figur es

As you can see, the Threads property of the System.Diagnostics.Process type provides access to the ProcessThreadCollection class. Here, we are printing out the assigned thread ID, start time, and priority level of each thread in the process specified by the client. Thus, if you update your program's Main() method to prompt the user for a PID to investigate:

List of Tables

Console.WriteLine("***** Enter PID of process to investigate *****"); Console.Write("PID: "); string pID = Console.ReadLine(); int theProcID = int.Parse(pID); EnumThreadsForPid(theProcID);

you would find output along the lines of the Figure 10-4.

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Figure 10-4: Enumerating the threads within a running process

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - C# Language The ProcessThread type Fundamentals has additional members of interest beyond Id, StartTime, and PriorityLevel. Table Chapter 10-3 documents 4 - Obj ectsome -Or iented members Pr ogr am of ming interest. w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Table 10-3: Members of the ProcessThread Type Chapter 6 - I Select nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Member of Meaning in Life Chapter 8 - Advanced C# Type Const ruction Techniques System.Diagnostics.ProcessThread Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter BasePriority 9 - Under standing .NET Assem blies

Gets the base priority of the thread

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

CurrentPriority

Gets the current priority of the thread

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa rId t Four - Le ve r a ging the .NET Libr a r ie s

Gets the unique identifier of the thread

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

IdealProcessor

Sets the preferred processor for this thread to run on

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

PriorityLevel Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Gets or sets the priority level of the thread Chapter 16 - The Sy stem .I O Nam espace

ProcessorAffinity

Chapter 17 - Data Access w ith ADO.NET

Sets the processors on which the associated thread can run

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

StartAddress Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex StartTime List of Figur es List of Tables

Gets the memory address of the function that the operating system called that started this thread Gets the time that the operating system started the thread

ThreadState

Gets the current state of this thread

TotalProcessorTime

Gets the total amount of time that this thread has spent using the processor

WaitReason

Gets the reason that the thread is waiting

Now before reading any further, be very aware that the ProcessThread type is not the entity used to create, suspend, or kill threads under the .NET platform. Rather, ProcessThread is a vehicle used to obtain diagnostic information for the active threads within a running process.

Investigating a Process' Module Set Next up, let's check out how to iterate over the number of loaded modules that are hosted within a given process. Recall that a module is a generic name used to describe a given *.dll (or the *.exe itself) which is

hosted by a specific process. When you access the ProcessModuleCollection via the Process.Module an d th e .N ET Plat f orm , Se con d Ed it ion property, you areC# able to enumerate over all modules in a process; .NET-based, COM-based, or traditional ISBN:1590590554 by Andr ewthe Tr oelsen C-based binaries. Ponder following helper function: Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the

public staticC#void EnumModsForPid(int pID) language and then quickly m oves to key technical and { ar chitectur al issues for .NET developer s. Process theProc; try theProc = Process.GetProcessById(pID); } Ta ble o f { Con t en t s catch C# and t he .NET Plat for m, Second Edition { I ntr oduction Console.WriteLine("-> Sorry...bad PID!"); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Console.WriteLine("************************************\n"); Chapter 1 - The Philosophy of .NET return; Chapter 2 - Building C# Applications } Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Console.WriteLine("Here are the loaded modules for: {0}", Chapter 3 - C# Language Fundamentals theProc.ProcessName); Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# try Chapter 5 - Exceptions and Obj ect Lifetim e { Chapter 6 - I nter faces and Collections ProcessModuleCollection theMods = theProc.Modules; Chapter 7 - Callback I nter faces, Delegates, and Ev ents foreach(ProcessModule pm in theMods) Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Thre e - Pr ogr am mstring i ng w i th .N ET Assem bl ie s info = string.Format("-> Mod Name: {0}", pm.ModuleName); Chapter 9 - Under standing .NET Assem blies Console.WriteLine(info); Chapter 10 - Pr } ocesses, AppDomains, Cont exts, and Threads Chapter Console.WriteLine("************************************\n"); 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four} - Le ve r a ging the .NET Libr a r ie s Chapter catch{Console.WriteLine("No 12 - Obj ect Ser ialization and the .NET Remoting Lay er mods!");} Chapter } 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

To illustrate one possible invocation of this function, let's check out the loaded modules for the process hosting your current console application (ProcessManipulator). To do so, run the application, identify the Chapter 17 - Data Access w ith ADO.NET PID assigned to ProcessManipulator.exe, and pass this value to the EnumModsForPid() method (be sure to Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces update your Main() method accordingly). Once you do, you may be surprised to see the list of *.dlls used for Chapter 18 - ASP.NET Web Pages and Web Contr ols a simple console application (atl.dll, mfc42u.dll, oleaut32.dll and so forth.) Figure 10-5 shows a test run. Chapter 16 - The Sy stem .I O Nam espace

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 10-5: Enumerating the loaded modules within a running process

C# an d th e .N ET Plat f orm , Se con d Ed it ion Starting and Killing Processes Programmatically ISBN:1590590554 by Andr ew Tr oelsen

2003 (1200 pages) The final aspectsApr of ess the ©System.Diagnostics.Process type examined here are the Start() and Kill() methods. This ehensiv ethese text star ts w ith provide a brief ov viewtoofprogrammatically the As you can gather by compr their names, members aerway launch and terminate C# language and then quickly m oves to key technical and a process. For example:

ar chitectur al issues for .NET developer s.

public static void StartAndKillProcess() Ta{ble o f Con t en t s Launch Explorer. C# and t// he .NET Plat forInternet m, Second Edition Process ieProc = Process.Start("IExplore.exe", I ntr oduction Pa r t One - I nt r"www.intertech-inc.com"); oduci ng C# a nd the .NET P la tf or m Console.Write("--> Hit enter to kill {0}...", ieProc.ProcessName); Chapter 1 - The Philosophy of .NET Console.ReadLine(); Chapter 2 - Building C# Applications // Kill the iexplorer.exe process. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge try { ieProc.Kill(); } Chapter 3 - C# Language Fundamentals catch{} // In case user already killed it... Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# } Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7 -Process.Start() Callback I nter faces, Delegates, andoverloaded Ev ents The static method has been a few times, however. At minimum you will need to Chapter specify8the- friendly Advanced name C# Type of theConst process ruction youTechniques wish to launch (such as MS Internet Explorer). This example Pa makes r t Threuse e - Pr ofogr a variation am m i ng w ofi th the.NStart() ET Assem method bl ie s

that allows you to specify any additional arguments to pass

into the9program's entry point (i.e., theblies Main() method). Chapter - Under standing .NET Assem Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

The Start() method also allows you to pass in a System.Diagnostics.ProcessStartInfo type to specify additional bits of information regarding how a given process should come into life. Here is the formal Pa r t Four - Le ve r a ging the .NET Libr a r ie s definition of ProcessStartInfo (see online Help for full details of this type): Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

public sealed class System.Diagnostics.ProcessStartInfo : object Chapter 15 - Pr ogr am ming with Windows Form s Contr ols { Chapter 16 - The Sy stem .I O Nam espace public ProcessStartInfo(); Chapter 17 - Data Access w ith ADO.NET public ProcessStartInfo(string fileName); Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces public ProcessStartInfo(string fileName, string arguments); Chapter 18 - ASP.NET Web Pages and Web Contr ols public string Arguments { get; set; } Chapterpublic 19 - ASP.NET Applicat ions boolWeb CreateNoWindow { get; set; } Chapterpublic 20 - XMLStringDictionary Web Ser vices EnvironmentVariables { get; } I ndex public bool ErrorDialog { get; set; } List of Figur es public IntPtr ErrorDialogParentHandle { get; set; } List of Tables public string FileName { get; set; } public bool RedirectStandardError { get; set; } public bool RedirectStandardInput { get; set; } public bool RedirectStandardOutput { get; set; } public bool UseShellExecute { get; set; } public string Verb { get; set; } public string[] Verbs { get; } public ProcessWindowStyle WindowStyle { get; set; } public string WorkingDirectory { get; set; } public virtual bool Equals(object obj); public virtual int GetHashCode(); public Type GetType(); public virtual string ToString(); } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Regardless of which version of the Process.Start() method you invoke, do note that you are returned a C# an d th e .N ET Plat f orm , Se con d Ed it ion reference to the newly activated process. When you wish to terminate the process, simply call the instance ISBN:1590590554 by Andr ew Tr oelsen level Kill() method. Apr ess © 2003 (1200 pages)

SOURCE CODE

ProcessManipulator ThisThe compr ehensiv e text star tsapplication w ith a briefisovincluded er view ofunder the the Chapter 10 subdirectory. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET Plat f orm , Se con d Ed it ion Type Understanding System.AppDomain ISBN:1590590554

by Andr ew Tr oelsen

Now that you understand how(1200 to interact Apr ess © 2003 pages) with a Win32 process from managed code, we need to examine more closely the new (but related) concept of astar .NET domain. Asthe I mentioned briefly in the introduction, This compr ehensiv e text ts wapplication ith a brief ov er view of unlike a traditional (non-.NET) Win32 *.exe application, .NET assemblies C# language and then quickly m oves to key technical and are hosted in a logical partition within chitectur al issues for .NET s. aprocess termedaran application domain (akadeveloper AppDomain) and many application domains can be hosted inside a single OS process. This additional subdivision of a traditional Win32 process offers several benefits, some of which are: Ta ble o f Con t en t s

AppDomains a key aspect of the OS-neutral nature of the .NET platform, given that this logical division C# and t he .NET Platare for m, Second Edition abstracts away the differences in how an underlying operating system represents a loaded executable. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

AppDomains are far less expensive in terms of processing power and memory than a full blown process - The Philosophy of .NET (for example, the CLR is able to load and unload application domains much quicker than a formal Chapter 2 - Building C# Applications process). Chapter 1

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - C# Language AppDomains provideFundamentals a deeper level of isolation for hosting a loaded application. If one AppDomain within a Chapter 4 - Obj ect -Or Pr ogrAppDomains am ming w ith C# process fails, theiented remaining remain functional. Chapter 5

- Exceptions and Obj ect Lifetim e As suggested in faces the previous hit-list, a single process can host any number of AppDomains, each of which is Chapter 6 - I nter and Collections

fully and from other AppDomains Chapter 7 completely - Callback Iisolated nter faces, Delegates, and Ev ents within this process (or any other process). Given this

factoid, be- very aware that applications that run in unique AppDomains are unable to share any information of Advanced C# Type Const ruction Techniques any kind (global variables or static fields) unless they make use of the .NET Remoting protocol (examined in Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 12) to marshal the data. Chapter 8 Chapter 9

- Under standing .NET Assem blies

Chapter 10 In - Pr ocesses, AppDomains, Cont exts, and Threads Note some respects, .NET application domains are reminiscent of the "apartment" architecture of classic Chapter 11 COM. - TypeOf Reflection, Late Binding, and Attr ibuteBased Pr ogramm ing course, .NET AppDomains are managed types whereas the COM apartment architecture is Pa r t Four - Le ve ron a ging the .NET Libr (and a r ie s hideously built an unmanaged

complex) structure.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Understand that while a single host multiples AppDomains, this is not always the case. At the very Chapter 13 - Building a Bet ter Winprocess dow ( Intmay roducin g Window For ms) least an14OS will host Chapter - Aprocess Better Paint ing Frwhat amewisortermed k ( GDI +the ) default application domain. This specific application domain is automatically created by the at theForm times the process launches. After this point, the CLR creates additional Chapter 15 - Pr ogr am ming withCLR Windows Contr ols

application domains on an as-needed basis. If the need should arise (which it most likely will not for a majority of your .NET endeavors), you are also able to programmatically create application domains at runtime within a Chapter 17 - Data Access w ith ADO.NET given process using static methods of the System.AppDomain class. This class is also useful for low-level Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces control of application domains. Key members of this class are shown in Table 10-4. Chapter 16 - The Sy stem .I O Nam espace

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Table 10-4: Select Members of AppDomain

Chapter 20 - XML Web Ser vices

AppDomain I ndex

Meaning in Life

ListMember of Figur es List of Tables

CreateDomain()

This static method creates a new AppDomain in the current process. Understand that the CLR will create new application domains as necessary, and thus the chance of you absolutely needing to call this member is slim to none (unless you happen to be building a custom CLR host).

GetCurrentThreadId()

This static method returns the ID of the active thread in the current application domain.

Unload()

Another static method that allows you to unload a specified AppDomain within a given process.

BaseDirectory

This property returns the base directory that the assembly resolver used to probe for dependent assemblies.

CreateInstance()

Creates an instance of a specified type defined in a specified assembly file.

ExecuteAssembly()

Executes an assembly within an application domain, given its file name.

GetAssemblies() thePlat setf orm of .NET assemblies C# an d thGets e .N ET , Se con d Ed it ionthat have been loaded into this application domain. Unlike the Process type, the GetAssemblies() method will only ISBN:1590590554 by Andr ew Tr oelsen return the list of true-blue .NET binaries. COM-based or C-based binaries are Apr ess © 2003 (1200 pages) ignored. This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and Used to dynamically load an assembly into the current application domain. ar chitectur al issues for .NET developer s.

Load()

In addition, the AppDomain type also defines a small set of events that correspond to various aspects of an application domain's life-cycle (Table 10-5).

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntr oduction

Table 10-5: Events of the AppDomain Type

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Events Chapter 1 - of The Philosophy of .NET

Meaning in Life

System.AppDomain Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

AssemblyLoad

Chapter 3

Occurs when an assembly is loaded

- C# Language Fundamentals

Chapter AssemblyResolve 4 - Obj ect -Or iented Pr ogr am ming Occurs w ithwhen C# the resolution of an assembly fails Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

DomainUnload

Occurs when an AppDomain is about to be unloaded

ProcessExit Occurs onEvthe default application domain when the default Chapter 7 - Callback I nter faces, Delegates, and ents Chapter 8

application domain's parent process exits - Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

ResourceResolve

Chapter 9

Occurs when the resolution of a resource fails

- Under standing .NET Assem blies

TypeResolve Occurs the resolution of a type fails Chapter 10 - Pr ocesses, AppDomains, Cont exts,when and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

UnhandledException

Occurs when an exception is not caught by an event handler

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Fun with AppDomains

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

To illustrate how to interact with .NET application domains programmatically, assume you have a new C# console application named AppDomainManipulator. The static PrintAllAssembliesInAppDomain() helper Chapter - Datause Access w ith ADO.NET method17makes of AppDomain.GetAssemblies() to obtain a list of all .NET binaries hosted within the Pa r t Fi ve W e b Appl ica ti ons and X ML W e b Se r vi ces application domain in question. Chapter 16 - The Sy stem .I O Nam espace

Chapter 18 - ASP.NET Web Pages and Web Contr ols

This list19is -represented by Applicat an array of System.Reflection.Assembly types, and thus we are required to use the Chapter ASP.NET Web ions System.Reflection namespace Chapter 20 - XML Web Ser vices (full details of this namespace and the Assembly type are seen in Chapter 11). Once we obtain the list of loaded assemblies, we iterate over the array and print out the friendly name and I ndex version of es each module: List of Figur List of Tables

using System.Reflection; // For the Assembly type. ... public static void PrintAllAssembliesInAppDomain(AppDomain ad) { Assembly[] loadedAssemblies = ad.GetAssemblies(); Console.WriteLine("***** Here are the assemblies loaded in {0} *****\n", ad.FriendlyName); foreach(Assembly a in loadedAssemblies) { Console.WriteLine("-> Name: {0}", a.GetName().Name); Console.WriteLine("-> Version: {0}\n", a.GetName().Version); } }

Now assume you have updated the Main() method to obtain a reference to the current application domain C# an d th e .N ET Plat f orm , Se con d Ed it ion before invoking PrintAllAssembliesInAppDomain(), using the AppDomain.CurrentDomain property. To make ISBN:1590590554 Andr ew Trnotice oelsenthat the Main() method launches things a bit more by interesting, a message box to force the assembly Apr ess © 2003 (1200 pages) resolver to load the System.Windows.Forms.dll and System.dll assemblies (so be sure to set a reference to ehensiv text star ts w ith a brief ov er view of the these assembliesThis andcompr update your e"using" statements appropriately): C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

public static int Main(string[] args) { The Amazing AppDomain app *****\n"); Ta ble o f Console.WriteLine("***** Con t en t s // Get info for current AppDomain. C# and t he .NET Plat for m, Second Edition AppDomain defaultAD= AppDomain.CurrentDomain; I ntr oduction MessageBox.Show("This loaded System.Windows.Forms.dll and System.dll"); Pa r t One - I nt r oduci ng C# a nd the .NET call P la tf or m PrintAllAssembliesInAppDomain(defaultAD); Chapter 1 - The Philosophy of .NET 0; C# Applications Chapter return 2 - Building } Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# Figure 10-6 shows the output.

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - 10-6: A Better Paint ing Fr amew or k ( GDIwithin +) Figure Enumerating assemblies a given app domain (within a given process) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Programmatically Creating New AppDomains

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Recall 18 that- aASP.NET single process is capable hosting Chapter Web Pages and WebofContr ols multiple AppDomains. While it is true that you will seldom (if ever) need manually AppDomains directly (unless you happen to be creating a custom host for the Chapter 19 - to ASP.NET Webcreate Applicat ions CLR), you able dovices so via the static CreateDomain() method. As you would guess, this method has been Chapter 20 -are XML WebtoSer overloaded a number of times. At minimum you will simply specify the friendly name of the new application I ndex domain asesseen here: List of Figur List of Tables

public static int Main(string[] args) { ... // Make a new AppDomain in the current process. AppDomain anotherAD = AppDomain.CreateDomain("SecondAppDomain"); PrintAllAssembliesInAppDomain(anotherAD); return 0; }

Now, if you run the application again (Figure 10-7), notice that the System.Windows.Forms.dll and System.dll assemblies are only loaded within the default application domain! This may seem counterintuitive if you have a background in traditional Win32 (as you might suspect that both application domains have access to the same assembly set). Recall, however, that an assembly loads into an applicationdomain, not directly into the process itself.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter Figure 1 - 10-7: The Philosophy A single process of .NET with two application domains Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Next, notice how the SecondAppDomain application domain automatically contains its own copy of mscorlib.dll, - C# Language Fundamentals as this key assembly is automatically loaded by the CLR for each and every application domain. This begs the Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# question, "How can I programmatically load an assembly into an application domain?" Answer? The Chapter 5 - Exceptions and Obj Lifetim e AppDomain.Load() method (orect alternatively, AppDomain.ExecuteAssembly()). I'll hold off on this topic until I Chapter 6 I nter faces and Collections discuss the process of dynamically loading assemblies in Chapter 11 during our examination of .NET reflection Chapter 7 - Callback I nter faces, Delegates, and Ev ents services. Chapter 3

Chapter 8

- Advanced C# Type Const ruction Techniques

To relationship processes, Pa r t solidify Thre e - the Pr ogr am m i ng w ibetween th .N ET Assem bl ie s

application domains, and assemblies, Figure 10-8 diagrams the internal composition of the AppDomainManipulator.exe process you have just constructed. Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List ofFigure Figur es10-8: The AppDomainManipulator.exe process under the hood List of Tables

Programmatically Unloading AppDomains (and Hooking into Events) It is important to point out that the CLR does not permit unloading individual .NET assemblies. However, using the AppDomain.Unload() method you are able to selectively unload a given application domain from its hosting process. When you do so, the application domain will unload each assembly in turn. Recall that the AppDomain type defines a small set of events, one of which is DomainUnload. This is fired when a (non-default) AppDomain is unloaded from the containing process. Another event of interest is the ProcessExit event, which is fired when the default application domain is unloaded from the process (which obviously entails the termination of the process itself). Thus, if you wish to programmatically unload anotherAD from the AppDomainManipulator.exe process, and be notified when the application domain is torn down, you are able to write the following event logic: public static void anotherAD_DomainUnload(object sender, EventArgs e)

{ Console.WriteLine("***** Unloaded anotherAD! *****\n"); } C# an d th e .N ET Plat f orm , Se con d Ed it ion ... ISBN:1590590554 Andr ew Tr oelsen event. // Hook into byDomainUnload Apr ess © 2003 (1200 pages) anotherAD.DomainUnload += This compr ehensiv e text star ts w ith a brief ov er view of the new EventHandler(anotherAD_DomainUnload); language and then quickly m oves to key technical and // Now unloadC#anotherAD. ar chitectur al issues for .NET developer s. AppDomain.Unload(anotherAD); Ta ble o f Con t en t s

If you wish to be notified when the default AppDomain is unloaded, modify your application to support the following event logic:

C# and t he .NET Plat for m, Second Edition I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

private static void defaultAD_ProcessExit(object sender, EventArgs e) - The Philosophy of .NET { Console.WriteLine("***** Unloaded defaultAD! *****\n"); } Chapter 2 - Building C# Applications ... Pa r t Tw o - The C# Pr ogr am m ing La ngua ge defaultAD.ProcessExit +=new EventHandler(defaultAD_ProcessExit); Chapter 1

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter SOURCE 6 - I nter facesThe andAppDomainManipulator Collections project is included under the Chapter 10 subdirectory.

CODE Chapter 7 - Callback I nter faces, Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dContext th e .N ET Plat f orm , Se con d Ed itCan ion Understanding (or How Low You Go?) ISBN:1590590554

by Andr ew Tr oelsen

As you have just Apr seen, are logical partitions within a process used to host .NET assemblies. A give essAppDomains © 2003 (1200 pages) application domain may be further subdivided context In a nutshell, a .NET context This compr ehensiv e text star ts into w ithnumerous a brief ov er view of boundaries. the provides a way for a single AppDomain to partition .NET objects that have similar execution requirements. Using C# language and then quickly m oves to key technical and al issuesthat for objects .NET developer s. special runtime requirements are handled appropriatel context, the CLR ar ischitectur able to ensure that have and in a consistent manner by intercepting method invocations into and out of a given context. This layer of interception allows CLR to adjust the current method invocation to conform to the contextual settings of a given Ta ble o f Con t en t s

Just a process a default AppDomain, every application domain has a default context. This default con C# andast he .NET Platdefines for m, Second Edition (sometimes I ntr oduction referred to as context 0, given that it is always the first context created within an application domain) used to -group together objects Pa r t One I nt r oduci ng C#.NET a nd the .NET that P la tfhave or m

no specific or unique contextual needs. As you may expect, a vas

majority1 of- your classoftypes Chapter The .NET Philosophy .NETwill be loaded into context 0. If the CLR determines a newly created object has special2needs, a newC#context boundary is created within the hosting application domain. Figure 10-9 illustrates th Chapter - Building Applications process, Pa r t Tw o - AppDomain, The C# Pr ogr context am m ing relationship. La ngua ge Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - 10-9: Obj ectProcesses, Ser ializationapplication and the .NET Remoting er Figure domains, andLay context boundaries Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Context-Agile and Context-Bound Types

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

.NET types not demand any special contextual treatment are termed context-agile objects. These objec Chapter 17 - that Datado Access w ith ADO.NET can from anywhere within Pa r t Fibe ve accessed - W e b Appl ica ti ons and X ML W e bthe Se rhosting vi ces

AppDomain without interfering with the object's runtime

requirements. Building context-agile objects isols a no-brainer, given that you simply do nothing (specifically, you do Chapter 18 - ASP.NET Web Pages and Web Contr adorn the with any attributes and do not derive from the System.ContextBoundObject base class Chapter 19 type - ASP.NET Webcontextual Applicat ions Chapter 20 - XML Web Ser vices

// A context-agile object is loaded into context 0. I ndex public IAmAContextAgileClassType{} List of Figurclass es List of Tables

On the other hand, objects that do demand contextual allocation are termed context-bound objects, and must derive from the System.ContextBoundObject base class. This base class solidifies the fact that the object in question can only function appropriately within the context in which it was created. In addition to deriving from System.ContextBoundObject, a context-sensitive type will also be adorned with a spe category of .NET attributes termed (not surprisingly) context attributes. All context attributes derive from the System.Runtime.Remoting.Contexts.ContextAttribute base class, which is defined as follows (note this class typ implements two context-centric interfaces, IContextAttribute and IContextProperty): public class System.Runtime.Remoting.Contexts.ContextAttribute : Attribute, System.Runtime.Remoting.Contexts.IContextAttribute, System.Runtime.Remoting.Contexts.IContextProperty { public ContextAttribute(string name);

public string Name { virtual get; } C# an d TypeId th e .N ET { Plat f orm , Se con d Ed}it ion public object virtual get; ISBN:1590590554 by Andr ew Tr oelsen public virtual bool Equals(object o); Apr ess © 2003 (1200 pages) public virtual void Freeze(System.Runtime.Remoting.Contexts.Context newContex This compr ehensiv e text star ts w ith a brief ov er view of the public virtual int GetHashCode(); C# language and then quickly m oves to key technical and public virtual void GetPropertiesForNewContext( ar chitectur al issues for .NET developer s. System.Runtime.Remoting.Activation.IConstructionCallMessage ctorMsg); public Type GetType(); public virtual bool IsContextOK( Ta ble o f Con t en t s System.Runtime.Remoting.Contexts.Context ctx, C# and t he .NET Plat for m, Second Edition System.Runtime.Remoting.Activation.IConstructionCallMessage ctorMsg); I ntr oduction public virtual bool IsDefaultAttribute(); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public virtual bool IsNewContextOK( Chapter 1 - The Philosophy of .NET System.Runtime.Remoting.Contexts.Context newCtx); Chapter 2 - Building C# Applications public virtual bool Match(object obj); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge public virtual string ToString(); Chapter 3 - C# Language Fundamentals } Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e The .NET define numerous context attributes that describe specific runtime requirements (s Chapter 6 -base I nterclass faces libraries and Collections

as thread and URL activation). Chapter 7 synchronization - Callback I nter faces, Delegates, and EvGiven ents the role of .NET context, it should stand to reason that if a context-bound object were to somehow endTechniques up in an incompatible context, bad things are guaranteed to occur a Chapter 8 - Advanced C# Type Const ruction the moste inopportune times. Pa r t Thre - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

Creating a Context-Bound Object

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

So, what- sort might Pa r t Four Le veof r a bad ging things the .NET Libroccur a r ie s

if a context-bound object is placed into an incompatible context? The

answer12 depends the object'sand advertised settings. Assume for example that you wish to define a .N Chapter - Obj ecton Ser ialization the .NET contextual Remoting Lay er type that thread-safe in nature, though Chapter 13is- automatically Building a Bet ter Win dow ( Int roducin geven Window s Foryou ms)have not hard-coded thread-safe-centric logic within the implementations. so, Chapter 14 method - A Better Paint ing Fr amew To or k do ( GDI + )you may apply the

System.Runtime.Remoting.Contexts.SynchronizationAttribute attribute as follows:

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

using17System.Runtime.Remoting.Contexts; Chapter - Data Access w ith ADO.NET ... Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces // This will only Chapter 18 - context-bound ASP.NET Web Pagestype and Web Contr ols be loaded into a // synchronized (and hence, thread safe) context. [Synchronization] Chapter 20 - XML Web Ser vices public class MyThreadSafeObject : ContextBoundObject I ndex {} Chapter 19 - ASP.NET Web Applicat ions

List of Figur es List of Tables

As you will see in greater detail later in this chapter, classes that are attributed with the [Synchronization] attribut are loaded into a thread-safe context. Given the special contextual needs of the MyThreadSafeObject class type imagine the problems that would occur if an allocated object were moved from a synchronized context into a nonsynchronized context. The object is suddenly no longer thread-safe and thus becomes a candidate for mass data corruption, as numerous threads are attempting to interact with the (now thread-volatile) reference object. is obviously a huge problem, given that the code base has not specifically wrapped thread-sensitive resources w hard-coded synchronization logic.

Placing Context in Context Now, the good news is that you do not have to concern yourself with the act of ensuring that your context-bound objects are loaded into the correct contextual setting. The .NET runtime will read the assembly metadata when constructing the type, and build a new context within the current application domain when necessary. To be honest, the notion of .NET context is an extremely low-level facility of the CLR. So much so, that a key

context-centric namespace, System.Runtime.Remoting.Context, only formally lists the SynchronizationAttribute an d th e .N ET Plat f orm , Se con d Ed it ion class type within C# online Help (as of .NET version 1.1). The remaining members are considered usable only by th ISBN:1590590554 by Andr oelsen (which you should do, given CLR, and are intended toewbeTrignored that many members of this namespace are Apr ess © 2003 (1200 pages) subject to change in future releases of .NET). This compr ehensiv e text star ts w ith a brief ov er view of the language and then m oves to key types, technical and as an academic endeavor. Thus, by wa Nevertheless, it isC#possible to make usequickly of these hands-off simply ar chitectur al issues developer s. a friendly heads-up, understand thatfor the.NET following example is purely illustrative in nature. As a .NET programme you can safely ignore these low-level primitives in 99.99 percent of your applications. If you wish to see the form definition of the any of the following context-centric types, make use of the wincv.exe utility.

Ta ble o f Con t en t s

C# and t he COM+ .NET Plat for m, Second Note developers are Edition already aware of the notion of context. Using COM IDL attributes and the I ntr oductionComponent Services utility, developers are able to establish contextual settings for a given COM+ type Pa r t One - I Although nt r oduci ng C# aand nd the .NETboth P la tf make or m .NET COM+

use of contextual boundaries, understand that the underlying

Chapter 1 implementations - The Philosophy of of .NET both systems are not the same and cannot be treated identically. Chapter 2

- Building C# Applications

Fun with Context

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4 assume - Obj ect -Or amconsole ming w ith C# To begin, youiented havePr a ogr new application named ContextManipulator. This application defines two Chapter context-agile 5 - Exceptions types andand a single Obj ectcontext-bound Lifetim e type: Chapter 6

- I nter faces and Collections

Chapter - Callback I nter faces, Delegates, and Ev ents using7 System.Runtime.Remoting.Contexts;

// For Context type.

Chapter - Advanced C# Type Const ruction using8 System.Threading; // For Techniques Thread type. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s ...

Chapter // These 9 - Under classes standing have .NETno Assem special blies contextual

// needs and willAppDomains, be loaded into theThreads Chapter 10 - Pr ocesses, Cont exts, and // default context the app and domain. Chapter 11 - Type Reflection,of Late Binding, Attr ibute- Based Pr ogramm ing public NoSpecialContextClass Pa r t Four - class Le ve r a ging the .NET Libr a r ie s { Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er NoSpecialContextClass() Chapterpublic 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter{14 - A Better Paint ing Fr amew or k ( GDI + )

// Get context information and print out context ID. Context ctx = Thread.CurrentContext; Chapter 16 - The Sy stem .I O Nam espace Console.WriteLine("Info about context {0}", ctx.ContextID); Chapter 17 - Data Access w ith ADO.NET foreach(IContextProperty itfCtxProp in ctx.ContextProperties) Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name); Chapter 18 - ASP.NET Web Pages and Web Contr ols } Chapter 19 - ASP.NET Web Applicat ions } Chapter 20 class - XML Web Ser vices public NoSpecialContextClass2 I ndex { List of Figur es public NoSpecialContextClass2() List of Tables { // Get context information and print out context ID. Context ctx = Thread.CurrentContext; Console.WriteLine("Info about context {0}", ctx.ContextID); foreach(IContextProperty itfCtxProp in ctx.ContextProperties) Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name); } } // This class demands to be loaded in // a synchronization context. // RECALL! All context-bound types must derive from // System.ContextBoundObject. [Synchronization] public class SynchContextClass : ContextBoundObject { public SynchContextClass() Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

{ an dcontext th e .N ET information Plat f orm , Se conand d Ed itprint ion // C# Get out context ID. ISBN:1590590554 by Andr ew Tr oelsen Context ctx = Thread.CurrentContext; Apr ess © 2003 (1200 pages) Console.WriteLine("Info about context {0}", ctx.ContextID); This compr ehensiv e text star ts w itfCtxProp ith a brief ov er view the foreach(IContextProperty in of ctx.ContextProperties) C# language and then quickly m oves to key technical and Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name); ar chitectur al issues for .NET developer s.

} } Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

Notice that each of the class constructors obtains a System.Runtime.Remoting.Contexts.Context type from the

I ntr oduction current thread of execution, via the static Thread.CurrentContext property. Using this type, you are able to print o Pa r t One - about I nt r oduci C# a nd the .NET P la tf or m statistics theng contextual boundary, such

as its assigned ID, as well as a set of descriptors obtained via the

Chapter 1 - The Philosophy of .NET This instance-level property returns a (very) low-level interface named Context.ContextProperties property. Chapter 2 Building C# Applications IContextProperty, which exposes each descriptor through the Name property. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Now, assume has Fundamentals been updated to allocate an instance of each class type. As the objects come to life, th Chapter 3 - C#Main() Language class constructors williented dumpProut context-centric information (Figure 10-10): Chapter 4 - Obj ect -Or ogrvarious am ming bits w ithofC# Chapter 5

- Exceptions and Obj ect Lifetim e static Main(string[] Chapter 6 void - I nter faces and Collectionsargs)

{ Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Amazing Context Application *****\n"); Chapter Console.WriteLine("***** 8 - Advanced C# Type Const ructionThe Techniques // Make each class type and print contextual info. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s NoSpecialContextClass noBigDealObj = new NoSpecialContextClass(); Chapter 9 - Under standing .NET Assem blies Console.WriteLine(); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads NoSpecialContextClass2 noBigDealObj2 = new NoSpecialContextClass2(); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Console.WriteLine(); Pa r t Four - Le ve r a ging the .NET Libr a r ie s SynchContextClass synchObj = new SynchContextClass(); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Console.WriteLine(); Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 10-10: Investigating an object's context

Given that the NoSpecialContextClass and NoSpecialContextClass2 types have not been qualified with a specif context attribute, the CLR will have both loaded into context 0 (i.e., the default context). However, the SynchContextClass type is loaded into a unique contextual boundary within the current application domain, given fact that this context-bound type was adorned with the [Synchronization] attribute. SOURCE CODE

The ContextManipulator project is included under the Chapter 10 subdirectory.

C# an d th e .N ET Plat fAppDomains, orm , Se con d Ed it ion and Context Summarizing Processes, ISBN:1590590554

by Andr ew Tr oelsen

So then, at this point in the game have seen how the .NET runtime has altered the composition of a Apr ess © 2003 (1200you pages) traditional Win32 This process to function within common compr ehensiv e text starthe ts w ith a brieflanguage ov er view runtime of the (CLR). To summarize the key points, rememberC#thelanguage following: and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

A .NET process hosts one to many application domains. Each AppDomain is able to host any number of related .NET assemblies, and may be independently loaded and unloaded by the CLR (or Ta ble o programmatically f Con t en t s via the System.AppDomain type). C# and t he .NET Plat for m, Second Edition

A given AppDomain consists of one to many contexts. Using a context, the CLR is able to group special needs objects into a logical container, to ensure that their runtime requirements are honored. One - I nt r oduci ng C# a nd the .NET P la tf or m

I ntr oduction Pa r t

Chapter 1 - Thepages Philosophy .NET to be a bit too low-level for your liking, fear not. For the most part, the If the previous have of seemed Chapter 2 Building C# Applications .NET runtime automatically deals with the details of processes, application domains, and contexts on your Pa r t Tw o However, - The C# Pr ogrbackground am m ing La ngua ge behalf. this discussion has

provided a solid foundation regarding how the CLR

Chapter 3 processes, - C# Language Fundamentals creates, and destroys specific threads of execution (as well as increased your understanding of Chapter 4 - Obj ectCLR -Or iented Pr ogr am ming w ith C# some underlying concepts). Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion The Process/AppDomain/Context/Thread Relationship ISBN:1590590554

by Andr ew Tr oelsen

As mentioned at the opening thispages) chapter, a thread is a path of execution within a loaded application. Apr ess © 2003 of (1200 While many .NETThis applications can live lives, the primary thread may compr ehensiv e texthappy star tsand w ithproductive a brief ov ersingle-threaded view of the spawn secondaryC# threads of execution to perform additional units of work. In just a moment, you will be language and then quickly m oves to key technical and chitectur al issues for .NET developer s. defines numerous types used to create introduced to the ar System.Threading namespace, which multithreaded .NET applications. First however, we need to check out exactly "where" a thread lives within a .NET process. Ta ble o f Con t en t s

The first is that under the .NET platform, there is not a direct one-to-one C# and t hething .NETyou Platmust for m, understand Second Edition correlation I ntr oduction between application domains and threads. In fact, a given AppDomain can have numerous threads within at any givenP la time. Furthermore, Pa r t One -executing I nt r oduci ng C# it a nd the .NET tf or m

a particular thread is not confined to a single

application during its Threads are free to cross application domain boundaries as the Chapter 1 - domain The Philosophy of lifetime. .NET thread 2scheduler and CLR see fit. Chapter - Building C#the Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Although active threads can be moved between application boundaries, a given thread can only execute - C# Language Fundamentals within a single application domain at any point in time (in other words, it is impossible for a single thread to Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# be doing work in more than one AppDomain). If you wish to gain access to the AppDomain that is currently Chapter Exceptions and Objthe ectstatic Lifetim e hosting5the- Thread type, call Thread.GetDomain method: Chapter 3

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

// Thread.GetDomain() returns an AppDomain type. Chapter 8 - Advanced C# Type Const ruction Techniques Console.WriteLine(Thread.GetDomain().FriendlyName); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter - Pr ocesses, AppDomains, exts, and Threads A single10thread may also be moved Cont into a particular context at any given time, and may be relocated within Chapter a new context 11 - Type at the Reflection, whim ofLate theBinding, CLR. If you and wish Attr ibuteto programmatically Based Pr ogramm ing discover the current context a Pa thread r t Fourhappens - Le ve r a ging to bethe executing .NET Libr in,a rmake ie s

use of the static Thread.CurrentContext property:

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet returns ter Win dow a( Int roducin g Window // CurrentContext Context type.s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Console.WriteLine(Thread.CurrentContext.ContextID); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

As you 17 would guess, thewCLR is the entity that is in charge of moving threads into (and out of) application Chapter - Data Access ith ADO.NET domains As aand .NET developer, Pa r t Fi ve - and W e bcontexts. Appl ica ti ons X ML W e b Se r viyou ces are

able to remain blissfully unaware where a given thread ends up (or exactly when it is placed into its new boundary). Nevertheless, you should be aware of Chapter 18 - ASP.NET Web Pages and Web Contr ols the underlying model. Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

The Problem of Concurrency and Thread Synchronization

I ndex

List of Figur es

One of the many joys (read: painful aspects) of multithreaded programming is that you have little control over how the underlying operating system makes use of its threads. For example, if you craft a block of code that creates a new thread of execution, you cannot guarantee that the thread executes immediately. Rather, such code only instructs the OS to execute the thread as soon as possible (which is typically when the thread scheduler gets around to it).

List of Tables

Furthermore, given that threads can be moved between application and contextual boundaries as required by the CLR, you must be mindful of which aspects of your application are thread-volatile and which operations are atomic. (Thread-volatile operations are the dangerous ones! ) For example, assume a given thread is accessing a shared point of data (or type member), and begins to modify its contents. Now assume that this thread is instructed to suspend its activity (by the thread scheduler) to allow another thread to access the same point of data. If the original thread was not completely finished with its current modification of the type, the second incoming thread may be viewing a partially modified object. At this point, the second thread is basically reading bogus values, which is sure to give way to extremely odd (and very hard to find) bugs (which are even harder to replicate and thus debug).

Atomic operations, on the other hand, are always safe in a multithreaded environment, and yet there are C# an d th e .N ET Plat f orm , Se con d Ed it ion very few operations in .NET that are guaranteed to be atomic. Even a simple assignment statement to a ISBN:1590590554 by Andr ew Tr oelsen double is not atomic! Unless the .NET Framework documentation specifically says an operation is atomic, Apr ess © 2003 (1200 pages) you must assume it is thread-volatile and take precautions. This compr ehensiv e text star ts w ith a brief ov er view of the C# be language and multithreaded then quickly m application oves to key domains technical are and in themselves quite volatile, as Given this, it should clear that ar chitectur al issues for .NET developer s. numerous threads can operate on the shared functionality at (more or less) the same time. To protect an application's resources from possible corruption, the .NET developer must make use of any number of threading primitives such as locks, monitors, and the [synchronization] attribute, to control access among Ta ble o f Con t en t s the executing threads. C# and t he .NET Plat for m, Second Edition

I ntr oductionthe .NET platform cannot make the difficulties of building robust multi-threaded applications Although Pa r t One - I ntdisappear, r oduci ng C#the a nd the .NET P la tf or msimplified completely process has been

considerably. Using types defined within the

Chapter 1 - The Philosophy of .NET System.Threading namespace, you are able to spawn additional threads with minimal fuss and bother. Chapter 2 Building C# Applications Likewise, when it is time to lock down shared points of data, you will find additional types that provide the Pa r t Tw functionality o - The C# Pras ogrthe am m ingWin32 La nguathreading ge same raw

primitives (using a much cleaner object model).

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# anProgramming d th e .N ET Plat f orm ,via Se con d Ed it ion Multithreaded Delegates ISBN:1590590554

by Andr ew Tr oelsen

Before checking out the©details of programming with threads under the .NET platform, it is worth Apr ess 2003 (1200 pages) reiterating that the whole point of creating additional to increase This compr ehensiv e text star ts w ith athreads brief ov is er view of the the overall functionality of a given application C# to the user. Recall, however, that many common programming tasks that traditionally language and then quickly m oves to key technical and chitectur issues for .NET developer s. required manual ar creation ofalthreads (e.g., remote method invocations, manipulating IO streams, and so forth) are automated using asynchronous delegates (first examined in Chapter 7). TaAs bleyou o f Con have t en seen t s throughout various points in this text (and will see in future chapters), when you invoke a

delegate the CLR automatically creates a worker thread to handle the task at hand. C# and t heasynchronously, .NET Plat for m, Second Edition However, I ntr oductionif you have an application-specific task to account for (such as printing a lengthy document or working GUIng display), required Pa r t One -with I nt ra oduci C# a nd you the will .NETbe P la tf or m

to manually manipulate threads if you wish to keep your

primary1 thread This disclaimer aside, allow me to formally introduce the System.Threading Chapter - Theresponsive. Philosophy of .NET namespace. Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion The System.Threading Namespace by Andr ew Tr oelsen

ISBN:1590590554

Under the .NET platform, the System.Threading namespace provides a number of types that enable Apr ess © 2003 (1200 pages) multithreaded programming. In addition to providing that represent This compr ehensiv e text star ts w ith atypes brief ov er view of the a specific CLR thread, this namespace also C# defines types that can manage a collection of threads language and then quickly m oves to key technical and(ThreadPool), a simple (non-GUI ar chitectur al issues for used .NET to developer based) Timer class, and various types provides.synchronized access to shared resources. Table 10-6 lists some (but not all) of the core members of this namespace. TaTable ble o f 10-6: Con t en ts Select Types of the System.Threading Namespace C# and t he .NET Plat for m, Second Edition I ntrSystem.Threading oduction Pa rType t One

Meaning in Life

- I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET Interlocked Provides atomic operations for objects that are shared by multiple - Building C# Applications threads.

Chapter 2

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Monitor Provides the synchronization of threading objects using locks and Chapter 3 - C# Language Fundamentals Chapter 4 Chapter Mutex5

wait/signals. - Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 6

- Exceptions and Obj ect Lifetim e Synchronization primitive that can be used for interprocess - I nter faces and Collections synchronization.

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 9

- Under standing .NET Assem blies

Thread Represents a thread that executes within the CLR. Using this type, Chapter 8 - Advanced C# Type Const ruction Techniques you are able to spawn additional threads in the originating Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s AppDomain. Chapter 10 - Pr ocesses, AppDomains, Cont manages exts, and Threads ThreadPool This type related threads in a given process. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Timer

Provides a mechanism for executing a method at specified intervals.

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization Delegate and the .NET ThreadStart thatRemoting specifies Lay theermethod to call for a given Thread. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

ThreadState

This enum specifies the valid states a thread may take (Running, Aborted, etc.).

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

TimerCallback Chapter 16 - The Sy stem .I O NamDelegate espace type used in conjunction with Timer types. Chapter 17 - Data Access w ith ADO.NET

ThreadPriority

This enum specifies the valid levels of thread priority.

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Examining the Thread Class

Chapter 20 - XML Web Ser vices I ndex

The most primitive of all types in the System.Threading namespace is Thread. This class represents an object-oriented wrapper around a given path of execution within a particular AppDomain. This type also List of Tables defines a number of methods (both static and shared) that allow you to create new threads from the scope of the current thread, as well as suspend, stop, and destroy a particular thread. Consider the list of core static members given in Table 10-7. List of Figur es

Table 10-7: Key Static Members of the Thread Type

Thread Static C# an d th eMeaning .N ET Plat fin ormLife , Se con d Ed it ion Member by Andr ew Tr oelsen CurrentContext CurrentThread Ta ble o f Con t en t s GetDomain()

ISBN:1590590554

Apr ess © 2003 (1200 pages)

This (read-only) property returns the context the thread is currently

This compr ehensiv e text star ts w ith a brief ov er view of the running. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

This (read-only) property returns a reference to the currently running thread. Returns a reference to the current AppDomain (or the ID of this

C# GetDomainID() and t he .NET Plat for m, Second domain) Edition in which the current thread is running. I ntr oduction

current Pa rSleep() t One - I nt r oduci ng C# a ndSuspends the .NET Pthe la tf or m

thread for a specified time.

Chapter 1

- The Philosophy of .NET Thread2also supports object level members shown in Table 10-8. Chapter - Building C#the Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Table 10-8: Select Instance Level Members of the Thread Type Chapter 3 - C# Language Fundamentals Chapter 4 - Instance Obj ect -Or iented Pr ogr am ming w ithin C# Life Thread Meaning Chapter 5 Member - Exceptions and Obj ect Lifetim e Level Chapter 6

- I nter faces and Collections Abort() This method instructs the CLR to terminate the thread ASAP. Chapter 7 - Callback I nter faces, Delegates, and Ev ents Chapter IsAlive8

- Advanced C# Type Const ruction Techniques This property returns a Boolean that indicates if this thread has

Pa r t Thre e - Pr ogr am m i ng w i th .N ETbeen Assem bl ie s started.

Chapter 9

- Under standing .NET Assem blies IsBackground Gets orexts, sets and a value indicating whether or not this thread is a Chapter 10 - Pr ocesses, AppDomains, Cont Threads

background thread.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa rName t Four - Le ve r a ging the .NET LibrThis a r ie sproperty

allows you to establish a friendly textual name of the

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er thread. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Priority

Gets or Sets the priority of a thread, which may be assigned a value from the ThreadPriority enumeration.

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter ThreadState 16 - The Sy stem .I O Nam espace Gets the state of this thread, which may be assigned a value from

the ThreadState enumeration. Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Interrupt()

Interrupts the current thread.

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Join()19 - ASP.NET Web Applicat ions Instructs a thread to wait for another thread to complete. Chapter Chapter 20 - XML Web Ser vices

Resume()

I ndex

Resumes a thread that has been previously suspended.

ListStart() of Figur es

Instructs the CLR to execute the thread ASAP.

List of Tables

Suspends the thread. If the thread is already suspended, a call to Suspend() has no effect.

Suspend()

Gathering Basic Thread Statistics Recall that the entry point of an executable assembly (i.e., the Main() method) runs on the primary thread of execution. To illustrate the basic use of the Thread type, assume you have a new console application named ThreadStats. The static Thread.CurrentThread property retrieves a Thread type that represents the currently executing thread. Thus, if you trigger this member within the scope of Main(), you are able to print out various statistics about the primary thread: using System.Threading; ... static void Main(string[] args)

{ C# an dinfo th e .Nabout ET Plat the f orm ,current Se con d Edthread. it ion // Get some ISBN:1590590554 by Andr ew Tr oelsen Thread primaryThread = Thread.CurrentThread; Apr ess © 2003 (1200 pages) // Get name of current AppDomain and context ID. This compr ehensiv e text star ts w ith aThread brief ov erstats view of the Console.WriteLine("***** Primary *****"); C# language and then quickly m oves to key technical Console.WriteLine("Name of current AppDomain:and {0}", ar chitectur al issues for .NET developer s. Thread.GetDomain().FriendlyName); Console.WriteLine("ID of current Context: {0}", Thread.CurrentContext.ContextID); Ta ble o f Con t en t s Console.WriteLine("Thread Name: {0}", primaryThread.Name); C# and t he .NET Plat for m, Second Edition Console.WriteLine("Apt state: {0}", primaryThread.ApartmentState); I ntr oduction Console.WriteLine("Alive: {0}", primaryThread.IsAlive); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Console.WriteLine("Priority Level: {0}", primaryThread.Priority); Chapter 1 - The Philosophy of .NET Console.WriteLine("Thread State: {0}", primaryThread.ThreadState); Chapter 2 - Building C# Applications Console.WriteLine(); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge } Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Naming Threads - I nter faces and Collections

Chapter 6 Chapter 7

Callback I nter faces, Delegates, and Ev ents When you-run this application, notice how the name of the default thread is currently an empty string. Chapter 8 - Advanced C# Type Constaruction Techniques string to a thread using the Name property. Thus, if Under .NET, it is possible to assign human-readable Pa r t Thre - Pr am m w i th .N ET Assemidentify bl ie s the primary thread via the moniker "ThePrimaryThread," you wishe to beogr able toi ng programmatically Chapter 9 -write Under .NET Assem blies you could thestanding following: Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

// Name the thread. primaryThread.Name = "ThePrimaryThread"; Chapter 12 - Obj ect Ser ialization and the .NETis Remoting Lay er{0}", primaryThread.Name); Console.WriteLine("This thread called: Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

.NET Threads and Legacy COM Apartments

Chapter 16 - The Sy stem .I O Nam espace

Chapter 17 - that Dataevery Access w ith ADO.NET Also notice Thread type has a property named ApartmentState. Those of you who come from a Pa r t Fi ve - W e b ica tiCOM ons and X ML W e b Se ces background inAppl classic may already ber viaware

of apartment boundaries. In a nutshell, COM

Chapter 18 - ASP.NET Web andused Web to Contr ols COM objects with similar threading needs. Under the apartments were a unit of Pages isolation group Chapter 19 - ASP.NET Webapartments Applicat ionsare no longer used by managed objects. If you happen to be making .NET platform however, Chapter 20 - XML Webfrom Ser vices use of COM objects managed code (via the interoperability layer), you are able to establish the I ndex apartment settings that should be simulated to handle the coclass in question. To do so, the .NET base List class of Figur libraries es provide two attributes to mimic the single-threaded apartment (STAThreadAttribute, which is

added by default to your application's Main() method when using the VS .NET IDE) and multithreadedList of Tables apartment (MTAThreadAttribute) of classic COM. In fact, when you create a new *.exe .NET application type, the primary thread is automatically established to function as an STA: // This attribute controls how the primary thread should // handle COM types. [STAThread] static void Main(string[] args) { // COM objects will be placed into an STA. }

If you wish to specify support for the MTA, simply adjust the attribute:

[MTAThread] static void { // COM }

C# an d th e .N ET Plat f orm , Se con d Ed it ion Main(string[] args) ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) objects will be placed into the MTA. This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Of course, if you don't know (or care) about classic COM objects, you can simply leave the [STAThread] attribute on your Main() method. Doing so will keep any COM types thread-safe without further work on Ta ble o f Con t en t s your part. If you don't make use of COM types within the Main() method, the [STAThread] attribute does C# and t he .NET Plat for m, Second Edition nothing. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Setting- The a Thread's Level Philosophy of Priority .NET

Chapter 1 Chapter 2

- Building C# Applications

As mentioned, we programmers have little control over when the thread scheduler switches between threads. We can, however, mark a given thread with a priority level to offer a hint to the CLR regarding the Chapter 3 - C# Language Fundamentals importance of the thread's activity. By default, all threads have a priority level of normal. However this can Chapter 4 - Obj ect -Or iented Pr ogr am minglifetime w ith C#using the ThreadPriority property and the related be changed at any point in the thread's Chapter 5 Exceptions and Obj ect Lifetim e ThreadPriority enumeration: Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents public enum System.Threading.ThreadPriority Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t ThreAboveNormal, e - Pr ogr am m i ng w i th .N ET Assem bl ie s BelowNormal, Chapter Highest, 9 - Under standing .NET Assem blies Lowest, Chapter Normal, 10 - Pr ocesses, Cont exts, and Threads // AppDomains, Default value. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing } Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Always13 keep in minda that a thread with valueg of ThreadPriority.Highest is not necessarily guaranteed to Chapter - Building Bet ter Win dow ( Intthe roducin Window s For ms) given the precedence. Again,orifk the scheduler is preoccupied with a given task (e.g., Chapter 14 highest - A Better Paint ing Fr amew ( GDIthread +)

synchronizing an am object, threads, threads, or whatnot) the priority level will most likely be Chapter 15 - Pr ogr ming switching with Windows Formmoving s Contr ols altered accordingly. However, all things being equal, the CLR will read these values and instruct the thread scheduler how to best allocate time slices. All things still being equal, threads with an identical Chapter 17 - Data Access w ith ADO.NET thread priority should each receive the same amount of time to perform their work. Chapter 16 - The Sy stem .I O Nam espace

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 Again, - ASP.NET Pages and Web Contr Note you Web will seldom (if ever) needols to directly alter a thread's priority level. In theory, it is Chapter 19 possible - ASP.NET ions to Web jack Applicat up the priority level on a set of threads, thereby preventing lower priority threads Chapter 20 from - XMLexecuting Web Ser vices at their required levels (so use caution). I ndex List of Figur es List of Tables

C# an d th e .N ETThreads Plat f orm , Se con d Ed it ion Spawning Secondary ISBN:1590590554

by Andr ew Tr oelsen

When you wish toApr create threads to carry on some unit of work, you need to interact with the ess © additional 2003 (1200 pages) Thread class as well as a special threading-related named The general process is This compr ehensiv e text star ts w ith adelegate brief ov er view ofThreadStart. the quite simple. FirstC#and foremost, you need to create a function (static or instance-level) to perform the language and then quickly m oves to key technical and ar chitectur al issues for the .NET developer s. additional work. For example, assume current SimpleThreadApp project defines the following additional static method, which mimics the work seen in Main(): Ta ble o f Con t en t s

static void MyThreadProc() { I ntr oduction Console.WriteLine("***** Secondary Thread stats *****"); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Thread.CurrentThread.Name = "TheSecondaryThread"; Chapter Thread 1 - The Philosophy of .NET secondaryThread = Thread.CurrentThread; Chapter Console.WriteLine("Name? 2 - Building C# Applications {0}", secondaryThread.Name); Pa r t Tw oConsole.WriteLine("Apt - The C# Pr ogr am m ing La ngua ge state? {0}", secondaryThread.ApartmentState); Chapter Console.WriteLine("Alive? 3 - C# Language Fundamentals {0}", secondaryThread.IsAlive); Chapter Console.WriteLine("Priority? 4 - Obj ect -Or iented Pr ogr am ming w ith C# {0}", secondaryThread.Priority); Chapter Console.WriteLine("State? 5 - Exceptions and Obj ect Lifetim e {0}", secondaryThread.ThreadState); Chapter Console.WriteLine(); 6 - I nter faces and Collections } Chapter 7 - Callback I nter faces, Delegates, and Ev ents C# and t he .NET Plat for m, Second Edition

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Note The target for the ThreadStart delegate cannot take any arguments and must return void.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Attr ibuteBaseda Pr ogramm ing Now, within Main(), create aLate newBinding, Thread and class and specify new ThreadStart delegate as a constructor Pa r t Four - Le(note ve r a ging the .NET Libr a r ie s parameter the lack of parentheses

in the constructor when you give the method name). To inform

Chapter 12that - Obj ectnew Ser ialization theto.NET Lay er method (but always remember that Start() the CLR this thread is and ready run,Remoting call the Start() Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms) doesn't actually start the thread). Starting a thread is a nondeterministic operation under the total control of Chapter 14 you - A Better Paint ing Fr amew or k (the GDICLR + ) to execute your thread. It will do so on its own time and the CLRcan't do anything to force Chapter on its own 15 -terms: Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET [STAThread] Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces static void Main(string[] args)

Chapter 18 - ASP.NET Web Pages and Web Contr ols { Chapter ... 19 - ASP.NET Web Applicat ions

a Ser secondary thread. Chapter // 20 - Start XML Web vices I ndex

Thread secondaryThread = new Thread(new ThreadStart(MyThreadProc));

secondaryThread.Start(); List of Figur es } of Tables List The output is seen in Figure 10-11.

Figure 10-11: Your first multithreaded application

C# an d th e .N ET Plat f orm , Se con d Ed it ion

One question that may be on your mind is exactly when a thread terminates. By default, a thread ISBN:1590590554 by Andr ew Tr oelsen terminates as soon as the function used to create it in the ThreadStart delegate has exited. Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the

language andand then quickly m oves to key technical and ForegroundC#Threads Background Threads ar chitectur al issues for .NET developer s.

The CLR assigns a given thread to one of two broad categories: Foreground Ta ble o f Con t en t s threads: Foreground threads have the ability to prevent the current application from terminating. The will not shut down an application (which is to say, unload the hosting C# and t he .NET Plat for CLR m, Second Edition AppDomain) until all foreground threads have ended. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Background threads: Background threads (sometimes called daemon threads) are viewed by the CLR - The Philosophy of .NET as expendable paths of execution, which can be ignored at any point in time (even if it is currently Chapter 2 - Building C# Applications laboring over some unit of work). Thus, if all foreground threads have terminated, any and all Pa r t Tw o - The C# Pr ogr am m ing La ngua ge background threads are automatically killed. Chapter 1

Chapter 3

- C# Language Fundamentals

Chapter 4 - Objtoect -Or iented Pr ogr am ming ith C# It is important note that foreground andwbackground threads are not synonymous with primary and Chapter worker 5threads. - Exceptions By default, and Obj every ect thread Lifetim eyou create via the Thread.Start() method is automatically a

foreground Again, means that the AppDomain will not unload until all threads of execution Chapter 6 - thread. I nter faces and this Collections have completed theirI nter units of work. In mostand cases, this is exactly the behavior you require. Chapter 7 - Callback faces, Delegates, Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

For the sake of argument, however, assume that you wish to spawn a secondary thread that should behave as a background thread. Again, this means that the method pointed to by the Thread type (via the Chapter 9 - Under standing .NET Assem blies ThreadStart delegate) should be able to halt safely as soon as all foreground threads are done with their Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads work. Configuring such a thread is as simple as setting the IsBackground property to true: Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

// Start a new background thread. Thread secondaryThread = new Thread(new ThreadStart(MyThreadProc)); Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) secondaryThread.Priority = ThreadPriority.Highest; Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) secondaryThread.IsBackground = true; Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve W e b Appl icadistinction, ti ons and Xassume ML W e b Se r vithe ces MyThreadProc() Now, to -illustrate the that

method has been updated to print out

Chapter 1000 lines 18 -toASP.NET the console, Web Pages pausing andfor Web 5 milliseconds Contr ols between iterations using the Thread.Sleep() method

(more on Thread.Sleep() method Chapter 19 the - ASP.NET Web Applicat ions later in this chapter): Chapter 20 - XML Web Ser vices I ndex static void MyThreadProc() List { of Figur es

... List of Tables for(int i = 0; i < 1000; i ++) { Console.WriteLine("Value of i is: {0}", i); Thread.Sleep(5); } }

If you run the application again, you will find that the for loop is only able to print out a tiny fraction of the values, given that the secondary Thread object has been configured as a background thread. Given that the Main() method has spawned a primary foreground thread, as soon as the secondary thread has been started, it is ready for termination. Now, you are most likely to simply allow all threads used by a given application to remain configured as foreground threads. If this is the case, all threads must finish their work before the AppDomain is unloaded from the hosting process. Nevertheless, marking a thread as a background type can be helpful when the

worker-thread in question is performing noncritical tasks or helper tasks that are no longer needed when C# an d th e .N ET Plat f orm , Se con d Ed it ion the main task of the program is over. by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

The VS .NET Threads Window This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

To wrap up our initial investigation threads, it is worth ar chitectur al issuesoffor .NET developer s. pointing out that the Visual Studio .NET IDE provides a Threads window, which can be accessed from the Debug | Windows menu item during a debugging session. As you can see from Figure 10-12, this window allows you to view the set of currently Taexecuting ble o f Conthreads t en t s in your .NET assembly. C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals Figure The VS .NET Threads Chapter 4 - 10-12: Obj ect -Or iented Pr ogr am ming wwindow ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6 - I nter facesThe andThreadStats Collections project is included under the Chapter 10 subdirectory. SOURCE Chapter 7 Callback I nter faces, Delegates, and Ev ents CODE Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th eThreading .N ET Plat f orm ,Example Se con d Ed it ion A More Elaborate by Andr ew Tr oelsen

ISBN:1590590554

Now that you have of creating a new thread of execution, we can turn to a more Aprseen ess ©the 2003basic (1200 process pages) illustrative example. Create a new console application named Next, define a This compr ehensiv e text star ts w ith a brief ov erSimpleMultiThreadApp. view of the helper class that C# supports a public method named DoSomeWork(): language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

internal class WorkerClass { Ta ble o f Con t en t s public void DoSomeWork() C# and t he .NET Plat for m, Second Edition { I ntr oduction // Get hash code for this worker thread. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Console.WriteLine("ID of worker thread is: {0} ", Chapter 1 - The Philosophy of .NET Thread.CurrentThread.GetHashCode()); Chapter 2 - Building C# Applications // Do the work. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Console.Write("Worker says: "); Chapter 3 - C#for(int Language i Fundamentals = 0; i < 10; i++) Chapter 4 - Obj {ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e Console.WriteLine(i + ", "); Chapter 6 - I nter } faces and Collections Chapter 7 - Callback Console.WriteLine(); I nter faces, Delegates, and Ev ents } Chapter 8 - Advanced C# Type Const ruction Techniques }r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Pa Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Now assume the Main() method creates a new instance of WorkerClass. For the primary thread to continue processing its workflow, create and start a new Thread that is configured to execute the Pa r t Four - Le ve r a ging the .NET Libr a r ie s DoSomeWork() method of the WorkerClass type: Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

public class MainClass { Chapter 15 - Pr ogr am ming with Windows Form s Contr ols public static int Main(string[] args) Chapter 16 - The Sy stem .I O Nam espace { Chapter 17 - Data Access w ith ADO.NET // Get hash code of the current thread. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Console.WriteLine("ID of primary thread is: {0} ", Chapter 18 - ASP.NET Web Pages and Web Contr ols Thread.CurrentThread.GetHashCode()); Chapter 19 - ASP.NET Web worker Applicat ions // Make class. Chapter 20 - XML Web Ser vices WorkerClass w = new WorkerClass(); I ndex // Now make (and start) the worker thread. List of Figur es Thread workerThread = List of Tables new Thread(new ThreadStart(w.DoSomeWork)); workerThread.Start(); return 0; } } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

If you run the application you would find each thread has a unique hash code (which is a good thing, as you should have two separate threads at this point).

Clogging Up the Primary Thread Currently, our application creates a secondary thread to perform a unit of work (in this case, printing 10 numbers). The problem is the fact that printing 10 numbers takes no time at all, and therefore we are not really able to appreciate the fact that the primary thread is free to continue processing. Let's update the

application to illustrate this very fact. First, let's tweak the WorkerClass to print out 30,000 numbers, to C# an d th e .N ET Plat f orm , Se con d Ed it ion account for a more labor-intensive process: by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

internal class WorkerClass This compr ehensiv e text star ts w ith a brief ov er view of the { C# language and then quickly m oves to key technical and public void DoSomeWork() ar chitectur al issues for .NET developer s. { ... Ta ble o f Con t en// t s Do a lot of work. Console.Write("Worker says: "); C# and t he .NET Plat for m, Second Edition for(int i = 0; i < 30000; i++) I ntr oduction { Console.WriteLine(i + ", "); } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Console.WriteLine(); Chapter 1 - The Philosophy of .NET Chapter } 2 - Building C# Applications }r t Tw o - The C# Pr ogr am m ing La ngua ge Pa Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# Next, update the MainClass such that it launches a Windows Forms message box directly after it creates

Chapter 5 - thread Exceptions and Obj ect Lifetim e the worker (don't forget to set a reference to System.Windows.Forms.dll): Chapter 6 - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

public class MainClass Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s public static int Main(string[] args) Chapter { 9 - Under standing .NET Assem blies Chapter 10 - Pr // ocesses, AppDomains, exts, and Create workerCont thread asThreads before. Chapter 11 Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing ... Pa r t Four - Le ve// r a ging .NET Libr a r ie s Nowthewhile worker thread is busy, Chapter 12 - Obj ect Ser ialization and the .NET Remoting er // do some additional work onLay primary thread. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) MessageBox.Show("I'm buzy"); Chapter 14 - A return Better Paint 0; ing Fr amew or k ( GDI + ) Chapter } 15 - Pr ogr am ming with Windows Form s Contr ols } Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

If you were to now run the application, you would see that the message box is displayed and can be moved around the desktop while the worker thread is busy pumping numbers to the console (Figure 10Chapter 19 - ASP.NET Web Applicat ions 13). Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 10-13: Two threads each performing a unit of work Now, contrast this behavior with what you might find if you had a single-threaded application. Assume the Main() method has been updated with logic that allows the user to enter the number of threads used within the current AppDomain (one or two): public static int Main(string[] args) {

Console.Write("Do you want [1] or [2] threads? "); C# an d th e .N ET= Plat f orm , Se con d Ed it ion string threadCount Console.ReadLine(); ...

ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) // Make worker class. This compr e text star ts w ith a brief ov er view of the WorkerClass w =ehensiv new WorkerClass(); C# language and then quickly oves user to key said technical and // Only make a new thread if mthe so. ar chitectur al issues for .NET developer s.

if(threadCount == "2") { // Now make the thread. Ta ble o f Con t en t s Thread workerThread = C# and t he .NET Plat for m, Second Edition new Thread(new ThreadStart(w.DoSomeWork)); I ntr oduction workerThread.Start(); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m } Chapter 1 - The Philosophy of .NET else // Execute this method on the single thread. Chapter 2 - Building C# Applications w.DoSomeWork(); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge // Do some additional work. Chapter MessageBox.Show("I'm 3 - C# Language Fundamentals buzy"); Chapter return 4 - Obj ect -Or iented Pr ogr am ming w ith C# 0; Chapter 5 - Exceptions and Obj ect Lifetim e } Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

As you 8can- guess, if the the value "1" he or she must wait for all 30,000 numbers to be printed Chapter Advanced C# user Typeenters Const ruction Techniques before seeing the message box appear, given Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s that there is only a single thread in the AppDomain. However, user enters.NET "2" he or she Chapter 9 if - the Under standing Assem bliesis able to interact with the message box while the secondary thread spins right along. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Putting a Thread to Sleep

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

The static method can used gtoWindow currently suspend the current thread for a specified Chapter 13 -Thread.Sleep() Building a Bet ter Win dow ( Intbe roducin s For ms)

amount14of -time (specified in milliseconds). In+particular, you can use this to pause a program. To illustrate, Chapter A Better Paint ing Fr amew or k ( GDI ) let's update the WorkerClass again. This time around, the DoSomeWork() method does not print out 30,000 lines to the console, but 10 lines. The trick is, between each call to Console.WriteLine(), this Chapter 16 - The Sy stem .I O Nam espace worker thread is put to sleep for approximately 2 seconds. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

internal class WorkerClass Chapter 18 - ASP.NET Web Pages and Web Contr ols {

Chapter 19 - ASP.NET Web Applicat ions

public void DoSomeWork() { I ndex // Get some information about the worker thread. List of Figur es Console.WriteLine("ID of worker thread is: { 0} ", List of Tables Thread.CurrentThread.GetHashCode()); // Do the work (and take a nap). Console.Write("Worker says: "); for(int i = 0; i < 10; i++) { Console.WriteLine(i + ", "); Thread.Sleep(2000); } Console.WriteLine(); } } Chapter 20 - XML Web Ser vices

Now run your application a few times and specify both threading options. You will find radically different behaviors based on your choice of thread number.

SOURCE CODE

C# an d th e .N ET Plat f orm , Se con d Ed itision The SimpleMultiThreadApp project included under the Chapter 10 subdirectory. ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Concurrency Revisited ISBN:1590590554

by Andr ew Tr oelsen

Given this previous Aprexample, ess © 2003 you (1200might pages)be thinking that threads are the magic bullet you have been looking for. Simply create threads for each part application the result will be increased This compr ehensiv e text star ts wof ithyour a brief ov er view and of the application performance to the user. You already know this is a loaded C# language and then quickly m oves to key technical andquestion, as the previous statement chitectur issues for .NETand developer s. is not necessarilyartrue. If notalused carefully thoughtfully, multithreaded programs are slower than single threaded programs. TaEven ble o fmore Con timportant en t s is the fact that each and every thread in a given AppDomain has direct access to the

shared data of the application. the current example, this is not a problem. However, imagine what might C# and t he .NET Plat for m, SecondInEdition happen if the primary and secondary threads were both modifying a shared point of data. As you know, the I ntr oduction thread force threads to Psuspend Pa r t One scheduler - I nt r oduciwill ng C# a nd the .NET la tf or m

their work at random. Since this is the case, what if thread

A is kicked the way before Chapter 1 - out Theof Philosophy of .NETit has fully completed its work? Again, thread B is now reading unstable data. 2 Chapter

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

To illustrate, let's build another C# console application named MultiThreadSharedData. This application - C# Language Fundamentals also has a class named WorkerClass, which maintains a private System.Int32 that is manipulated by the Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# DoSomeWork() helper function. Also notice that this helper function also leverages a for loop to printout Chapter 5 of - Exceptions Obj ect Lifetim e the value this privateand integer, the iterator's value as well as the name of the current thread. Finally, to Chapter 6 I nter faces and Collections simulate additional work, each iteration of this logic places the current thread to sleep for approximately Chapter 7 - Callback ntertype faces, one second. Here is Ithe in Delegates, question: and Ev ents Chapter 3

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

internal class WorkerClass

Chapter 9 {

- Under standing .NET Assem blies

Chapter private 10 - Pr ocesses, int AppDomains, theInt; Cont exts, and Threads Chapter public 11 - Type void Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing DoSomeWork() Pa r t Four{ - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er theInt++; Chapter 13 - Building a Bet i ter =Win dow Int 5; roducin g Window s For ms) for(int 0; i (< i++) Chapter 14 - A { Better Paint ing Fr amew or k ( GDI + )

Console.WriteLine("theInt: {0}, i: {1}, current thread: {2}", Chapter 15 - Pr ogr am ming with Windows Form s Contr ols theInt, Chapter 16 - The Sy stem .I O Nam espace i, Thread.CurrentThread.Name); Thread.Sleep(1000); Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b }Appl ica ti ons and X ML W e b Se r vi ces

Chapter } 18 - ASP.NET Web Pages and Web Contr ols

} Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex

The Main() method is responsible for creating three uniquely named secondary threads of execution, each

List of Figurises of which making calls to the same instance of the WorkerClass type: List of Tables

public class MainClass { public static int Main(string[] args) { // Make the single worker object. WorkerClass w = new WorkerClass(); // Create and name three secondary threads, // each of which makes calls to the same shared object. Thread workerThreadA = new Thread(new ThreadStart(w.DoSomeWork)); workerThreadA.Name = "A"; Thread workerThreadB = new Thread(new ThreadStart(w.DoSomeWork)); workerThreadB.Name = "B"; Thread workerThreadC =

new Thread(new ThreadStart(w.DoSomeWork)); C# an d th e .N ET Plat f orm , Se con d Ed it ion workerThreadC.Name = "C"; ISBN:1590590554 by Andr ew Tr oelsen // Now start each one. Apr ess © 2003 (1200 pages) workerThreadA.Start(); This compr ehensiv e text star ts w ith a brief ov er view of the workerThreadB.Start(); C# language and then quickly m oves to key technical and workerThreadC.Start(); ar chitectur al issues for .NET developer s. return 0; } } Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt ryou oduci ng some C# a nd theruns, .NETlet's P la tfrecap or m the Now before see test

problem. The primary thread within this AppDomain

Chapter The Philosophy of .NET begins 1life-by spawning three secondary worker threads. Each worker thread is told to make calls on the Chapter 2 Building C# Applications DoSomeWork() method of a single WorkerClass instance. Given that we have taken no precautions to Pa r t Tw o - The Pr ogr am m ing resources, La ngua ge lock down theC# object's shared

there is a good chance that a given thread will be kicked out of

Chapter - C# the Language Fundamentals the way3 before WorkerClass is able to print out the results for the previous thread. Because we don't Chapter 4 - Obj ect -Or ogr am happen, ming w ithwe C#are bound to get unpredictable results. For example, you know exactly when (oriented if) thisPrmight Chapter might find 5 -the Exceptions output shown and Obj in ect Figure Lifetim 10-14. e Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - 10-14: ASP.NET Web Applicat ions Figure Possible output of the MultiThreadSharedData application Chapter 20 - XML Web Ser vices I ndex Now run the application a few more times. Figure 10-15 shows another possibility (note the ordering

among thread List of Figur es names). List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Figure Another possible output of the MultiThreadSharedData application Chapter 3 - 10-15: C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Humm. There are clearly some problems here. As each thread is telling the WorkerClass to "do some - Exceptions and Obj ect Lifetim e work," the thread scheduler is happily swapping threads in the background. The result is inconsistent Chapter 6 - I nter faces and Collections output. What we need is a way to programmatically enforce synchronized access to the shared resources. Chapter 5 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter - Advanced C# System.Threading Type Const ruction Techniques As you 8would guess, the namespace provides a number of synchronization-centric Pa r t Thre e - Pr am m i ng w i thlanguage .N ET Assem bl ieprovides s types. The C#ogr programming also

a particular keyword for the very task of synchronizing

Chapter - Under standing .NET Assem blies shared9data in multithreaded applications. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d thUsing e .N ET Plat f orm , Se"lock" con d Ed it ion Synchronization the C# Keyword ISBN:1590590554

by Andr ew Tr oelsen

The first approach toess providing synchronized access to our DoSomeWork() method is to make use of the C# Apr © 2003 (1200 pages) "lock" keyword. This intrinsic keyword allows you to alock a block of code so that incoming threads must This compr ehensiv e text star ts w ith briefdown ov er view of the wait in line for theC# current thread to finish up its work completely. The "lock" keyword requires you to pass in a language and then quickly m oves to key technical and ar chitectur althat issues forbe .NET developer token (an object reference) must acquired by as. thread to enter within the scope of the lock statement. When you are attempting to lock down an instance level method, you can simply pass in a reference to the current type: Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

internal class WorkerClass { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m private int theInt; Chapter public 1 - The Philosophy of .NET void DoSomeWork() Chapter { 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge lock(this) Chapter 3 - C#{ Language Fundamentals Chapter 4 - Obj ect -OrtheInt++; iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect for(int i Lifetim = 0;e i < 5; i++) Chapter 6 - I nter faces{and Collections Console.WriteLine("theInt: {0}, i: {1}, current thread: {2}", Chapter 7 - Callback I nter faces, Delegates, and Ev ents theInt, i, Thread.CurrentThread.Name); Chapter 8 - Advanced C# Type Const ruction Techniques Thread.Sleep(1000); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s } Chapter 9 - Under standing .NET Assem blies // Lock tokenCont released here! Chapter 10 - Pr } ocesses, AppDomains, exts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing }r t Four - Le ve r a ging the .NET Libr a r ie s Pa I ntr oduction

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Now, once a thread enters into a locked block of code, the token (in this case, a reference to the current object)

Chapter 14 - A Better Paintthreads ing Fr amew k ( lock GDI +is ) released. Thus, if threadA has obtained the lock token, and is inaccessible by other untilorthe Chapter 15 Pr ogr am ming with Windows Form s Contr ols wait until threadA relinquishes the lock. threadB or threadC are attempting to enter, they must Chapter 16 - The Sy stem .I O Nam espace

Note attempting to lock down code in a static method, you obviously cannot use the "this" Chapter 17 If- you Dataare Access w ith ADO.NET keyword. If this the Xcase, can simply Pa r t Fi ve - W e b Appl ica ti onsis and ML Wyou e b Se r vi ces

pass in the System.Type of the current class using the C#

operator (although anyContr object Chapter 18 "typeof" - ASP.NET Web Pages and Web olsreference will work). Chapter 19 - ASP.NET Web Applicat ions

If you now rerun the application, you can see that the threads are instructed to politely wait in line for the current thread to finish its business (Figure 10-16).

Chapter 20 - XML Web Ser vices I ndex

List of Figur es List of Tables

Figure 10-16: Consistent output of the MultiThreadSharedData application

SOURCE CODE

C# an d th e .N ET Plat f orm , Se con d Ed it ion

The MultiThreadSharedData application isISBN:1590590554 included under the Chapter 10 subdirectory.

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the

C# language and then quickly m oves to key technical and Synchronization Using the System.Threading.Monitor Type ar chitectur al issues for .NET developer s.

The C# lock statement is really just a shorthand notation for working with the System.Threading.Monitor class type. Under the hood, the previous locking logic (via the C# "lock" keyword) actually resolves to the following Ta(which ble o f Con en tverified s can tbe using ildasm.exe): C# and t he .NET Plat for m, Second Edition I ntr oduction

internal class WorkerClass { Chapter private 1 - The Philosophy of .NET int theInt; Chapter public 2 - Building C# Applications void DoSomeWork() Pa r t Tw o{- The C# Pr ogr am m ing La ngua ge Chapter 3 - C#// Language Enter Fundamentals the monitor with token. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Monitor.Enter(this); Chapter 5 - Exceptions and Obj ect Lifetim e try Chapter 6 - I nter { faces and Collections Chapter 7 - Callback ItheInt++; nter faces, Delegates, and Ev ents for(int i =ruction 0; i Techniques < 5; i++) Chapter 8 - Advanced C# Type Const { Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Console.WriteLine("theInt: {0}, i: {1}, current thread: {2}", Chapter 9 - Under standing .NET Assem blies theInt, i, Thread.CurrentThread.Name); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Thread.Sleep(1000); Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging }the .NET Libr a r ie s } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er finally Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) { Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) // Error or not, you must exit the monitor Chapter 15 - Pr ogr am ming with Windows Form s Contr ols // and release the token. Chapter 16 - The Sy stem .I O Nam espace Monitor.Exit(this); Chapter 17 - Data } Access w ith ADO.NET Pa r t Fi ve}- W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 18 - ASP.NET Web Pages and Web Contr ols } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

If you run the modified application, you will see no changes in the output (which is good). Here, you make use o I ndex theofstatic and Exit() members of the Monitor type, to enter (and leave) a locked block of code. Now, List FigurEnter() es given that the "lock" keyword seems to require less code than making explicit use of the List of Tables

System.Threading.Monitor type, you may wonder about the benefits. The short answer is control. If you make use of the Monitor type, you are able to instruct the active thread to wait for some duration of time (via the Wait() method), inform waiting threads when the current thread is completed (via the Pulse() and PulseAll() methods), and so on. As you would expect, in a great number of cases, the C# "lock" keyword will fit the bill. If you are interested in checking out additional members of the Monitor class, consult online Help.

C# an d thUsing e .N ET Plat f orm , Se con d Ed it ion Synchronization the System.Threading.Interlocked Type ISBN:1590590554

by Andr ew Tr oelsen

Although it always isess hard to believe until you look at the underlying CLR code, assignments and simple Apr © 2003 (1200 pages) arithmetic operations are not atomic. For star thistsreason, the System.Threading namespace also provides a This compr ehensiv e text w ith a brief ov er view of the type that allows you to operate on a single point of data atomically. The Interlocked class type defines the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. static members shown in Table 10-9. Table 10-9: Members of the Interlocked Type Ta ble o f Con t en t s

of Plat thefor m, Second Edition C# Member and t he .NET

Meaning in Life

Type I ntrSystem.Threading.Interlocked oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Increment()

Chapter 1

- The Philosophy of .NET

Safely increments a value by one

Decrement() Chapter 2 - Building C# Applications

Safely decrements a value by one

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Safely swaps two values

Exchange()

Chapter 3

- C# Language Fundamentals

CompareExchange() Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Safely tests two values for equality, and if so, changes one of the values with a third

Chapter 6

- I nter faces and Collections Although notI nter seem like Delegates, it from the and onset, the process of atomically altering a single value is quite Chapter 7 it- might Callback faces, Ev ents

common multithreaded environment. rather than writing synchronization code such as the Chapter 8 in - a Advanced C# Type Const ructionThus, Techniques following: Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

int i10= - 9; Chapter Pr ocesses, AppDomains, Cont exts, and Threads lock(this) Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing {r t i++; Pa Four - } Le ve r a ging the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

you can simply write:

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

// Pass by reference the value you wish to alter. int i = 9; Chapter 17 - Data Access w ith ADO.NET Interlocked.Increment(ref i); Chapter 16 - The Sy stem .I O Nam espace

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 if- you ASP.NET Applicat Likewise, wish Web to assign theions value of a previously assigned System.Int32 to the value 83, you can Chapter 20 need - XMLtoWeb Ser viceslock statement (or Monitor logic) and make use of the Interlocked.Exchange() avoid the an explicit I ndex method: List of Figur es List of Tables int i = 9;

Interlocked.Exchange(ref i, 83);

Finally, if you wish to test two values for equality to change the point of comparison in a thread-safe manner, you would be able to leverage the Interlocked.CompareExchange() method as follows: // If the value of i is currently 83, change i to 99. Interlocked.CompareExchange(ref i, 99, 83);

C# an d thUsing e .N ET Plat f orm , Se con d Ed it ion Synchronization the [Synchronization] Attribute by Andr ew Tr oelsen

ISBN:1590590554

The final synchronization primitive here is the [Synchronized] attribute, which, as you recall, is a Apr ess © 2003 (1200 examined pages) contextual attribute that can be applied to context-bound When This compr ehensiv e text star ts w ith a briefobjects. ov er view of theyou apply this attribute on a .NET class type, you are effectively locking down all members of the object for thread safety: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

using System.Runtime.Remoting.Contexts; ... Ta ble o f Con t en t s // This context-bound type will only be loaded into a C# and t he .NET Plat for m, Second Edition // synchronized (and hence, thread-safe) context. I ntr oduction [Synchronization] Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public class MyThreadSafeObject : ContextBoundObject Chapter 1 - The Philosophy .NET are now thread safe */} { /* all methods on ofclass Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter In some3 ways, - C# this Language approach Fundamentals can be seen as the lazy approach to writing thread-safe code, given that we

are not4required to-Or dive into Pr the about aspects of the type are truly manipulating threadChapter - Obj ect iented ogrdetails am ming w ith which C# sensitive The major of thise approach, however, is that even if a given method is not making Chapter 5 data. - Exceptions anddownfall Obj ect Lifetim use of thread-sensitive data, the CLR will still lock invocations to the method. Obviously, this could Chapter 6 - I nter faces and Collections degrade overall functionality of the type, Chapter 7 the - Callback I nter faces, Delegates, andsoEvuse entsthis technique with care. Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# anand d th e the .N ET Plat f ormBase , Se con dClass Ed it ion Libraries Thread Safety .NET by Andr ew Tr oelsen

ISBN:1590590554

Although this chapter has illustrated how you can build custom thread-safe types, you should also be Apr ess © 2003 (1200 pages) aware that many This of the types of the base class libraries have been to be thread-safe. In compr ehensiv e text star ts w ith a brief ov er view preprogrammed of the fact, when you look up a given type using online Help (such as System.Console) you will find information C# language and then quickly m oves to key technical and chitectur issues(Figure for .NET developer s. regarding its levelarof threadalsafety 10-17).

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies Figure Many (but not all)Cont .NET types already thread-safe . Chapter 10 - 10-17: Pr ocesses, AppDomains, exts, andare Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Sadly, many .NET types in the base class libraries are not thread-safe, and therefore, you will have to make use of the various locking techniques you have examined to ensure the object is able to survive Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er multiple requests from the thread base. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat fCallbacks orm , Se con d Ed it ion Programming with Timer by Andr ew Tr oelsen

ISBN:1590590554

At this point you have seen a number of ways in which you are able to provide synchronized access to shared Apr ess © 2003 (1200 pages) blocks of data. ToThis be compr sure, ehensiv there are additional underovthe System.Threading namespace, which I will allow e text star ts wtypes ith a brief er view of the you to explore at C# yourlanguage leisure. and However, to wrap up our examination of thread programming, allow me to introdu then quickly m oves to key technical and ar chitectur al issues for developer s. two additional types, TimerCallback and.NET Timer. Many applications have the need to call a specific method during regular intervals of time. For example, you ma Tahave ble o an f Con application t en t s that needs to display the current time on a status bar via a given helper function. As another

example, wish have your application call a helper function every so often to perform noncritical C# and t he you .NETmay Plat for m, to Second Edition background I ntr oduction tasks such as checking for new e-mail messages. For situations such as these, the System.Threading.Timer can be Pused Pa r t One - I nt r oduci ng C# atype nd the .NET la tf orin mconjunction Chapter 1

with a related delegate named TimerCallback.

- The Philosophy of .NET

To illustrate, assume you have a console application that will print the current time every second until the user h - Building C# Applications a key to terminate the application. The first obvious step is to write the method that will be called by the Timer ty

Chapter 2

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

class TimePrinter - Obj ect -Or iented Pr ogr am ming w ith C# { Chapter 5 - Exceptions and Obj ect Lifetim e static void PrintTime(object state) Chapter 6 - I nter faces and Collections { Chapter 7 - Callback I nter faces, Delegates, and Ev ents Console.WriteLine("Time is: {0}", Chapter 8 - Advanced C# Type Const ruction Techniques DateTime.Now.ToLongTimeString()); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s } Chapter ... 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads } Chapter 4

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Notice 12 how- this method has a single parameter of typeLay System.Object and returns void. This is not optional, give Chapter Obj ect Ser ialization and the .NET Remoting er that the13TimerCallback delegate can( only call methods match Chapter - Building a Bet ter Win dow Int roducin g Windowthat s For ms) this signature. The value passed into the targ of your14 TimerCallback delegate can or be Chapter - A Better Paint ing Fr amew k any ( GDIbit + ) of information whatsoever (in the case of the e-mail example, this parameter represent theWindows name ofForm the MS Exchange server to interact with during the process). Also note Chapter 15 - might Pr ogr am ming with s Contr ols that given parameter isespace indeed a System.Object, you are able to pass in multiple arguments using a Chapter 16 -that Thethis Sy stem .I O Nam System.Array type.

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

The next step would be to configure an instance of the TimerCallback type and pass it into the Timer object. In

Chapter Web Pages and Web olsconstructor also allows you to specify the optional parameter addition18to-aASP.NET TimerCallback delegate, theContr Timer Chapter 19 - to ASP.NET Webthe Applicat ions target, the interval to poll the method, as well as the amount of time to wait information pass into delegate Chapter - XMLthe Web Ser vices before 20 making first call. For example: I ndex List of Figurvoid es static Main(string[] args) List of Tables {

Console.WriteLine("***** Working with Timer type *****\n"); // Create the delegate for the Timer type. TimerCallback timeCB = new TimerCallback(PrintTime); // Establish timer settings. Timer t = new Timer( timeCB, // The TimerCallback delegate type. null, // Any info to pass into the called method (null for no info 0, // Amount of time to wait before starting. 1000); // Interval of time between calls. Console.WriteLine("Hit key to terminate..."); Console.ReadLine(); }

In this case, the PrintTime() method will be called roughly every second, and will pass in no additional informatio

to said method. If you did wish to send in some information for use by the delegate target, simply substitute the n C# an d th e .N ET Plat f orm , Se con d Ed it ion value of the second constructor parameter with the appropriate information. For example, ponder the following ISBN:1590590554 by Andr ew Tr oelsen updates: Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the

static void PrintTime(object state) C# language and then quickly m oves to key technical and { ar chitectur al issues for .NET developer s. Console.WriteLine("Time is: {0}, Param is: {1}", DateTime.Now.ToLongTimeString(), state.ToString()); } Ta ble o f Con t en t s ... C# and t he .NET Plat for m, Second Edition Timer t = new Timer(timeCB, "Hi", 0, 1000); I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Figure 10-18 shows the output.

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure The (very useful) clock application Chapter 9 - 10-18: Under standing .NET Assemconsole-based blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

SOURCE CODE

The TimerApp application is included under the Chapter 10 subdirectory.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - up Obj our ect Ser ialization and the .NET Remoting Lay er That wraps examination of multithreaded programming under .NET. To be sure, the System.Threading Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms) to examine in this chapter. Nevertheless, at th namespace defines numerous types beyond what I had the space Chapter 14 should - A Better Paint ing Frfoundation amew or k ( GDI + ) on. point you have a solid to build Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Summary

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

The point of this chapter expose Apr ess ©was 2003 to (1200 pages)the internal composition of a .NET executable image. As you have seen, the long-standing notion of a process been altered This compr ehensiv eWin32 text star ts w ith has a brief ov er view ofunder the the hood to accommodate the needs of the CLR. A single process (which can be programmatically manipulated via the C# language and then quickly m oves to key technical and ar chitectur al type) issuesisfor .NET developeron s. multiple application domains, which represent System.Diagnostics.Process now composed isolated and independent boundaries within a process. As you recall, a single process can host multiple application domains, each of which is capable of hosting and executing any number of related assemblies. TaFurthermore, ble o f Con t enat ssingle application domain can contain any number of contextual boundaries. Using this C# and t he .NET for m,isolation, Second Edition additional level Plat of type the CLR can ensure that special-need objects are handled correctly. I ntr oduction

The remainder of this chapter examined the role Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

of the System.Threading namespace. As you have seen,

when an creates threads of execution, the result is that the program in question is Chapter 1 application - The Philosophy of additional .NET able to 2carry out numerous tasks at (what appears to be) the same time. Finally, the chapter examined Chapter - Building C# Applications various inogr which mark Pa r t Tw o manners - The C# Pr am myou ing can La ngua ge thread-sensitive

blocks of code to ensure that shared resources

do not become unusable Fundamentals units of bogus data. Chapter 3 - C# Language Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Chapter C# 11: Type Reflection, Late Binding, and AttributeISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) Based Programming This compr ehensiv e text star ts w ith a brief ov er view of the language and quicklyunit m oves to key technical As you have seenC#,assemblies arethen the basic of deployment in theand in the .NET universe. Tools such as ar chitectur al issues for .NET developer s. Visual Studio .NET have integrated Object Browsers that allow you to examine the internal types of referenced assemblies (as well as the assembly you happen to be building). Furthermore, external tools such as ildasm.exe allow us to peek into the underlying CIL code, type metadata, and assembly manifest. In addition to Ta ble o f Con t en t s this design-time investigation of .NET assemblies, you are also able to programmatically obtain this same C# and t he .NET Plat for m, Second Edition information using the types defined within the System.Reflection namespace. I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P laa tf number or m The remainder of the chapter examines

of closely related topics. For example, you learn how a .NET

Chapter 1 -employ The Philosophy of .NET client may late binding to activate and manipulate a given type, as well as how to insert custom Chapter 2 Building C# Applications metadata into your .NET assemblies through the use of system-supplied and custom attributes. Finally, to pull Pa r t Tw o - all The ogr ampresented m ing La ngua together ofC# thePrtopics in ge this

chapter, you learn how to build custom snap-in utilities that can be

Chapter plugged 3 into - C# anLanguage extendable Fundamentals application. Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

- Exceptions and Obj ect Lifetim e The Necessity of Type Metadata

Chapter 5 Chapter 6

- I nter faces and Collections The ability fully qualify the definition of types using Chapter 7 - toCallback I nter faces, Delegates, and Ev ents metadata is a key element of the .NET runtime. Numerous

.NET technologies such serialization, remoting, and XML Web services (among other things) all hinge on the Chapter 8 - Advanced C# as Type Const ruction Techniques ability toediscover the at runtime. Pa r t Thre - Pr ogr am m iformat ng w i thof.Ntypes ET Assem bl ie s

Furthermore, as you have already seen in the previous chapters, cross-language interoperability, compiler support, and an IDE's IntelliSense capabilities all rely on a Chapter 9 - Under standing .NET Assem blies concrete description of type. As mentioned numerous times thus far, a .NET type is any member from the set Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads {class, interface, structure, enumeration, delegate}. .NET metadata is the Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing vehicle used to describe the internal composition of said members. Pa r t Four - Le ve r a ging the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Regardless of (or perhaps due to) its importance, metadata is not a new idea supplied by the .NET Framework.

Chapter 13 - Building a Bet ter dow ( Int roducin g Window s For ms) under COM, IDL (Interface Definition Java, CORBA, and COM all Win have similar concepts. For example, Chapter 14 - is A used BettertoPaint ing Fr amew or k ( GDI + ) types found within a given COM server. Like COM, .NET code Language) describe the internal COM Chapter - Prsupport ogr am ming Windows Form s Controf olscourse, that the .NET type metadata does not have the libraries15also typewith metadata. Understand, Chapter 16 - The stemIDL! .I O Nam espace same syntax as Sy COM Rather, type metadata is internally documented as a more tabular (i.e., indexed) Chapter format.17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

As you 18 are- already usingand ildasm.exe, you Chapter ASP.NETaware, Web Pages Web Contr ols are able to view an assembly's type metadata using the

"Ctrl+M" option (see Chapter Chapter 19keyboard - ASP.NET Web Applicat ions 1). Thus, if you were to open any of the *.dll or *.exe assemblies created over the course of this book (such as CarLibrary.dll) using ildasm.exe and hit Ctrl+M, you would find the relevan metadata visible for viewing (Figure 11-1).

Chapter 20 - XML Web Ser vices I ndex

List of Figur es List of Tables

Figure 11-1: Viewing an assembly's metadata As you can see, .NET type metadata is very verbose (for good reason) when contrasted to COM IDL. Using this assembly-embedded metadata, the .NET runtime is able to locate and load a given type for a calling client as well as obtain a complete description of each item. In fact, if I were to list the entire set of metadata generated for the CarLibrary.dll assembly, it would span several pages. Given that this act would be a woeful waste of your time (and paper), let's just glimpse into some key types of the CarLibrary.dll assembly.

Viewing (Partial) Metadata for the EngineState Enumeration

First, understand that each type contained within an assembly is documented using a "TypeDef #n" token C# an d th e .N ET Plat f orm , Se con d Ed it ion (where TypeDef is short for type definition). If the type being described uses a type defined within a separate ISBN:1590590554 by Andr ew Tr oelsen .NET assembly, the referenced type is documented using the "TypeRef #n" token (where TypeRef is short for Apr ess © 2003 (1200 pages) type reference). A "TypeRef" token is a pointer (if you will) to the referenced type's full metadata definition. In a This compr ehensiv e text star ts w ith a brief ov er view of the nutshell, .NET metadata is a set of tables that clearly mark all internal type definitions (TypeDefs) and C# language and then quickly m oves to key technical and referenced entities (TypeRefs), all offorwhich be viewed using ildasm.exe's metadata window. ar chitectur al issues .NETcan developer s. As far as CarLibrary.dll goes, the first TypeDef we encounter (assuming that the CarLibrary.EngineState enumeration is the first type encountered by the C# compiler) is the following metadata description: Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

TypeDef I ntr oduction #1 ------------------------------------------------------Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m CarLibrary.EngineState Chapter TypDefName: 1 - The Philosophy of .NET

(02000002) Flags : [Public] [AutoLayout] [Class] [Sealed] [AnsiClass] (00000101) Chapter 2 - Building C# Applications Extends : 01000001 [TypeRef] System.Enum Pa r t Tw o - The C# Pr ogr am m ing La ngua ge ... Chapter 3 - C# Language Fundamentals Field #2 Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# ------------------------------------------------------Chapter 5 - Exceptions and Obj ect Lifetim e Field Name: engineAlive (04000002) Chapter 6 - I nter faces and Collections Flags : [Public] [Static] [Literal] [HasDefault] (00008056) Chapter DefltValue: 7 - Callback I nter faces,0Delegates, and Ev ents (I4) Chapter CallCnvntn: 8 - Advanced C#[FIELD] Type Const ruction Techniques Pa r t ThreField e - Pr ogr am m i ng w i th .N ET AssemCarLibrary.EngineState bl ie s type: ValueClass Chapter ... 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Here, the- Le "TypDefName" token is aused Pa r t Four ve r a ging the .NET Libr r ie s to

establish the name of the given type. The "Extends" metadata token

is used12 to -document base class of a.NET given .NET type (in this case, the referenced type, System.Enum). Chapter Obj ect Serthe ialization and the Remoting Lay er Each field an enumeration is marked "Field #n" Chapter 13 -ofBuilding a Bet ter Win dow ( Int using roducinthe g Window s Fortoken. ms) For brevity, I have simply listed the metadata for EngineState.engineAlive. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Viewing (Partial) Metadata for the Car Type

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Each of -our is and alsoXcompletely Pa r t Fi ve W eautomobiles b Appl ica ti ons ML W e b Se rdocumented vi ces

using the .NET metadata format. As you may expect, the complete metadata dump for a given type would be pages worth of data. To hit the highlights, here is a Chapter 18 - ASP.NET Web Pages and Web Contr ols partial dump of the Car type that illustrates (a) how fields are defined in terms of .NET metadata, (b) how Chapter 19 - ASP.NET Web Applicat ions methods are documented via .NET metadata, and (c) how a single type property is mapped to two discrete Chapter 20 - XML Web Ser vices member functions: I ndex

List of Figur es

TypeDef #3 ------------------------------------------------------TypDefName: CarLibrary.Car (02000004) Flags : [Public] [AutoLayout] [Class] [Abstract] [AnsiClass] Extends : 01000002 [TypeRef] System.Object Field #1 ------------------------------------------------------Field Name: petName (04000008) Flags : [Family] (00000004) CallCnvntn: [FIELD] Field type: String ... Method #1 ------------------------------------------------------MethodName: .ctor (06000001) Flags : [Public] [HideBySig] [ReuseSlot] [SpecialName] [RTSpecialName] [.ctor] (00001886)

List of Tables

(00100081)

RVA : 0x00002050 C# an d th e: .N[IL] ET Plat f orm , Se con d(00000000) Ed it ion ImplFlags [Managed] ISBN:1590590554 by Andr ew Tr oelsen CallCnvntn: [DEFAULT] Apr ess © 2003 (1200 pages) hasThis This compr ehensiv e text star ts w ith a brief ov er view of the ReturnType: Void C# language and then quickly m oves to key technical and No arguments. ar chitectur al issues for .NET developer s.

...

Property #1 ------------------------------------------------------Ta ble o f Con t en t s Prop.Name : PetName (17000001) C# and t he .NET Plat for m, Second Edition Flags : [none] (00000000) I ntr oduction CallCnvntn: [PROPERTY] Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m hasThis Chapter 1 - The Philosophy of .NET ReturnType: String Chapter 2 - Building C# Applications No arguments. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge DefltValue: Chapter 3 - C#Setter Language Fundamentals : (06000004) set_PetName Chapter 4 - Obj ect -Or iented : Pr ogr am ming w ith get_PetName C# Getter (06000003) Chapter 5 - Exceptions and Obj ect Lifetim e 0 Others Chapter ... 6 - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

First, note the class marks Pa r t Thre e - that Pr ogr amCar m i ng w i thmetadata .N ET Assem bl ie s the

type's base class, and includes various flags that describe how this type was constructed (e.g., [public], [abstract], and whatnot). Methods (such as our Car's constructor) Chapter 9 - Under standing .NET Assem blies are described in regard to their parameters, return value, Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads and name. Finally, note how properties are mapped to their internal getter and setter methods using the .NET metadata "Setter"/"Getter" tokens. As you would expect, Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing the derived Car types (SportsCar and MiniVan) are described in a similar manner. Pa r t Four - Le ve r a ging the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Examining a TypeRef

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Recall that an assembly's metadata will not only describe the set of internal types (Car, EngineState, etc) but each external type referenced by the types themselves. For example, given that CarLibrary.dll has defined two Chapter 16 - The Sy stem .I O Nam espace enumerations, we find a TypeRef block for the System.Enum type: Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

TypeRef (01000001) Chapter 18 - #1 ASP.NET Web Pages and Web Contr ols ------------------------------------------------------Token: 0x01000001 Chapter 20 - XML Web Ser vices ResolutionScope: 0x23000001 I ndex TypeRefName: System.Enum List of Figur es MemberRef #1 List of Tables ------------------------------------------------------Member: (0a00000f) ToString: CallCnvntn: [DEFAULT] hasThis ReturnType: String No arguments. Chapter 19 - ASP.NET Web Applicat ions

Documenting the Defining Assembly The ildasm.exe metadata window also allows you to view the .NET metadata that describes the assembly itself using the "Assembly" token. As you can see from this (partial) listing, information documented within the Assembly table is (surprise, surprise) the same information that can be viewed via the MANIFEST icon: Assembly

------------------------------------------------------C# an d th e .N ET Plat f orm , Se con d Ed it ion Token: 0x20000001 ISBN:1590590554 by Andr ew Tr oelsen Name : CarLibrary Apr ess © 2003 (1200 pages) Public Key : This compr ehensiv e text star ts w ith a brief ov er view of the Hash Algorithm : 0x00008004 C# language and then quickly m oves to key technical and Major Version: 0x00000001 ar chitectur al issues for .NET developer s. Minor Version: 0x00000000 Build Number: 0x000003d6 Revision Number: 0x00005da4 Ta ble o f Con t en t s Locale: C# and t he .NET Plat for m, Second Edition Flags : [SideBySideCompatible] (00000000) I ntr oduction CustomAttribute #1 (0c000001) Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m ------------------------------------------------------Chapter 1 - The Philosophy of .NET CustomAttribute Type: 0a000001 Chapter 2 - Building C# Applications CustomAttributeName: Pa r t Tw o - The C# Pr ogr am m ing La ngua ge System.Reflection.AssemblyKeyNameAttribute :: Chapter instance 3 - C# Language void Fundamentals .ctor(class System.String) Chapter Length: 4 - Obj ect 5 -Or iented Pr ogr am ming w ith C# Chapter Value 5 - Exceptions and 00 Obj ect : 01 00 00 Lifetim 00 e Chapter ctor 6 - I nter faces and Collections args: ("") Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Documenting Referenced Assemblies - Under standing .NET Assem blies

Chapter 9

Chapter 10 - toPrthe ocesses, AppDomains, Cont Threads and TypeRef blocks, .NET metadata also makes use In addition Assembly token and theexts, set and of TypeDef Chapter 11 - Type Reflection, Binding, and Attrexternal ibute- Based Pr ogramm ing that our CarLibrary.dll makes use of of "AssemblyRef #n" tokensLate to document each assembly. Given Pa r t Four - Le ve r a ging a r ie s the MessageBox type,the we.NET find Libr an AssemblyRef

for System.Windows.Forms. For example:

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building AssemblyRef #2 a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) ------------------------------------------------------Chapter 15 0x23000002 - Pr ogr am ming with Windows Form s Contr ols Token: Chapter 16 Key - Theor Sy stem .I O Nam Public Token: b7espace 7a 5c 56 19 34 e0 89 Chapter Name:System.Windows.Forms 17 - Data Access w ith ADO.NET Pa Major r t Fi ve -Version: W e b Appl ica0x00000001 ti ons and X ML W e b Se r vi ces

Minor18Version: Chapter - ASP.NET 0x00000000 Web Pages and Web Contr ols Build19Number: Chapter - ASP.NET0x00000ce4 Web Applicat ions Revision Number: Chapter 20 - XML Web Ser0x00000000 vices Locale: I ndex HashValue List of Figur es Blob: Flags: [none] (00000000)

List of Tables

Documenting String Literals The final point of interest regarding .NET metadata is the fact that each and every string literal in your code base is documented under the "User Strings" token: User Strings ------------------------------------------------------70000001 : ( 8) L"Jamming " 70000013 : (13) L"Quiet time..." 7000002f : (14) L"Ramming speed!" 7000004d : (19) L"Faster is better..." 70000075 : (16) L"Time to call AAA" 70000097 : (16) L"Your car is dead"

700000b9 : ( 9) L"Be quiet " d th e .N ET Plat f orm , Se con d Ed it ion 700000cd : ( C# 2)anL"!!" by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

Now, don't be tooThis concerned with the exact and every compr ehensiv e text starsyntax ts w ithof a each brief ov er view of piece the of .NET metadata. The bigger point C# language andisthen m oves to lists key technical and to absorb is that .NET metadata veryquickly descriptive and each internally defined (and externally referenced) al issues .NET developer s. on your mind may be (in the best-case scenario), "How type found within ar a chitectur given code base.for The next question can I leverage this information" or (in a worse case scenario), "Why do I care?" To address both points of view, allow me to introduce .NET reflection services. Be aware that the pages that follow may be a bit of a headTa ble o f Con t en t s scratcher until this chapter's endgame. So hang tight. C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dReflection th e .N ET Plat f orm , Se con d Ed it ion Understanding ISBN:1590590554

by Andr ew Tr oelsen

In the .NET universe, reflection is the process of runtime type discovery. Using reflection services, you are Apr ess © 2003 (1200 pages) able to load an assembly at runtime and discover same of information presented by the This compr ehensiv e text star ts w iththe a brief ovsort er view of the ildasm.exe metadata window, using a friendly object model. For example, through reflection, you can C# language and then quickly m oves to key technical and chitectur al issues for .NET developer s. obtain a list of all ar types contained within a given assembly (or *.netmodule), including the methods, fields, properties, and events defined by a given type. You can also dynamically discover the set of interfaces supported by a given class (or structure), the parameters of a method as well as other related details Ta(base ble o fclass Con t en ts details, namespace information, manifest data, and so forth). C# and t he .NET Plat for m, Second Edition

Tooduction understand how to use reflection services to read .NET metadata, you need to come to terms with the I ntr Type class System namespace) Pa r t One - I nt(defined r oduci nginC#the a nd the .NET P la tf or m

as well as a new namespace, System.Reflection. As you

will see, System.Type contains a number of methods that allow you to extract valuable Chapter 1 the - The Philosophy class of .NET information the type you happen to be observing. The System.Reflection namespace Chapter 2 - about Building C#current Applications contains related types to facilitate Pa r t Tw o - numerous The C# Pr ogr am m ing La ngua ge

late binding and dynamic loading of assemblies. To begin,

let's investigate System.Type in some detail. Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th eClass .N ET Plat f orm , Se con d Ed it ion The System.Type by Andr ew Tr oelsen

ISBN:1590590554

Many of the itemsApr defined within thepages) System.Reflection namespace make use of the abstract System.Type ess © 2003 (1200 class. This class This provides a number of the details behind a given item. compr ehensiv e textmethods star ts w that ith a can briefbe ovused er viewtoofdiscover the The complete setC# of language membersand is quite expansive; however, Table 11-1 offers a partial snapshot of the then quickly m oves to key technical and ar chitectur al issues for .NET developer s. members supported by System.Type. Table 11-1: Select Members of System.Type Ta ble o f Con t en t s

Member in Life C# Type and t he .NET Plat for m,Meaning Second Edition I ntr oduction

IsAbstract

These properties (among others) allow you to discover a number of basic traits about the Type you are referring to (e.g., if it is an abstract method, an IsArray Chapter 1 - The Philosophy of .NET array, a nested class, and so forth). IsClass Chapter 2 - Building C# Applications Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Pa rIsCOMObject t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

IsEnum

IsInterface Chapter 5 - Exceptions and Obj ect Lifetim e IsPrimitive Chapter 6 - I nter faces and Collections

Chapter 7 - Callback I nter faces, Delegates, and Ev ents IsNestedPublic Chapter 8

- Advanced C# Type Const ruction Techniques

IsNestedPrivate

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

IsSealed Chapter 9 - Under standing .NET Assem blies

IsValueType Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

GetConstructors()

These methods (among others) allow you to obtain an array representing the items (interface, method, property, etc.) you are interested in. Each method GetEvents() Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er returns a related array (e.g., GetFields() returns a FieldInfo array, GetFields() Chapter 13 - Building a Bet ter Win dow ( Int roducin Window s For ms) etc.). GetMethods() returns a gMethodInfo array, Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) GetInterfaces() Be aware that each of these methods has a singular form (e.g., GetMethod(), Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

GetMethods()

GetProperty()) that allows you to retrieve a specific item by name, rather than an array of all related items.

Chapter 16 - The Sy stem .I O Nam espace

GetMembers()

Chapter 17 - Data Access w ith ADO.NET

Pa rGetNestedTypes() t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols GetProperties() Chapter 19 - ASP.NET Web Applicat ions

FindMembers()

Returns an array of MemberInfo types, based on search criteria.

Chapter 20 - XML Web Ser vices I ndex GetType() List of Figur es

InvokeMember()

List of Tables

This static method returns a Type instance given a string name. This method allows late binding to a given item.

Obtaining a Type Reference There are numerous ways you can obtain an instance of the Type class. However, the one thing you cannot do is directly create a Type object using the "new" keyword, as Type is an abstract class. Regarding your first choice, as you recall, System.Object defines a method named GetType() that returns an instance of the Type class: // Extract Type using a valid Foo instance. Foo theFoo = new Foo(); Type t = theFoo.GetType();

In addition to the previous technique, you may also obtain a Type using (of all things) the Type class itself. To

do so, call the static GetType() member and specify the textual name of the item you are interested in C# an d th e .N ET Plat f orm , Se con d Ed it ion examining (and optionally, a System.Boolean to indicate case sensitivity): by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

// Get a Type using the static Type.GetType() method. This compr ehensiv e text star ts w ith a brief ov er view of the Type t = null; C# language and then quickly m oves to key technical and t = Type.GetType("Foo"); ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s

Here, are able to m, simply pass in the friendly name of the Type.GetType() method, assuming a type C# and you t he .NET Plat for Second Edition

named Foo is within your same assembly. If this were not the case, Type.GetType() would require a string that describes the fully qualified name of the entity you are interested in examining, followed by the friendly Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m name of the assembly containing the type (each of which is separated by a comma). Furthermore, the string Chapter 1 - The Philosophy of .NET passed into Type.GetType() may specify the plus token (+) to signify a nested type definition. Given this Chapter 2 - Building C# Applications information, ponder the following type request: I ntr oduction

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

// Get a- Obj nested type in a distinct assembly. ect -Or iented Pr ogr am ming w ith C# Type t = Chapter 5 - Exceptions and Obj ect Lifetim e Type.GetType("MyNamespace.OuterType+NestedType, myOtherAsm"); Chapter 4 Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter C# Type ruction Techniques Finally,8you- Advanced can also obtain an Const instance of Type using the C# typeof() operator: Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies // Get the Type using typeof.

Chapter 10 =- Pr ocesses, AppDomains, Cont exts, and Threads Type t typeof(Foo); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter Notice 12 that- Type.GetType() Obj ect Ser ialization andand typeof() the .NET areRemoting helpful inLay that er you do not need to first create an object instance

to extract information (which is obviously quite helpful when Chapter 13 type - Building a Bet ter Win dow ( Int roducin g Window s For ms)employing late binding), whereas the use of the inherited Chapter 14 - ASystem.Object.GetType() Better Paint ing Fr amew or k method ( GDI + ) does. In any case, now that you understand how to obtain a Type reference, examine how you Form can exercise it. Chapter 15 - Pr ogrlet's am ming with Windows s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Fun with the Type Class

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

To illustrate the usefulness of System.Type, assume you have a class named Foo that has been defined as Chapter 18 - ASP.NET Web Pages and Web Contr ols follows19 (the implementation of theions various methods is irrelevant for this example): Chapter - ASP.NET Web Applicat Chapter 20 - XML Web Ser vices

// These are the items we will discover at runtime. I ndex namespace List of Figur es TheType { of Tables List // Two interfaces. public interface IFaceOne { void MethodA(); } public interface IFaceTwo { void MethodB(); } // Foo supports these 2 interfaces. public class Foo: IFaceOne, IFaceTwo { // Fields. public int myIntField; public string myStringField; // A method. public void myMethod(int p1, string p2){...} // A property. public int MyProp

{ C# an d th{e .Nreturn ET Plat f orm , Se con d Ed it}ion get myIntField; by Andr setew{Tr oelsen myIntField = value; } ISBN:1590590554 Apr ess © 2003 (1200 pages) } This compr ehensiv text star ts w ith a brief ov er view of the // IFaceOne and e IFaceTwo methods. C# language and then quickly m oves public void MethodA() {...} to key technical and ar chitectur al issues for .NET developer s.

public void MethodB() {...}

} }

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Now, let's create a program that is able to discover the methods, properties, supported interfaces, and fields Pa rt a One - I nt r oduci ng C# nd the .NET P la tf or m for given Foo object (inaaddition to some other

points of interest). The FooReader class defines a number

Chapter - The Philosophy .NET of static1 methods that look of more or less identical. First you have ListMethods(), which extracts each method Chapter 2 Building C# Applications from Foo using a Type object. Notice how Type.GetMethods() returns an array of MethodInfo types: Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

C# Language Fundamentals // Suck - out all method names from Foo.

Chapter 4 static - Obj ect -Or ientedListMethods(Foo Pr ogr am ming w ith C# f) public void Chapter 5 Exceptions and Obj ect Lifetim e { Chapter Console.WriteLine("***** 6 - I nter faces and Collections Methods of Foo *****"); Chapter Type 7 - Callback I nter faces, Delegates, and Ev ents t = f.GetType(); Chapter MethodInfo[] 8 - Advanced C# mi Type= Const ruction Techniques t.GetMethods(); Pa r t Threforeach(MethodInfo e - Pr ogr am m i ng w i th .N ETm Assem bl ie s in mi)

- Under Console.WriteLine("Method: standing .NET Assem blies {0} ", m.Name); Chapter Console.WriteLine("*************************\n"); 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 9

} Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

The implementation of ListFields() is similar. The only notable difference is the call to Type.GetFields() and the resulting FieldInfo array:

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

// Suck out all fields from Foo. public static void ListFields(Foo f) Chapter 17 - Data Access w ith ADO.NET { Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Console.WriteLine("***** Fields of Foo *****"); Chapter 18 - ASP.NET Web Pages and Web Contr ols Type t = f.GetType(); Chapter 19 - ASP.NET Web Applicat ions FieldInfo[] fi = t.GetFields(); Chapter 20 - XML Web Ser vices foreach(FieldInfo field in fi) I ndex Console.WriteLine("Field: {0} ", field.Name); List of Figur es Console.WriteLine("*************************\n"); List } of Tables Chapter 16 - The Sy stem .I O Nam espace

The ListVariousStats(), ListProps(), and ListInterfaces() methods should be self-explanatory at this point: // Suck out some interesting statistics about Foo. public static void ListVariousStats(Foo f) { Console.WriteLine("***** Various stats about Foo *****"); Type t = f.GetType(); Console.WriteLine("Full name is: {0} ", t.FullName); Console.WriteLine("Base is: {0} ", t.BaseType); Console.WriteLine("Is it abstract? {0} ", t.IsAbstract); Console.WriteLine("Is it a COM object? {0} ", t.IsCOMObject); Console.WriteLine("Is it sealed? {0} ", t.IsSealed); Console.WriteLine("Is it a class? {0} ", t.IsClass);

Console.WriteLine("***********************************\n"); C# an d th e .N ET Plat f orm , Se con d Ed it ion } ISBN:1590590554 Andr ew Tr oelsen // Gather allby properties. Apr ess © 2003 (1200 pages) public static void ListProps(Foo f) This compr ehensiv e text star ts w ith a brief ov er view of the { C# language and then quickly m oves to key and Console.WriteLine("***** Properties of technical Foo *****"); ar chitectur al issues for .NET developer s. Type t = f.GetType(); PropertyInfo[] pi = t.GetProperties(); foreach(PropertyInfo prop in pi) Ta ble o f Con t en t s Console.WriteLine("Prop: {0} ", prop.Name); C# and t he .NET Plat for m, Second Edition Console.WriteLine("*****************************\n"); I ntr oduction } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // Dump all interfaces supported by Foo. Chapter 1 - The Philosophy of .NET public static void ListInterfaces(Foo f) Chapter 2 - Building C# Applications { Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Console.WriteLine("***** Interfaces of Foo *****"); Chapter Type 3 - C#t Language Fundamentals = f.GetType(); Chapter Type[] 4 - Obj ect -Or iented ogr am ming w ith C# ifaces =Prt.GetInterfaces(); Chapter foreach(Type 5 - Exceptions and Obj Lifetim e i inectifaces) Chapter 6 - I nter faces and Collections Console.WriteLine("Interface: {0} ", i.Name); Chapter Console.WriteLine("*****************************\n"); 7 - Callback I nter faces, Delegates, and Ev ents Chapter } 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies The Main() of the FooReader class calls each static method: Chapter 10 - method Pr ocesses, AppDomains, Cont exts,simply and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

// Put - Foo under Pa r t Four Le ve r a ging thethe .NETmagnifying Libr a r ie s

glass.

using12System; Chapter - Obj ect Ser ialization and the .NET Remoting Lay er // Needed to gain of MethodInfo, FieldInfo, etc. Chapter 13 - Building a Bet definitions ter Win dow ( Int roducin g Window s For ms) using14System.Reflection; Chapter - A Better Paint ing Fr amew or k ( GDI + ) namespace TheType { Chapter 16 - The Sy stem .I O Nam espace public class FooReader Chapter 17 - Data Access w ith ADO.NET { Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces // ...Static methods seen previously... Chapter 18 - ASP.NET Web Pages and Web Contr ols public static int Main(string[] args) Chapter 19 - ASP.NET Web Applicat ions { Chapter 20 - XML Web // Ser vices Make a new Foo object. I ndex Foo theFoo = new Foo(); List of Figur es // Now examine everything. List of Tables ListVariousStats(theFoo); ListMethods(theFoo); ListFields(theFoo); ListProps(theFoo); ListInterfaces(theFoo); return 0; } } } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Here, I made use of Object.GetType() to gather information about the Foo class defined in the current namespace. Now assume you wish to obtain metadata information for a nested enumeration of the Foo type: // Foo now supports a nested enum.

public class Foo: IFaceOne, IFaceTwo C# an d th e .N ET Plat f orm , Se con d Ed it ion { ISBN:1590590554 by AndrMyNestedEnum{} ew Tr oelsen public enum Apr ess © 2003 (1200 pages) ... This compr ehensiv e text star ts w ith a brief ov er view of the } C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Recall that nested items can be identified using the "+" token. Thus, to obtain metadata information for MyNestedEnum, you could write the following:

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

// Get info on nested enum. Type t = Type.GetType("TheType.Foo+MyNestedEnum"); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Console.WriteLine("Enum name? {0}", t.Name); Chapter 1 - The Philosophy of .NET Console.WriteLine("Is enum nested private? {0}", t.IsNestedPrivate); Chapter 2 - Building C# Applications Console.WriteLine("Is enum nested public? {0}", t.IsNestedPublic); I ntr oduction

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4 - System.Type Obj ect -Or iented Pr ogr am ming w ithmembers C# Obviously, provides additional beyond the items seen thus far. One especially Chapter 5 - member Exceptions and ObjGetInterfaceMap(). ect Lifetim e interesting is named Recall that explicit interface implementation allows you to Chapter map a 6given - I nter interface faces and method Collections to a particular class method. GetInterfaceMap() can be used to obtain these

relationships at runtime. illustrate, update Foo type to make use of explicit interface implementation: Chapter 7 - Callback I nterTo faces, Delegates, andthe Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre Pr ogr am m i ng w i th .N ET Assem bl ie s // Usee -explicit interface impl.

Chapter 9 class - Under standing .NET Assem blies public Foo: IFaceOne, IFaceTwo Chapter { 10 - Pr ocesses, AppDomains, Cont exts, and Threads

IFaceOne.MethodA(){} Chapter void 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Fourvoid - Le veIFaceTwo.MethodB(){} r a ging the .NET Libr a r ie s

Chapter ... 12 - Obj ect Ser ialization and the .NET Remoting Lay er

} Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Now, create the following additional helper method:

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

public static void MapInterfaceMethodsToClassMethods(Foo f) { Chapter 18 - ASP.NET Web Pages and Web Contr ols Console.WriteLine("***** Explicit interface impl mappings *****"); Chapter 19 - ASP.NET Web Applicat ions Type t = f.GetType(); Chapter 20 - XML Web Ser vices // Get all interfaces on type. I ndex Type[] iFaces = t.GetInterfaces(); List of //Figur Do esthe following for each interface on type. List of Tables for(int i = 0; i < iFaces.Length; i ++) { Console.WriteLine("Info on Interface named: {0}", iFaces[i]); // Get method infos for name of method on the class. MethodInfo[] classMethodNames = t.GetInterfaceMap(iFaces[i]).TargetMethods; MethodInfo[] interfaceMethodNames = t.GetInterfaceMap(iFaces[i]).InterfaceMethods; for(int j = 0; j < classMethodNames.Length; j++) { Console.WriteLine("Interface method: {0}", interfaceMethodNames[j].Name); Console.WriteLine("is implemented by class method: {0}", classMethodNames[j].Name); } Console.WriteLine(); } Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

} C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

© 2003 (1200 pages) This example is aApr bitess more involved. First, we obtain a list of each interface supported by the Foo type using GetInterfaces(), which is held in a System.Type Next, loopofthrough each member in the array and This compr ehensiv e text star ts warray. ith a brief ovwe er view the C#MethodInfo language and then m oves key technical and extract an array of types to quickly represent the to names class methods, and another MethodInfo array ar chitectur al issues for .NET developer s. we have all the necessary information, we simply representing the names of the interface methods. Once print out the association to the console window. Figure 11-2 shows partial output of your first reflection application.

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - 11-2: The SyReflecting stem .I O Nam Figure on espace Foo Chapter 17 - Data Access w ith ADO.NET Pa Interesting r t Fi ve - Wstuff, e b Appl huh? ica tiWhile ons and theX ML System.Type W e b Se r vi ces class

can be very helpful on its own, reflection becomes even

more powerful when Web you make theContr Assembly class defined within the System.Reflection namespace. Chapter 18 - ASP.NET Pages use and of Web ols Chapter 19 - ASP.NET Web Applicat ions

SOURCE CODE

The TheType project can be found under the Chapter 11 subdirectory.

Chapter 20 - XML Web Ser vices I ndex

List of Figur es List of Tables

C# an d thSystem.Reflection e .N ET Plat f orm , Se con d EdNamespace it ion Investigating the ISBN:1590590554

by Andr ew Tr oelsen

Like any namespace, System.Reflection Apr ess © 2003 (1200 pages) contains a number of related types. Like any namespace, some types are of moreThis immediate interest thanstar others. 11-2 compr ehensiv e text ts w ithTable a brief ov erlists viewsome of theof the core items you should be familiar with, many of which you have already seen in the previous Foo C# language and then quickly m oves to key technical andexample. ar chitectur al issues for .NET developer s.

Table 11-2: A Sampling of Members of the System.Reflection Namespace System.Reflection Ta ble o f Con t en t s

Meaning in Life Type C# and t he .NET Plat for m, Second Edition I ntr oduction

Assembly

This class (in addition to numerous related types) contains a number of methods that allow you to load, investigate, and Chapter 1 - The Philosophy of .NET manipulate an assembly. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 2

- Building C# Applications

This class Pa rAssemblyName t Tw o - The C# Pr ogr am m ing La ngua ge

allows you to discover numerous details behind an assembly's identity (version information, culture information, and so Chapter 3 - C# Language Fundamentals forth). Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e EventInfo Holds information for a given event. Chapter 6 - I nter faces and Collections

FieldInfo Holds information for a given field. Chapter 7 - Callback I nter faces, Delegates, and Ev ents

Chapter 8 - Advanced C# Type Const Techniques MemberInfo Thisruction is the abstract base class that defines common behaviors for Pa r t Thre e - Pr ogr am m i ng w i th .N ET bl ie s theAssem EventInfo,

Chapter 9

FieldInfo, MethodInfo, and PropertyInfo types.

- Under standing .NET Assem blies

MethodInfo

Contains information for a given method.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Allows Binding,you andtoAttr ibute-aBased ogrammwithin ing a multifile assembly. Module access givenPrmodule Pa r t Four - Le ve r a ging the .NET Libr a r ie s

ParameterInfo

Holds information for a given parameter.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win Holds dow ( Int roducin g Window s For ms) PropertyInfo information for a given property. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an th e .N ET Plat f orm , Se con d Ed it ion Reflecting on adPrivate Assembly by Andr ew Tr oelsen

ISBN:1590590554

The real workhorse Apr of essSystem.Reflection © 2003 (1200 pages) is the Assembly class. Using this type, you are able to dynamically load an assembly, invoke class members at ts runtime well as discover properties about the This compr ehensiv e text star w ith a (late brief binding), ov er view as of the assembly itself. The first step to investigating the contents of a .NET binary is to load the assembly in memory. C# language and then quickly m oves to key technical and al issues for .NET developer s. Assume you havearachitectur new console project named CarReflector, which has set a reference to the CarLibrary assembly created in Chapter 9. The static Assembly.Load() method can now be called by passing in the friendly string name: Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

using System; using System.Reflection; Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m using System.IO; // Needed for FileNotFoundException definition. Chapter 1 - The Philosophy of .NET // Investigate the CarLibrary assembly. Chapter 2 Building C# Applications namespace CarReflector Pa {r t Tw o - The C# Pr ogr am m ing La ngua ge Chapter public 3 - C# Language Fundamentals class CarReflector Chapter { 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions Obj ect int Lifetim e public and static Main(string[] args) Chapter 6 - I nter { faces and Collections class to load the CarLibrary. Chapter 7 - Callback I// nterUse faces,Assembly Delegates, and Ev ents Assembly a = null; Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am mtry i ng w i th .N ET Assem bl ie s { Chapter 9 - Under standing .NET Assem blies a = Assembly.Load("CarLibrary"); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing e) Pa r t Four - Le ve r a ging catch(FileNotFoundException the .NET Libr a r ie s { Console.WriteLine(e.Message);} Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er return 0; Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols } I ntr oduction

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi vethat - We b Appl icaAssembly.Load() ti ons and X ML W e method b Se r vi ces Notice the static has

been passed in the friendly name of the assembly we are

Chapter 18 -inASP.NET Web memory Pages and Webthus Contr ols interested loading into (and assumes that the CarLibrary.dll is contained within the application Chapter directory 19of - the ASP.NET executable). Web Applicat As you ionsmay suspect, this method has been overloaded a number of times to

provide20 a number of ways in which you can bind to an assembly. One variation to be aware of is that the textual Chapter - XML Web Ser vices information sent into Assembly.Load() may contain additional string segments beyond the friendly name. I ndex Specifically, List of Figur es you may choose to specify a version number, culture value (for localized assemblies) and public keyoftoken List Tablesvalue (for shared assemblies). Collectively speaking, the set of items identifying an assembly is termed the "display name." The format of a display name is a comma-delimited string of name/value pairs that begins with the friendly name of the assembly, followed by optional qualifiers (that may appear in any order). Here is the template to follow (optional items have been placed in parentheses): Name (,Culture = culture token) (,Version = major.minor.build.revision) (,PublicKeyToken= public key token)

When crafting a display name, the convention PublicKeyToken=null, indicates that binding and matching against a non-strongly-named assembly is required. Additionally, the convention Culture= "" indicates matching against the default culture of the target machine. To illustrate: // A fully specified AssemblyName for simply named assembly with default culture.

a = Assembly.Load( C# anVersion=1.0.982.23972, d th e .N ET Plat f orm , Se con d Ed it ion @"CarLibrary, PublicKeyToken=null, Culture="""); ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C#the language and then quickly m oves tosupplies key technical and Also be aware that System.Reflection namespace the AssemblyName type, which allows you to ar chitectur al issues for in .NET developer s. variable. Typically, this class is used in conjunction with represent the above string information a handy object System.Version, which is an OO wrapper round an assembly's version number. Once you have established the display name, it can then be passed into the overloaded Assembly.Load() method:

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

// Our OO-Aware display name. AssemblyName asmName; Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m asmName = new AssemblyName(); Chapter 1 - The Philosophy of .NET asmName.Name = "CarLibrary"; Chapter 2 - Building C# Applications Version v = new Version("1.0.982.23972"); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge asmName.Version = v; Chapter 3 - C# Language Fundamentals a = Assembly.Load(asmName); I ntr oduction

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections Note Assembly definesand a static LoadFrom() method that allows you to load an assembly Chapter 7 The - Callback I ntertype faces,also Delegates, Ev ents

a given example, C:\MyAsms). Chapter 8 using - Advanced C#code Typebase Const(for ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

- Under standing .NET in Assem blies Enumerating Types a Referenced Assembly

Chapter 9

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Now that have a reference the CarLibrary assembly, can discover the name of each type it contains Chapter 11 you - Type Reflection, LatetoBinding, and Attr ibuteBased you Pr ogramm ing using the- static Pa r t Four Le ve r aAssembly.GetTypes() ging the .NET Libr a r ie smethod.

Here is a helper method named ListAllTypes() that does this very

thing (assume method is called within afterLay loading the CarLibrary.dll): Chapter 12 - Objthis ect Ser ialization and the .NETMain() Remoting er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter // List 14 - all A Better types Paint within ing Fr amew the or k (assembly. GDI + )

private voidwith ListAllTypes(Assembly a) Chapter 15 - static Pr ogr am ming Windows Form s Contr ols { Chapter 16 - The Sy stem .I O Nam espace Types in Assembly *****"); Chapter Console.WriteLine("***** 17 - Data Access w ith ADO.NET a.FullName); Pa r t Fi veConsole.WriteLine("->{0}\n", - W e b Appl ica ti ons and X ML W e b Se r vi ces types = a.GetTypes(); Chapter 18Type[] - ASP.NET Web Pages and Web Contr ols in types) Chapter foreach(Type 19 - ASP.NET Web tApplicat ions Console.WriteLine("Type: {0}", t); Console.WriteLine("******************************\n");

Chapter 20 - XML Web Ser vices I ndex

}

List of Figur es List of Tables

Enumerating Class Members Let's now assume you are interested in discovering the full set of members supported by one of our automobiles. To do so, you can make use of the GetMembers() method defined by the Type class. As you recall, the Type class also defines a number of related methods (GetInterfaces(), GetProperties(), GetMethods(), and so forth) that allow you to request a specific kind of member. GetMembers() returns an array of MemberInfo types. Here is an example that lists the type and signature of each method defined by the MiniVan: // Another static method of the CarReflector class. private static void ListAllMembers(Assembly a) { Console.WriteLine("***** Members of MiniVan *****"); Type miniVan = a.GetType("CarLibrary.MiniVan");

MemberInfo[] mi = miniVan.GetMembers(); C# an d th e .N ETm Plat foreach(MemberInfo in f orm mi), Se con d Ed it ion ISBN:1590590554 by Andr ew Tr oelsen Console.WriteLine("{0}: {1} ", Apr ess © 2003 (1200 pages) m.MemberType.ToString(), m); This compr ehensiv e text star ts w ith a brief ov er view of the Console.WriteLine("******************************\n"); C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

}

Enumerating Method Parameters

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

Not only can you use reflection to gather information for the members of a type, you can also obtain information I ntr oduction about of aand given member. Tom illustrate, Pa r t Onethe - I parameters nt r oduci ng C# the .NET P la tf or

let's assume that the Car class has defined the following

additional Chapter 1 -method: The Philosophy of .NET Chapter 2

- Building C# Applications

// A onew Car Pa r t Tw - Themember C# Pr ogrof am mthe ing La nguaclass. ge public TurnOnRadio(bool Chapter 3 void - C# Language Fundamentals state, MusicMedia mm) { Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# Chapter if(state) 5 - Exceptions and Obj ect Lifetim e

MessageBox.Show("Jamming with {0} ", mm.ToString()); - I nter faces and Collections else Chapter 7 - Callback I nter faces, Delegates, and Ev ents MessageBox.Show("Quiet time..."); Chapter 8 - Advanced C# Type Const ruction Techniques } Chapter 6

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads TurnOnRadio() takes two parameters, the second of which is a custom enumeration: Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

// Holds source of music. public enum MusicMedia Chapter 13 - Building a Bet ter Win dow ( Int roducin { musicCD, musicTape, musicRadio } g Window s For ms) Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Extracting parameters of TurnOnRadio() requires using MethodInfo.GetParameters(). This Chapter 16 -information The Sy stemfor .I Othe Nam espace method17returns ParameterInfo array. Each item in this array contains numerous properties for a given Chapter - DataaAccess w ith ADO.NET parameter. isica another static method the Pa r t Fi ve - W eHere b Appl ti ons and X ML W e b Seofr vi cesCarReflector

class, GetParams(), which displays various details

for each thePages TurnOnRadio() method Chapter 18parameter - ASP.NETof Web and Web Contr ols (see Figure 11-3 for partial output): Chapter 19 - ASP.NET Web Applicat ions

// Get for the TurnOnRadio() method. Chapter 20 parameter - XML Web Serinformation vices private static void GetParams(Assembly a) I ndex { of Figur es List Console.WriteLine("***** Here are the params for TurnOnRadio() *****"); List of Tables // Get a MethodInfo type. Type miniVan = a.GetType("CarLibrary.MiniVan"); MethodInfo mi = miniVan.GetMethod("TurnOnRadio"); // Show number of params. Console.WriteLine("Here are the params for {0} ", mi.Name); ParameterInfo[] myParams = mi.GetParameters(); Console.WriteLine("Method has {0} params", myParams.Length); // Show some info for param. foreach(ParameterInfo pi in myParams) { Console.WriteLine("Param name: {0} ", pi.Name); Console.WriteLine("Position in method: {0} ", pi.Position); Console.WriteLine("Param type: {0} ", pi.ParameterType); } Console.WriteLine("******************************\n");

} C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction

Figure 11-3: Reflecting on a private assembly

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - The Philosophy of .NET SOURCE The CarReflector project is included in the Chapter 11 subdirectory. Chapter 2 Building C# Applications CODE Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ETAssemblies Plat f orm , Se con d Ed it ion Reflecting on Shared by Andr ew Tr oelsen

ISBN:1590590554

The Assembly type used to load a shared assembly (i.e., a GAC deployed .NET binary). To do so, Aprcan ess ©also 2003be (1200 pages) your Load() method must specify a full to be loaded. Assume you wish to load This compr ehensiv e textdisplay star ts name w ith a for briefthe ovassembly er view of the version 1.0.0.0 ofC# thelanguage SharedAssembly.dll you created in Chapter 9. The and then quickly m oves to key technical and following code prints out various ar chitectur al issues developer s. type (be sure to update the value of publickeytoken to statistics of this binary and then lists for the.NET names of each use your own! ): Ta ble o f Con t en t s

namespace SharedAsmReflector { I ntr oduction public class SharedAsmReflector Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m { Chapter 1 - The Philosophy of .NET void DisplayInfo(Assembly a) private static Chapter 2 - Building C# Applications { Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Console.WriteLine("***** Info about Assembly *****"); Chapter 3 - C# Language Fundamentals Console.WriteLine("Loaded from GAC? {0}", a.GlobalAssemblyCache); Chapter 4 - Obj ect -OrConsole.WriteLine("Asm iented Pr ogr am ming w ith C# Name: {0}", a.GetName().Name); Chapter 5 - Exceptions and Obj ect Lifetim e Console.WriteLine("Asm Version: {0}", a.GetName().Version); Chapter 6 - I nter facesConsole.WriteLine("Asm and Collections Culture: {0}", Chapter 7 - Callback I nter faces,a.GetName().CultureInfo.DisplayName); Delegates, and Ev ents = a.GetTypes(); Chapter 8 - AdvancedType[] C# Type types Const ruction Techniques foreach(Type t in Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie stypes) Console.WriteLine("Type: {0}", t); Chapter 9 - Under standing .NET Assem blies Console.WriteLine("******************************\n"); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads } Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Chapter 11 - Type Pa r t Four - Le vepublic r a ging thestatic .NET Librint a r ie s Main(string[] args) { Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er // Load from GAC (without error checking...) Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) // Adjust your publickeytoken value! Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Assembly a = null; Chapter 15 - Pr ogr am ming with Windows Form s Contr ols string displayName = "SharedAssembly," + Chapter 16 - The Sy stem .I O Nam espace "Version=1.0.0.0," + Chapter 17 - Data Access w ith"PublicKeyToken=82fbc820d160f2b8," ADO.NET + Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces @"Culture="""; Chapter 18 - ASP.NET a Web and Web Contr ols = Pages Assembly.Load(displayName); Chapter 19 - ASP.NET DisplayInfo(a); Web Applicat ions Chapter 20 - XML Web return Ser vices 0; I ndex } List of Figur } es } of Tables List C# and t he .NET Plat for m, Second Edition

Of course, you may load any item installed in the GAC using a full display name, including standard .NET binaries. For example, to load System.Drawing.Design.dll from the GAC, you simply update the display name as follows (your version may differ): // Load System.Drawing.Design.dll from GAC. displayName = null; displayName = "System.Drawing.Design," + "Version=1.0.5000.0," + "PublicKeyToken=b03f5f7f11d50a3a," + @"Culture="""; a = Assembly.Load(displayName);

SOURCE CODE

C# an d th e .N ET Plat f orm , Seproject con d Ed ion The SharedAsmReflector isitincluded in the Chapter 11 subdirectory. ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Sweet! At this point understand of the items defined within the System.Reflection Thisyou compr ehensiv e how text to staruse ts wsome ith a brief ovcore er view of the namespace to discover a wealth of information at runtime. And, maybe C# language and then quickly m oves to key technical andyou are already envisioning the code chitectur al issues .NET developer s. let's check out how to create and interact with types behind tools sucharas ildasm.exe andfor wincv.exe. Next up, on the fly via .NET late binding. Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dDynamic th e .N ET PlatInvocation f orm , Se con d Ed(Late it ion Understanding Binding) ISBN:1590590554

by Andr ew Tr oelsen

The System.Reflection provides additional functionality beyond runtime type discovery. .NET Apr ess namespace © 2003 (1200 pages) reflection servicesThis also provides the totsexercise "lateov binding" to the a type. Simply put, late binding is a compr ehensiv e ability text star w ith a brief er view of technique in which you are able create a given type and invoke its members at runtime without having C# language and then quickly m oves to key technical and ar chitectur for .NET developer s. compile-time knowledge of alitsissues existence. Therefore, when you are building an application that binds late to a type in a given assembly, you have no reason to set a reference to the type (and therefore, the caller's manifest has no direct listing of the binary). Do be aware, however, that the CLR will still follow the same Tasearch ble o f Con t en t s when searching for the location of the dynamically referenced type (code bases, public heuristics C# and t he .NET Plat for m, Secondfiles, Edition key tokens, XML configuration and the like). I ntr oduction

The value ofr oduci late binding not.NET be immediately Pa r t One - I nt ng C# amay nd the P la tf or m

understood. It is true that if you can "bind early" to a type

(e.g., set assembly reference Chapter 1 an - The Philosophy of .NETand use the C# "new" keyword) you should opt to do so. Early binding allows you determine errors at compile time, rather than runtime. Nevertheless, late binding does have Chapter 2 - to Building C# Applications arplace builders, Pa t Tw o among - The C#tool Pr ogr am m ingasLawell nguaas geCOM/.NET

interoperability. For example, using late binding, a .NET programmer is able to obtain a COM object's IDispatch reference. Let's examine how to dynamically Chapter 3 - C# Language Fundamentals invoke a method on the MiniVan class. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

The Activator - I nter facesClass and Collections

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

The System.Activator class is the key to .NET late binding. Beyond the methods inherited from Object, Chapter 8 - Advanced C# Type Const ruction Techniques Activator only defines a small set of members. Activator.CreateInstance() is one core method that creates Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s an instance of a type at runtime. This method has been overloaded numerous times to provide a good Chapter 9 - Under standing .NET Assem blies deal of flexibility. The simplest variation of the CreateInstance() member takes a valid Type variable that Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads describes the entity you wish to invoke: Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

// Create a type dynamically. public class LateBind Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) { Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) public static int Main(string[] args) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols { Chapter 16 - The Sy stem .I O Nam espace // Assume the CarLibrary is in the app directory. Chapter 17 - Data Access w ith Assembly a ADO.NET = null; Pa r t Fi ve - W e b try Appl ica ti ons and X ML W e b Se r vi ces Chapter 18 - ASP.NET Pages and Web Contr ols { a =Web Assembly.Load("CarLibrary"); } Chapter 19 - ASP.NET Web Applicat ions catch(FileNotFoundException e) Chapter 20 - XML Ser vices { Web Console.WriteLine(e.Message);} I ndex // Specify the fully qualified name of the Minivan type. List of Figur es Type miniVan = a.GetType("CarLibrary.MiniVan"); List of Tables // Create the Minivan on the fly. object obj = Activator.CreateInstance(miniVan); } } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

At this point, the "obj" variable is pointing to a MiniVan instance in memory that has been created indirectly using the Activator class. Now assume you wish to invoke the TurboBoost() method of the MiniVan. As you recall, this will set the state of the engine to "dead" and display an informational message box. The first step is to obtain a MethodInfo type for the TurboBoost() method using Type.GetMethod(). From a MethodInfo type, you are then able to call the method it describes using Invoke(). MethodInfo.Invoke() requires you to send in all parameters that are to be given to the method represented by MethodInfo. These parameters are represented by an array of System.Object types (as the parameters for a given method could be any number of various entities). Given that TurboBoost() does not require any parameters, you can simply pass "null" (meaning "this method has no parameters"):

public static int Main(string[] args) C# an d th e .N ET Plat f orm , Se con d Ed it ion { ISBN:1590590554 by Andr ew Tr oelsen // Use Assembly class to load the CarLibrary. Apr ess © 2003 (1200 pages) ... This compr ehensiv e text star ts w ith a brief ov er view of the // Get the MiniVan type. C# language and then quickly m oves to key technical and Type miniVan = a.GetType("CarLibrary.MiniVan"); ar chitectur al issues for .NET developer s. // Create the MiniVan on the fly. object obj = Activator.CreateInstance(miniVan); Ta ble o f // Con tGet en t s info for TurboBoost. MethodInfo miSecond = miniVan.GetMethod("TurboBoost"); C# and t he .NET Plat for m, Edition // Invoke method ('null' for no parameters). I ntr oduction mi.Invoke(obj, null); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m return 0; Chapter 1 - The Philosophy of .NET } Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - C# Fundamentals At this point youLanguage are happy to see Figure 11-4. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Figure Late bound method invocation Chapter 11 - 11-4: Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

To illustrate invoking a method that does take some number of parameters, assume you added the following new method to the MiniVan type of the CarLibrary.dll assembly:

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

// Quiet down the troops... public void TellChildToBeQuiet(string kidName, int shameIntensity) Chapter 16 - The Sy stem .I O Nam espace { Chapter 17 - Data Access w ith ADO.NET for(int i = 0 ; i < shameIntensity; i++) Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces MessageBox.Show("Be quiet {0} !!", kidName); Chapter 18 - ASP.NET Web Pages and Web Contr ols } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex TellChildToBeQuiet() takes two parameters. In this case, the array of parameters must be fleshed out as List follows: of Figur es List of Tables

// Now a method with params. object[] paramArray = new object[2]; paramArray[0] = "Fred"; // Child name. paramArray[1] = 4; // Shame Intensity. mi = miniVan.GetMethod("TellChildToBeQuiet"); mi.Invoke(obj, paramArray);

If you run this program, you will see four message boxes popping up, shaming young Fredrick. At this point you have seen the basic details regarding reflection services and late binding. As I am sure you might be guessing, System.Reflection defines additional functionality, which I will assume you will check out at your leisure. SOURCE CODE

The LateBinding project is included in the Chapter 11 subdirectory.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dAttributed th e .N ET Plat f orm , Se con d Ed it ion Understanding Programming by Andr ew Tr oelsen

ISBN:1590590554

The official metalanguage of the component object model (COM) is IDL. As you may know, IDL is used to Apr ess © 2003 (1200 pages) describe the set of types defined within a given classic COM Tothe describe these types in completely This compr ehensiv e text star ts w ith a brief ov server. er view of unambiguous terms, IDL makes use of "attributes," which are simply IDL C# language and then quickly m oves to key technical and keywords placed in square chitecturblock al issues for .NET developer brackets. A givenarattribute always applies to the s.very next thing. For example, when a COM programmer describes an interface, he or she is required to make use of the [uuid] and [object] attributes (at minimum). Parameters can be specified using the [in], [out], [in, out] ,and [out, retval] attributes. Here is Taan bleexample o f Con t en of tas classic COM interface, making use of various IDL attributes: C# and t he .NET Plat for m, Second Edition I ntr oduction

[object, uuid(4CB8B79A-E991-4AA4-8DB8-DD5D8751407D), oleautomation] Chapter 1 - The Philosophy of .NET interface IRememberCOM : IUnknown Chapter 2 Building C# Applications { Pa r t Tw o[helpstring("If - The C# Pr ogr am m ing La ngua ge me a string, I will change it...")] you send Chapter 3 HRESULT - C# Language Fundamentals TextManipulation([in] BSTR myStr, [out, retval] BSTR* newStr); Chapter } ; 4 - Obj ect -Or iented Pr ogr am ming w ith C# Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections Once a7COM type has been assigned various it can be discovered at runtime programmatically, Chapter - Callback I nter faces, Delegates, and attributes, Ev ents

or at design time usingC#various tools.ruction For example, notice how the TextManipulation() method has been Chapter 8 - Advanced Type Const Techniques assigned [helpstring] attribute, which is used Pa r t Thre e -a Pr ogr am m i ng w i th .N ET Assem bl ie s to

document how a given item is to be used. If you examine this COM method using the Visual Basic 6.0 Object Browser utility, you will see the custom [helpstring] is Chapter 9 - Under standing .NET Assem blies automatically extracted and displayed (Figure 11-5). Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Figure 11-5: Attributes in action

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

Attributes have proven to be so helpful, that C# (as well as other .NET-aware languages) has integrated I ndex them as official aspects of the language. Using attributes, you are able to extend the metadata generated List of Figur es by of a given List Tablescompiler with your custom information.

As you explore the .NET namespaces, you will find that there are many predefined attributes that you are able to make use of in your applications. Furthermore, you are free to build custom attributes to further qualify the behavior of your types. Keep in mind that .NET attributes (predefined or custom) are actually classes, all of which extend System.Attribute (contrast this to IDL, in which attributes are nothing more than simple keywords).

Working with Existing Attributes Like IDL, C# attributes are nothing more than annotations that can be applied to a given type (class, interface, structure, etc.), member (property, method, etc.), assembly, or module. As mentioned, the .NET library defines a number of predefined attributes in various namespaces. Many of the predefined attributes are most useful in the context of COM and .NET interoperability, debugging, and other "exotic" aspects of building managed code. Table 11-3 gives a snapshot of some (but by absolutely no means all) predefined attributes.

Table 11-3: A Tiny Sampling of Predefined System Attributes C# an d th e .N ET Plat f orm , Se con d Ed it ion

Predefined .NET Meaning in Life by Andr ew Tr oelsen Attribute Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the

CLSCompliant C# language Enforces all types in the assembly to the Common and thenthat quickly m oves to key technicalconform and Language (CLS). This is the .NET equivalent of the IDL ar chitectur al issues for Specification .NET developer s. [oleautomation] attribute. DllImport

Ta ble o f Con t en t s

Used to make calls to the native OS.

C# StructLayout and t he .NET Plat for m, Second UsedEdition to configure the underlying representation of a structure. I ntr oduction

Dispid

Specifies the DISPID for a member in a COM dispinterface.

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - The Philosophy ofMarks .NET a class or structure as being serializable. Serializable Chapter 2 - Building C# Applications

NonSerialized

Specifies that a given field in a class or structure is not serializable.

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - C# Language Fundamentals WebMethod Marks a method as being invokable via HTTP requests. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter As an example, 5 - Exceptions assume and that Objyou ect wish Lifetim toeassign the [Serializable] attribute to a given item. The Motorcycle

class that has assigned an attribute to the class itself, as well as a field named temp. As you can Chapter 6 follows - I nter faces and Collections see, C#7 attributes look very much like IDL and attributes, Chapter - Callback I nter faces, Delegates, Ev ents in that they are enclosed within square brackets: Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am can m i ng w i th saved .N ET Assem ie s // This class be to bl disk.

Chapter [Serializable] 9 - Under standing .NET Assem blies

public Motorcycle Chapter 10 class - Pr ocesses, AppDomains, Cont exts, and Threads { Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Fourbool - Le vehasRadioSystem; r a ging the .NET Libr a r ie s

hasHeadSet; Chapter bool 12 - Obj ect Ser ialization and the .NET Remoting Lay er hasSissyBar; Chapter bool 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) when you do, don't bother with this field. Chapter // 14 - But A Better Paint ing Fr amew or k ( GDI +) [NonSerialized] float weightOfCurrentPassengers;

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

}

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web 11-6), Pages and Contr ols these attributes are now specified within the type Using ildasm.exe (Figure you Web can see that Chapter 19 (note - ASP.NET Web Applicat ions metadata the "serializable" and "notserialized" metadata tags). Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 11-6: Attributes seen via ildasm.exe Be aware that if you wish to apply more than one attribute to a single type, simply separate each using a comma-delimited list or make use of multiple bracketed attributes stacked on top (or beside) one another: [AttOne, AttTwo, AttThree] public class SomeClass{...}

... C# an d th e .N ET Plat f orm , Se con d Ed it ion [AttOne] by Andr ew Tr oelsen [AttTwo] [AttThree] ess © 2003 (1200 pages) public class Apr SomeOtherClass{...}

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and chitectur al issues for .NET s. is on the lookout for the presence of these Now at this point,ardon't concern yourself withdeveloper who or what

attributes. Just understand that attributed programming allows you to extend an assembly's metadata with annotations.

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d thAttributes e .N ET Plat f orm , Se con d Ed it ion Building Custom by Andr ew Tr oelsen

ISBN:1590590554

C# (as well as other .NET-aware allows you to build custom attributes. Recall that attributes are Apr ess © 2003 (1200languages) pages) in fact a class derived from System.Attribute. Thus, applied This compr ehensiv e text star ts w ith awhen brief we ov er view of the the[Serializable] attribute to the Motorcycle class,C# welanguage in fact applied an instance of the System.Serializable type. From a design point of and then quickly m oves to key technical and issues for s. to some other type. In the world of OOP, this view, an attribute ar ischitectur a class al instance that.NET candeveloper be applied approach is termed aspect-oriented programming . TaThe ble ofirst f Con step t ento t sbuilding your custom attribute is to create a new class deriving from System.Attribute. The

naming convention you C# and t he .NET Plat for m, should Secondfollow Editionis to suffix "-Attribute" to the new type. Here is a basic custom attribute named VehicleDescriptionAttribute that allows a programmer to inject a string into the type metadata I ntr oduction describing a rparticular Pa r t One - I nt oduci ng C#automobile: a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

Chapter // A custom 2 - Building attribute. C# Applications Pa public r t Tw o - The class C# Pr VehicleDescriptionAttribute ogr am m ing La ngua ge

: System.Attribute { Chapter 3 - C# Language Fundamentals Chapter private 4 - Obj ect string -Or iented description; Pr ogr am ming w ith C# public string Chapter 5 - Exceptions and Desc Obj ect Lifetim e Chapter { 6 - I nter faces and Collections get {I nter return description; } Chapter 7 - Callback faces, Delegates, and Ev ents set { description = value; } Chapter 8 - Advanced C# Type Const ruction Techniques } Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s public VehicleDescriptionAttribute(string desc) Chapter 9 - Under standing .NET Assem blies { description = desc;} Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads public VehicleDescriptionAttribute(){ } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing } Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter Building a Bet ter Win dow ( Int roducin g Window For ms)internal string (description) that can be As you 13 can- see, VehicleDescriptionAttribute maintains a sprivate Chapter 14 - Ausing BetteraPaint ing Fr amew or k ( GDI manipulated custom constructor and+a) named property (Desc). Now assume you wish to apply this Chapter attribute 15to- aPrnew ogr am class mingnamed with Windows Winnebago. Form Notice s Contr ols how the constructor signature determines the exact

syntax of attribute: Chapter 16 the - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t FiThis ve - Wclass e b Appl ica ti ons and X ML W e b attributes. Se r vi ces // using a custom

Chapter 18 - ASP.NET Web Pages and Web Contr ols long, slow but feature rich auto")] [VehicleDescriptionAttribute("A very Chapter public 19 class - ASP.NET Winnebago Web Applicat ions

{ Chapter 20 - XML Web Ser vices I ndex

public Winnebago(){ }

// esVarious methods... List of Figur } of Tables List Now, let's see your new type in action. The VehicleDescriptionAttribute attribute (or any attribute) makes use of parentheses to pass arguments to the constructor of the associated System.Attribute-derived class. As you have already seen, one of the constructors does indeed take a string parameter. Now, using ildasm.exe, you find your string message has been injected into the related metadata (Figure 11-7).

Figure 11-7: Metadata value

If you look at the C# CILan itself, custom attributes d thyou e .Nnotice ET Platthat f orm , Se con d Ed it ionare marked using the CIL instruction ".custom." ISBN:1590590554

by Andr ew Tr oelsen

.class publicAprauto ansi beforefieldinit Winnebago ess © 2003 (1200 pages) extends [mscorlib]System.Object This compr ehensiv e text star ts w ith a brief ov er view of the { C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. .custom instance void CustomAtt.VehicleDescriptionAttribute::.ctor(string) ... Ta}ble// o f end Con t en oft s class Winnebago C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Attribute Shorthand Notation - The Philosophy of .NET

Chapter 1

Chapter - Building C# offer Applications The C#2 language does a shorthand notation for assigning an attribute to a given item. If the name of Pa r t Tw o - The attribute C# Pr ogrclass am m ing La ngua ge have your custom does indeed

a "-Attribute" suffix, you are allowed to omit this same suffix in

Chapter 3 base: - C# Language Fundamentals the code Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

Exceptions and Obj ect Lifetim e // This - shortcut only works if the class is named VehicleDescriptionAttribute.

Chapter 6 - I nter faces and Collections [VehicleDescription("A very long, slow but feature rich auto")] Chapter 7 class - Callback I nter faces, Delegates, and Ev ents public Winnebago Chapter 8 {

- Advanced C# Type Const ruction Techniques

Pa r t Threpublic e - Pr ogr am m i ng w i th .N ET } Assem bl ie s Winnebago(){

Chapter // 9 - Various Under standing .NET Assem blies methods... Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Be aware aialization courtesyand provided by Remoting C#. Not allLay .NET-enabled languages support this feature. Chapter 12 that - Objthis ect is Ser the .NET er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion RestrictingC#Attribute Usage ISBN:1590590554

by Andr ew Tr oelsen

Currently, the custom attribute haspages) no mechanism to prevent a developer from making illogical aspect Apr ess © 2003 (1200 specifications. ForThis example, the following is syntactically butofsemantically out of whack: compr ehensiv e text star ts w ith a briefcorrect, ov er view the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. // Syntactically OK, but an odd use of this custom attribute... public class Winnebago { Ta ble o f Con t en t s [VehicleDescriptionAttribute] // Calls default ctor of attribute class. C# and t he .NET Plat for m, Second Edition public void TurnOnRadio() I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m } Chapter 1 - The Philosophy of .NET } Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter Ideally,3it would - C# Language be nice toFundamentals enforce the fact that this particular custom attribute should only be allowed to

modify 4a class structure), else. If you wish to constrain your attributes in this way, Chapter - Obj (and ect -Orperhaps iented Praogr am ming wbut ith nothing C# you need make use and of the enumeration: Chapter 5 to - Exceptions ObjAttributeTargets ect Lifetim e Chapter 6

- I nter faces and Collections

Chapter // This 7 - enumeration Callback I nter faces, is Delegates, used to and control Ev ents how a custom attribute can be applied.

public AttributeTargets Chapter 8 enum - Advanced C# Type Const ruction Techniques {r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Pa Assembly, Class, Chapter All, 9 - Under standing .NET AssemConstructor, blies Enum, Event, Field, Chapter Delegate, 10 - Pr ocesses, AppDomains, Cont exts, and Threads Method, Module, Chapter Interface, 11 - Type Reflection, Late Binding, and Parameter, Attr ibute- Based Pr ogramm ing Pa r t FourProperty, - Le ve r a ging ReturnValue, the .NET Libr a r ie s Struct

} Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

These values are passed as a parameter to the AttributeUsage attribute. This pre-defined attribute is used by

Chapter - Pr ogrto amenforce ming with Form s Controf olsa custom attribute. The first parameter is an OR-ing the C# 15 compiler theWindows correct application Chapter 16 The Sy stem .I O Nam espace together of members from the AttributeTarget enumeration. The second (optional) parameter is typically a Chapter - Data Access w ith ADO.NET named17 argument (AllowMultiple), which specifies if the custom attribute can be used more than once on the Pa r t Fi ve - W eThe b Appl ica(optional) ti ons and X ML W e b parameter Se r vi ces same type. final Boolean

determines if the attribute should be inherited by derived

Chapter 18 - ASP.NET Web Pages and Web Contr ols classes. Chapter 19 - ASP.NET Web Applicat ions

Thus, you now configure Chapter 20 -can XML Web Ser vices the VehicleDescriptionAttribute to apply only to classes or structures as follows: I ndex

//ofThis time, we are using the predefined AttributeUsage attribute List Figur es //ofto qualify our custom attribute! List Tables [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] public class VehicleDescriptionAttribute : System.Attribute { ... }

With this, if a developer attempted to apply the [VehicleDescription] attribute on anything other than a class or structure, they are issued a compile-time error. Note Always get in the habit of explicitly marking the usage flags for any custom attribute you may create, as not all .NET programming languages honor the use of unqualified attributes!

an d Module-) th e .N ET Plat f Level orm , Se con d Ed it ion Assembly- C# (and Attributes ISBN:1590590554

by Andr ew Tr oelsen

It is also possibleApr to apply attributes on all types within a given module, or all modules within a given ess © 2003 (1200 pages) assembly using the [assembly: ] and [module: you wish to ensure that every This compr ehensiv e text star ts ]wtags. ith a For briefexample, ov er view assume of the type defined within your assembly is compliant with the CLS. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

// Enforce CLS compliance! using System; Ta ble o f Con t en t s [assembly:System.CLSCompliantAttribute(true)] C# and t he .NET Plat for m, Second Edition namespace MyAttributes I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m [VehicleDescriptionAttribute("A very long, slow but feature rich auto")] Chapter public 1 - The Philosophy of .NET class Winnebago Chapter { 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge } public Winnebago(){ Chapter } 3 - C# Language Fundamentals Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# } Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections If we now a bit ofI nter code that Delegates, falls outside Chapter 7 add - Callback faces, andthe Ev CLS ents specification: Chapter 8

- Advanced C# Type Const ruction Techniques

// Ulong withbl the Pa r t Thre e - Prtypes ogr am mdon't i ng w i th jive .N ET Assem ie s

CLS. public class Winnebago Chapter 9 - Under standing .NET Assem blies { Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads } Chapter public 11 - Type Winnebago(){ Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing public ulong notCompliant; Pa r t Four - Le ve r a ging the .NET Libr a r ie s } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

you are issued a compiler error. To be sure, if you are building a .NET assembly that is to be used by

Chapter 15 -.NET Pr ogrlanguages, am ming withthe Windows Form s Contr ols numerous [CLSCompliant] attribute is extremely helpful. Chapter 16 - The Sy stem .I O Nam espace

Note .NET [CLSCompliant] Chapter 17 The - Data Access w ith ADO.NETattribute can be applied to any item defined by the AttributeUsage enumeration. Thus, only wish to selectively Pa r t Fi ve - W e b Appl ica ti ons andifXyou ML W e b Se r vi ces

mark specific items as CLS compliant, you

do so.Web Pages and Web Contr ols Chapter 18 may - ASP.NET Chapter 19 - ASP.NET Web Applicat ions

Notice that the [assembly:] syntax is used to inform the compiler that the CLSCompliant attribute must be applied to the assembly level, and not (for example) a single type within the assembly. One fact to be I ndex aware of is that the [assembly:] and [module:] modifiers must be placed outside a namespace definition. Chapter 20 - XML Web Ser vices List of Figur es List of Tables

Visual Studio .NET AssemblyInfo.cs File Visual Studio .NET projects define a file called AssemblyInfo.cs. This file is a handy place to put attributes that are to be applied at the assembly level. Table 11-4 lists some assembly-level attributes to be aware of. Table 11-4: Select Assembly-level Attributes

Assembly-level Life C# anAttribute d th e .N ET Plat f orm ,Meaning Se con d Edin it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

AssemblyCompanyAttribute

ISBN:1590590554

Holds basic company information.

AssemblyConfigurationAttribute This compr ehensiv e text starBuild ts w ithinformation, a brief ov ersuch view of asthe "retail" or "debug." C# language and then quickly m oves to key technical and

AssemblyCopyrightAttribute anys.copyright information for the product or ar chitectur al issues for .NET Holds developer assembly. AssemblyDescriptionAttribute

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntrAssemblyInformationalVersionAttribute oduction

A friendly description of the product or modules that make up the assembly. Additional or supporting version information, such as a product version number.

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or commercial m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

AssemblyProductAttribute

Pa rAssemblyTrademarkAttribute t Tw o - The C# Pr ogr am m ing La ngua ge

Product information. Trademark information.

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

AssemblyCultureAttribute

AssemblyKeyFileAttribute Chapter 6 - I nter faces and Collections

Information on what cultures or languages the assembly supports. Specifies the name of the file containing the key pair

Chapter 7

used to sign the assembly (i.e. establish a shared - Callback I nter faces, Delegates, and Ev ents

Chapter 8

name). - Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

AssemblyKeyNameAttribute

Specifies the name of the key container. Instead of placing a key pair in a file, you can store it in a key Chapter 10 - Pr ocesses, AppDomains, Cont exts,container and Threads in the CSP. If you choose this option, this Chapter 11 - Type Reflection, Late Binding, andattribute Attr ibute-will Based Pr ogramm ing of the key container. contain the name Chapter 9

- Under standing .NET Assem blies

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

AssemblyOperatingSystemAttribute Information Chapter 12 - Obj ect Ser ialization and the .NET Remoting Layon er which operating system the assembly was built to support.

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDIInformation +) AssemblyProcessorAttribute on which processors the assembly was Chapter 15 - Pr ogr am ming with Windows Form built s Contr to ols support. Chapter 16 - The Sy stem .I O Nam espace

AssemblyVersionAttribute

Chapter 17 - Data Access w ith ADO.NET

Specifies the assembly's version information, in the format .

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Platat f orm , Se con d Ed it ion Reflecting on Attributes Runtime by Andr ew Tr oelsen

ISBN:1590590554

As you have seen, itess is possible to obtain Apr © 2003 (1200 pages) attributes at runtime using the Type class. The logic behind doing so should be no surprise at this point: This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and issues for .NET developer s. // Reflectingar chitectur on theal custom attributes... public class AttReader { Ta ble o f Con t en t s public static int Main(string[] args) C# and t he .NET Plat for m, Second Edition { I ntr oduction // Get the Type of Winnebago. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Type t = typeof(Winnebago); Chapter 1 - The .NET //Philosophy Get allof attributes in the assembly. Chapter 2 - Building C# Applications object[] customAtts = t.GetCustomAttributes(false); Pa r t Tw o - The C# ogr amall m ing info. La ngua ge // PrList Chapter 3 - C#Console.WriteLine("***** Language Fundamentals Value of VehicleDescriptionAttribute *****\n") Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# foreach(VehicleDescriptionAttribute v in customAtts) Chapter 5 - Exceptions and Obj ect Lifetim e Console.WriteLine("-> {0}\n", v.Desc); Chapter 6 - I nter return faces and 0;Collections Chapter } 7 - Callback I nter faces, Delegates, and Ev ents } Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

As the name implies, Type.GetCustomAttributes() returns an array (of System.Object types) that represent all th attributes applied to the member represented by the Type. From this array you are able to determine a specific Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing attribute on the fly. What you do with this information is (of course) up to you. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 Be - Obj ect Ser ialization andAttribute.GetCustomAttribute() the .NET Remoting Lay er Note aware that the static method allows you to obtain information for a Chapter 13 specific - Building a Bet ter Win dow ( Intan roducin s For ms) attribute, rather than arraygofWindow all attributes on a given type. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

SOURCE The CustomAtt and AttReader applications are included under the Chapter 11 subdirectory Chapter 15 - Pr ogr am ming with Windows Form s Contr ols CODE Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se conand d Ed it ion Putting Reflection, Late Binding, Custom Attributes in ISBN:1590590554 by Andr ew Tr oelsen PerspectiveApr ess © 2003 (1200 pages) e text star ts wwill ith aever briefneed ov er view of the At this point, you This may compr reallyehensiv be wondering if you to make use of reflection, late binding, or C# language and then quickly m oves to key technical and custom attributes. To be sure, these topics (while fascinating) can seem a bit on the academic side of ar chitectur al issues for .NET developer s. programming (which may or may not be a bad thing, depending on your point of view). To help map these topics to a real-world situation, we need a solid example. Ta ble o f Con t en t s

Assume for the moment that you are on a programming team that is building an application that has the following requirement:

C# and t he .NET Plat for m, Second Edition I ntr oduction

Pa r t One I nt r oduci ng C#bea nd the .NETby P lathe tf oruse m The- product must extendible

Chapter 1

of additional third party tools.

- The Philosophy of .NET

So, what heck does that mean? Well, consider Visual Studio .NET. When the VS .NET team was Chapter 2 the - Building C# Applications constructing application, it left various Pa r t Tw o - Thethis C# Pr ogr am m ing La ngua ge

hooks that allow other software vendors to snap in custom modules into the environment. Obviously the VS .NET team had no way to set references to external .NET Chapter 3 - C# Language Fundamentals assemblies it had not programmed (thus, no early binding)! However, to provide an open-ended model, the Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# VS .NET team had to provide a mechanism by which other individuals (including yourself) could plug in new Chapter 5 - Exceptions and Obj ect Lifetim e behaviors. Chapter 6

- I nter faces and Collections

Chapter 7 - Callback I nter faces, Delegates, and Ev ents Extendability is an awesome benefit, as third-party vendors can build (and profit from) custom software Chapter 8 We - Advanced C# developers Type Const ruction modules. benefit as as well,Techniques in that we are not required to by a brand-new (full price) IDE Pa r t Threto e gain - Pr ogr am m i ng w i thfunctionality. .N ET Assem bl ie s how simply augmentative So,

is it that tools such as VS .NET (and numerous other

Chapter applications) 9 - Under havestanding been programmed .NET Assem blies for extendability? Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

As you would guess, there are many ways to skin the proverbial cat. First, a tool built for extendability must provide some input vehicle to allow the user to specify the module to plug in (a dialog box, command line Pa r t Four - Le ve r a ging the .NET Libr a r ie s flag, or whatnot). Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13the - Building a Betinter Win dowmust ( Int roducin g Window s For ms) Second, application question be able to determine if the module in question supports the correct Chapter 14 - AtoBetter Paint inginto Fr amew or k ( GDI + ) This advertisement of functionality could be provided via a functionality be plugged the environment. Chapter - Pr ogr am with Windows Form s Contr ols specific15interface or ming custom attribute. The key, however, is to make the entity as generic as possible. Given Chapter 16 - The Synothing stem .I O but Namadvertisements, espace that attributes are they seem like the most logical choice. Chapter 17 - Data Access w ith ADO.NET

Finally, the application able Pa r t Fi ve if- W e bextendible Appl ica ti ons and X ML is We b Seto r videtermine ces

the type in question is compatible with its needs, it will need to obtain an interface reference (again, think about the polymorphic nature of interface-types) to Chapter 18 - ASP.NET Web Pages and Web Contr ols trigger the real functionality of the snap-in. Once the snap-in has been loaded and used, the assembly may Chapter 19 - ASP.NET Web Applicat ions be cached for further use or discarded (at the whim of the extendible application). Chapter 20 - XML Web Ser vices

I ndex Simply put, if the extendible application has been preprogrammed to query for specific interfaces (and/or List of Figur esit is able to determine at runtime if the item in question is worthy of activation. Once this attributes), List of Tables test has been passed, the type in question may support additional interfaces that provide a verification

polymorphic fabric to their functionality. This same generalized approach is the exact approach taken by the VS .NET team, and despite what you may be thinking, is not at all difficult!

Building a Custom Snap-In Consumer In the sections that follow, I will walk through a complete example that illustrates the process of building an extendible Windows Forms application that can be augmented by the functionality of additional snap-in *.dll assemblies. What I will not do at this point is comment on the process of programming Windows Forms applications (Chapters 13-15 will tend to that chore). So, if you are not familiar with the process of building Windows Forms applications, feel free to simply open up the supplied sample code and follow along (or build a console-based alternative). To serve as a roadmap, our extendible application entails the following assemblies: CommonSnappableTypes.dll: This assembly contains type definitions that will be implemented by each snap-in as well as referenced by the extendible Windows Forms application.

CSharpSnapIn.dll: A simple snap-in written in C#, which leverages the types of C# an d th e .N ET Plat f orm , Se con d Ed it ion CommonSnappableTypes.dll.

ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) VbNetSnapIn.dll: A simple snap-in written in VB .NET, which leverages the types of This compr ehensiv e text star ts w ith a brief ov er view of the CommonSnappableTypes.dll. C# language and then quickly m oves to key technical and ar chitecturThis al issues for .NET developer s. MyPluggableApp.exe: Windows Forms application will be the entity that may be extended by the

functionality of each snap-in. Again, remember! This application will make use of reflection, late binding, and custom attributes to dynamically gain the functionality of assemblies it has no Ta ble o f Con t en t s foreknowledge about. C# and t he .NET Plat for m, Second Edition I ntr oduction

Building the Common Snappable Types

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Our first order of business is to create an assembly that contains the types that a given snap-in must Building C# Applications leverage to- be plugged into our expandable Windows Forms application. If you are following along, create a Pa r t Tw o - The C# Pr ogr am m ing La ngua ge new C# code library (CommonSnappableTypes) that defines the following two types: Chapter 2 Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

namespace CommonSnappableTypes - Exceptions and Obj ect Lifetim e { Chapter 6 - I nter faces and Collections public interface IUseMyFunctionality Chapter { 7 void - Callback I nter faces, DoIt(); } Delegates, and Ev ents Chapter 5

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre[AttributeUsage(AttributeTargets.Class)] e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter public 9 - Underclass standingSnappableAttribute .NET Assem blies : System.Attribute Chapter { 10 public - Pr ocesses, AppDomains, Cont exts, and Threads SnappableAttribute(){} } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing } Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Here, the offers sa For public Chapter 13 CommonSnappableTypes.dll - Building a Bet ter Win dow ( Int assembly roducin g Window ms) interface (IUseMyFunctionality) that

provides for or allk snap-ins Chapter 14a- polymorphic A Better Paintinterface ing Fr amew ( GDI + ) that can be consumed by the extendible Windows Forms

application. Of course, as this example is purely illustrative in nature, we supply a single method named DoIt(). To map this to a more real world example, imagine an interface (or set of interfaces) that allows the Chapter 16 - The Sy stem .I O Nam espace snapper to generate scripting code, render an image onto the application's toolbox, or integrate into the Chapter 17 - Data Access w ith ADO.NET main menu. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Webtype Pages Web Contr ols that will be applied on any class type that wishes to be The SnappableAttribute is aand custom attribute Chapter 19 in- to ASP.NET Web Applicat ions snapped the container. Again, the theory here is that if (and only if) a type has been adorned with the Chapter 20 - XML Web Ser vices [Snappable] attribute, it will support the functionality of the IUseMyFunctionality type. I ndex

Building the C# Snap-In

List of Figur es List of Tables

Next up, we need to create a concrete type that supports the [Snappable] attribute and implements the IUseMyFunctionality interface. Again, to focus on the overall design of an extendible application, a trivial type is in order. Assume the following class type is defined in a new C# code library named CSharpSnapIn. Given that the contained class type must make use of the types defined in CommonSnappableTypes, be sure to set a reference to this binary (as well as System.Windows.Forms.dll to display a noteworthy message). This being said, here is the code: using System; using CommonSnappableTypes; using System.Windows.Forms; namespace CSharpSnapIn { // This type is Snappable into other containers. [Snappable] public class TheCSharpSnapIn : IUseMyFunctionality

{ C# an dTheCSharpSnapIn(){} th e .N ET Plat f orm , Se con d Ed it ion public ISBN:1590590554 by Andr ew Tr oelsen void IUseMyFunctionality.DoIt() Apr ess © 2003 (1200 pages) { ThisMessageBox.Show("You compr ehensiv e text star ts w ithhave a briefjust ov er view of the used the C# snap in!"); C# language and then quickly m oves to key technical and } ar chitectur al issues for .NET developer s.

} } Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

Note that the TheCSharpSnapIn type has been marked with the [SnappableAttribute] type to flag itself as a

I ntr oduction type that can be plugged into the extendible application you have yet to build. Given that it has advertised its Pa r t One -for I ntsnap-in-ability, r oduci ng C# a nd the .NET P la tf or m support you also implement

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

the IUseMyFunctionality.

Building the VB .NET Snap-In

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals Now, to simulate the role of a third-party vendor who prefers VB .NET over C#, create a new VB .NET code

Chapter 4 - Obj ect -Or iented Pr ogr am ming ith C#external assemblies as the previous CSharpSnapIn project. library (VbNetSnapIn) that references thewsame Chapter 5 Exceptions and Obj ect Lifetim e The code is (again) straightforward: Chapter 6

- I nter faces and Collections

Chapter 7

Callback I nter faces, Delegates, and Ev ents Imports - System.Windows.Forms Chapter 8 - CommonSnappableTypes Advanced C# Type Const ruction Techniques Imports Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Public Class VbNetSnapIn ChapterImplements 9 - Under standing .NET Assem blies IUseMyFunctionality Chapter Public 10 - Pr ocesses, AppDomains, Cont exts, and Threads Sub DoIt() Implements IUseMyFunctionality.DoIt Chapter 11 - MessageBox.Show("You Type Reflection, Late Binding, have and Attr ibute- used Based Pr ogramm just the VB ing .NET snap in!") Pa r t Four - LeSub ve r a ging the .NET Libr a r ie s End Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er End Class Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Not too much to say here! This assembly contains another class type that is [Snappable] and implements the functionality of the IUseMyFunctionality interface. Do notice that VB .NET applies attributes using angled Chapter 17 - Data Access w ith ADO.NET brackets (< >) rather than square brackets ([ ]). Chapter 16 - The Sy stem .I O Nam espace

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Building the Extendable Windows Forms Application

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

Now, on to the good stuff! The final piece of the extendability puzzle is to create the Windows Forms application that allows the user to select a snap-in using a standard Windows Open dialog box (represented List of Figur es by the System.Windows.Forms.OpenFileDialog type). Before I dive into the details, set a reference to the List of Tables CommonSnappableTypes.dll assembly, but not the CSharpSnapIn.dll or VbNetSnapIn.dll binaries! Remember the goal of this application is to make use of late binding and reflection to determine the "snapability" of independent binaries created by third-party vendors (thus, there is no hope of early binding). I ndex

Again, I won't bother to examine all the details of Windows Forms development at this point in the game. However, assuming you have placed a MainMenu type onto the Form template, we will launch an Open File dialog via a custom "Tools | Snap In Something..." menu item (Figure 11-8).

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

Building C# Applications Figure- 11-8: Input for a snap-in module

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter C# Language Fundamentals Behind3the- Click event handler for this menu item (which may be created simply by double-clicking the Chapter 4 - from Obj ect -Ordesign-time iented Pr ogreditor), am ming our w ithgoal C# is to extract the path to the selected file, and using this menu item the Chapter path, perform 5 - Exceptions the following and Obj tasks: ect Lifetim e Chapter 6

- I nter faces and Collections

Check- to see if the user-selected assembly has any types marked with the [Snappable] attribute (by Callback I nter faces, Delegates, and Ev ents reflecting over custom attributes).

Chapter 7 Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre - Pr ogr amthat m i ng w i thsupport .N ET Assem bl ie s For eeach type does the [Snappable]

aspect, obtain the IUseMyFunctionality interface and

Chapter - Under Assem blies call9 the DoIt()standing method .NET (via late binding). Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Here is11 the- relevant code behind the Form type: Chapter Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 class - Obj ect MainForm: Ser ialization and the .NET Remoting Lay er public System.Windows.Forms.Form Chapter { 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter ... 14 - A Better Paint ing Fr amew or k ( GDI + )

| Windows Snap InForm Something..." event handler. Chapter // 15 - The Pr ogr"amTools ming with s Contr ols mnuToolsSnapIn_Click(object sender, System.EventArgs e) Chapter private 16 - The Syvoid stem .I O Nam espace Chapter { 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b if(myOpenFileDialog.ShowDialog() Appl ica ti ons and X ML W e b Se r vi ces

== DialogResult.OK) { Chapter 18 - ASP.NET Web Pages and Web Contr ols string pathToAsm = myOpenFileDialog.FileName; Chapter 19 - ASP.NET Web Applicat ions if(TryToUseSnapIn(pathToAsm) == false) Chapter 20 - XML Web Ser vices MessageBox.Show("This snap-in is bogus!"); I ndex } List of Figur es } List of Tables private bool TryToUseSnapIn(string path) { // Load the specified assembly. bool foundSnapIn = false; Assembly theSnapInAsm = Assembly.LoadFrom(path); // Get all types in assembly. Type[] theTypes = theSnapInAsm.GetTypes(); // Get custom attributes for each type, and // see if one of them is [Snappable] for(int i = 0; i < theTypes.Length; i++) { object[] theAtts = theTypes[i].GetCustomAttributes(false); for(int j = 0; j < theAtts.Length; j++) { if(theAtts[j] is SnappableAttribute) {

// It is snappable! C# an d th e .N ET // Plat Get f orm ,the Se con d Ed it ion IUseMyFunctionality interface. by Andr ew Tr oelsen foundSnapIn = true; ISBN:1590590554 Apr ess © 2003 (1200 object pages) o = This compr ehensiv e text star ts w ith a brief ov er view of the theSnapInAsm.CreateInstance(theTypes[i].FullName); C# language and then quickly m oves to key technical and IUseMyFunctionality itfUseMe; ar chitectur al issues for .NET developer s.

itfUseMe = o as IUseMyFunctionality; if(itfUseMe != null) { Ta ble o f Con t en t s itfUseMe.DoIt(); C# and t he .NET Plat for m, Second Edition lstBoxSnapIns.Items.Add(theTypes[i].FullName); I ntr oduction } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m } Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications } Pa r t Tw o - The C# Pr ogr am m ing La ngua ge return foundSnapIn; Chapter } 3 - C# Language Fundamentals Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# } Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

This really summarize allConst the information presented over the course of this chapter. Note how the Chapter 8 -does Advanced C# Type ruction Techniques application is able to determine a bogus assembly (i.e., an assembly that contains no type that is Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s [Snappable]-aware) via the Boolean value returned from TryToUseSnapIn() helper function. Within this Chapter 9 - Under standing .NET Assem blies helper method, we first leverage the Assembly.LoadFrom() Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads method to load the binary based on the user specified path. Next, we iterate over each type and check to see if the item has been adorned with the Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing [Snappable] attribute. If so, we set our Boolean flag and trigger the IUseMyFunctionality.DoIt() Pa r t Four - Le ve r a ging the .NET Libr a r ie s implementation of the given snap-in (to return the correct value to the caller). Finally, for good measure, we Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er log the name of the snap-in within the Form's ListBox type. Figure 11-9 shows the result. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 11-9: Snapping in external assemblies While this is a far cry from building real-world extendible applications, you should have a better understanding how such a program may be constructed. In a nutshell, building an extendible application demands the creation of an assembly that defines types implemented by the third-party snap-in vendor and queried for by the extendible application itself. If you wish, you can think of the CommonSnappableTypes.dll as the middleman that bridges the gap between snap-ins and snappee. SOURCE CODE

The CommonSnappableTypes, CSharpSnapIn, VbNetSnapIn, and MyPluggableApp applications are included under the Chapter 11 subdirectory.

Note If you are interested in learning how to build custom snap-ins for VS .NET, check out Writing Addins for Visual Studio .NET (Smith, Apress 2002).

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Summary

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

Reflection is a very aspect of a robust OO environment. In the world of .NET, the keys to Aprinteresting ess © 2003 (1200 pages) reflection servicesThis revolve around the System.Type namespace. As you compr ehensiv e text star ts w ith aclass brief and ov erthe viewSystem.Reflection of the have seen, reflection is the process of placing a type under the magnifying glass at runtime to understand C# language and then quickly m oves to key technical and ar chitectur issues for of .NET developer the "who, what, where, why,aland how" a given item.s. Late binding is the process of creating a type and invoking its members without foreknowledge of the Taspecific ble o f Con names t en t sof said members. As shown during our extendible application example, this is a very

powerful used by tool Edition builders as well as tool consumers. C# and t hetechnique .NET Plat for m, Second I ntr oduction

This chapter also examined the role of attribute-based programming. When you adorn your types with attributes, the result is the augmentation of the underlying assembly metadata. While you may never find Chapter 1 - The Philosophy of .NET yourself in the position of absolutely having to build custom attributes, you are bound to find the predefined Chapter 2 - Building C# Applications attributes invaluable, especially when building a bridge between your classic COM servers and .NET Pa r t Tw o - The C# Pr ogr am m ing La ngua ge assemblies, or leveraging .NET serialization services and the .NET Remoting layer. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Part Four: Leveraging the .NET ISBN:1590590554 Libraries by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Chapter List This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Chapter 12: Object Serialization and the .NET Remoting Layer Ta ble o f Con t en t s

Chapter 13: Building a Better Window (Introducing Windows Forms)

C# and t he .NET Plat for m, Second Edition

I ntr oduction Chapter 14: A Better Painting Framework (GDI+) Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 15:Philosophy Programming with Windows Forms Controls Chapter 1 - The of .NET Chapter 2

- Building C# Applications

Chapter 16: The System.IO Namespace

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - C# Fundamentals Chapter 17:Language Data Access with ADO.NET Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Chapter C# 12: Object SerializationISBN:1590590554 and the .NET by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) Remoting Layer

Overview

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Developers who are new to the .NET platform naturally assume that .NET is all about building InternetTacentric ble o f Con applications t en t s (given the term ".NET"). As you have already seen however, this is simply not the

case. fact, the construction of Edition Web-centric programs is simply one tiny (but quite well-touted) aspect of C# and In t he .NET Plat for m, Second theoduction .NET platform. In this same vein of misinformation, many new .NET developers tend to assume that I ntr XML Web services are only Pa r t One - I nt r oduci ng C#the a nd the way .NETtoP interact la tf or m

with remote objects. Again, this is not true. The .NET

platform numerous devoted to the creation of traditional distributed applications, Chapter 1 provides - The Philosophy of namespaces .NET which have whatsoever with XML Web services (or Web applications). In short, using .NET Chapter 2 - nothing Building to C#do Applications you are peer-to-peer distributed applications Pa r t Tw o -able The to C#build Pr ogr am m ing La ngua ge

that have nothing to do with HTTP or XML (if you so choose). As you will see over the course of this chapter, the .NET Remoting architecture is a managed Chapter 3 - C# Language Fundamentals replacement for classic DCOM. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 goal - Exceptions and Obj Lifetim e a critical remoting-centric topic: object serialization. Simply put, The first of this chapter isect to describe Chapter 6 I nter faces and Collections serialization is the act of persisting an object's state data to a given location (e.g., a memory stream, Chapter 7 file, - Callback I nter faces, Delegates, and Evhand, ents is the process of reading the persisted data from physical etc.). Deserialization, on the other Chapter 8 - Advanced C# Type Consttype ruction Techniques said location and recreating a new based on the preserved stateful values. As you might imagine, the Pa r t Thre - Pr ogr am m i ngiswcritical i th .N ET Assem bl ie s ability toeserialize types when attempting

to copy an object to a remote machine (e.g., marshal-

Chapter 9 -Understand, Under standing .NET Assem by-value). however, that blies serialization is quite useful in its own right, and will likely play a role in Chapter many of 10your - Pr.NET ocesses, applications AppDomains, (distributed Cont exts,orand not). Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Once you have the .NET .NETLibr serialization Pa r t Four - Le ve r aseen ging the a r ie s

protocol in action, the next goal is to examine the low-level grunge used by the CLR to move information between application boundaries. Along the way, you will Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er come to understand the numerous terms used when discussing .NET Remoting, such as proxies, Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) channels, marshaling by reference (as opposed to by value), server-activated (versus client-activated) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) objects, and so forth. With these background elements complete, the remainder of this chapter offers Chapter 15 - Pr ogr am ming with Windows Form s Contr ols numerous code examples that illustrate the process of building distributed systems using the .NET Chapter 16 - The Sy stem .I O Nam espace platform. Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N Plat f orm , Se con d Ed it ion Object Persistence inETthe .NET Framework ISBN:1590590554

by Andr ew Tr oelsen

Object serialization one of the key underlying technologies used by the .NET Remoting layer. Simply Apris ess © 2003 (1200 pages) put,serialization isThis thecompr term ehensiv describing thestar process theofstate e text ts w ith of a converting brief ov er view the of an object to a linear sequence of data. This data sequence contains all necessary information C# language and then quickly m oves to key technical and needed to reconstruct (or ar chitectur issuesfor foruse .NET developer s. deserialize) the state of thealobject later. The .NET serialization services are quite sophisticated: When a given object is serialized to a stream, any associated object references required by the root object are automatically serialized as well. For example, when a derived class is serialized, each serializable Taobject ble o f in Con t s of inheritance is able to write its own custom state data into the data stream. thet en chain C# and t he .NETif Plat for m,type Second Edition Furthermore, a given contains serializable member variables, the member variables themselves I ntr oduction also automatically participate in the serialization process. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Once a1set- of objects has been saved to a stream, the data pattern can be relocated as necessary. For Chapter The Philosophy of .NET example, serialized an object graph into a memory location using the Chapter 2 imagine - Buildingyou C# have Applications System.IO.MemoryStream type. Pa r t Tw o - The C# Pr ogr am m ing LaThis nguastream ge

could be forwarded to a remote computer, the Windows clipboard, burned to a CD, or simply written to a physical file. The object itself does not care where it is Chapter 3 - C# Language Fundamentals stored. All that matters is the fact that this stream of 1s and 0s (or, depending on your choice of formatter, Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# XML elements) correctly represents the state of the serialized objects. Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6 The - I nter faces andnamespace Collections defines numerous types that allow you to read (and write) Note System.IO Chapter 7 information - Callback I nter faces, Delegates, and Ev ents to (and from) files, memory locations, and character buffers. Chapter 16 examines Chapter 8 this - Advanced C# Type Consthowever, ruction Techniques namespace in detail; by necessity, you will be introduced to some System.IO types Pa r t Thre e -during Pr ogr am i ng w i th .N ET Assem bl ie thismchapter's examination ofs object

Chapter 9

serialization.

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion The Role ofC#Object Graphs ISBN:1590590554

by Andr ew Tr oelsen

As mentioned, when a type is (1200 serialized Apr ess © 2003 pages) by the CLR, the runtime will account for each related object. The chain of related objects serialized to a stream as an object graph. Object graphs This compr ehensiv e text star ts isw collectively ith a brief ovreferred er view oftothe provide a simple C# waylanguage to document how a set of objects refer to each other and are not intended to directly and then quickly m oves to key technical and chitectur al issues foras .NET s. model classic OOarrelationships (such the developer "is-a" or "has-a" relationship), although they do map to this paradigm quite well. To establish the relations among objects in a graph, each object is assigned a unique numerical value, followed by a graph of all related items. Keep in mind that the numbers assigned to the Tamembers ble o f Conint en ant sobject graph are arbitrary and have no real meaning to the outside world. C# and t he .NET Plat for m, Second Edition

Asoduction a simple example, assume you have created a set of classes that model some automobiles (of I ntr course). haveng a topmost type.NET named Pa r t One - You I nt r oduci C# a nd the P la tf Car, or m

which "has-a" Radio. Another class named JamesBondCar

extends1 the basic Car type.ofAn.NET object graph that models these relationships is shown in Figure 12-1. Chapter - The Philosophy Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Figure 12-1: A simple object graph

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter In Figure 1212-1 - Objyou ect can Ser ialization see that and the Car the .NET classRemoting refers to Lay theerRadio class (given the "has-a" relationship). The

JamesBondCar refers to ter theWin Cardow (given "is-a" relationship) as well as the Radio (as it inherits this Chapter 13 - Building a Bet ( Int the roducin g Window s For ms) protected Given Chapter 14 member - A Bettervariable). Paint ing Fr amewthat or k (we GDIhave + ) assigned an arbitrary value to each member in the object graph, 15 we -could theWindows relationship Chapter Pr ogrrepresent am ming with Formdocumented s Contr ols in the previous diagram with the following formula: Chapter 16 - The Sy stem .I O Nam espace

[Car 3, [Radio 2], [JamesBondCar 1, ref 3, ref 2] Chapter 17 - ref Data 2], Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

If we parse this formula, you can see that the Car type has a dependency on item 2 (the Radio). Also, the JamesBondCar has a dependency on item 3 (the Car) as well as item 2 (the Radio). Item 2, the Radio, is Chapter 20 - XML Web Ser vices a lone wolf. If you serialize an instance of JamesBondCar to a stream, the object graph ensures that the I ndex Radio and Car types also participate in the process. The beautiful thing about the default serialization List of Figur es process is that the graph representing the relationships among your objects is established automatically List of Tables behind the scenes. Chapter 19 - ASP.NET Web Applicat ions

an d th e .N ET Plat f orm , Se con d Ed it ion ConfiguringC#Objects for Serialization by Andr ew Tr oelsen

ISBN:1590590554

To make an object .NET serialization services, all you need to do is decorate each class with Apravailable ess © 2003to (1200 pages) the [Serializable] This attribute. That's it (really). you determine a given compr ehensiv e text starIfts w ith a brief ovthat er view of theclass has some member data that should not participate in the serialization scheme, you can mark such fields with the [NonSerialized] C# language and then quickly m oves to key technical and chitectur al ifissues for .NET developer s. attribute. This canarbe helpful you have member variables in a serializable class that do not need to be "remembered" (e.g., constants, transient data, and so on). For example, here is the Radio class, which has been marked as serializable (except for a single member variable): Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

// The Radio class can participate in the .NET serialization scheme. [Serializable] Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public class Radio Chapter 1 - The Philosophy of .NET { Chapter // 2 - This Building C# Applications member will not be persisted. Pa r t Tw o[NonSerialized] - The C# Pr ogr am m ing La ngua ge Chapter private 3 - C# Language Fundamentals int objectIDNumber = 9; Chapter // 4 - Other Obj ect -Or iented Pr ogr amstate ming w ith C# serialized data Chapter ... 5 - Exceptions and Obj ect Lifetim e Chapter public 6 - I nter Radio(){ faces and Collections } void On(bool state)and Ev ents Chapter public 7 - Callback I nter faces, Delegates, { Chapter 8 - Advanced C# Type Const ruction Techniques if(state true) Pa r t Thre e - Pr ogr am m i ng w == i th .N ET Assem bl ie s MessageBox.Show("Music is on..."); Chapter 9 - Under standing .NET Assem blies else Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads MessageBox.Show("No Chapter 11 - Type Reflection, Late Binding, and Attr tunes..."); ibute- Based Pr ogramm ing } Pa r t Four - Le ve r a ging the .NET Libr a r ie s } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er I ntr oduction

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter - A Better ingattributes Fr amew orare k ( GDI +) As you 14 would guess,Paint these embedded within the type's metadata, as you can see using Chapter 15 Pr ogr am ming with Windows Form s Contr ols ildasm.exe (Figure 12-2). Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 12-2: The Serializable and NonSerialized attributes To finish the coding of this car hierarchy, here are the definitions for the Car base class and JamesBondCar subtype, each marked with the [Serializable] attribute: // The Car class is serializable! [Serializable] public class Car { protected string petName; protected int maxSpeed;

protected Radio theRadio = new Radio(); C# an d th e .N ET Plat f orm ,int Se con d Ed it ion public Car(string petName, maxSpeed) ISBN:1590590554 by Andr ew Tr oelsen { Apr ess © 2003 (1200 pages) this.petName = petName; This compr ehensiv text star ts w ith a brief ov er view of the this.maxSpeed = e maxSpeed; C# language and then quickly m oves to key technical and } ar chitectur al issues for .NET developer s. public Car() { } public String PetName { Ta ble o f Con t en t s get { return petName; } C# and t he .NET Plat for m, Second Edition set { petName = value; } I ntr oduction } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public int MaxSpeed Chapter 1 - The Philosophy of .NET { Chapter 2 - Building C# Applications get { return maxSpeed; } Pa r t Tw o - The C# Pr ogr am m ing La ngua ge set { maxSpeed = value; } Chapter } 3 - C# Language Fundamentals Chapter public 4 - Obj ect -Or iented Pr ogr am ming w ith C# void TurnOnRadio(bool state) Chapter { 5 theRadio.On(state); - Exceptions and Obj ect Lifetim } e Chapter 6 - I nter faces and Collections } Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter // The 8 JamesBondCar - Advanced C# Type class Const ruction is also Techniques serializable! Pa [Serializable] r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

public JamesBondCar : blies Car Chapter 9 class - Under standing .NET Assem { Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads public for easy access. Chapter // 11 - Made Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing free use Pa r t Four// - LeFeel ve r a ging the to .NETmake Libr a r ie s

of type properties.

bool isFlightWorthy; Chapter public 12 - Obj ect Ser ialization and the .NET Remoting Lay er bool isSeaWorthy; Chapter public 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) public JamesBondCar(){ } public JamesBondCar(string petName, int maxSpeed, Chapter 15 - Pr ogr am ming with Windows Form s Contr ols bool canFly, bool canSubmerge) Chapter 16 - The Sy stem .I O Nam espace : base(petName, maxSpeed) Chapter 17 - Data Access w ith ADO.NET { Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces this.isFlightWorthy = canFly; Chapter 18 - ASP.NET Web Pages and Web Contr ols this.isSeaWorthy = canSubmerge; Chapter } 19 - ASP.NET Web Applicat ions Chapter public 20 - XML Web vices voidSerFly() I ndex { List of Figur es if(isFlightWorthy) List of Tables MessageBox.Show("Taking off!"); else MessageBox.Show("Falling off cliff!"); } public void GoUnderWater() { if(isSeaWorthy) MessageBox.Show("Diving...."); else MessageBox.Show("Drowning!!!"); } } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Choosing a Serialization Formatter

C# an d thyour e .N ET Plattof orm , Se con d Once you have configured types participate in Ed theit ion .NET serialization scheme, your next step is to ISBN:1590590554 choose which format by Andr should ew Trbe oelsen used when persisting your object graph. The System.Runtime.Serialization.Formatters Apr ess © 2003 (1200 pages) namespace contains two additional nested namespaces (*.Binary and *.Soap) that provide out-of-the-box As of you This compr ehensivtwo e text star ts w ith a formatters. brief ov er view thecan guess, the BinaryFormatter C# object language andto then quicklyusing m oves to key technical type serializes your graph a stream a compact binary and format. The SoapFormatter type ar chitectur issues(Simple for .NETObject developer s. represents your graph as a alSOAP Access Protocol) message that is expressed using XML data representation. TaThe ble oSystem.Runtime.Serialization.Formatters.Binary.BinaryFormatter f Con t en t s type is defined within mscorlib.dll. C# and t he .NET Plat for m, Second Edition Therefore, to serialize your objects using a binary format, all you need to do is specify the following C# I ntr using oduction directive: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - Theobject Philosophy of .NETusing a binary format! // Persist graph Chapter 2 Building C# Applications using System.Runtime.Serialization.Formatters.Binary; Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals However, System.Runtime.Serialization.Formatters.Soap.SoapFormatter type is defined in a separate Chapter 4 the - Obj ect -Or iented Pr ogr am ming w ith C#

assembly. format your Chapter 5 - To Exceptions and object Obj ect graph Lifetiminto e a SOAP message, you must set a reference to

System.Runtime.Serialization.Formatters.Soap.dll and make the following C# using directive: Chapter 6 - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

// Persist object using SOAP format! Chapter 8 - Advanced C# graph Type Const ructiona Techniques using System.Runtime.Serialization.Formatters.Soap; Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Regardless of which formatter you choose to make use of, do be aware that .NET formatters supply a common set of functionality through the implementation of the IFormatter and IRemotingFormatter Pa r t Four - Le ve r a ging the .NET Libr a r ie s interfaces. IFormatter defines the key Serialize() and Deserialize() methods, which do the grunt work to Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er move your object graphs into and out of a specific stream (represented by the System.IO.Stream abstract Chapter 13 - Building Betformal ter Windefinition dow ( Int roducin g Window s For ms) base class). Here is athe of IFormatter: Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

public interface System.Runtime.Serialization.IFormatter { ChapterSerializationBinder 17 - Data Access w ith ADO.NET Binder { get; set; } Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b {Se get; r vi ces set; } StreamingContext Context ChapterISurrogateSelector 18 - ASP.NET Web Pages SurrogateSelector and Web Contr ols { get; set; } Chapterobject 19 - ASP.NET Web Applicat ions Deserialize(System.IO.Stream serializationStream); Chaptervoid 20 - XML Web Ser vices Serialize(System.IO.Stream serializationStream, object graph); I ndex } Chapter 16 - The Sy stem .I O Nam espace

List of Figur es List of Tables

The IRemotingFormatter interface (which is leveraged internally by the .NET Remoting layer) overloads the Serialize() and Deserialize() members, into a manner more appropriate for remoting-centric persistence. Note that IRemotingFormatter derives from the more general IFormatter interface: public interface System.Runtime.Remoting.Messaging.IRemotingFormatter : System.Runtime.Serialization.IFormatter { object Deserialize(System.IO.Stream serializationStream, System.Runtime.Remoting.Messaging.HeaderHandler handler); void Serialize(System.IO.Stream serializationStream, object graph, System.Runtime.Remoting.Messaging.Header[] headers); }

C# Using an d th e .N Plat f orm Formatter , Se con d Ed it ion Serialization aETBinary ISBN:1590590554

by Andr ew Tr oelsen

To illustrate how Apr easy to persist an instance of our JamesBondCar to a physical file, let's make use of essit ©is2003 (1200 pages) the BinaryFormatter type. Again, the two key methods of the BinaryFormatter type to be aware of are This compr ehensiv e text star ts w ith a brief ov er view of the Serialize() and Deserialize() (Table 12-1). C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Table 12-1: BinaryFormatter Members BinaryFormatter Member Ta ble o f Con t en t s

Meaning in Life

C# and t he .NET Plat for m, Second Edition

Deserialize()

I ntr oduction

Deserializes a stream of bytes to an object graph

Pa rSerialize() t One - I nt r oduci ng C# a nd the .NETSerializes P la tf or m

Chapter 1

an object or graph of related objects to a stream

- The Philosophy of .NET

In addition the Deserialize() and Serialize() methods, the BinaryFormatter type defines a small number Chapter 2 - toBuilding C# Applications ofr tproperties configure specific details Pa Tw o - The that C# Pr ogr am m ing La ngua ge

regarding the (de)serialization process. By and large, the default configuration of BinaryFormatter is all you need to concern yourself with; however we will check Chapter 3 - C# Language Fundamentals out additional details as needed over the course Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# of this chapter. Chapter 5

- Exceptions and Obj ect Lifetim e

Now, assume you have created an instance of JamesBondCar, modified some state data, and want to - I nter faces and Collections persist your spy-mobile in a *.dat file. The first task is to create the *.dat file itself. This can be achieved Chapter 7 - Callback I nter faces, Delegates, and Ev ents using the static System.IO.File.Create() method, which returns an instance of the System.IO.FileStream Chapter 8 - Advanced Const ruction Techniques type (again, file IO willC# be Type examined in Chapter 16). Given that the BinaryFormatter.Serialize() method Pa r t Thre e a- Stream-derived Pr ogr am m i ng w itype th .N as ET its Assem ie s requires firstblparameter, be sure to maintain this variable. Here is the Chapter 9 serialization - Under standing .NET Assem blies complete code: Chapter 6

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

using System.Runtime.Serialization.Formatters.Binary, using System.IO; Chapter 12 static - Obj ect Ser ialization and the .NET Remoting Lay er public void Main() Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms) { Chapter // 14 - Make A Better Fr amew or k ( GDI + ) state data. a Paint car ing and change some Chapter JamesBondCar 15 - Pr ogr am ming myAuto with Windows FormJamesBondCar("Fred", s Contr ols = new 50, false, true); Chapter myAuto.TurnOnRadio(true); 16 - The Sy stem .I O Nam espace Chapter myAuto.GoUnderWater(); 17 - Data Access w ith ADO.NET Pa r t Fi ve// - WCreate e b Appl icaati ons file and stream X ML W e b to Se r vi hold ces the object's state. myStream File.Create("CarData.dat"); Chapter FileStream 18 - ASP.NET Web Pages and= Web Contr ols the object graph into the file stream using a binary format. Chapter // 19 - Move ASP.NET Web Applicat ions BinaryFormatter myBinaryFormat = new BinaryFormatter(); Chapter 20 - XML Web Ser vices myBinaryFormat.Serialize(myStream, myAuto); I ndex myStream.Close(); List of Figur es } List of Tables Pa r t Four - Le ve r a ging the .NET Libr a r ie s

As you can see, the BinaryFormatter.Serialize() method is the member responsible for composing the object graph and moving the byte sequence to some Stream-derived type. In this case, the stream happens to be a physical file. However, you could also serialize your object types to any Stream-derived type (such as a memory location, given that MemoryStream is a descendent of the Stream type). If you open the *.dat file, you can peek inside the byte sequence (Figure 12-3).

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter Figure 1 - 12-3: The Philosophy JamesBondCar of .NET serialized using a BinaryFormatter Chapter 2

- Building C# Applications

Chapter 5

- Exceptions and Obj ect Lifetim e

Now youPrwant tomread the persisted Pa r t Twsuppose o - The C# ogr am ing La ngua ge

JamesBondCar back to an object variable. Once you have programmatically opened the correct *.dat file (via the File.OpenRead() method), simply call Deserialize(). Chapter 3 - C# Language Fundamentals Be aware that Deserialize() returns a generic System.Object type, and therefore you need to impose an Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# explicit cast, as shown here: Chapter 6

- I nter faces and Collections // Read the ICar fromDelegates, the binary Chapter 7 - in Callback nter faces, and Ev stream. ents

myStream- Advanced = File.OpenRead("CarData.dat"); C# Type Const ruction Techniques JamesBondCar carFromDisk = Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s (JamesBondCar)myBinaryFormat.Deserialize(myStream); Chapter 9 - Under standing .NET Assem blies Console.WriteLine("{0} is alive!", carFromDisk.PetName); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads carFromDisk.TurnOnRadio(true); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing myStream.Close(); Chapter 8

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter Building Bet ter Win dow ( Intyou roducin g Window s For ms) Notice 13 that- when youa call Deserialize(), pass the Stream-derived type that represents the location of Chapter 14 - A objects Better Paint ing a Frfile amew or k ( GDI + ) case). Now if that is not painfully simple, I'm not sure what the persisted (again stream in this Chapter is. In a 15 nutshell, - Pr ogrmark am ming each with class Windows you wish Form tos persist Contr ols to a stream with the [Serializable] attribute. After this

point, use BinaryFormatter to move your object graph to and from a binary stream. Chapter 16 -the The Sy stem .I O Nam type espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# Using an d th e .N Plat f ormFormatter , Se con d Ed it ion Serialization aETSOAP by Andr ew Tr oelsen

ISBN:1590590554

The other available use when serializing your types is SoapFormatter. Remember you Aprformatter ess © 2003 you (1200may pages) must set a reference to System.Runtime.Serialization.Formatters.Soap.dll This compr ehensiv e text star ts w ith a brief ov er view of the to use this type! The following block of code extends the previous serialization to technical persist the JamesBondCar using the C# language and then quickly m example oves to key and ar chitectur al issues for .NET developer s. SoapFormatter type: using System.Runtime.Serialization.Formatters.Soap; ... C# and t he .NET Plat for m, Second Edition // Save the same car using a soap format. I ntr oduction FileStream myStream = File.Create("CarSoapData.xml"); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m SoapFormatter mySoapFormat = new SoapFormatter(); Chapter 1 - The Philosophy of .NET mySoapFormat.Serialize(myStream, myAuto); Chapter 2 - Building C# Applications myStream.Close(); Pa r t Tw o - The Pr ogr am mfrom ing La ngua // Read inC#the Car the ge XML file. Chapter 3 - C# Language Fundamentals myStream = File.OpenRead("CarSoapData.xml"); Chapter 4 - Obj ect carFromSoap -Or iented Pr ogr am=ming w ith C# JamesBondCar Chapter 5 - Exceptions and Obj ect Lifetim e (JamesBondCar)mySoapFormat.Deserialize(myStream); Chapter Console.WriteLine("{0} 6 - I nter faces and Collections is alive!", carFromSoap.PetName); myStream.Close(); Chapter 7 - Callback I nter faces, Delegates, and Ev ents

Ta ble o f Con t en t s

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

As you can- see, the SoapFormatter type has the same public interface as the BinaryFormatter. As before, Under standing .NET Assem blies use Serialize() and Deserialize() to move the object graph in and out of the stream. If you open the Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads resulting *.xml file (Figure 12-4), you can locate the XML tags that mark the stateful values of the current Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing JamesBondCar (as well as the relationship maintained by the graph). Chapter 9

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 12-4: JamesBondCar serialized using a SoapFormatter

C# Using an d th e .N ET XML Plat f orm , Se con d Ed it ion Serialization an Formatter by Andr ew Tr oelsen

ISBN:1590590554

In addition to the Apr SOAP and binary formatters, the System.Xml.dll assembly provides a third formatter ess © 2003 (1200 pages) (System.Xml.Serialization.XmlFormatter) thattscan usedov toerpersist This compr ehensiv e text star w ithbe a brief view ofthe thestate of a given object using pure XML (as opposedC#to language XML dataand expressed via a SOAP message). Assuming your application has set a then quickly m oves to key technical and ar chitectur al(and issues forhave .NETadeveloper s. directive specifying the System.Xml.Serialization reference to System.Xml.dll you C# "using" namespace), you are able to serialize and deserialize your JamesBondCar as pure XML: Ta ble o f Con t en t s

// Now save car using a pure XML format. Console.WriteLine("\n***** Saving car to CarXmlData.xml file *****"); I ntr oduction myStream = File.Create("CarXmlData.xml"); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m XmlSerializer myXmlFormat = Chapternew 1 - XmlSerializer(typeof(JamesBondCar), The Philosophy of .NET "Cars"); Chapter 2 Building C# Applications myXmlFormat.Serialize(myStream, myAuto); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge myStream.Close(); Chapter 3 - in C# the Language // Read Car Fundamentals from the XML file. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# car from Xml file *****"); Console.WriteLine("\n***** Reading Chapter 5 - Exceptions and Obj ect Lifetim e myStream = File.OpenRead("CarXmlData.xml"); Chapter JamesBondCar 6 - I nter faces carFromXml and Collections = Chapter(JamesBondCar)myXmlFormat.Deserialize(myStream); 7 - Callback I nter faces, Delegates, and Ev ents Console.WriteLine("{0} is alive!", carFromXml.PetName); Chapter 8 - Advanced C# Type Const ruction Techniques carFromSoap.TurnOnRadio(true); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s myStream.Close(); Chapter 9 - Under standing .NET Assem blies C# and t he .NET Plat for m, Second Edition

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

As you can see, the process is more or less identical to working with the BinaryFormatter and SoapFormatter types. The key difference is that the XmlFormatter type requires you to specify type Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er information of the item to be serialized as well as the name of the XML namespace of the *.xml file via a Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) constructor parameter. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter Note 15 The - Pr ogr XmlFormatter am ming withdemands Windows that Formall s Contr serialized ols types in the object graph support a default

(so sure to add it back if you define custom constructors). Chapter 16 constructor - The Sy stem .I Obe Nam espace Chapter 17 - Data Access w ith ADO.NET

If you were to look within the newly generated CarXmlData.xml file you would find the following:

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Chapter - ASP.NET Web Applicat ions

List of Tables Fred 50 false true

I ndex

SOURCE CODE

The CarToFile application is located under the Chapter 12 subdirectory.

C# the an d thSerialization e .N ET Plat f orm , Se con d Ed it ion Customizing Process ISBN:1590590554

by Andr ew Tr oelsen

Now that you understand how(1200 the .NET Apr ess © 2003 pages) platform makes use of serialization services to persist an object to a given stream, youThis arecompr just about ready check details of the ehensiv e texttostar ts wout ith athe brief ov er view of .NET the Remoting layer. Before moving on however, let's digC# a bit deeper into the .NET serialization process. language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

In a vast majority of cases, you will configure a type as serializable by applying the [Serializable] attribute. This attribute enables a given formatter to encode the type into the client-supplied stream. While this is typically Taexactly ble o f Con the tbehavior en t s you desire, the System.Runtime.Serialization namespace provides several ways to customize the .NET process. C# and t he .NET Plat forserialization m, Second Edition I ntr oduction

The types within this namespace allow you to build custom formatters, as well as extend the default serialization processes provided by the [Serializable] attribute. Table 12-2 describes some (but not all) of the Chapter 1 - The Philosophy of .NET core types to be aware of. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Table 12-2: System.Runtime.Serialization Namespace Core Types

Chapter 3

- C# Language Fundamentals

Chapter Types 4 of - Obj the ect -Or iented Pr ogr am ming w ith C# Meaning in Life

System.Runtime.Serialization Chapter 5 - Exceptions and Obj ect Lifetim e Namespace Chapter 6 - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Formatter

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

ObjectIDGenerator Chapter 9 - Under standing .NET Assem blies

An abstract base class that provides base functionality for runtime serialization formatters. Generates IDs for objects in an object graph.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

ObjectManager

Keeps track of objects as they are being deserialized.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa rSerializationBinder t Four - Le ve r a ging the .NET Libr a r ie s

An abstract base class that provides functionality to

serialize Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay era type to a stream. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

SerializationInfo

Used by objects that have custom serialization behavior. SerializationInfo holds together all the data Chapter 15 - Pr ogr am ming with Windows Form s Contr ols needed to serialize or deserialize an object. In Chapter 16 - The Sy stem .I O Nam espace essence, this class is a "property bag" that allows you Chapter 17 - Data Access w ith ADO.NET to establish name/value pairs to represent the state of Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces an object. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - toASP.NET Web Applicat ions In addition these types, there are two key interfaces used during the serialization process: IFormatter Chapter (mentioned 20 - XML previously) Web Serand vices ISerializable. Regardless of which formatter you choose (including any custom

formatter you might dream up), the formatter is in charge of transmitting all of the information required to I ndex persist thees object during the serialization process. Specifically, the necessary information includes: List of Figur List of Tables

The fully qualified name of the object (e.g., MyNamespace.MyClasses.Foo)

The name of the assembly containing the object (e.g., myAsm.dll) The object's stateful information, contained within a SerializationInfo type During the deserialization process, the formatter uses this same information to build an identical copy of the object, using the information extracted from the underlying stream. The big picture can be visualized as shown inFigure 12-5.

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble Figure o f Con t 12-5: en t s The serialization process C# and t he .NET Plat for m, Second Edition I ntr When oduction you wish to "get involved" with the serialization process, your first step is to implement the standard Pa ISerializable r t One - I nt rinterface oduci ng C# onathe nd the class .NET requiring P la tf or m custom

serialization. This interface is quite simple, given that it

only defines a single method, GetObjectData(): Chapter 1 - The Philosophy of .NET Chapter 2

- Building C# Applications

Pa r t Tw o - The C# wish Pr ogr am La ngua ge // When you tom ing tweak the

serialization process,

Chapter 3 - C# Language Fundamentals // implement ISerializable. Chapter public 4 interface - Obj ect -Or iented ISerializable Pr ogr am ming w ith C#

{ Chapter 5

- Exceptions and Obj ect Lifetim e void GetObjectData(SerializationInfo info, Chapter public 6 - I nter virtual faces and Collections

context); - StreamingContext Callback I nter faces, Delegates, and Ev ents } Chapter 8 - Advanced C# Type Const ruction Techniques Chapter 7

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

The GetObjectData() method is called automatically by a given formatter during the serialization process. The implementation of this method populates the incoming SerializationInfo parameter with a series of name/value Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing pairs. If you check out this type using wincv.exe, you essentially find numerous variations on the overloaded Pa r t Four - Le ve r a ging the .NET Libr a r ie s AddValue() method, in addition to a small set of properties that allow the type to get and set the type's name, Chapter - Obj ect Ser ialization and the .NET Laysnapshot: er defining12assembly, and member count. HereRemoting is a partial Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

public sealed class SerializationInfo : object { Chapter public 16 - The Sy stem .I O Nam espace SerializationInfo(Type type, Chapter 17 - Data Access w ith ADO.NET System.Runtime.Serialization.IFormatterConverter converter); Pa r t Fi vepublic - W e b Appl ica ti ons AssemblyName and X ML W e b Se r vi string {ces get; set; } Chapter public 18 - ASP.NET Web Pages and Web Contr string FullTypeName { ols get; set; } Chapter public 19 - ASP.NET Applicat ions { get; } intWeb MemberCount Chapter public 20 - XML Web vices voidSerAddValue(string name, short value); I ndex public void AddValue(string name, UInt16 value); public void AddValue(string name, int value); List of Figur es ... List of Tables } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

In addition to implementing the ISerializable interface, all objects that make use of custom serialization must provide a special constructor taking the following signature: // You must supply a custom constructor with this signature // to allow the runtime engine to set the state of your object. [Serializable] class SomeClass : ISerializable { private SomeClass (SerializationInfo si, StreamingContext ctx) {...} ... }

Notice that the visibility of this constructor is set as private. This is permissible given that the formatter will have C# an d th e .N ET Plat f orm , Se con d Ed it ion access to this member regardless of its visibility. These special constructors tend to be marked as private to ISBN:1590590554 by Andr ew Tr oelsen ensure that the casual object user would never create an object in this manner. Apr ess © 2003 (1200 pages)

As you can see, the Thisfirst compr parameter ehensiv eof text thisstar constructor ts w ith a brief is anovinstance er view ofofthe the SerializationInfo type (seen C# language and then quickly constructor m oves to keyis technical and previously). The second parameter of special a StreamingContext type, which contains ar chitectur al issues for .NET developer s. information regarding the source or destination of the bits. The most informative member of this type is the State property, which represents a value from the StreamingContextStates enumeration (Table 12-3). Ta ble o f Con t en t s

Table 12-3: StreamingContextStates Enumeration Members

C# and t he .NET Plat for m, Second Edition I ntrStreamingContextStates oduction

Meaning in Life

Pa rMember t One - I ntName r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

All

Specifies that the serialized data can be transmitted to or received from any of the other contexts.

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter Clone3 Chapter 4

- C# Language FundamentalsSpecifies that the object graph is being cloned. - Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

CrossAppDomain

Chapter 6

Specifies that the source or destination context is a new AppDomain.

- I nter faces and Collections CrossMachine Specifies Chapter 7 - Callback I nter faces, Delegates, and Evthat ents the source or destination context is a different Chapter 8

machine. - Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

CrossProcess

Chapter 9

Specifies that the source or destination context is a different process on the same machine.

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

File 11 - Type Reflection, Late Binding, Specifies the source or destination context is a file. Chapter and Attrthat ibuteBased Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Other

Specifies that the serialization context is unknown.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Persistence Specifies the source Chapter 13 - Building a Bet ter Win dow ( Int roducin gthat Window s For ms)or destination context is a persisted could include databases, files, or other backing Chapter 14 - A Better Paint ing Fr amew or kstore. ( GDI +This )

Usersols should assume that persisted data is more long Chapter 15 - Pr ogr am ming with Windowsstores. Form s Contr

lived than the process that created the data and not serialize objects in such a way that deserialization requires accessing any Chapter 17 - Data Access w ith ADO.NET data from the current process. Chapter 16 - The Sy stem .I O Nam espace

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr olsthat the source or destination context is remoting to an Remoting Specifies Chapter 19 - ASP.NET Web Applicat ions unknown location. Users cannot make any assumptions as to Chapter 20 - XML Web Ser vices

whether this is on the same machine.

I ndex List of Figur es

A Simple Example of Custom Serialization

List of Tables

Let me reiterate that you typically do not need to bypass the default serialization mechanism provided by the .NET runtime. However, by way of a simple illustration, here is an updated version of the Car type (named CustomCarType) that has been configured to take part of custom serialization. You are not doing anything too radical in the implementation of GetObjectState() or the custom constructor. Other than persisting the name of the petName field using all capital letters (just to simulate something custom), each method dumps out information regarding the current serialization context and manipulates the incoming SerializationInfo type: [Serializable] public class CustomCarType : ISerializable { public string petName; public int maxSpeed; public CustomCarType(string s, int i) { petName = s; maxSpeed = i;} // Return state info to the formatter.

public void GetObjectData(SerializationInfo si, StreamingContext ctx) C# an d th e .N ET Plat f orm , Se con d Ed it ion { ISBN:1590590554 Andr ew Tr oelsen is the stream? // byWhat context Apr ess © 2003 (1200 pages) Console.WriteLine("[GetObjectData] Context State: {0} ", This compr ehensiv e text star ts w ith a brief ov er view of the ctx.State.ToString()); C# language and then quickly m oves to key technical and si.AddValue("CapPetName", petName.ToUpper()); ar chitectur al issues for .NET developer s. si.AddValue("maxSpeed", maxSpeed); } // Rehydrate a new object based on incoming SerializationInfo type. Ta ble o f Con t en t s private CustomCarType(SerializationInfo si, StreamingContext ctx) C# and t he .NET Plat for m, Second Edition { I ntr oduction // What context is the stream? Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Console.WriteLine("[ctor] Context State: {0} ", ctx.State.ToString()); Chapter 1 - The Philosophy of .NET petName = si.GetString("CapPetName"); Chapter 2 - Building C# Applications maxSpeed = si.GetInt32("maxSpeed"); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge } Chapter 3 - C# Language Fundamentals } Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e Now that typefaces has and beenCollections configured with the correct infrastructure, you will be happy to see that the caller's Chapter 6 the - I nter

serialization and deserialization process remains unaltered (see Figure 12-6 for output): Chapter 7 - Callback I nter faces, Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e -static Pr ogr am m i ng w i th .N ET Assem bl ieargs) s public int Main(string[]

Chapter { 9

- Under standing .NET Assem blies myAuto Cont = new 50); Chapter CustomCarType 10 - Pr ocesses, AppDomains, exts,CustomCarType("Sid", and Threads

= File.Create("CarData.dat"); Chapter Stream 11 - Type myStream Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing interface Pa r t Four// - LeISerializable ve r a ging the .NET Libr a r ie s

obtained!

myBinaryFormat = new Chapter BinaryFormatter 12 - Obj ect Ser ialization and the .NET Remoting Lay erBinaryFormatter(); Chapter myBinaryFormat.Serialize(myStream, 13 - Building a Bet ter Win dow ( Int roducin g WindowmyAuto); s For ms) Chapter myStream.Close(); 14 - A Better Paint ing Fr amew or k ( GDI + )

myStream = File.OpenRead("CarData.dat"); // Special constructor called! Chapter 16 - The Sy stem .I O Nam espace CustomCarType carFromDisk = Chapter 17 - Data Access w ith ADO.NET (CustomCarType)myBinaryFormat.Deserialize(myStream); Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Console.WriteLine("{0} is alive!", carFromDisk.petName); Chapter 18 - ASP.NET Web Pages and Web Contr ols return 0; Chapter 19 - ASP.NET Web Applicat ions } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 12-6: Custom serialization SOURCE CODE

The CustomSerialization project is included under the Chapter 12 subdirectory.

So at this point you should have a solid handle on the .NET serialization process. Understand that this C# an d th e .N ET Plat f orm , Se con d Ed it ion technology is useful in a variety of circumstances, even when you are not building a distributed application. For ISBN:1590590554 by Andr Tr oelsen example, you could saveew applicationspecific data, user preferences, or whatnot with these same techniques. Apr ess © 2003 (1200 pages) As you would expect however, the .NET Remoting layer makes substantial use of these serialization primitives. Thisexactly compr ehensiv e text star ts w ith a brief ov er view of the Next question: what is remoting? C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# anRemoting d th e .N ET Plat f orm , Se con d Ed it ion Defining .NET by Andr ew Tr oelsen

ISBN:1590590554

As you recall from your reading in Chapter 10, an application domain is a logical boundary for a .NET Apr ess © 2003 (1200 pages) assembly, which This is itself contained within a Process compr ehensiv e text star ts w ith atype. briefUnderstanding ov er view of thethese concepts is critical when discussing distributed computing under .NET, given that remoting is nothing more than the act of two C# language and then quickly m oves to key technical and ar communicating chitectur al issuesacross for .NET developer domains. s. pieces of software application The two application domains in question could be physically configured in any of the following manners: Ta ble o Two f Con application t en t s domains in the same process (and thus on the same machine) C# and t he .NET Plat for m, Second Edition

Two application domains in separate processes on the same machine

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Two application domains in separate processes on different machines

Chapter 1

- The Philosophy of .NET

Chapter Given these 2 - Building three possibilities, C# Applications you can see that remoting does not necessarily need to involve two (or Pa more) r t Tw onetworked - The C# Pr computers. ogr am m ingInLafact, nguaeach ge

of the examples presented in this chapter can be successfully run on a single, stand-alone machine (but don't worry, you'll see how to distribute your applications across Chapter 3 - C# Language Fundamentals machine boundaries as well). Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Regardless of the distance between two software entities, it is common to refer to each agent using the - I nter faces and Collections terms client and server. Simply put, the client is a piece of software that attempts to interact with a remote Chapter 7 - Callback I nter faces, Delegates, and Ev ents object. The server is the software agent that provides remote access to select objects. As you will see over Chapter 8 - Advanced C# Type Const ruction Techniques the course of this chapter, a .NET server application is quite a different beast from that of classic DCOM. Chapter 6

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .NNamespaces ET Plat f orm , Se con d Ed it ion The .NET Remoting ISBN:1590590554

by Andr ew Tr oelsen

Before we dive too details Aprdeep ess ©into 2003the (1200 pages) of the .NET Remoting layer, we need to check out the functionality provided by the remoting-centric namespaces. The classoflibraries provide numerous This compr ehensiv e text star ts w ith a.NET brief base ov er view the namespaces thatC# allow you to build distributed applications. The bulk of the types found within these language and then quickly m oves to key technical and chitectur alwithin issues for .NET developer s. the System.Runtime.Remoting.dll assembly does namespaces arear contained mscorlib.dll, however, complement and extend the basic type set. The truth of the matter, however, is that many of these types are of little use to you unless you do wish to extend the default remoting architecture. Over the course of Tathis ble chapter, o f Con t en t s are required to make use of many of the core types within the namespaces seen in Table you C# and Be t hesure .NETtoPlat for m,out Second 12-4. check onlineEdition Help if you wish to view every possible entity. I ntr oduction Pa r t One12-4: - I nt rThe oduci.NET ng C#Remoting a nd the .NET P la tf or m Table Namespaces

Chapter 1

- The Philosophy of .NET

Remoting-Centric Namespace - Building C# Applications

Chapter 2

Pa rSystem.Runtime.Remoting t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

System.Runtime.Remoting.Activation - I nter faces and Collections

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa rSystem.Runtime.Remoting.Channels t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Meaning in Life This is the core namespace you must use when building any sort of application using the .NET Remoting layer. This relatively small namespace defines a handful of types that allow you to fine-tune the process of activating a remote object. This namespace contains types that represent channels and channel sinks.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

System.Runtime.Remoting.Channels.Http

This namespace contains types that use the HTTP protocol to transport messages and objects to and from remote locations.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

System.Runtime.Remoting.Channels.Tcp contains types that use Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window This s For namespace ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace System.Runtime.Remoting.Contexts Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

System.Runtime.Remoting.Lifetime Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices System.Runtime.Remoting.Messaging I ndex List of Figur es

the TCP protocol to transport messages and objects to and from remote locations. This namespace allows you to configure the details of an object's context. This namespace contains types that manage the lifetime of remote objects. This namespace contains types used to create and transmit message object.

System.Runtime.Remoting.Metadata

This namespace contains types that can be used to customize the generation and processing of SOAP formatting.

System.Runtime.Remoting.Metadata.W3cXsd2001

Closely related to the previous namespace, this namespace contains types that represent the XML Schema Definition (XSD) defined by the World Wide Web Consortium (W3C) in 2001.

System.Runtime.Remoting.MetadataServices

This namespace contains the types used by the Soapsuds.exe command line tool to convert .NET metadata to and from XML schema for the remoting infrastructure.

System.Runtime.Remoting.Proxies

This namespace contains types that provide functionality for proxy objects.

List of Tables

System.Runtime.Remoting.Services This C# an d th e .N ET Plat f orm , Se con d Ed it ion namespace defines a number of common base classes (and interfaces) ISBN:1590590554 by Andr ew Tr oelsen that are typically only leveraged by other Apr ess © 2003 (1200 pages) intrinsic remoting agents. This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET PlatRemoting f orm , Se con d Ed it ion Understanding .NET Framework ISBN:1590590554

by Andr ew Tr oelsen

When clients andApr servers exchange information across application boundaries, the CLR makes use of ess © 2003 (1200 pages) several low-level This primitives to ensure the star entities in question able communicate with each other as compr ehensiv e text ts w ith a brief ov are er view of to the transparently as possible. Meaning, as a .NET programmer, you are not C# language and then quickly m oves to key technical and required to provide reams and chitectur alcode issues .NET adeveloper reams of grungy ar networking tofor invoke method s. on a remote object. Likewise, the server process is not required to manually pluck a network packet out of the queue and reformat the message into terms the remote object can understand. As you would hope, the CLR will take care of such details automatically Tausing ble o faCon t en t set s of remoting types (although you are certainly able to get involved with the process if you default C# t he .NET Plat for m, Second Edition soand choose). I ntr oduction

Now, if you coming .NET from Pa r t One - I ntare r oduci ng C# to a nd the Remoting .NET P la tf or m

a classic DCOM background, do understand that the .NET

Remoting not quite of as.NET transparent as DCOM. Much of the reason has to do with the simple fact Chapter 1 -layer The is Philosophy that .NET not registered in the system registry, and therefore you lose any concept of an Chapter 2 assemblies - Building C#are Applications AppID makes the La use of ge dcomcnfg.exe Pa r t Tw ovalue, - The which C# Pr ogr am m ing ngua Chapter 3

obsolete in the .NET universe.

- C# Language Fundamentals

Although .NET does expose a wee-bit more network-centric details to the developer, the upside is that Obj ect -Or iented Pr ogr am ming w ith C# there is no- need to manually author IDL code to describe your remotable types (given the advent of .NET Chapter 5 Exceptions Obj ect metadata), and you canand forget all Lifetim about eimplementing IMarshal, IPropertyBag, or making use of ADO Chapter 6 I nter faces and Collections Recordsets to marshal objects by value. Under .NET, marshaling a type by value (e.g., placing a copy of Chapter 7 - type Callback ntercaller's faces, Delegates, and isEvas ents the remote into Ithe app domain) simple as applying the [Serializable] attribute. Chapter 4

Chapter 8

- Advanced C# Type Const ruction Techniques

Basically, .NET Remoting layer revolves Pa r t Thre e -the Pr ogr am m i ng w i th .N ET Assem bl ie around s

a careful orchestration that takes place between four

key players: Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Proxies

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s Messages

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Channels Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Formatters

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - out The each Sy stem .I O Nam espace Let's check entity in turn, and see how their combined functionality facilitates remote method Chapter 17 - Data Access w ith ADO.NET invocations. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Understanding Proxies and Messages

Chapter 19 - ASP.NET Web Applicat ions

Chapter XML Web Ser vices Clients20 and- server objects do not communicate via a direct connection, but rather through the use of a I ndex middleman termed a proxy. Like Java RMI, CORBA and DCOM, the role of a .NET proxy is to fool the List client of Figur into es believing it is communicating with a local object in the same application domain. To facilitate this

illusion, a proxy has the identical interface (i.e., members, properties, fields, and whatnot) as the remote List of Tables type it represents. As far as the client is concerned, a given proxy is the remote object, and can be operated on as if it were a true-blue local entity. Under the hood however, the proxy is forwarding calls to the remote type. Formally speaking, the proxy invoked directly by the client is termed the transparent proxy. This CLR autogenerated entity is in charge of ensuring that the client has provided the correct number of (and type of) parameters to invoke the remote method. Given this, you can regard the transparent proxy as a fixed interception layer that cannot be modified or extended programmatically. Assuming the transparent proxy is able to verify the incoming arguments, this information is packaged up into another CLR generated type termed the message object. By definition, all message objects implement the System.Runtime.Remoting.Messaging.IMessage interface: public interface IMessage {

IDictionary Properties { get; } C# an d th e .N ET Plat f orm , Se con d Ed it ion

}

ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

As you can see, the interface property (named ThisIMessage compr ehensiv e textdefines star ts waithsingle a brief ov er view of the Properties) that provides access C# to language then quickly m oves to keyOnce technical to a collection used hold theand client-supplied arguments. this and message object has been populated ar chitectur al into issues for .NETrelated developer by the CLR, it is then passed a closely types. termed the real proxy. The real proxy is the entity that literally passes the message object into the channel (described Tamomentarily). ble o f Con t en Unlike ts the transparent proxy, the real proxy can be extended by the programmer, and is C# and t he .NET for m,class Second represented by Plat a base typeEdition named (of course) RealProxy. Again, it is worth pointing out that the CLR I ntr willoduction always generate a default implementation of the client-side real proxy, which will serve your needs Pa r t One I ntall) r oduci ng C# a ndNevertheless, the .NET P la tfto or m most (if -not of the time. gain

some insight into the functionality provided by the

Chapter abstract 1 RealProxy - The Philosophy base class, of .NET ponder the formal definition type: Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogrclass am m ing RealProxy La ngua ge public abstract

Chapter 3 {

: object

- C# Language Fundamentals

Chapterpublic 4 - Obj virtual ect -Or ientedObjRef Pr ogr am ming w ith C# CreateObjRef(Type requestedType); Chapterpublic 5 - Exceptions virtual and bool Obj ect Equals(object Lifetim e obj);

virtual Chapterpublic 6 - I nter faces and IntPtr CollectionsGetCOMIUnknown(bool fIsMarshalled); virtual int Delegates, GetHashCode(); Chapterpublic 7 - Callback I nter faces, and Ev ents virtual void GetObjectData(SerializationInfo info, Chapterpublic 8 - Advanced C# Type Const ruction Techniques context); Pa r t Thre e - PrStreamingContext ogr am m i ng w i th .N ET Assem bl ie s Type GetProxiedType(); Chapterpublic 9 - Under standing .NET Assem blies staticAppDomains, object GetStubData(RealProxy rp); Chapterpublic 10 - Pr ocesses, Cont exts, and Threads public virtual object GetTransparentProxy(); public Type GetType(); Pa r t Four - Le ve r a ging the .NET Libr a r ie s public IConstructionReturnMessage InitializeServerObject( Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er IConstructionCallMessage ctorMsg); Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) public virtual IMessage Invoke(IMessage msg); Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) public virtual void SetCOMIUnknown(IntPtr i); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols public static void SetStubData(RealProxy rp, object stubData); Chapterpublic 16 - Thevirtual Sy stem .I O IntPtr Nam espace SupportsInterface(ref Guid iid); Chapterpublic 17 - Data Access w ith ADO.NET virtual string ToString(); Pa }r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Again, unless youWeb areSer interested in building a custom implementation of the client-side real proxy, the only Chapter 20 - XML vices member of interest is RealProxy.Invoke(). Under the hood, the CLR-generated transparent proxy passes I ndex theofformatted List Figur es message object into the RealProxy type via its Invoke() method. List of Tables

Understanding Channels Once the proxies have validated and formatted the client-supplied arguments into a message object, this IMessage-compatible type is passed from the real proxy into a channel object. As in other remoting architectures, channels are the entities in charge of transporting a message to the remote object, and if necessary, ensuring that any method return values are passed from the remote object back to the client. Unlike classic DCOM however, .NET channels are not limited to the ORPC (Object Remote Procedure Call) wire protocol. In fact, the .NET base class libraries provide two channel implementations out of the box: The TCP channel The HTTP channel The TCP channel is represented by the TcpChannel class type, and is used to pass messages using the TCP/IP network protocol. TcpChannel is helpful in that the formatted packets are quite lightweight, given

that the messages are converted into a tight binary format using a related binary formatter. The result is C# an d th e .N ET Plat f orm , Se con d Ed it ion that use of the TcpChannel type tends to result in faster remote access. On the downside, TCP channels ISBN:1590590554 by Andrand ew Tr oelsen are not firewall friendly, may require the services of a system administrator to allow messages to pass Apr ess © 2003 (1200 pages) across machine boundaries (which does indeed echo the same limitations of classic DCOM). This compr ehensiv e text star ts w ith a brief ov er view of the C# language then quickly by m oves to key technical andtype, which converts message In contrast, the HTTP channeland is represented the HttpChannel class ar chitectur issues for .NETsoap developer s. objects into a SOAP formatalusing a related formatter. As you have seen, SOAP is XML-based and thus tends to result in beefier payloads than those used by the TcpChannel type. Given this, using the HttpChannel can result in slightly slower remote access. On the plus side, HTTP is far more firewall Ta ble o f Con t en t s friendly, given that most firewalls allow textual packets to be passed over port 80. C# and t he .NET Plat for m, Second Edition

I ntr oduction of which channel type you chose to use, understand that both the HttpChannel and Regardless Pa r t One - I nt r oduci ng C# a nd the P la tf orIChannelSender, m TcpChannel type implement the .NET IChannel,

and IChannelReciever interfaces (and yes, if

Chapter you were 1 to - The buildPhilosophy your own of custom .NET channel type, you make use of these same interfaces). The IChannel

interface you willC# seeApplications in just a bit) defines a small set of members that provide common functionality to Chapter 2 (as - Building all types. role of IChannelSender Pa r t channel Tw o - The C# PrThe ogr am m ing La ngua ge

is to define a common set of members for channels that are able to send information to a specific receiver. On the other hand, IChannelReceiver defines a set of Chapter 3 - C# Language Fundamentals members that allow a channel to receive information from a given sender. The HttpChannel and Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# TcpChannel types (as you would hope) are able to send and receive network packets, and therefore Chapter 5 - Exceptions and Obj ect Lifetim e implement all three channel-centric interfaces. Chapter 6 - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents To allow the client and server applications to register their channel of choice, you will make use of the Chapter 8 - Advanced C# Type Const ruction Techniques ChannelServices.RegisterChannel() method, which (surprise, surprise) takes a type implementing Pa r t Thre e - To Pr ogr am m i ng w i thto.Ncome, ET Assem ie s IChannel. preview things theblfollowing code snippet illustrates how a server-side application Chapter - Under standing .NETchannel Assem blies domain9 can register an HTTP on port 32469 (you see the client's role in just a bit): Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

// Create and register a server side HttpChannel on port 32469. HttpChannel c = new HttpChannel(32469); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er ChannelServices.RegisterChannel(c); Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Revisiting the Role of .NET Formatters

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fifinal ve - piece W e b Appl ica ti ons and X ML W epuzzle b Se r viis ces The of the .NET Remoting the

role of formatter objects. A given channel object

Chapter 18 - ASP.NET Web Pagesleverages and Web Contr ols internal formatter, whose job it is to translate the (TcpChannel or HttpChannel) a specific Chapter 19 object - ASP.NET Applicat ions terms. As you would guess, the TcpChannel type makes use of the message into Web protocol specific Chapter 20 - XML Web Ser vices System.Runtime.Serialization.Formatters.Binary.BinaryFormatter type, while the HttpChannel type uses I ndex the functionality provided by the System.Runtime.Serialization.Formatters.Soap.SoapFormatter type. List Given of Figur youreswork at the beginning of this chapter, you should already have some insights as to how a given

channel will format the incoming messages. List of Tables Once the formatted message has been generated, it is passed into the channel, where it will eventually reach its destination application domain, at which time the message is formatted from protocol-specific terms back to .NET-specific terms at which point an entity termed the dispatcher invokes the correct method on the remote object.

C# Now! an d th e .N ET Plat f orm , Se con d Ed it ion All Together ISBN:1590590554

by Andr ew Tr oelsen

If your head is spinning the previous sections, fear not! The transparent proxy, real proxy, Apr ess from © 2003reading (1200 pages) message object, This and compr dispatcher can typically completely you are happy with the ehensiv e text star tsbe w ith a brief ovignored, er view of provided the default plumbing C# (which is the case most of the time). As you will see, the process of specifying the language and then quickly m oves to key technical and ar chitectur issues for is .NET developer channel object (and relatedalformatter) as simple ass.a single line of code. Furthermore, the .NET runtime is the entity in charge of orchestrating the creation and handshaking that takes place to invoke methods on objects located in distinct application domains. To help solidify the sequence of events, ponder Figure 12Ta7, ble o f Con t en t s the basic process of two objects communicating across distinct application domains. which illustrates C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Figure 12-7: A high-level view of the default .NET Remoting architecture

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

Under standing .NET Assem blies A Brief- Word Regarding the Extension of the Default Plumbing

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, Attr ibuteBased Pr ogrammfrom ing that of classic DCOM) is the A key aspect of the .NET Remoting layerand (which is markedly different Pa r t Four Le ve rof a ging the .NET Libr a r ie slayers fact that -most the default remoting

can be extended or completely replaced at the whim of the

Chapter 12 - Thus, Obj ectif Ser and(or thepossibly .NET Remoting er a custom message dispatcher, custom developer. youialization truly want need) toLay build Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms) formatter, or custom real proxy, you are free to do so. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

You are15also toming injectwith additional levels indirection by plugging in custom types that stand between a Chapter - Prable ogr am Windows Formof s Contr ols given layer custom sink used to perform preprocessing or post-processing of a given Chapter 16 - (for The example, Sy stem .I Oa Nam espace

message). Now, to be sure, you may never need to retrofit the core .NET Remoting layer in such ways. However the fact remains that the .NET platform does provide the namespaces to allow you to do so. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 17 - Data Access w ith ADO.NET

Chapter 18 This - ASP.NET Web Pages Web Contr ols of extending the default .NET Remoting layer. If you Note chapter does not and address the topic Chapter 19 wish - ASP.NET Web Applicat to learn how to do ions so, check out Advanced .NET Remoting (Rammer, Apress 2002). Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# .NET an d th e Remoting .N ET Plat f orm , Trade Se con d Ed it ion Terms of the by Andr ew Tr oelsen

ISBN:1590590554

Like any new paradigm, Remoting Apr ess ©.NET 2003 (1200 pages) brings a number of TLAs (three-letter-acronyms) into the mix. Thus, before youThis see compr your first code example, toerdefine number of terms used when ehensiv e text star ts we w ithdo a need brief ov view ofa the describing the composition of a .NET Remoting application. As you would C# language and then quickly m oves to key technical and guess, this terminology is used ar chitectur al issues for .NET developer s. to describe a number of details regarding common questions that arise during the construction of a distributed application: How do we pass a type across application domain boundaries? When exactly is a remote type activated ? How do we manage the lifetime of a remote object? (and so forth). Once you have Taan bleunderstanding o f Con t en t s of the related terminology, the act of building a distributed .NET application will be far C# and t he .NET Plat m, Second that Edition less perplexing. Dofor understand the acronyms that follow are mapped to specific code examples over I ntr theoduction course of the chapter. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e Choices .N ET Plat f orm(MBR , Se con dor Ed it ion Object Marshaling MBV?) ISBN:1590590554

by Andr ew Tr oelsen

Under the .NET platform, you (1200 havepages) two options regarding how a remote object is marshaled to the client. Apr ess © 2003 First question: What the heck is marshaling? Simply a term that describes how a remote This compr ehensiv e text star ts w ith aput, briefmarshaling ov er view ofisthe object is passed between application domains. When you are designing C# language and then quickly m oves to key technical and a remotable object, you may chitectur al issues for .NET developer s. or marshal-by-value (MBV, for short) semantics. choose to employarmarshal-by-reference (MBR, for short) The distinction is as follows: Ta ble o MBR f Conobjects: t en t s The caller receives a proxy to the remote object C# and t he .NET Plat for m, Second Edition

MBV objects: The caller receives a full copy of the object in its own application domain

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

If you configure an MBR object type, the CLR ensures that the transparent and real proxies are created in

Chapter 1 - application The Philosophy of .NET the client's domain, while the MBR object itself remains in the server's application domain. As Chapter 2 Building C# Applications the client invokes methods on the remote type, the .NET Remoting plumbing (examined previously) takes Pa r t Tw o - show The C# Pr will ogr am m ing Lapass, ngua ge over the and package, and

return information between application domain boundaries. To

Chapter 3 MBR - C#objects Language Fundamentals be sure, have a number of traits above and beyond their physical location. As you will see, Chapter 4 - Obj ect -Or ientedconfiguration Pr ogr am mingoptions w ith C#regarding their activation options and lifetime MBR objects have various Chapter 5 - Exceptions and Obj ect Lifetim e management. Chapter 6

- I nter faces and Collections MBV objects, on the Iother hand,Delegates, are local and copies of remote objects (which as you can guess make use of Chapter 7 - Callback nter faces, Ev ents

the .NET serialization protocol examined at the beginning of this chapter). MBV objects have far fewer - Advanced C# Type Const ruction Techniques configuration settings, given that their lifetime is directly controlled by the client. Like any .NET object, once Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s a client has released all references to an MBV type, it is a candidate for garbage collection. Given that Chapter 9 - Under standing .NET Assem blies MBV types are local copies of remote objects, as a client invokes members on the type no network activity Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads occurs during the process. Chapter 8

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t solidify Four - Le ve rdistinction a ging the .NET Libr aMBR r ie s To the between

and MBV objects, think back to Chapter 3 when you examined the

Chapter Obj"ref" ect Ser ialization and the Remoting Lay er role of 12 the-C# keyword. Recall that.NET by default, parameters are passed into a method by value. Thus, Chapter 13 Building a Bet ter Win dow ( Int roducin g Window Forincoming ms) if the receiving function attempts to reassign the value of sthe parameters, the caller is unaware of Chapter the modification. 14 - A Better On Paint the other ing Frhand, amew or if kmethod ( GDI + ) parameters are modified using the "ref" keyword, a

reference the type is passed into thes method, Chapter 15 -toPr ogrvalue am ming with Windows Form Contr ols and thus any modifications are realized after the call. 16 - The Sy stem .I O Nam espace Chapter Chapter 17 - Data Access w ith ADO.NET

The same basic behavior applies in the world of .NET Remoting. If a remote object has been configured as an MBV type, the caller receives a full copy of the remote object within the application's domain, again Chapter 18 - ASP.NET Web Pages and Web Contr ols using the same object serialization technique presented at the start of this chapter. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 - object XML Web vices If a remote hasSer been configured to be an MBR type, the client does not receive a local copy of the I ndex type. Rather, the remote object is bound to the application domain in which it was created, forcing the List caller of Figur to interact es with the remote type via the intervening proxy layer. List of Tables

Now, understand that it will be quite common for a single server to provide access to numerous MBR and MBV types. As you may also suspect, MBR types tend to support methods that return various MBV types, which gives way to the familiar factory pattern (e.g., an object that creates and returns other related objects). Next question: How do we configure our custom class types as MBR or MBV entities?

Configuring an MBV Object To configure an object as an MBV type, you have two options, which happen to be the exact same choices you have when configuring a local .NET object for serialization. Recall that the simplest (and typically most common) approach is to mark your type with the [Serializable] attribute: [Serializable] public class MyCustomMBVClass {...}

C# an d th e .N ET Plat f orm , Se con d Ed it ion

The other, more exotic, approach is to implement the ISerializable interface. Using this technique, you are ISBN:1590590554 by Andr ew Tr oelsen able to customizeApr the serialization process to fit your needs (as illustrated previously in this chapter). ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the

language andObject then quickly m oves to key technical and ConfiguringC#an MBR ar chitectur al issues for .NET developer s.

MBR objects are not marked as such using a .NET attribute, but rather derive (directly or indirectly) from the System.MarshalByRefObject base class: Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

public class MyCustomMBRClass : MarshalByRefObject {...}

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2 exactly - Building C#the Applications So, what does MarshalByRefObject base class bring to the table? Here is the formal definition: Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 abstract - C# Language Fundamentals public class MarshalByRefObject : object Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# { Chapter public 5 - Exceptions and Obj ect Lifetim e virtual ObjRef CreateObjRef(Type requestedType); Chapter public 6 - I nter virtual faces and Collections bool Equals(object obj); Chapter public 7 - Callback virtual I nter faces, intDelegates, GetHashCode(); and Ev ents

virtual object GetLifetimeService(); Chapter public 8 - Advanced C# Type Const ruction Techniques Type Pa r t Threpublic e - Pr ogr am m i ngGetType(); w i th .N ET Assem bl ie s object Chapter public 9 - Undervirtual standing .NET AssemInitializeLifetimeService(); blies virtual stringCont ToString(); Chapter public 10 - Pr ocesses, AppDomains, exts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Beyond the expected functionality provided by System.Object, Table 12-5 describes the role of the remaining members.

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Table 12-5: Key Members of System.MarshalByRefObject

Chapter 16 - The Sy stem .I O Nam espace

System.MarshalByRefObject Chapter 17 - Data Access w ith ADO.NET

Meaning in Life

Pa rMember t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

CreateObjRef()

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object

I ndex ListGetLifetimeServices() of Figur es List of Tables

InitializeLifetimeServices()

Retrieves the current lifetime service object that controls the lifetime policy for this instance Obtains a lifetime service object to control the lifetime policy for this instance

As you can tell, the gist of MarshalByRefObject is to define members that can be overridden to programmatically control the lifetime of the MBR object (more on lifetime management later in this chapter). Note Just because you have configured a type as an MBV or MBR entity does not mean it is only useable within a remoting application, just that it may be used in a remoting application. For example, the System.Windows.Forms.Form type is a descendent from MarshalByRefObject, and thus if it is accessed remotely, is realized as an MBR type. If not, it is just another local object in the client's application domain.

C# an dtoththe e .Nprevious ET Plat f note, orm , understand Se con d Ed itthat ion if a .NET type is not serializable and does Note As a corollary ISBN:1590590554 by Andr ew Tr oelsen not include MarshalByRefObject in its inheritance chain, the type in question can only be Aprand ess © 2003 in (1200 activated used thepages) originating application domain (meaning, they are context bound types). This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con dObjects Ed it ion Final NotesC#Regarding MBR/MBV ISBN:1590590554

by Andr ew Tr oelsen

The .NET Remoting layer has(1200 a number Apr ess © 2003 pages) of intrinsic optimizations that help ensure that when a client interacts with remotable objects, network traffic to aovminimum. This compr ehensiv e text star ts wisithkept a brief er view of To the provide some insights to these internal tweaks, ponder the following points: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Treatment of static members: Static type members are never invoked remotely, but are triggered within the client-side application domain. Ta ble o f Con t en t s

Treatment and accessor methods: For object-level fields and accessor methods, the C# and t he .NET of Platobject for m, fields Second Edition

system inserts a check at runtime to see whether the object is a proxy. If it is not a proxy, field access is direct. Otherwise, the proxy provides accessors to the caller. One - I nt r oduci ng C# a nd the .NET P la tf or m

I ntr oduction Pa r t

Chapter 1 - TheofPhilosophy of .NETmembers: Provided that a remote type has not overridden the virtual Treatment System.Object Chapter 2 Building C# Applications methods of System.Object, methods always execute in the client's application domain. However, if the Pa r t Tw o - Thetype C# Pr ogr am mEquals() ing La ngua remote overrides orge ToString(),

Chapter 3

a network round-trip will occur.

- C# Language Fundamentals

Now that understand the traitswof Chapter 4 you - Obj ect -Or iented Pr distinct ogr am ming ithMBR C# and MBV types, let's check out some issues that are specific5 to -MBR types (MBV types need not Chapter Exceptions and Obj ect Lifetim e apply). Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm Types , Se con d Ed it ion Activation Choices for MBR (WKO or CAO?) ISBN:1590590554

by Andr ew Tr oelsen

Another remoting-centric you face as a .NET programmer has to do with exactly when an MBR Apr ess © choice 2003 (1200 pages) object is activatedThis andcompr whenehensiv it should be star a candidate for garbage on the server. This might e text ts w ith a brief ov er viewcollection of the seem like a strange choice to make, as you might naturally assume that MBR objects are created when C# language and then quickly m oves to key technical and ar chitectur issuesthe for client .NET developer s. the client requests it and diealwhen is done. While it is true that the client is the entity in charge of instructing the remoting layer it wishes to communicate with a remote type, the server application domain may (or may not) create the type at the exact moment the client's code base requests it. The reason for Tathis ble seemingly o f Con t en tstrange s behavior has to do with the optimization. Specifically, every MBR type may be C# and t he .NET for m, Second configured to bePlat activated using Edition one of two techniques: I ntr oduction

As a- IWell Known Object (WKO) Pa r t One nt r oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

As a Client Activated Object (CAO)

Pa r t Tw o - The C# Pr ogr am mof ingconfusion La ngua geis Note A potential point

that fact that the acronym WKO is also called a server-activated

Chapter 3 object - C# Language Fundamentals in the .NET literature. In fact, you may see the SAO acronym in various .NET-centric Chapter 4 articles - Obj ectand -Or iented ogr you am ming ith C# Help and find the terms WKO, server-activated object, or books.PrAs readwonline Chapter 5 SAO, - Exceptions and Obj ectthese Lifetim e understand that three terms are one and the same. Given that WKO seems to be Chapter 6 the - I nter moniker faces and of choice Collections at present, I make use of this acronym in this chapter. Chapter 7

- Callback I nter faces, Delegates, and Ev ents

WKO objects are MBR types whose lifetimes are directly controlled by the server's application domain. Chapter 8 - Advanced C# Type Const ruction Techniques The client-side application activates the remote type using a friendly, well-known string name (hence the Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s term, WKO). The server's application domain allocates WKO types only when the client makes the first Chapter 9 - Under standing .NET Assem blies method call on the object (via the transparent proxy), not when the client's code base makes use of the Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads "new" keyword or via the static Activator.GetObject() method. To illustrate: Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

// Get a proxy to remote object. This line does NOT create the WKO type! object remoteObj = Activator.GetObject(/* params seen later... */); Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) // Invoke a method on remote WKO type. This WILL create the WKO object Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) // and invoke the ReturnMessage() method. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols RemoteMessageObject simple = (RemoteMessageObject)remoteObj; Chapter 16 - The Sy stem .I O Nam espace Console.WriteLine("Server says: {0}", simple.ReturnMessage()); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Pages This and Web Contr ols The rationale for this Web behavior? approach saves a network round-trip solely for the purpose of Chapter creating19the - ASP.NET object. As Web another Applicat interesting ions corollary, WKO types can onlybe created via the type's default

constructor. ThisWeb should make sense, given that the remote type's constructor is only triggered when the Chapter 20 - XML Ser vices client makes the initial member invocation. Thus, the runtime has no other option than to invoke the type's I ndex default constructor. List of Figur es List of Tables

Note Always remember all WKO types must support a default constructor!

If you wish to allow the client to create a remote MBR object using a custom constructor, the server must configure the object as a client-activated object (CAO). CAO objects are entities whose lifetime is controlled by the client's application domain. When accessing a CAO type, a round-trip to the server occurs at the time the client makes use of the "new" keyword (using any of the type's constructors) or via the Activator type.

Stateful Configuration of WKO Types (Singleton or Single Call?) The final .NET design choice to consider with regard to MBR types has to do with how the server should handle multiple requests to a WKO type. CAO types need not apply, given that there is always a one-toone correspondence between a client and a remote CAO type (given that they are stateful). Your first option is to configure a WKO type to function as a singleton type. As the name implies, the CLR will create a single instance of the remote type that will take requests from any number of clients, and is a

natural choice if you need to maintain stateful information among multiple remote callers. Given the fact C# an d th e .N ET Plat f orm , Se con d Ed it ion that multiple clients could invoke the same method at the same time, the CLR places each client by Andr ew Tr invocation on a new thread. It oelsen is your responsibility, however, toISBN:1590590554 ensure that your objects are thread-safe Apr ess © 2003 (1200 using the same techniques seen inpages) Chapter 10. This compr ehensiv e text star ts w ith a brief ov er view of the C# call language quickly m oves to key technical and context of a single method In contrast, a single objectand is athen WKO type that exists only during the al 20 issues for .NET developer invocation. Thus,arif chitectur there are clients making use of s.a WKO type configured with single call semantics, the server will create 20 distinct objects (one for each client), all of which are candidates for garbage collection directly after the method invocation. As you can guess, single call objects are far more scalable Ta ble o f Con t en t s than singleton types, given that they are invariably stateless entities. C# and t he .NET Plat for m, Second Edition

I ntr oduction The server is the entity in charge of determining the stateful configuration of a given WKO type. Pa r t One - I nt r oduci ng C# aoptions nd the .NET P la tf or m Programmatically, these are expressed

via the System.Runtime.Remoting.WellKnownObjectMode

Chapter enumeration: 1 - The Philosophy of .NET Chapter 2

- Building C# Applications

Pa r t Tw o - The C# WellKnownObjectMode Pr ogr am m ing La ngua ge public enum

Chapter 3 {

- C# Language Fundamentals

ChapterSingleCall, 4 - Obj ect -Or iented Pr ogr am ming w ith C# ChapterSingleton 5 - Exceptions and Obj ect Lifetim e

} Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

- Under standing Assemof blies Summarizing the .NET Traits MBR Object Types

Chapter 9

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

As you 11 have seen, the configuration options anibuteMBVBased objectPrare a no-brainer: apply the [Serializable] Chapter - Type Reflection, Late Binding, and of Attr ogramm ing attribute copies theLibr typea rto Pa r t Four -toLeallow ve r a ging the of .NET ie sbe

returned to the client's application domain. At this point, all

interaction theSer MBV type takes place in Remoting the client's locale. When the client is finished using the MBV Chapter 12 - with Obj ect ialization and the .NET Lay er type, it 13 is a- candidate collection, and all is well with the world. Chapter Building a for Bet garbage ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

MBR types, however, have a number of possible configuration choices. As you have seen, a given MBR type can be configured with regard to its time of activation, statefullness, and lifetime management. To Chapter 16 - The Sy stem .I O Nam espace summarize the array of possibilities, Table 12-6 documents how WKO and CAO types stack up against Chapter 17you - Data Access w ith ADO.NET the traits have just examined. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Table 12-6: Configuration Options for Contr MBRols Types Chapter 19 - ASP.NET Web Applicat ions

MBR 20 Object Behavior (aka ServerChapter - XML WebWKO Ser vices

CAO Behavior

Trait I ndex

Activated Object)

ListInstantiation of Figur es

WKO types can only be activated using the default constructor of the type, which is triggered when the client makes the first method invocation.

CAO types can be activated using any constructor of the type. The remote object is created at the point the caller makes use of constructor semantics (or via the Activator type).

WKO types can be configured as singleton or single call entities. Singleton types can service multiple clients, and are therefore stateful. Single call types are alive only during a specific client-side invocation, and are therefore stateless.

The lifetime of a CAO type is dictated by the caller, and therefore, CAO types are stateful entities.

Listoptions of Tables

State management

Lifetime WKO types make usedofEdait ion CAO types make use of a leaseC# Singleton an d th e .N ET Plat f orm , Se con management by lease-based management scheme based management scheme ISBN:1590590554 Andr ew Tr oelsen (described later in this chapter). Single (described later in this chapter). Apr ess © 2003 (1200 pages) call WKO types are a candidate for This compr ehensiv e text star ts w ith a brief ov er view of the after the C# garbage languagecollection and then quickly m current oves to key technical and ar chitectur methodalinvocation. issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N f orm ,Remoting Se con d Ed it ionProject Basic Deployment ofETaPlat .NET by Andr ew Tr oelsen

ISBN:1590590554

Enough acronyms! point youpages) are almost ready to build your first .NET Remoting application. Before AprAt essthis © 2003 (1200 you do, however,This I need to discuss one When you are building a .NET Remoting compr ehensiv e textfinal star detail—deployment. ts w ith a brief ov er view of the application, you are almost certain to end up with three distinct .NET assemblies that will constitute the C# language and then quickly m oves to key technical and ar chitectur al issues(yes, for .NET developer s. The first two assemblies I am sure you can already entirety of your remote application three, not two). account for: Ta ble o The f Con client: t en t s This assembly is the entity that is interested in obtaining access to a remote object. Like

any .NET the client may be a Windows Forms application, a console application or an C# and t he .NETapplication, Plat for m, Second Edition ASP.NET Web application. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

The server: This assembly is the entity that receives channel requests from the remote client and - The Philosophy of .NET hosts the remote objects. Be aware that the server application is often termed the listener application. Chapter 2 - Building C# Applications The server may be a custom console application, a custom Windows Service (as you will see), or MS Pa r t Tw o - The C# Pr ogr am m ing La ngua ge IIS. Chapter 1

Chapter 3

- C# Language Fundamentals

Chapter 4 where - Obj ect -Or iented Pr ogr am mingfit w in? ith C# So then, does the third assembly Well, in reality, the server application is typically a host to a Chapter 5 - Exceptions and Obj Lifetim e third assembly that defines andectimplements the remote objects. For convenience, I'll call this assembly the Chapter 'general 6 assembly'. - I nter faces This anddecoupling Collections of the assembly containing the remote objects and server host is quite

important, that both thefaces, clientDelegates, and the server assemblies typically set a reference to the general Chapter 7 -inCallback I nter and Ev ents assembly order to obtain theConst metadata of the remotable types. Chapter 8 in - Advanced C# Type ructiondefinitions Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

In the simplest case, the general assembly is placed into the application directory of the client and server. - Under standing .NET Assem blies The only possible drawback to this approach is the fact that the client has a reference to an assembly that Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads contains CIL code that is never used (which may be a problem if you wish to ensure that the remote clients Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing cannot examine your custom proprietary code). Specifically, the only reason the client requires a reference Pa r t Four - Le ve r a ging the .NET Libr a r ie s to the general assembly is to obtain the metadata descriptions of the remotable types. There are several Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er ways to overcome this glitch, for example: Chapter 9

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter Construct 14 - A Better your remote Paint ingobjects Fr amewto ormake k ( GDIuse + ) of interface-based programming techniques. In this way,

you15can build anming additional assembly that contains Chapter - Pr ogr am with Windows Form s Contr ols nothing but interface definitions for the remote types. is able to set a reference to a .NET binary that contains nothing but Chapter 16 - Given The Sythis, stemthe .I Oclient Nam espace interface definitions. Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Make use of the soapsuds.exe command line application. Using this tool, you are able to generate an assembly that contains nothing but metadata descriptions of the remote types. You'll check out the Chapter 19 - ASP.NET Web Applicat ions use of soapsuds.exe later in this chapter. Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 20 - XML Web Ser vices

I ndex Manually build an assembly that contains nothing but metadata descriptions of the remote types (from List ofscratch Figur es or by altering the assembly generated via soapsuds.exe). List of Tables

To keep things simple over the course of this chapter, you will build and deploy general assemblies that contain the required metadata as well as the CIL implementation. Note If you wish to examine how to implement general assemblies using each of these alternatives, check out Distributed .NET Programming in C# (Barnaby, Apress 2002).

C# First an d th e Distributed .N ET Plat f orm , SeApplication con d Ed it ion Building Our ISBN:1590590554

by Andr ew Tr oelsen

There is nothing more than building a distributed application using a new platform. To illustrate how Apr esssatisfying © 2003 (1200 pages) quickly you are able to get up and running with the This compr ehensiv e text star ts w ith .NET a briefRemoting ov er view layer, of the let's build a simple example. As mentioned, the entirety of this example consists of three .NET assemblies: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

A general assembly named SimpleRemotingAsm.dll Af client assembly named SimpleRemoteObjectClient.exe Ta ble o Con t en ts C# and t he .NET Plat for m, Second Edition

A server assembly named SimpleRemoteObjectServer.exe

I ntr oduction

Pa r t One I nt r oduciof ngthis C# example a nd the .NET P la use tf or mof The first- iteration makes

various remoting-centric types (RemotingConfiguration and

Chapter 1 - The Philosophy of .NET ChannelServices) that are examined in further detail in just a bit. Chapter 2 - Building C# Applications

Building the General Assembly

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4 -create Obj ectthe -Orgeneral iented Prassembly ogr am ming(SimpleRemotingAsm.dll), w ith C# First, let's which will be referenced by both the server Chapter 5 -binaries. Exceptions and Obj ect Lifetim e and client SimpleRemotingAsm.dll defines a single MBR type named RemoteMessageObject, which Chapter supports 6 two - I nter public faces members: and Collections DisplayMessage() prints a client supplied message to the server's console

window, ReturnMessage() returns a and textual message to the client. Here is the complete code of this new C Chapter 7 while - Callback I nter faces, Delegates, Ev ents class library: Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - Under standing .NET Assem blies namespace SimpleRemotingAsm Chapter { 10 - Pr ocesses, AppDomains, Cont exts, and Threads

is a type will beibute- Based Pr ogramm ing Chapter // 11 - This Type Reflection, Late that Binding, and Attr Pa r t Four// - Lemarshaled ve r a ging the by .NETreference Libr a r ie s

(MBR) if accessed remotely.

class RemoteMessageObject: MarshalByRefObject Chapter public 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter { 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

The ctor message just to Chapter 14 - A // Better Paint ing Fr prints amew or k (aGDI +) confirm has been Chapter 15 - Pr // ogr am ming withit Windows Form s activated. Contr ols public RemoteMessageObject() { Console.WriteLine("RemoteMessageObject ctor called!");} Chapter 17 - Data Access w ith ADO.NET // This method takes an input string Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces // from the caller. Chapter 18 - ASP.NET Web Pages and Web Contr ols public void DisplayMessage(string msg) Chapter 19 - ASP.NET Web Applicat ions { Console.WriteLine("Message is: {0}", msg);} Chapter 20 - XML Web Ser vices // This method returns a value to the caller. I ndex public string ReturnMessage() List of Figur es { return "Hello from the server!"; } List of Tables } } Chapter 16 - The Sy stem .I O Nam espace

The major point of interest is the fact that the type derives from the System.MarshalByRefObject base class, which ensures that the derived class will be accessible via a client-side proxy (e.g., an MBR object type). Also note I have added a Console.WriteLine() call in the type's constructor, to see exactly when the type is created. That's it. Go ahead and build your new SimpleRemotingAsm.dll assembly.

Building the Server Assembly Recall that server assemblies are essentially hosts for general assemblies that contain the remotable objects. Thus, create a console-based *.exe assembly named SimpleRemoteObjectServer. The role of this binary is to open a channel for the incoming requests and register RemoteMessageObject as a WKO type. Set a reference to the System.Runtime.Remoting.dll and SimpleRemotingAsm.dll assemblies, and update Main() as follows:

using using using using using

System; C# an d th e .N ET Plat f orm , Se con d Ed it ion System.Runtime.Remoting; ISBN:1590590554 by Andr ew Tr oelsen System.Runtime.Remoting.Channels; Apr ess © 2003 (1200 pages) System.Runtime.Remoting.Channels.Http; This compr ehensiv e text star ts w ith a brief ov er view of the SimpleRemotingAsm; C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

namespace SimpleRemoteObjectServer { class SimpleObjServer Ta ble o f Con t en t s { C# and t he .NET Plat for m, Second Edition static void Main(string[] args) I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Console.WriteLine("***** SimpleRemoteObjectServer started! *****") Chapter 1 - The Philosophy of .NET Console.WriteLine("Hit enter to end."); Chapter 2 - Building C# Applications // Register a new HttpChannel Pa r t Tw o - The C# Pr ogr am m ing La ngua ge HttpChannel c = new HttpChannel(32469); Chapter 3 - C# Language Fundamentals ChannelServices.RegisterChannel(c); Chapter 4 - Obj ect -Or// iented Pr ogr am ming w ith type, C# Register a WKO using singleton activation. Chapter 5 - Exceptions and Obj ect Lifetim e RemotingConfiguration.RegisterWellKnownServiceType( Chapter 6 - I nter faces and Collections typeof(SimpleRemotingAsm.RemoteMessageObject), Chapter 7 - Callback I nter faces, Delegates, and Ev ents "RemoteMsgObj.soap", Chapter 8 - Advanced C# Type WellKnownObjectMode.Singleton); Const ruction Techniques Pa r t Thre e - Pr ogr am mConsole.ReadLine(); i ng w i th .N ET Assem bl ie s } standing .NET Assem blies Chapter 9 - Under Chapter } 10 - Pr ocesses, AppDomains, Cont exts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Main() begins by creating a new HttpChannel type using an arbitrary port ID. This port is opened on registering the channel via the static ChannelServices.RegisterChannel() method. Once the channel has been registered, Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) the remote server assembly is now equipped to process incoming messages via port number 32469. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 16 The - Thenumber Sy stem you .I O Nam espace Note assign to a port is typically up to you (or your system administrator). Do be aware, Chapter 17 however, - Data Access that port w ith IDs ADO.NET below 1024 are reserved for use. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Next, to18register the SimpleRemotingAsm.RemoteMessageObject type as a WKO requires the use of the Chapter - ASP.NET Web Pages and Web Contr ols

RemotingConfiguration.RegisterWellKnownServiceType() method. Here you are informing the CLR that this object is to be realized as a WKO type named RemoteMsgObj.soap. This second parameter to the static Chapter 20 - XML Web Ser vices RegisterWellKnownServiceType() is a simple string (of your choosing) that will be used to identify the object I ndex across application domain boundaries (hence the notion of a well-known object). Chapter 19 - ASP.NET Web Applicat ions

List of Figur es

List of final Tables The parameter is a member of the WellKnownObjectMode enumeration, which you have specified as

WellKnownObjectMode.Singleton. Recall that singleton WKO types ensure that a single instance of the RemoteMessageObject will service all incoming requests. Cool! Build your server assembly and move onto the client-side code.

Building the Client Assembly Now that you have a listener that is hosting your remotable object, the final step is to build an assembly that will request access to its services. Again, let's use a simple console application. Set a reference to System.Runtime.Remoting.dll and SimpleRemotingAsm.dll. Implement Main() as follows: using using using using using

System; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Http; SimpleRemotingAsm;

C# an d th e .N ET Plat f orm , Se con d Ed it ion namespace SimpleRemoteObjectClient ISBN:1590590554 by Andr ew Tr oelsen { Apr ess © 2003 (1200 pages) class SimpleObjClient This compr ehensiv e text star ts w ith a brief ov er view of the { C# language then quickly m oves to key technical and static void and Main(string[] args) ar chitectur al issues for .NET developer s. { Console.WriteLine("***** SimpleRemoteObjectClient started! *****") Console.WriteLine("Hit enter to end."); Ta ble o f Con t en t s // Create a new HttpChannel C# and t he .NET Plat for m, Second Edition HttpChannel c = new HttpChannel(); I ntr oduction ChannelServices.RegisterChannel(c); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // Get a proxy to remote WKO type. Chapter 1 - The Philosophy of .NET object remoteObj = Activator.GetObject( Chapter 2 - Building C# Applications typeof(SimpleRemotingAsm.RemoteMessageObject), Pa r t Tw o - The C# Pr ogr am m ing La ngua ge "http://localhost:32469/RemoteMsgObj.soap"); Chapter 3 - C# Language Fundamentals // Now use the remote object. Chapter 4 - Obj ect -OrRemoteMessageObject iented Pr ogr am ming w ith C# simple = (RemoteMessageObject)remoteObj; Chapter 5 - Exceptions and Obj ect Lifetim e simple.DisplayMessage("Hello from the client!"); Chapter 6 - I nter facesConsole.WriteLine("Server and Collections says: {0}", simple.ReturnMessage()); Chapter 7 - Callback IConsole.ReadLine(); nter faces, Delegates, and Ev ents Chapter 8 - Advanced } C# Type Const ruction Techniques Pa r t Thre}e - Pr ogr am m i ng w i th .N ET Assem bl ie s } Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

A few notes about this client app. First, note that the client is also required to register an HTTP channel, but the client does not specify a port ID as this is dynamically assigned by the .NET Remoting layer. Given that the clien Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) is interacting with a registered WKO type, you are limited to triggering the type's default constructor. To do so, Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) make use of the Activator.GetObject() method, specifying two parameters. The first is the type information that Chapter 15 - Pr ogr am ming with Windows Form s Contr ols describes the remote object you are interested in interacting with. Read that last sentence again. Given that the Chapter 16 - The Sy stem .I O Namrequires espace the object's metadata description, it should make more sense why the Activator.GetObject() method Chapter 17 Data Access w ith ADO.NET client is also required to reference the general assembly! Again, at the end of the chapter you examine various Pa r t Fi ve W e b up Appl ica aspect ti ons and ML W e b Se r vi ces ways to -clean this of Xyour client-side assembly. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 18 - ASP.NET Web Pages and Web Contr ols

The second parameter to Applicat Activator.GetObject() is termed the activation URL. Unlike classic DCOM which Chapter 19 - ASP.NET Web ions identified objects using a numerical GUID, .NET makes use of a friendlier, more readable string name. Chapter 20 remote - XML Web Ser vices Activation URLs that describe a WKO type can be generalized into the following format: I ndex List of Figur es

ProtocolScheme://ComputerName:Port/ObjectUri List of Tables Finally, note that the Activator.GetObject() method returns a generic System.Object type, and thus you must make use of an explicit cast to gain access to the members of the RemoteMessageObject.

an d th e .N ET Application Plat f orm , Se con d Ed it ion Testing theC#Remoting by Andr ew Tr oelsen

ISBN:1590590554

To test your application, by launching the server application, which will open an HTTP channel and Apr ess ©begin 2003 (1200 pages) register your remote object for access. Next, launch instance of the client application. If all is well, your This compr ehensiv e text star ts w ith aan brief ov er view of the server window should appear as follows (Figure 12-8) while the client application presents what you see in C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. Figure 12-9.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET Figure The output Chapter 2 - 12-8: Building C#server's Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections Figure The client's Chapter 7 - 12-9: Callback I nter faces,output Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET Plat f orm , Se con d Ed itType ion Understanding ChannelServices ISBN:1590590554

by Andr ew Tr oelsen

As you have seen, when server wishes to advertise the existence of a remote type, it makes Apr ess ©a2003 (1200application pages) use of the System.Runtime.Remoting.Channels.ChannelServices ChannelServices provides a small This compr ehensiv e text star ts w ith a brief ov er viewtype. of the set of static methods that aid in the process of remoting channel registration, resolution, and URL C# language and then quickly m oves to key technical and ar chitectur al issues .NET developer s. discovery. Table 12-7 documents theformembers in question. Table 12-7: Select Members of the ChannelServices Type Ta ble o f Con t en t s

of Plat for m, Second Edition Meaning in Life C# Member and t he .NET I ntrChannelServices oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

RegisteredChannels

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

This property gets or sets a list of currently registered channels, each of which is represented by the IChannel interface.

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

AsyncDispatchMessage() Chapter 3 - C# Language Fundamentals Asynchronously dispatches the given message to the Chapter 4 Chapter 5

server-side - Obj ect -Or iented Pr ogr am ming w ith C# chain(s) based on the URI embedded in the - Exceptions and Obj ect Lifetimmessage. e

Chapter 6 - I nter faces and Collections CreateServerChannelSinkChain() Chapter 7

Creates a channel sink chain for the specified channel.

- Callback I nter faces, Delegates, and Ev ents

DispatchMessage() Dispatches incoming remote calls. - Advanced C# Type Const ruction Techniques Pa rGetChannel() t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s a registered channel with the specified name. Returns Chapter 8 Chapter 9

- Under standing .NET Assem blies

GetChannelSinkProperties()

Returns an IDictionary of properties for a given proxy.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding,Returns and Attran ibuteBased Pr the ogramm ingthat can be used to reach GetUrlsForObject() array of all URLs Pa r t Four - Le ve r a ging the .NET Libr a r ie s

the specified object.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

RegisterChannel()

Registers a channel with the channel services.

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Chapter 14 - A Better Paint ing Fr amew or k Synchronously ( GDI + ) SyncDispatchMessage() dispatches the incoming message to the Chapter 15 - Pr ogr am ming with Windows Form server-side s Contr ols chain(s) based on the URI embedded in the Chapter 16 - The Sy stem .I O Nam espace message. Chapter 17 - Data Access w ith ADO.NET

UnregisterChannel()

Unregisters a particular channel from the registered channels list.

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

In addition to the aptly named RegisterChannel() and UnregisterChannel() methods, ChannelServices

Chapter XML Web Ser vices defines20 the- RegisteredChannels property. This member returns an array of IChannel interfaces, that each I ndex represent a handle to each channel registered in a given application domain. The definition of the List of Figurinterface es IChannel is quite straightforward: List of Tables

public interface IChannel { string ChannelName { get; } int ChannelPriority { get; } string Parse(string url, ref String objectURI); }

As you can see, each channel is given a friendly string name as well as a priority level. To illustrate, if you were to update the SimpleRemoteObjectClient application with the following logic: // List all registered channels. IChannel[] channelObjs = ChannelServices.RegisteredChannels; foreach(IChannel i in channelObjs) {

Console.WriteLine("Channel name: {0}", i.ChannelName); C# an d th e .N ET Plat f orm ,Priority: Se con d Ed it ion Console.WriteLine("Channel {0}", i.ChannelPriority); ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

}

This compr ehensiv e text star ts w ith a brief ov er view of the C#client language and then now quickly m oves key technical You would find the side console looks like to Figure 12-10. and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - 12-10: The Philosophy of .NET Figure Enumerating client-side channels Chapter 2 - Building C# Applications Pa r t Tw o - The of C#the Pr ogr am m ing methods La ngua geof The majority remaining

ChannelServices are used to interact with custom sink types,

Chapter which may 3 - be C# plugged Language into Fundamentals the .NET Remoting layer. Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET Plat f orm , Se con d Ed it ion Understanding RemotingConfiguration Type ISBN:1590590554

by Andr ew Tr oelsen

Another key remoting-centric RemotingConfiguration, which as the name suggests, is used to Apr ess © 2003 type (1200 is pages) configure variousThis aspects of a remoting you have compr ehensiv e text application. star ts w ith aCurrently, brief ov er view of theseen this type in use on the server side (via the call to the RegisterWellKnownServiceType() method). Table C# language and then quickly m oves to key technical and 12-8 lists additional static ar chitectur members of interest, some alofissues whichfor you.NET seedeveloper in action s. over the remainder of this chapter: Table 12-8: Members of the RemotingConfiguration Type Ta ble o f Con t en t s

of Plat for m, Second Edition C# Member and t he .NET

Meaning in Life

I ntrRemotingConfiguration oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

ApplicationId

Chapter 1

- The Philosophy of .NET

Gets the ID of the currently executing application

ApplicationName Chapter 2 - Building C# Applications

Gets or sets the name of a remoting application

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Gets the ID of the currently executing process

ProcessId

Chapter 3

- C# Language Fundamentals

Configure() Reads the configuration file and configures the Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6 - I nter faces and Collections GetRegisteredActivatedClientTypes() Chapter 7 Chapter 8

remoting infrastructure Retrieves an array of object types registered on the

- Callback I nter faces, Delegates, and Ev ents as types that will be activated remotely client - Advanced C# Type Const ruction Techniques

Pa rGetRegisteredActivatedServiceTypes() t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Retrieves an array of object types registered on the service end that can be activated on request from a Chapter 9 - Under standing .NET Assem blies client Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing types registered on the GetRegisteredWellKnownClientTypes() Retrieves an array of object Pa r t Four - Le ve r a ging the .NET Libr a r ie s client end as well-known types Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

GetRegisteredWellKnownServiceTypes()

Retrieves an array of object types registered on the service end as well-known types

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter IsActivationAllowed() 15 - Pr ogr am ming with Windows Form s Contr Returns ols a Boolean value indicating whether the Chapter 16 - The Sy stem .I O Nam espace

specified Type is allowed to be client activated

Chapter 17 - Data Access w ith ADO.NET

Checks whether the specified object type is registered as a remotely activated client type

IsRemotelyActivatedClientType()

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

IsWellKnownClientType() Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex RegisterActivatedClientType() List of Figur es List of Tables

Checks whether the specified object type is registered as a well-known client type Registers an object Type on the client end as a type that can be activated on the server

RegisterActivatedServiceType()

Registers an object Type on the service end as one that can be activated on request from a client

RegisterWellKnownClientType()

Registers an object Type on the client end as a wellknown type (single call or singleton)

RegisterWellKnownServiceType()

Registers an object Type on the service end as a well-known type (single call or singleton)

Recall that the .NET Remoting layer distinguishes between two types of MBR objects: WKO (aka server activated) and CAO (aka client activated). Furthermore, WKO types can be configured to make use of singleton or single call activations. Using the functionality of the RemotingConfiguration type, you are able to dynamically obtain such information at runtime. For example, if you update the Main() method of your SimpleRemoteObjectServer application with the following:

static void Main(string[] args) C# an d th e .N ET Plat f orm , Se con d Ed it ion { ISBN:1590590554 by Andr ew Tr oelsen ... Apr ess © 2003 (1200 pages) // Set a friendly name for this server app. This compr ehensiv e text star ts w ith a brief ov=er"First view of theserver app!"; RemotingConfiguration.ApplicationName C# language and then quickly m oves to key technical and Console.WriteLine("App Name: {0}", ar chitectur al issues for .NET developer s. RemotingConfiguration.ApplicationName); // Get an array of WellKnownServiceTypeEntry types // that represent all the registered WKOs. Ta ble o f Con t en t s WellKnownServiceTypeEntry[] WKOs = C# and t he .NET Plat for m, Second Edition RemotingConfiguration.GetRegisteredWellKnownServiceTypes(); I ntr oduction // Now print their statistics. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m foreach(WellKnownServiceTypeEntry wko in WKOs) Chapter 1 - The Philosophy of .NET { Chapter 2 - Building C# Applications Console.WriteLine("Asm name containing WKO: {0}", wko.AssemblyName); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Console.WriteLine("URL to WKO: {0}", wko.ObjectUri); Chapter 3 - C#Console.WriteLine("Type Language Fundamentals of WKO: {0}", wko.ObjectType); Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Console.WriteLine("Mode of WKO: {0}", wko.Mode); Chapter } 5 - Exceptions and Obj ect Lifetim e Chapter 6 - I nter faces and Collections } Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

you will efind listam ofmall WKO registered Pa r t Thre - Praogr i ng w i th types .N ET Assem bl ie s by

this server application domain. As you iterate over the array of WellKnownServiceTypeEntry types, you are able to print out various points of interest regarding each Chapter 9 - Under standing .NET Assem blies WKO. Given that our server's application only registered Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threadsa single type (SimpleRemotingAsm.RemoteMessageObject), we find the following output (Figure 12-11). Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter Figure 18 - 12-11: ASP.NET Server-side Web Pagesstatistics and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

The other method of the RemotingConfiguration type is Configure(). As you see in just a bit, this static Chapter 20 -major XML Web Ser vices member allows the client- and server-side application domains to make use of remoting configuration files.

I ndex

List of Figur es List of Tables

C# anActivation d th e .N ET PlatMode f orm , Se con Ed it ion Types Revisiting the of dWKO ISBN:1590590554

by Andr ew Tr oelsen

Recall that WKOApr types be(1200 configured ess can © 2003 pages) to function under singleton or single call activation. Currently, our server application has registered our star WKO toithemploy activation semantics: This compr ehensiv e text ts w a brief singleton ov er view of the C# language and then quickly m oves to key technical and al issues for .NET developer s. // Singletonsar chitectur can service multiple clients. RemotingConfiguration.RegisterWellKnownServiceType( typeof(SimpleRemotingAsm.RemoteMessageObject), Ta ble o f Con t en t s "RemoteMsgObj.soap", C# and t he .NET Plat for m, Second Edition WellKnownObjectMode.Singleton); I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - The Philosophy .NET of receiving requests from multiple clients. Thus, singleton objects Again, singleton WKOs areofcapable Chapter 2 Building C# Applications maintain a one-to-many relationship between themselves and the remote clients. To test this behavior for Pa r t Tw o - run The the C# server Pr ogr am m ing La ngua yourself, application (if itgeis

not currently running) and launch three separate client

Chapter applications. 3 - C# If you Language look atFundamentals the output for the server, you will find a single call to the

RemoteMessageObject's default constructor 12-12). Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith (Figure C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Figure SingletonLate WKOs are shared remote clients. ing Chapter 11 - 12-12: Type Reflection, Binding, and Attramong ibute- Based Pr ogramm Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Now to test the behavior of single call objects, modify the server to register the WKO to support single call activation:

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

// Single call types maintain a 1-to-1 relationship // between client and WKO. Chapter 16 - The Sy stem .I O Nam espace RemotingConfiguration.RegisterWellKnownServiceType( Chapter 17 - Data Access w ith ADO.NET typeof(SimpleRemotingAsm.RemoteMessageObject), Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces "RemoteMsgObj.soap", Chapter WellKnownObjectMode.SingleCall); 18 - ASP.NET Web Pages and Web Contr ols Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

Once you have recompiled and run the server application, again launch three clients. This time you can I ndex seeofthat a es new RemoteMessageObject is created for each client request (Figure 12-13). List Figur List of Tables

Figure 12-13: Single call WKOs maintain a one-to-one relationship with their remote clients. SOURCE CODE

The SimpleRemotingAsm, SimpleRemoteObjectServer, and SimpleRemoteObjectClient projects are located under the Chapter 12 directory.

C# anServer d th e .N ETto Plat , Se con d Machine Ed it ion Deploying the af orm Remote by Andr ew Tr oelsen

ISBN:1590590554

So far so good! At this have just crossed an application and process boundary on a single Apr esspoint, © 2003you (1200 pages) machine. If you are connected to an additional machine, This compr ehensiv e text star ts w ith a brieflet's ov erextend view ofthis theexample to allow the client to interact with the RemoteMessageObject type across a machine boundary. To do so, follow these steps: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

1. On your server machine, create and share a folder to hold your server-side assemblies. 2. Copy the SimpleRemoteObjectServer.exe and SimpleRemotingAsm.dll assemblies to this serverTa ble o f side Con tshare en t s point. C# and t he .NET Plat for m, Second Edition

3. Open your SimpleRemoteObjectClient project workspace and retrofit the activation URL to specify I ntr oduction name ofngthe Pa r t Onethe - I nt r oduci C#remote a nd themachine. .NET P la tfFor or mexample: Chapter 1

- The Philosophy of .NET

Chapter // 2 - Get Building C# Applications a proxy to remote object. Pa r t Tw oobject - The C# remoteObj Pr ogr am m ing = La ngua ge Activator.GetObject(

Chapter 3

- C#typeof(SimpleRemotingAsm.RemoteMessageObject), Language Fundamentals

Chapter 4

"http://YourRemoteBoxName:32469/RemoteMsgObj.soap"); - Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

4. Execute the SimpleRemoteObjectServer.exe application on the server machine.

Chapter 8 - Advanced C# Type Const ruction Techniques 5. Execute the SimpleRemoteObjectClient.exe application on the client machine. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

6. Sit and grin. .NET Assem blies Chapter 9 back - Under standing Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Note Activation URLs may specify a machine's IP address in place of its friendly name.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an dTCP th e .NChannel ET Plat f orm , Se con d Ed it ion LeveragingC#the by Andr ew Tr oelsen

ISBN:1590590554

Currently, your remote is accessible via the HTTP network protocol. As mentioned, this protocol is Apr essobject © 2003 (1200 pages) quite firewall-friendly, however the resulting are a bitofonthe the bloated side (given the nature This compr ehensiv e text starSOAP ts w ith packets a brief ov er view of XML data representation). To lighten the payload, we can update the C# language and then quickly m oves to key technical and client and server assemblies to ar chitectur al issues for .NET developer s. of the BinaryFormatter type behind the scenes. make use of the TCP channel, and therefore make use Here are the relevant updates to the server assembly: Ta ble Note o f Con When t en t syou are defining an object to be URI-accessible via a TCP endpoint, it is common (but not

tom, make use Edition of the *rem" extension (i.e., remote). C# and t he required) .NET Plat for Second I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // Server adjustments!

Chapter - The Philosophy of .NET using1 System.Runtime.Remoting.Channels.Tcp; Chapter ... 2

- Building C# Applications

Pa static r t Tw o - The void C# Main(string[] Pr ogr am m ing La ngua args) ge

{ Chapter 3

- C# Language Fundamentals

... 4 Chapter

- Obj ect -Or iented Pr ogr am ming w ith C# a and newObjTcpChannel Chapter // 5 - Create Exceptions ect Lifetim e

new TcpChannel(32469); Chapter TcpChannel 6 - I nter faces c and=Collections Chapter ChannelServices.RegisterChannel(c); 7 - Callback I nter faces, Delegates, and Ev ents

// - Register a 'well-known' object in single call mode. Advanced C# Type Const ruction Techniques RemotingConfiguration.RegisterWellKnownServiceType( Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s typeof(SimpleRemotingAsm.RemoteMessageObject), Chapter 9 - Under standing .NET Assem blies "RemoteMsgObj.rem", Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads WellKnownObjectMode.SingleCall); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Console.ReadLine(); Pa r t Four - Le ve r a ging the .NET Libr a r ie s } Chapter 8

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter A Better Paint ing Fr amew k ( GDI + ) Notice 14 that- we are now registering a or System.Runtime.Remoting.Channels.Tcp.TcpChannel type to the Chapter .NET Remoting 15 - Pr ogrlayer. am ming Also with note Windows that theForm object s Contr URIols has been altered to support a more generic name

(RemoteMsgObj.rem) than the SOAP centric *.soap extension. The client-side updates are equally Chapter 16 - The Sy stemrather .I O Nam espace as simple: Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols // Client adjustments! Chapter using19System.Runtime.Remoting.Channels.Tcp; - ASP.NET Web Applicat ions

... 20 - XML Web Ser vices Chapter static void Main(string[] args) I ndex { of Figur es List ... List of Tables // Create a new TcpChannel TcpChannel c = new TcpChannel(); ChannelServices.RegisterChannel(c); // Get a proxy to remote object. object remoteObj = Activator.GetObject( typeof(SimpleRemotingAsm.RemoteMessageObject), "tcp://localhost:32469/RemoteMsgObj.rem"); // Use object. RemoteMessageObject simple = (RemoteMessageObject)remoteObj; simple.DisplayMessage("Hello from the client!"); Console.WriteLine("Server says: {0}", simple.ReturnMessage()); Console.ReadLine(); }

The only point to be aware of here is that the client's activation URL now must specify the tcp:// channel

qualifier rather than http://. Beyond that, the bulk of the code base is identical to the previous HttpChannel C# an d th e .N ET Plat f orm , Se con d Ed it ion logic. by Andr ew Tr oelsen

SOURCE CODE

ISBN:1590590554

Apr ess © 2003 (1200 pages) The TCPSimpleRemoteObjectServer and TCPSimpleRemoteObjectClient projects are located under the Chapter (both use the SimpleRemotingAsm.dll This compr ehensiv e text star12 ts directory w ith a brief ov erprojects view of the C# language and then quickly m oves to key technical and created previously). ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET PlatFiles f orm , Se con d Ed it ion Remoting Configuration ISBN:1590590554

by Andr ew Tr oelsen

At this point you have successfully built a distributed application (leveraging two computers) using the .NET Apr ess © 2003 (1200 pages) Remoting layer. One issue you may noticed first This compr ehensiv e have text star ts w ithinathese brief ov er examples view of theis that fact that the client and the server applications have a good deal of hard-coded logic within their and respective binaries. For example, the C# language and then quickly m oves to key technical chitectur issues .NET developer server specifies aarfixed portalID, fixedfor activation mode, s. and fixed channel type. The client, on the other hand, hard-codes the name of the remote object it is attempting to interact with. TaAs bleyou o f Con might t enagree, ts it is wishful thinking to assume that initial design notes remain unchanged once an

application is deployed. C# and t he .NET Plat for m, Ideally, Second details Edition such as port ID and object activation mode (and whatnot) could be altered on the fly without needing to recompile and redistribute the client or server code bases. Under the I ntr oduction .NET Remoting scheme, Pa r t One - I nt r oduci ng C# aall nd the the aforementioned .NET P la tf or m

issues can be circumvented using the remoting

configuration file. Chapter 1 - The Philosophy of .NET Chapter 2

- Building C# Applications

As you recall from Chapter 9, *.config can be used to provide hints to the CLR regarding the loading of externally referenced assemblies. The same *.config files can be used to inform the CLR of a number of Chapter 3 - C# Language Fundamentals remoting-related details, on both the client side and the server side. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - Exceptions and *.config Obj ect Lifetim e element is used to hold various When building a remoting file, the Chapter remoting-centric 6 - I nter faces details. andDo Collections be aware that if you are building an application that already has a *.config file

that specifies assembly details, and you Ev are free to add remoting elements within the same file. Thus, Chapter 7 - Callback I nterresolution faces, Delegates, ents a single8 *.config file that remoting binding information would look something like this: Chapter - Advanced C# contains Type Const ruction and Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

If your configuration file has no need to specify assembly binding logic, you can omit the element and make use of the following skeleton *config file:

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

I ndex

List of Figur es

List of Tables

Chapter 20 - XML Web Ser vices

Building Server-Side *.config Files Server-side configuration files allow you to declare the objects that are to be reached via remote invocations as well as channel and port information. Basically, using the , , and elements, you are able to replace the following server-side logic: // Hard coded HTTP server logic. HttpChannel c = new HttpChannel(32469); ChannelServices.RegisterChannel(c); RemotingConfiguration.RegisterWellKnownServiceType( typeof(SimpleRemotingAsm.RemoteMessageObject), "RemoteMsgObj.soap",

WellKnownObjectMode.Singleton); C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

ess © 2003 with the followingApr *.config file: (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

ar chitectur al issues for .NET developer s.



Ta ble o f Con t en t s

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - C# Language Fundamentals

Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e

Chapter 6 - I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Notice much ofmthe server-side Pa r t Threthat e - Pr ogr am i ngrelevant w i th .N ET Assem bl ie remoting s

information is wrapped within the scope of the

(not server) element. The child

element makes use of three attributes (mode, type, Chapter 9 - Under standing .NET Assem blies and objectUri) to specify the well-known object to register Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads with the .NET Remoting layer. The child

element contains any number of Attr

elements thating allow you to define the type of Chapter 11 - Type Reflection, Late Binding, and ibute- Based Pr ogramm channel (in this case HTTP) to open on the server. TCP channels would simply make use of the "tcp" string Pa r t Four - Le ve r a ging the .NET Libr a r ie s token in place of "http". Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducinfile g Window s For As the SimpleRemoteObjectServer.exe.config contains allms) the necessary information, the server-side Chapter 14 - A Better Paint Fr amew or k All ( GDI + ) are required to do is make a single call to Main() method cleans uping considerably. you Chapter 15 - Pr ogr am ming with Windows Form s Contr RemotingConfiguration.Configure(), and specify theols name of your configuration file. Chapter 16 - The Sy stem .I O Nam espace Chapter 17 void - Data Main(string[] Access w ith ADO.NET static args) Pa {r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter // 18 - Register ASP.NET Web and Web Contr ols a Pages 'well-known' object using a *.config file. Chapter RemotingConfiguration.Configure("SimpleRemoteObjectServer.exe.config"); 19 - ASP.NET Web Applicat ions Chapter Console.WriteLine("Server 20 - XML Web Ser vices started! Hit enter to end"); I ndex Console.ReadLine(); List } of Figur es List of Tables

Building Client-Side *.config Files Clients are also able to leverage remoting-centric *.config files. Unlike a server-side configuration file, clientside configuration files make use of the element to identify the name of the well-known object the caller wishes to interact with. In addition to providing the ability to dynamically change the remoting information without a need to recompile the code base, client-side *.config files allow you to create the proxy type directly using the C# "new" keyword, rather than the Activator.GetObject() method. Thus, if you have the following client-side *.config file:



ISBN:1590590554 by Andr ew Tr oelsen

Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the

C# language and then quickly m oves to key technical and

ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntr oduction You are able to update the client's Main() method as follows: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

static void Main(string[] args) - Building C# Applications { Pa r t Tw o - The C# Pr ogr am m ing La ngua ge RemotingConfiguration.Configure("SimpleRemoteObjectClient.exe.config"); Chapter 3 - C# Language Fundamentals // Using *config file, the client is able to directly 'new' the type. Chapter RemoteMessageObject 4 - Obj ect -Or iented Pr ogr amsimple ming w ith= C# new RemoteMessageObject(); Chapter simple.DisplayMessage("Hello 5 - Exceptions and Obj ect Lifetim e from the client!"); Chapter Console.WriteLine("Server 6 - I nter faces and Collections says: {0}", simple.ReturnMessage()); Chapter Console.WriteLine("Client 7 - Callback I nter faces, Delegates, and Ev ents started! Hit enter to end"); Chapter Console.ReadLine(); 8 - Advanced C# Type Const ruction Techniques Pa }r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 2

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Of course, run theLate application, the output is identical. If the client Chapter 11 - when Type you Reflection, Binding, and Attr ibuteBased Pr ogramm ing wishes to make use of the TCP channel, "url" property of the Pa r t Four - the Le ve r a ging the .NET Libr a r ie s

element and ref property must make use of the "tcp"" token in place of "http." Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building Bet ter Win dow ( Int roducin g Window s Forand ms) SimpleRemoteObjectClientWithConfig SOURCE The aSimpleRemoteObjectServerWithConfig Chapter 14 - A Better Paintare ing located Fr amew or k ( GDI + ) Chapter 12 subdirectory (both of which make use of the CODE projects under the Chapter 15 - Pr ogr am ming with Windows Form s Contr ols SimpleRemotingAsm.dll created previously). Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Working with MBV Objects ISBN:1590590554

by Andr ew Tr oelsen

Our first remotingApr applications allowed ess © 2003 (1200 pages)client-side access to a single WKO type. Recall that WKO types are (by definition) MBR types, and therefore takes This compr ehensiv e text client star ts access w ith a brief ovplace er viewvia of an theintervening proxy. In contrast, MBV types are local copies of a server-side type, which are typically returned C# language and then quickly m oves to key technical and from a public member of an MBR ar chitectur issues forto.NET developer s. type. Although you already al know how configure an MBV type (mark a class with the [Serializable] attribute), we have not yet seen an example of MBV types in action. To illustrate the interplay of MBR and MBV types, let's see another example which will involve three assemblies: Ta ble o f Con t en t s

The assembly named CarGeneralAsm.dll C# and t hegeneral .NET Plat for m, Second Edition I ntr oduction

The client assembly named CarProviderClient.exe

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 server - The assembly Philosophynamed of .NETCarProviderServer.exe The Chapter 2

- Building C# Applications

Pa As r t you Tw o might - The C# assume, Pr ogr am themcode ing Labehind ngua gethe

client and server applications is more or less identical to the previous example, especially since these applications will again make use of *.config files. Nevertheless, let's Chapter 3 - C# Language Fundamentals step through the process of building each assembly one at a time. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

- I nter faces and Collections Building the Cars General Assembly

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

At the beginning of thisC#chapter (during our Techniques examination of object serialization), you created a type named Chapter 8 - Advanced Type Const ruction JamesBondCar. The CarGeneralAsm.dll code Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s library will reuse this type (in addition to the dependent Radio and Car sostanding begin by using the blies Project | Add Existing Item... menu command, and include these *.cs Chapter 9 types), - Under .NET Assem files into this new Class Library project. thatThreads each of these types have already been marked with the Chapter 10 - Pr ocesses, AppDomains, ContGiven exts, and [Serializable] attribute, they are ready to be marshaled by value to a remote client. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

All we need now is an MBR type which provides access to the JamesBondCar type. To make things a bit more interesting, however, our MBR object (CarProvider) will maintain an ArrayList of JamesBondCar types. Chapter 13 - Building Bet ter two Win dow ( Int roducin g Window s For ms) to obtain a specific JamesBondCar, as well CarProvider will alsoa define members, which allow the caller Chapter 14 - the A Better ing Frof amew or k Here ( GDI +is) the complete code for our new class type: as receive entirePaint ArrayList types. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

namespace CarGeneralAsm

Chapter 17 - Data Access w ith ADO.NET { Pa r t Fi ve// - WThis e b Appltype ica ti ons W e object b Se r vi ceswhich isand anX ML MBR

provides

Chapter // 18 - access ASP.NET to Web related Pages and Web ols MBV Contr types. Chapter public 19 - ASP.NET Web CarProvider Applicat ions class : MarshalByRefObject Chapter { 20 - XML Web Ser vices I ndex private ArrayList theJBCars = new ArrayList(); List of Figur es // Add some cars to the array list. List of Tables

} }

public CarProvider() { Console.WriteLine("Car provider created"); theJBCars.Add(new JamesBondCar("QMobile", 140, true, true)); theJBCars.Add(new JamesBondCar("Flyer", 140, true, false)); theJBCars.Add(new JamesBondCar("Swinner", 140, false, true)); theJBCars.Add(new JamesBondCar("BasicJBC", 140, false, false)); } // Get all the JamesBondCars. public ArrayList GetAllAutos() { return theJBCars; } // Get one JamesBondCar. public JamesBondCar GetJBCByIndex(int i) { return (JamesBondCar)theJBCars[i]; }

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Notice the GetAllAutos() method returns the internal ArrayList type. The obvious question is how this member Apr ess © 2003 (1200 pages) of the System.Collections namespace is marshaled back to the caller. If you look up this type using online comprto ehensiv e text star ts whas ith abeen briefdecorated ov er view ofwith thethe [Serializable] attribute: Help, you may beThis surprise find that ArrayList C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

[Serializable] public class ArrayList : IList, ICollection, TaIEnumerable, ble o f Con t en t s ICloneable{...} C# and t he .NET Plat for m, Second Edition I ntr oduction

Therefore, entire of .NET the ArrayList Pa r t One - I ntthe r oduci ng contents C# a nd the P la tf or m type

will be marshaled by value to the caller (provided the contained types are also serializable)! This brings up a very good point regarding .NET Remoting and Chapter 1 - The Philosophy of .NET members of the base class libraries. In addition to the custom MBV and MBR types you may create yourself, Chapter 2 - Building C# Applications do understand that any type in the base class libraries which is decorated with the [Serializable] attribute is Pa r t Tw o - The C# Pr ogr am m ing La ngua ge able to function as an MBV type in the .NET Remoting architecture. Likewise, any type which derives (directly Chapter 3 - C# Language Fundamentals or indirectly) from MarshalByRefObject will function as an MBR type. Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Building the Server Assembly - I nter faces and Collections

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

The server host assembly (CarProviderServer.exe) has the following logic within Main():

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

using System; - Under standing .NET Assem blies using System.Runtime.Remoting; Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads using System.Runtime.Remoting.Channels; Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing using System.Runtime.Remoting.Channels.Http; Pa r t Four - Le ve r a ging the .NET Libr a r ie s using CarGeneralAsm; Chapter 9

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

namespace CarProviderServer

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) { Chapter class 15 - Pr ogr am ming with Windows Form s Contr ols CarServer Chapter { 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access void w ith ADO.NET static Main(string[] args) Pa r t Fi ve - W e b {Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET RemotingConfiguration.Configure("CarProviderServer.exe.config"); Web Pages and Web Contr ols Chapter 19 - ASP.NET Console.WriteLine("Car Web Applicat ions server started! Hit enter to end"); Chapter 20 - XML Web Console.ReadLine(); Ser vices I ndex

}

} es List of Figur } of Tables List The related *.config file is just about identical to the previous server side *.config file you created in the previous example. The only point of interest is to define an object URI value which makes sense for the CarProvider type (pick your channel of choice):





C# an d th e .N ET Plat f orm , Se con d Ed it ion

ISBN:1590590554 by Andr ew Tr oelsen

Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the

C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Building the Client Assembly Ta ble o f Con t en t s

Last least, have the client application which will make use of the MBR CarProvider type in order to C# andbut t henot .NET Platwe for m, Second Edition obtain discrete JamesBondCars types as well as the ArrayList type. Once we obtain a type from the I ntr oduction CarProvider, we'll send into.NET the UseCar() Pa r t One - I nt r oduci ng C# them a nd the P la tf or m Chapter 1

helper function from processing:

- The Philosophy of .NET

using2 System; Chapter - Building C# Applications using Pa r t Tw o -System.Runtime.Remoting; The C# Pr ogr am m ing La ngua ge using3 System.Runtime.Remoting.Channels; Chapter - C# Language Fundamentals using4 System.Runtime.Remoting.Channels.Http; Chapter - Obj ect -Or iented Pr ogr am ming w ith C# using5 CarGeneralAsm; Chapter - Exceptions and Obj ect Lifetim e using6 System.Collections; Chapter - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

namespace CarProviderClient Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s class CarClient Chapter 9 - Under standing .NET Assem blies { Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads private static void UseCar(JamesBondCar c) Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing { Pa r t Four - Le ve r a ging the .NET Libr a r ie s Console.WriteLine("-> Name: {0}", c.PetName); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Layspeed: er Console.WriteLine("-> Max {0}", c.MaxSpeed); Chapter 13 - Building aConsole.WriteLine("-> Bet ter Win dow ( Int roducin g Window s For ms) Sea worthy? : {0}", c.isSeaWorthy); Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Console.WriteLine("-> Flight worthy? : {0}", c.isFlightWorthy); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Console.WriteLine(); Chapter 16 - The Sy stem .I O Nam espace c.TurnOnRadio(true); Chapter 17 - Data } Access w ith ADO.NET Pa r t Fi ve - W e b static Appl ica ti ons void and Main(string[] X ML W e b Se r vi ces args) { Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET RemotingConfiguration.Configure("CarProviderClient.exe.config"); Web Applicat ions Make the car provider. Chapter 20 - XML Web // Ser vices CarProvider cp = new CarProvider(); I ndex // Get first JBC. List of Figur es JamesBondCar qCar = cp.GetJBCByIndex(0); List of Tables // Get all JBCs. ArrayList allJBCs = cp.GetAllAutos(); // Use first car. UseCar(qCar); // Use all cars in ArrayList foreach(JamesBondCar j in allJBCs) UseCar(j); Console.WriteLine("Client started! Hit enter to end"); Console.ReadLine(); } } }

The client side *.config is also what you would expect. Simply update the activation URL:

C# an d th e .N ET Plat f orm , Se con d Ed it ion

ISBN:1590590554 by Andr ew Tr oelsen

Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the

Ta ble o f Con t en ts

C# and t he .NET Plat for m, Second Edition

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 your - C# server Language Now, run andFundamentals client applications (in that order, of course) and observe the output. Your client-side Chapter - Obj ect -Orwhirl iented Pr ogr am ming w ith C# console4 window will through the JamesBondCars and print out the statistics of each type. Recall that as Chapter 5 - Exceptions and Objand ect Lifetim e you interact with the ArrayList JamesBondCar types you are operating on their members within the Chapter client's 6application - I nter faces domain, and Collections as they have both been marked with the [Serializable] attribute. Chapter 7

- Callback I nter faces, Delegates, and Ev ents

To prove that point, update the UseCar() helper function to call the TurnOnRadio() method on the incoming Chapter 8 - Advanced C# Type Const ruction Techniques JamesBondCar. Now, run the server and client applications once again. Notice that the message box Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s appears on the client machine! Had the Car, Radio, and JamesBondCar types been configured as MBR Chapter 9 - Under standing .NET Assem blies types, the server would be the machine displaying the message box prompts. If you wish to verify this, derive Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads each type from MarshalByRefObject, and recompile all three assemblies (to ensure VS .NET copies the Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing latest CarGeneralAsm.dll into the client's and server's application directory). When you run the application Pa r t Four - Le ve r a ging the .NET Libr a r ie s once again, the message boxes appear on the remote machine. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - BuildingThe a Bet ter Win dow ( Int roducin g Window s Forand ms) CarProviderClient projects are located SOURCE CarGeneralAsm, CarProviderServer, Chapter CODE 14 - A Betterunder Paint the ing Fr Chapter amew or12 k ( GDI subdirectory. +) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dClient-Activated th e .N ET Plat f orm , Se con d Ed it ion (CAO) Understanding Objects ISBN:1590590554

by Andr ew Tr oelsen

All of our current Apr remoting examples have made use of so-called well-known objects (which again, sometimes ess © 2003 (1200 pages) go by the term server-activated objects). Recall theoffollowing characteristics: This compr ehensiv e text star ts wthat ith aWKOs brief ovhave er view the C# language and then quickly m oves to key technical and

WKOs can be configured either for as .NET singleton or single call. ar chitectur al issues developer s.

WKOs can only be activated using the type's default constructor. Ta ble o f Con t en t s

WKOs are instantiated on the server on the first client-side member invocation.

C# and t he .NET Plat for m, Second Edition

I ntr oduction CAO types on the other hand, can be instantiated using any constructor on the type and are created at the point Pa r t One - Imakes nt r oduci ng C# a ndC# the"new" .NET P la tf or m the client use of the keyword

or Activator type. Furthermore, the lifetime of CAO types is

Chapter 1 -by The of .NET monitored thePhilosophy .NET leasing mechanism. Do be aware that when you configure a CAO type, the .NET Chapter Remoting 2 -layer Building will generate C# Applications a specific CAO remote object to service each client. Again, the big distinction is the Pa fact r t Tw that o -CAOs The C#are Pr ogr always am malive ing La(and nguatherefore ge

Chapter 3

stateful) beyond a single method invocation.

- C# Language Fundamentals

To illustrate the construction, hosting, and consumption of CAO types, let's retrofit our previous automobile- Obj ect -Or iented Pr ogr am ming w ith C# centric general assembly. Assume that our MBR CarProvider class has defined an additional constructor that Chapter 5 - Exceptions and Obj ect Lifetim e allows the client to pass in an array of JamesBondCar types that will be used to populate the internal ArrayList: Chapter 4 Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

public class CarProvider : MarshalByRefObject Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s private ArrayList theJBCars = new ArrayList(); Chapter 9 - Under standing .NET Assem blies public CarProvider(JamesBondCar[] theCars) Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads { Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Console.WriteLine("Car provider created with custom ctor"); Pa r t Four - Le ve r a ging the .NET Libr a r ie s theJBCars.AddRange(theCars); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er } Chapter ... 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

In order17to-allow caller to ADO.NET activate the CarProvider using our new constructor syntax, we need to build a serve Chapter Data the Access w ith application that registers CarProvider as a CAO Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi cestype

rather than a WKO type. This may be done

programmatically (a Web la thePages RemotingConfiguration.RegisterActivatedServiceType() method) or using a serverChapter 18 - ASP.NET and Web Contr ols side *.config file. If you wish to hard-code the name of the CAO object within the host server's code base, all you Chapter 19 - ASP.NET Web Applicat ions need to20do- isXML pass in the type information of the type(s) (after creating and registering a channel) as follows: Chapter Web Ser vices I ndex

//ofHard code the fact that CarProvider is a CAO type. List Figur es RemotingConfiguration.RegisterActivatedServiceType( List of Tables typeof(CAOCarGeneralAsm.CarProvider));

If you would rather leverage the *.config file, replace the element with the element as follows:





C# an d th e .N ET Plat f orm , Se con d Ed it ion

by Andr ew Tr oelsen

Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues .NET developer s. by way of the *.config file (or programmatically in the Finally, we need to update the clientfor application, not only

code base) to request access to the remote CAO, but to indeed trigger the custom constructor of the CarProvide type. Here are the relevant updates to the client side Main() method:

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

static void Main(string[] args) { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // Read updated *.config file. Chapter 1 - The Philosophy of .NET RemotingConfiguration.Configure("CAOCarProviderClient.exe.config"); Chapter 2 - Building C# Applications // Create array of types to pass to provider. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge JamesBondCar[] cars = Chapter 3 - C# Language Fundamentals { Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# new JamesBondCar("One", 100, false, false), Chapter 5 - Exceptions and Obj ect Lifetim e new JamesBondCar("Two", 100, false, false), Chapter 6 - I nter faces and Collections new JamesBondCar("Three", 100, false, false) Chapter }; 7 - Callback I nter faces, Delegates, and Ev ents Chapter // 8 - Now Advanced C# Type Const ruction ctor. Techniques trigger the custom Pa r t ThreCarProvider e - Pr ogr am m i ngcp w i th ET Assem bl ie s = .Nnew CarProvider(cars); Chapter ... 9 - Under standing .NET Assem blies } Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads I ntr oduction

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

The updated client side *.config file also makes use of the element, as opposed to . In addition, however, the element now requires the url property to define the location of the registered CAO Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Recall that when the server registered the CarProvider as a WKO, the client specified such information within th Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) element. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Chapter 20 - XML Web Ser vices = 50) Chapter 4 - Obj ect -Or iented Pr=ogr0; am ming w ith C# swellValue Chapter // 5 - Just Exceptions and Obj ect Lifetim e invalidate the 'minimal dirty rectangle to help reduce flicker. Chapter Invalidate(new 6 - I nter faces and Collections Rectangle(0, 0, ClientRectangle.Width, 100)); Chapter 7 - Callback I nter faces, Delegates, and Ev ents } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Now that upper 100 pixels your blies client area are refreshed with each tick of the Timer, you better have Chapter 9 the - Under standing .NETofAssem something the Form's Paint handler, create a Font object based on the user-defined font face Chapter 10 - to Prrender! ocesses,InAppDomains, Cont exts, and Threads (as selected fromReflection, the appropriate menu item) and current swellValue Chapter 11 - Type Late Binding, and Attr ibuteBased Pr ogramm(as ing dictated by the timer). Once you have your Font fully configured, Pa r t Four - Le ve r aobject ging the .NET Libr a r ie s render

a message into the center of the dirty rectangle:

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

private FontForm_Paint(object PaintEventArgs e) Chapter 13 - void Building a Bet ter Win dow ( Int roducin g sender, Window s For ms) { Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) = e.Graphics; Chapter Graphics 15 - Pr ogr amgming with Windows Form s Contr ols // The font size can be between 12 and 62, // based on the current swellValue. Chapter 17 - Data Access w ith ADO.NET Font theFont = new Font(fontFace, 12 + swellValue); Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces string message = "Hello GDI+"; Chapter 18 - ASP.NET Web Pages and Web Contr ols // Display message in the center of the rect. Chapter 19 - ASP.NET Web Applicat ions float windowCenter = this.DisplayRectangle.Width/2; Chapter 20 - XML Web Ser vices SizeF stringSize = g.MeasureString(message, theFont); I ndex float startPos = windowCenter - (stringSize.Width/2); List of Figur es g.DrawString(message, theFont, new SolidBrush(Color.Blue), startPos, 10); List of Tables } Chapter 16 - The Sy stem .I O Nam espace

As you would guess, if a user selects a specific font face, the Clicked handler for each menu selection is in charge of updating the fontFace string variable and invalidating the client area. The sample code for this example takes this a bit further to ensure that the user's font of preference is identified with a check mark. Given that the previous chapter has already pounded out the details of menu manipulations, I'll assume you will implement these details as you see fit. The menu handler for the Swell menu item will be used to allow the user to stop or start the swelling of the text (i.e., enable or disable the animation). Thus, configure the Clicked handler to enable or disable the Timer as follows: private void ConfigSwell_Clicked(object sender, EventArgs e) { timer.Enabled = !timer.Enabled;

mainMenu.MenuItems[1].MenuItems[0].Checked = timer.Enabled; C# an d th e .N ET Plat f orm , Se con d Ed it ion

}

ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Enumerating Installed Fonts (a la System.Drawing.Text) Next, let's expand the FontApp to programmatically discover the set of installed fonts on the target machine. gives a chance to explore another namespace of GDI+, System.Drawing.Text. This TaDoing ble o f so Con t en t you s namespace contains C# and t he .NET Plat for a m,(small) Secondhandful Edition of useful types that can be used to discover and manipulate the set of fonts installed on the target machine. The highlights are shown in Table 14-15. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Table 14-15: The Text Type Chapter 1 - The Philosophy of .NET Chapter 2 - Building C# Applications System.Drawing.Text Meaning in Life Pa rType t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals InstalledFontCollection Represents Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith the C# set of all fonts installed on the target system. Chapter 5

- Exceptions and Obj ect Lifetim e PrivateFontCollection Encapsulates a collection of specific Font types.

Chapter 6

- I nter faces and Collections LineSpacing This enumeration Chapter 7 - Callback I nter faces, Delegates, and Ev entsspecifies the spacing between lines of text in a Chapter 8

textruction string Techniques that spans more than a single line. - Advanced C# Type Const

Pa rTextRenderingHint t Thre e - Pr ogr am m i ng w i th .N ETAnother Assem blenumeration ie s

that allows you to specify the quality of the

Chapter 9

- Under standing .NET Assem bliestext rendering operation. For example, the Text value current Chapter 10 - Pr ocesses, AppDomains, Cont exts, aand represents fastThreads (but low quality) rendering. AntiAliased marks Chapter 11 - Type Reflection, Late Binding, and Attr ibuteBased rendering Pr ogramm cycle. ing better quality but a slower Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 -user Obj ect Ser ialization and the |.NET Remoting er item, the corresponding Clicked handler When the selects the "Configure List All Fonts" Lay menu Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms) creates an instance of the InstalledFontCollection class. This class maintains an array named FontFamily, Chapter which represents 14 - A Better thePaint set of ingall Fr amew fonts on or k the ( GDI target +) machine, and may be obtained using the

InstalledFontCollection.Families property. Using theols FontFamily.Name property, you are able to extract the Chapter 15 - Pr ogr am ming with Windows Form s Contr font face Roman, Arial, etc.) for each font. Chapter 16 (e.g., - TheTimes Sy stemNew .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Here, you have added a private string data member named installedFonts to hold each font face. The logic in the "List Installed Fonts" menu handler creates an instance of the InstalledFontCollection type, reads the Chapter 18 - ASP.NET Web Pages and Web Contr ols name of each string, and adds the new font face to the private installedFonts data member: Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

public class FontForm : System.Windows.Forms.Form { List of Figur es // Holds the list of fonts. List of Tables private string installedFonts; // Menu handler to get the list of installed fonts. private void mnuConfigShowFonts_Clicked(object sender, EventArgs e) { InstalledFontCollection fonts = new InstalledFontCollection(); for(int i = 0; i < fonts.Families.Length; i++) installedFonts += fonts.Families[i].Name + " "; // This time, we need to invalidate the entire client area, // as we will paint the installedFonts string on the lower half // of the client rectangle. Invalidate(); } ... } I ndex

The final task is to render the installedFonts string to the client area, directly below the screen real estate C# an d th e .N ET Plat f orm , Se con d Ed it ion that is used for your swelling text: by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

private void FontForm_Paint(object sender, PaintEventArgs e) This compr ehensiv e text star ts w ith a brief ov er view of the { C# language and then quickly m oves to key technical and Graphicsar chitectur g = e.Graphics; al issues for .NET developer s. Font theFont = new Font(fontFace, 12 + swellValue); string message = "Hello GDI+"; message in the center of the window! Ta ble o f // Con tDisplay en t s float windowCenter = this.DisplayRectangle.Width/2; C# and t he .NET Plat for m, Second Edition SizeF stringSize = e.Graphics.MeasureString(message, theFont); I ntr oduction float startPos = windowCenter - (stringSize.Width/2); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m g.DrawString(message, theFont, new SolidBrush(Color.Blue), startPos, 10); Chapter 1 - The Philosophy of .NET // Show installed fonts in the rectangle below the swell area. Chapter 2 - Building C# Applications Rectangle myRect = new Rectangle(0, 100, Pa r t Tw o - The C# Pr ogr am m ing La ngua ge ClientRectangle.Width, ClientRectangle.Height); Chapter 3 - C# Language Fundamentals // Paint this area of the Form black. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# g.FillRectangle(new SolidBrush(Color.Black), myRect); Chapter 5 - Exceptions and Obj ect Lifetim e g.DrawString(installedFonts, new Font("Arial", 12), Chapter 6 - I nter faces and Collections new SolidBrush(Color.White), myRect); Chapter 7 - Callback I nter faces, Delegates, and Ev ents } Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter Under standing .NET Assem blies has been mapped to the upper 100 pixels of the client rectangle. Recall 9that- the size of the "dirty rectangle" Chapter Because 10 your - Pr ocesses, Tick handler AppDomains, only invalidates Cont exts, a portion and Threads of the Form, the remaining area is not redrawn when

the Tick11event has been sent (to Binding, help optimize the rendering ofogramm the client Chapter - Type Reflection, Late and Attr ibuteBased Pr ingarea). Pa r t Four - Le ve r a ging the .NET Libr a r ie s

As a final touch, to ensure proper redrawing let's handle the Resize event to ensure that if the user resizes the Form, the lower part of client rectangle is redrawn correctly:

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

private FontForm_Resize(object sender, System.EventArgs e) Chapter 15 - void Pr ogr am ming with Windows Form s Contr ols {

Chapter 16 - The Sy stem .I O Nam espace

Rectangle myRect = new Rectangle(0, 100, ClientRectangle.Width, ClientRectangle.Height); Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Invalidate(myRect);

Chapter 17 - Data Access w ith ADO.NET Pa r t

Chapter 18 - ASP.NET Web Pages and Web Contr ols

}

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex With that, Figure 14-11 shows the result. List of Figur es List of Tables

Figure 14-11: The FontApp application in action SOURCE CODE

The FontApp application is included under the Chapter 14 subdirectory.

C# an d Class th e .N ET Plat f orm , Se con d Ed it ion The FontDialog by Andr ew Tr oelsen

ISBN:1590590554

As you might assume, a default Apr essthere © 2003is(1200 pages) font dialog box (FontDialog), as seen in Figure 14-12. This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - 14-12: Exceptions Obj.NET ect Lifetim Figure Theand stock Font edialog Chapter 6 - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Like the ColorDialog type examined earlier in this chapter, when you wish to work with the FontDialog, Chapter 8 - Advanced C# Type Const ruction Techniques simply call the ShowDialog() method. Using the Font property, you may extract the characteristics of the Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s current selection for use in the application. To illustrate, here is a new Form that mimics the logic of the Chapter 9 - Under standing .NET Assem blies previous ColorDlgForm (i.e., click the form to launch the File dialog and render GDI+ logic onto the form's Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads client area). Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

public class FontDlgForm : System.Windows.Forms.Form { Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) private FontDialog fontDlg; Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) private Font currFont; Chapter private 15 - Pr ogr am ming FontDlgForm_Paint(object with Windows Form s Contr ols void sender, PaintEventArgs e) Chapter { 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith Graphics g ADO.NET = e.Graphics; Pa r t Fi ve - W e b g.DrawString("Testing...", Appl ica ti ons and X ML W e b Se r vi ces currFont, Chapter 18 - ASP.NET new Web Pages and Web Contr ols SolidBrush(Color.Black), 0, 0); Chapter } 19 - ASP.NET Web Applicat ions Chapter public 20 - XML Web FontDlgForm() Ser vices { I ndex List of Figur es CenterToScreen(); List of Tables fontDlg = new FontDialog(); fontDlg.ShowHelp = true; Text = "Click on me to change the font"; currFont = new Font("Times New Roman", 12); ... } // Event handler for MouseUp event. private void FontDlgForm_MouseUp(object sender, MouseEventArgs e) { if (fontDlg.ShowDialog() != DialogResult.Cancel) { currFont = fontDlg.Font; Invalidate(); } } } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

C# an d th e .N ET Plat f orm , Se con d Ed it ion

SOURCE CODE

ISBN:1590590554 by Andr Tr oelsen Theew FontDlgForm application is included under the Chapter 14 subdirectory. Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Survey of the System.Drawing.Drawing2D Namespace ISBN:1590590554

by Andr ew Tr oelsen

Now that you have Font types, the next task is to examine how to manipulate Pen and Brush Aprmanipulated ess © 2003 (1200 pages) objects to renderThis geometric patterns. While do so compr ehensiv e text staryou ts wcould ith a brief ov making er view ofuse theof nothing more than the types found in the System.Drawing namespace, you should be aware that many of the more "sexy" pen and C# language and then quickly m oves to key technical and ar chitectur al issuesthe for HatchBrush .NET developer s. used at the beginning of this chapter) require brush configurations (for example, type types defined within the System.Drawing.Drawing2D namespace. TaThis ble oadditional f Con t en t GDI+ s namespace (which is substantially smaller than System.Drawing) provides a number

of and classes that allow to modify the line cap (triangle, diamond, etc.) used for a given pen, build C# t he .NET Plat foryou m, Second Edition textured brushes, as well as work with vector graphic manipulations. Some core types to be aware of, I ntr oduction grouped functionality, are shown Pa r t One - by I ntrelated r oduci ng C# a nd the .NET P la tf orin m Table Chapter 1

14-16.

- The Philosophy of .NET

Table 14-16: The Classes of System.Drawing.Drawing2D Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

System.Drawing.Drawing2D

Meaning in Life

Chapter 3 - C# Language Fundamentals Class Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# AdjustableArrowCap caps are used to paint the beginning and end points of Chapter 5 - Exceptions and Obj ect Lifetim Pen e Chapter 6 - I nter faces and Collections CustomLineCap

a given line. These types represent an adjustable arrow-

Chapter 7

shaped - Callback I nter faces, Delegates, and Evand ents user-defined cap.

Chapter Blend8

- Advanced C# Type Const ruction Techniques Used to define a blend pattern (and colors) used in

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assemconjunction bl ie s with

ColorBlend

Chapter 9

a LinearGradientBrush.

- Under standing .NET Assem blies

Chapter GraphicsPath 10 - Pr ocesses, AppDomains, ContA exts, GraphicsPath and Threadsobject represents a series of connected

andibutecurves. This class allows Chapter 11 - Type Reflection, Late Binding,lines and Attr Based Pr ogramm ing you to insert just about GraphicsPathIterator Pa r t Four - Le ve r a ging the .NET Libr a r ie s

PathData

any type of geometrical pattern (arcs, rectangles, lines,

strings, polygons, Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay eretc.) into the path. PathData holds the data that makes Chapter 13 - Building a Bet ter Win dow ( Int graphical roducin g Window s For ms) up a path. Chapter 14 - A Better Paint ing Fr amew or k (Exotic GDI + )brush types. HatchBrush Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

LinearGradientBrush

Chapter 16 - The Sy stem .I O Nam espace

PathGradientBrush Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Also be18aware that the System.Drawing.Drawing2D namespace defines another set of enumerations that Chapter - ASP.NET Web Pages and Web Contr ols are used theseions core types. Table 14-17 gives a quick rundown. Chapter 19 in- conjunction ASP.NET Webwith Applicat Chapter 20 - XML Web Ser vices

Table 14-17: The Enumerations of System.Drawing.Drawing2D

I ndex

List of Figur es List of Tables

System.Drawing.Drawing2D Meaning C# an d th e .N ET Plat f orm , Se con d Ed it ion in Life Enumeration by Andr ew Tr oelsen ISBN:1590590554 DashStyle FillMode

Apr ess © 2003 (1200 pages)

Specifies the style of dashed lines drawn with a

This compr ehensiv e text star ts w ith a brief ov er view of the Pen C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Specifies how the interior of a closed path is filled

HatchStyle

Specifies the different patterns available for HatchBrush objects

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

LinearGradientMode

Specifies the direction to apply a linear gradient

I ntr oduction

Pa rLineCap t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

PenAlignment

Specifies the current cap styles used by a Pen Specifies the alignment of a Pen in relation to the line being drawn

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter PenType 3 - C# Language Fundamentals

Specifies the type of fill a Pen uses to fill lines

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

QualityMode

SmoothingMode Chapter 6 - I nter faces and Collections

Specifies the overall quality used to render a graphic image

RenderingHint Chapter 7 - Callback I nter faces, Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

- Under standing .NET Assem blies Quality Establishing the Rendering

Chapter 9

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter Notice 11 that- some Type Reflection, of the enumerations Late Binding, defined and Attr in ibutethe System.Drawing.Drawing2D Based Pr ogramm ing namespace (such as Pa QualityMode r t Four - Le ve and r a ging SmoothingMode) the .NET Libr a rallow ie s

you to configure the overall quality of the current rendering

operation. a Graphics object, it has aLay default rendering mode, which is a middle-of-theChapter 12 -When Obj ectyou Serobtain ialization and the .NET Remoting er road combination of aspeed examine one way to tweak a Graphics object to Chapter 13 - Building Bet terand Win overall dow ( Intquality. roducinLet's g Window s For ms) override default values. Chapter 14these - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

The SmoothingMode enumeration (Table 14-18) is typically used to control how the GDI+ objects being rendered with the current Graphics object are antialiased (or not).

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Table 14-18: Various SmoothingMode Values

Chapter 18 - ASP.NET Web Pages and Web Contr ols

SmoothingMode Meaning Chapter 19 - ASP.NET Web Applicat ions in Life Value Chapter 20 - XML Web Ser vices I ndex

AntiAlias

List of Figur es List of Tables

HighQuality

Specifies antialiased rendering. The AntiAlias mode uses shades of gray or color to smooth the edges of lines and curves, and is effective on CRT screens as well as LCD screens. Specifies high-quality, lower-performance rendering. The high-quality mode uses more sophisticated techniques that take advantage of the subpixel resolution of LCD screens. A single pixel on an LCD screen is divided into three stripes that are set to various shades to produce the line or curve that appears the smoothest to the human eye.

HighSpeed

Specifies low-quality, high-performance rendering. The high-speed mode does not smooth the item being rendered; pixels are either on or off.

When you wish to override the default rendering quality for a current GDI+ rendering operation, make use of the SmoothingMode property of the Graphics object:

private void MainForm_Paint(object sender, PaintEventArgs e) C# an d th e .N ET Plat f orm , Se con d Ed it ion { ISBN:1590590554 by Andr ew Tr oelsen Graphics g = e.Graphics; Apr ess © 2003 (1200 pages) // Set quality of GDI+ object rendering. This compr ehensiv e text star ts w ith a brief ov er view of the g.SmoothingMode = SmoothingMode.AntiAlias; C# language and then quickly m oves to key technical and ... ar chitectur al issues for .NET developer s. } Ta ble o f Con t en t s

Be aware that the SmoothingMode property is only used to control the quality of rendering GDI+ objects, not textual information. If you wish to modify the rendering quality for Font types, you need to set the I ntr oduction TextRenderingHint property using the related System.Drawing.Text.TextRenderingHint enumeration: C# and t he .NET Plat for m, Second Edition

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

public enum System.Drawing.Text.TextRenderingHint - Building C# Applications { Pa r t Tw o - The C# Pr ogr am m ing La ngua ge AntiAlias, AntiAliasGridFit, Chapter 3 - C# Language Fundamentals ClearTypeGridFit, SingleBitPerPixel, Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# SingleBitPerPixelGridFit, SystemDefault Chapter 5 - Exceptions and Obj ect Lifetim e } Chapter 2

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Working with Pens

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

GDI+ Pen objects are used to draw lines (not too much of a stretch there! ). However, a pen in and of itself is of little value. When you need to render a geometric shape onto a Control-derived type, you send a pass Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing valid Pen type to any number of render methods defined by the Graphics class. In general, the Pa r t Four - Le ve r a ging the .NET Libr a r ie s DrawXXXX() methods are used to render some set of lines to a graphics surface, and are typically used Chapter 12objects. - Obj ectThe Ser ialization thealso .NETdefines Remoting Lay er of FillXXXX() methods that render an image with Pen Graphicsand class a number Chapter 13 Building a Bet ter Win dow ( Int roducin g Window Fora ms) using some sort of Brush-derived type (more on those in sjust minute). Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Although drawing Form members earlier in the chapter, here they are again (Table 14-19) Chapter 15 you - Pr have ogr amseen ming many with Windows s Contr ols in a bit 16 more detail (be aware that each of these methods have been overloaded a number of times). Chapter - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Table Members ofWthe Graphics Pa r t Fi ve14-19: - W e b Drawing Appl ica ti ons and X ML e b Se r vi ces

Class

Chapter 18 - ASP.NET and Web Contr ols Drawing MethodWeb of PagesMeaning in Life Chapter 19 - ASP.NET Graphics Type Web Applicat ions Chapter 20 - XML Web Ser vices

DrawArc() I ndex List of Figur es ListDrawBezier() of Tables

This method renders an arc given a pen, and an ellipse on which to base the angle of the arc.

DrawBeziers()

Given four points, this method draws a cubic Bezier curve (or a number of Beziers).

DrawCurve()

Draws a curve defined by an array of points.

DrawEllipse()

Draws the outline of an ellipse within the scope of a bounding rectangle.

DrawLine()

Given a Point (or an array of Point types), these methods connect the dots (if you will).

DrawLines() DrawPath()

Using the GraphicsPath type defined in the System.Drawing.Drawing2D namespace, this method renders a collection of lines/curves as specified by the path.

DrawPie()

Draws the outline of a pie section defined by an ellipse and two radial lines.

DrawPolygon() C# an d th e .NDraws the outline of ad polygon ET Plat f orm , Se con Ed it ion defined by an array of Point types. ISBN:1590590554 by Andr ew Tr oelsen DrawRectangle() Renders a box, or a whole bunch of boxes, based on top-leftApr ess © 2003 (1200 pages) bottom-right coordinates. This can be specified using Rectangle DrawRectangles() This compr ehensiv e text star ts or w ith a briefpoint ov er numbers. view of the types, integers, floating

C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Now that you better understand the core methods used to render geometric images, you can examine the Pen class itself. This class defines a small set of constructors that allow you to determine the initial color and width the Ta ble o f Conof t en t s pen nib (you can also construct a new Pen based on an existing Brush object...more later). Most of Pen's functionality comes by way of its supported properties. Table 14-20 gives a partial C# and t he .NETaPlat for m, Second Edition list. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Table 14-20: Pen Properties - The Philosophy of .NET

Chapter 1

Chapter - Building C#Meaning Applications Pen 2Property in Life Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Brush3 Chapter

Determines the Brush used by this Pen. - C# Language Fundamentals

Chapter Color4

- Obj ect -Or iented Pr ogr am ming w ithtype C# used by this Pen. Determines the Color - Exceptions and Obj ect Lifetim e

Chapter 5

CompoundArray or sets an array of custom dashes and spaces. Chapter 6 - I nter faces Gets and Collections Chapter 7 - Callback I nter faces, Delegates, andcap Ev ents CustomStartCap Gets or sets a custom style to use at the beginning or end of lines drawn Chapter 8 - Advanced C# ruction Techniques withType this Const Pen. Cap styles are simply the term used to describe how the initial

CustomEndCap

Pa r t Thre e - Pr ogr am m i ng i th .Nstroke ET Assem bl iePen s andw final of the

should look and feel. These properties allow you

- Under standing .NETcustom Assem blies to build caps for your Pen types. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 9

DashCap

Gets or sets the cap style used at the beginning or end of dashed lines drawn with this Pen.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter DashOffset 12 - Obj ect Ser ialization Gets or sets and the the distance .NET Remoting from the Laystart er of a line to the beginning of a dash Chapter 13 - Building a pattern. Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

DashPattern

Gets or sets an array of custom dashes and spaces. The dashes are made up of line segments.

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

DashStyle Gets sets the style used for dashed lines drawn with this Pen. Chapter 17 - Data Access w ithorADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

LineJoin

Gets or sets the join style for the ends of two overlapping lines drawn with this

Chapter 18 - ASP.NET Web Pen.Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

PenType Gets the style of lines drawn with this Pen. Chapter 20 - XML Web Ser vices I ndex StartCap

EndCap

Gets or sets the predefined cap style used at the beginning or end of lines drawn with this Pen. Set the cap of your Pen using the LineCap enumeration defined in the System.Drawing.Drawing2D namespace.

Width

Gets or sets the width of this Pen.

List of Figur es List of Tables

Remember that in addition to the Pen type, GDI+ also provides a Pens collection. Using a number of static properties, you are able to retrieve a Pen (or a given color) on the fly, rather than creating a custom Pen by hand. Be aware, however, that the Pen types returned will always have a width of 1. If you require a more exotic pen, you will need to build a Pen type by hand. First, let's render some geometric images using simple Pen types. Assume we have a main Form object, which is capable of responding to paint requests. The implementation is as follows: private void MainForm_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; // Make a big blue pen.

Pen bluePen = new Pen(Color.Blue, 20); an d th epen .N ETfrom Plat f orm con dtype. Ed it ion // Get aC#stock the, Se Pens ISBN:1590590554 by Andr ew Tr oelsen Pen pen2 = Pens.Firebrick; Apr ess © 2003 (1200 pages) // Render some shapes with the pens. This compr ehensiv e text star10, ts w ith100, a brief100); ov er view of the g.DrawEllipse(bluePen, 10, C# language and then quickly m oves to key g.DrawLine(pen2, 10, 130, 110, 130); technical and ar chitectur al issues for .NET developer s. g.DrawPie(Pens.Black, 150, 10, 120, 150, 90, 80); // Draw a purple dashed polygon as well... Pen pen3 = new Pen(Color.Purple, 5); Ta ble o f Con t en t s pen3.DashStyle = DashStyle.DashDotDot; C# and t he .NET Plat for m, Second Edition g.DrawPolygon(pen3, new Point[]{new Point(30, 140), I ntr oduction new Point(265, 200), new Point(100, 225), Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m new Point(190, 190), new Point(50, 330), Chapter 1 - The Philosophy of .NET new Point(20, 180)}); Chapter 2 - Building C# Applications // And a rectangle containing some text... Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Rectangle r = new Rectangle(150, 10, 130, 60); Chapter g.DrawRectangle(Pens.Blue, 3 - C# Language Fundamentals r); Chapter g.DrawString("Hello 4 - Obj ect -Or iented Pr ogr amout mingthere...How w ith C# are ya?", Chapter 5 - Exceptions and Obj ect Lifetim e new Font("Arial", 12), Brushes.Black, r); Chapter 6 - I nter faces and Collections } Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Notice 9that- the Pen that is used to render Chapter Under standing .NET Assem bliesyour polygon makes use of the DashStyle enumeration (defined in System.Drawing.Drawing2D). ThisCont is the .NET of the raw Win32 pen style flags (e.g., Chapter 10 - Pr ocesses, AppDomains, exts, and equivalent Threads PS_SOLID).Table 14-21 lists your choices.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Table 14-21: Dash Styles

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow (in Int roducin DashStyle Meaning Life g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Value Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Custom

Specifies a user-defined custom dash style

Chapter 16 - The Sy stem .I O Nam espace

Chapter ith ADO.NET Dash 17 - Data Access wSpecifies a line comprised of dashes Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

DashDot

Specifies a line comprised of an alternating pattern of dash-dot-dash-dot

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Chapter 19 - ASP.NET Web Specifies Applicat ions DashDotDot a line comprised of an alternating pattern of dash-dot-dot-dashChapter 20 - XML Web Ser vices dot-dot I ndex

Dot

List of Figur es ListSolid of Tables

Specifies a line comprised of dots Specifies a solid line

In addition to the preconfigured DashStyles, you are also able to define custom dash types using the DashPattern property of the Pen type: (see Figure 14-13 for complete output).

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr amWorking m i ng w i th .N ET Assem bl ie s Figure 14-13: with Pen types

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - custom Type Reflection, Late Binding, and around Attr ibute- the Basedboarder Pr ogramm ing // Draw dash pattern all of the form. Pa r t Four - Le ve r a ging the = .NET LibrPen(Color.BlueViolet, a r ie s Pen customDashPen new

5);

Chapter 12 - myDashes Obj ect Ser ialization and the2.0f, .NET Remoting er float[] = { 5.0f, 1.0f, Lay 3.0f} ; Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms) customDashPen.DashPattern = myDashes; Chapter g.DrawRectangle(customDashPen, 14 - A Better Paint ing Fr amew or k ( GDI ClientRectangle); +) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

SOURCE The PenApp project is included under the Chapter 14 subdirectory. CODE Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 17 - Data Access w ith ADO.NET Pa r t

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Working with Pen Caps

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

If you examined the output of the previous pen example, you should have noticed that the beginning and end of each line was rendered using a standard pen protocol (an end cap composed of 90 degree List of Figur es angles). Using the LineCap enumeration however, you are able to build Pens that exhibit a bit more flair. List of Tables The core values of this enumeration are seen in Table 14-22. I ndex

Table 14-22: LineCap Values

LineCap Values Meaning in, Se Life C# an d th e .N ET Plat f orm con d Ed it ion ArrowAnchor

ISBN:1590590554 by Andr ew Tr oelsen Specifies an arrow-shaped cap Apr ess © 2003 (1200 pages)

DiamondAnchorThis compr ehensiv Specifies e textastar diamond ts w ith anchor a brief ov cap er view of the C# language and then quickly m oves to key technical and Specifies a flatdeveloper line cap s. ar chitectur al issues for .NET

Flat Round

Specifies a round line cap

Ta ble o f Con t en t s RoundAnchor

Specifies a round anchor cap

C# and t he .NET Plat for m, Second Edition

Square

I ntr oduction

Specifies a square line cap

Pa rSquareAnchor t One - I nt r oduci ng C# a nd the .NET P lano tf or m Specifies line

Chapter 1

cap

- The Philosophy of .NET

Triangle - Building C# Applications Specifies a triangular line cap

Chapter 2

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

To illustrate, the following Pens application draws a series of lines using each of the LineCap styles. First, - C# Language Fundamentals the result can be seen in Figure 14-14.

Chapter 3 Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 14-14: Working with pen caps The code simply loops through each member of the LineCap enumeration, and prints out the name of the item (e.g., ArrowAnchor) and then configures and draws a line with the current cap: private void MainForm_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics;

Pen thePen = new Pen(Color.Black, 10); C# an d= th10; e .N ET Plat f orm , Se con d Ed it ion int yOffSet by Andr ew Tr oelsen // Get all members of the LineCap enum. ISBN:1590590554 Apr ess © 2003 (1200 pages) Array obj = Enum.GetValues(typeof(LineCap)); This compr ehensiv e text star ts w ith a brief ov er view of the // Draw a line with a LineCap member. C# language and then quickly m oves to key technical and for(int x = 0; x < obj.Length; x++) ar chitectur al issues for .NET developer s. { // Get next cap and configure pen. LineCap temp = (LineCap)obj.GetValue(x); Ta ble o f Con t en t s thePen.StartCap = temp; C# and t he .NET Plat for m, Second Edition thePen.EndCap = temp; I ntr oduction // Print name of LineCap enum. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m g.DrawString(temp.ToString(), new Font("Times New Roman", 10), Chapter 1 - The Philosophy of .NET new SolidBrush(Color.Black), 0, yOffSet); Chapter 2 - Building C# Applications // Draw a line with the correct cap. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge g.DrawLine(thePen, 100, yOffSet, Width - 50, yOffSet); Chapter 3 - C#yOffSet Language += Fundamentals 40; Chapter } 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e } Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

SOURCE The PenCapApp project is included under the Chapter 14 subdirectory. Chapter 9 - Under standing .NET Assem blies CODE Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Working with Solid Brushes

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

So much drawinga lines. Brush-derived ares used to fill the space between the lines, with a Chapter 13 for - Building Bet terGDI+ Win dow ( Int roducin gtypes Window For ms) given color, pattern, or image. Recallorthat the+ Brush class is an abstract type, and cannot be directly Chapter 14 - A Better Paint ing Fr amew k ( GDI )

created. Rather, this type serves as a base class to the other related brush types (for example, SolidBrush, HatchBrush, LinearGradientBrush, and so forth). In addition to the aforementioned Brush-derived types, Chapter 16 - The Sy stem .I O Nam espace the System.Drawing namespace also defines two types that return a configured brush using a number of Chapter 17 - Data Access w ith ADO.NET static properties: Brushes and SystemBrushes. Using a properly configured brush, you are able to call any Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces number of methods [such as DrawString()], as well as the following set of FillXXXX() methods (Table 14Chapter 18 - ASP.NET Web Pages and Web Contr ols 23). Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

Table 14-23: Fill Methods of the Graphics Type

I ndex

Method of Graphics ListFill of Figur es

Meaning in Life

ListClass of Tables

FillClosedCurve()

Fills the interior of a closed curve defined by an array of points

FillEllipse()

Fills the interior of an ellipse defined by a bounding rectangle

FillPath()

Fills the interior of a path

FillPie()

Fills the interior of a pie section

FillPolygon()

Fills the interior of a polygon defined by an array of points

FillRectangle() FillRectangles()

Fills the interior of a rectangle (or a number of rectangles) with a Brush

FillRegion()

Fills the interior of a Region

Also recall, that you are able to build a custom Pen type by making use of a given brush. In this way, you C# an d th e .N ET Plat f orm , Se con d Ed it ion are able to build some brush of interest (for example, a brush that paints a bitmap image) and render by with Andrconfigured ew Tr oelsenPen. To illustrate, here is aISBN:1590590554 geometric patterns small sample program that makes use of Apr ess © 2003types (1200 [the pages) the SolidBrush and Brushes output of this program (Figure 14-15) should look familiar...] This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Figure 14-15: Working with Brush types

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

If you can't this is little more theolsoriginal Pens application, making use of the Chapter 15 - tell, Pr ogr amapplication ming with Windows Formthan s Contr FillXXXX() and.I O SolidBrush types, rather than pens and the related DrawXXXX() methods. Here is Chapter 16 - methods The Sy stem Nam espace the implementation of the paint handler: Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

private MainForm_Paint(object Chapter 18 - void ASP.NET Web Pages and Web Contr olssender, PaintEventArgs e) { Chapter 19 - ASP.NET Web Applicat ions g Ser = vices e.Graphics; Chapter Graphics 20 - XML Web // Make a blue SolidBrush. SolidBrush blueBrush = new SolidBrush(Color.Blue); List of Figur es // Get a stock brush from the Brushes type. List of Tables SolidBrush pen2 = (SolidBrush)Brushes.Firebrick; // Render some shapes with the brushes. g.FillEllipse(blueBrush, 10, 10, 100, 100); g.FillPie(Brushes.Black, 150, 10, 120, 150, 90, 80); // Draw a purple polygon as well... SolidBrush brush3= new SolidBrush(Color.Purple); g.FillPolygon(brush3, new Point[]{ new Point(30, 140), new Point(265, 200), new Point(100, 225), new Point(190, 190), new Point(50, 330), new Point(20, 180)}); // And a rectangle with some text... Rectangle r = new Rectangle(150, 10, 130, 60); g.FillRectangle(Brushes.Blue, r); g.DrawString("Hello out there...How are ya?", new Font("Arial", 12), Brushes.White, r); } I ndex

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

SOURCE CODE

SolidBrushApp project Chapter 14 subdirectory. ThisThe compr ehensiv e text star ts w is ithincluded a brief ovunder er viewthe of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Working with Hatch Style Brushes Ta ble o f Con t en t s

The System.Drawing.Drawing2D namespace defines another Brush-derived type named HatchBrush. This type allows you to fill a region using a (very large) number of predefined patterns, represented by the I ntr oduction HatchStyle enumeration. Here are some (but not all) of the hatch values (Table 14-24). C# and t he .NET Plat for m, Second Edition

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Table 14-24: Values of the HatchStyle Enumeration

Pa rHatchStyle t Tw o - The C# Enumeration Pr ogr am m ing La ngua ge Meaning

in Life

Chapter Value 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter Cross6 Chapter 7

- I nter faces and Collections Creates a brush consisting of horizontal and vertical crossing - Callback I nter faces, Delegates, linesand Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

BackwardDiagonal

DiagonalCross

Creates a brush consisting of backward diagonal lines

Creates a brush consisting of diagonal crossing lines

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter ForwardDiagonal 9 - Under standing .NET Assem blies Creates a brush consisting of forward diagonal lines Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Hollow

Configures a "hollow" brush that doesn't paint anything

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa rHorizontal t Four - Le ve r a ging the .NET Libr a r ie sCreates

a brush consisting of horizontal lines

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Pattern

Creates a Brush with a pattern consisting of a custom bitmap

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Solid 14 - A Better Paint ing Fr amew orCreates Chapter k ( GDI + )a solid colored brush (as an alternative to using the type Chapter 15 - Pr ogr am ming with WindowsSolidBrush Form s Contr ols directly) Chapter 16 - The Sy stem .I O Nam espace

Vertical

A brush consisting of vertical lines

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

In addition, when constructing a HatchBrush, you need to specify the foreground and background colors to

Chapter 18 - the ASP.NET Web Pages and Web Contr ols use during fill operation. To illustrate, let's rework the logic seen previously from the PenCapApp Chapter 19 The - ASP.NET Applicat ions oval for the first ten hatch values (Figure 14-16). example. output Web renders a filled Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 14-16: The hatch styles

Here is the code C# behind an d the th eForm: .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

ess © 2003 (1200 pages) private void Apr MainForm_Paint(object sender, PaintEventArgs e) This compr ehensiv e text star ts w ith a brief ov er view of the { and then quickly m oves to key technical and GraphicsC#glanguage = e.Graphics; ar chitectur al issues for .NET developer s. int yOffSet = 10; // Get all members of the HatchStyle enum. Array obj = Enum.GetValues(typeof(HatchStyle)); Ta ble o f Con t en t s // Draw an oval with first 10 HatchStyle values. C# and t he .NET Plat for m, Second Edition for(int x = 0; x < 10; x++) I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // Configure Brush. Chapter 1 - The Philosophy of .NET HatchStyle temp = (HatchStyle)obj.GetValue(x); Chapter 2 - Building C# Applications HatchBrush theBrush = new HatchBrush(temp, Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Color.White, Color.Black Chapter 3 - C#// Language Print Fundamentals name of HatchStyle enum. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# g.DrawString(temp.ToString(), new Font("Times New Roman", 10), Chapter 5 - Exceptions and Obj ect Lifetim e new SolidBrush(Color.Black), 0, yOffSet); Chapter 6 - I nter andaCollections //faces Fill rectangle with the correct brush. Chapter 7 - Callback g. FillEllipse(theBrush, I nter faces, Delegates, and Ev 150, ents yOffSet, 200, 25); yOffSet += 40; Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre}e - Pr ogr am m i ng w i th .N ET Assem bl ie s } Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

SOURCE CODE

The BrushStyles application is included under the Chapter 14 subdirectory.

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Working with Textured Brushes

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Next, we have the TextureBrush type. This type allows you to attach a bitmap image to a brush, which can then be used in conjunction with a fill operation. In just a few pages, you will learn about the details of the Chapter 18 - ASP.NET Web Pages and Web Contr ols GDI+ Image class. For the time being, understand that a TextureBrush is assigned an Image reference for Chapter 19 - its ASP.NET Web use during lifetime. TheApplicat imageions itself is typically found stored in some local file (*.bmp, *.gif, *.jpg) or Chapter 20 XML Web Ser vices embedded into a .NET assembly. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

I ndex

Let's buildes a sample application that makes use of the TextureBrush type. One brush is used to paint the List of Figur entire client area with the image found in a file named "clouds.bmp," while the other brush is used to paint List of Tables text with the image found within "soap bubbles.bmp" (yes, you can use TextureBrush types to render text as well! ). The output is shown in Figure 14-17.

Figure 14-17: Bitmaps as brushes

C# an d th e .N ET Plat f orm , Se con d Ed it ion

ISBN:1590590554 Andr ew oelsenyour Form-derived class maintains The code is very by simple. ToTr begin, two abstract Brush types, which are Apr ess © 2003 (1200 assigned to a new TextureBrush in pages) the constructor. Notice that the constructor of the TextureBrush type requires a type derived This compr fromehensiv Image:e text star ts w ith a brief ov er view of the

C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

public class MainForm : System.Windows.Forms.Form { These *.bmp files must be in the same folder Ta ble o f // Con Note! t en t s // as the (or specify hard coded paths). C# and t he .NET Plat forapplication m, Second Edition // We'll fix this limitation later in this chapter. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

// Data for the image brush. - The Philosophy of .NET private Brush texturedTextBrush; Chapter 2 - Building C# Applications private Brush texturedBGroundBrush; Pa r t Tw o - The C# Pr ogr am m ing La ngua ge public MainForm() Chapter 3 - C# Language Fundamentals { Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# ... Chapter 5 - Exceptions Obj ect for Lifetim e // Loadand image background brush. Chapter 6 - I nter faces and Collections Image bGroundBrushImage = new Bitmap("Clouds.bmp"); Chapter 7 - Callback I nter faces, Delegates, and Ev ents texturedBGroundBrush = new TextureBrush(bGroundBrushImage); Chapter 8 - Advanced Type image Const ruction // NowC#load for Techniques text brush. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl = ie snew Bitmap("Soap Bubbles.bmp"); Image textBrushImage Chapter 9 - Under standing .NET Assem blies texturedTextBrush = new TextureBrush(textBrushImage); Chapter } 10 - Pr ocesses, AppDomains, Cont exts, and Threads ... 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Chapter }r t Four - Le ve r a ging the .NET Libr a r ie s Pa Chapter 1

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Now that you have two TextureBrush types to render with, the paint handler should be a no-brainer:

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

private sender, PaintEventArgs e) Chapter 16 - void The SyMainForm_Paint(object stem .I O Nam espace {

Chapter 17 - Data Access w ith ADO.NET

Graphics g = e.Graphics; Rectangle r = ClientRectangle; Chapter 18 - ASP.NET Web Pages and Web Contr ols // Paint the clouds on the client area. Chapter 19 - ASP.NET Web Applicat ions g.FillRectangle(texturedBGroundBrush, r); Chapter 20 - XML Web Ser vices // Some big bold text with a textured brush. I ndex g.DrawString("Bitmaps as brushes! Way cool...", List of Figur es new Font("Arial", 60, List of Tables FontStyle.Bold | FontStyle.Italic), texturedTextBrush, r); } Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Not bad at all huh? For those of you who have spent time achieving the same effects using the raw Win32 API (or even MFC for that matter), you should be quite pleased with the minimal amount of work required to achieve rather complex results. Now, before moving on to a discussion of image manipulation, there is one final brush typeto consider. SOURCE CODE

The TexturedBrushes application is included under the Chapter 14 subdirectory.

Working with Gradient Brushes

Last but not least, there is the LinearGradientBrush type, which can be used whenever you want to blend C# an d th e .N ET Plat f orm , Se con d Ed it ion two colors together in a gradient pattern. Working with this type is just as simple as working with the other ISBN:1590590554 Andr ew of Tr oelsen brush types. The by only point interest is that when building a LinearGradientBrush, you need to specify the Apr ess © 2003 (1200 pages) direction of the blend, using a value from the LinearGradientMode enumeration (Table 14-25). This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and Table 14-25: LinearGradientMode Enumeration ar chitectur al issues for .NET developer s.

LinearGradientMode Value Ta ble BackwardDiagonal o f Con t en t s C# and t he .NET Plat for m, Second Edition

ForwardDiagonal

I ntr oduction

Meaning in Life Specifies a gradient from upper right to lower left Specifies a gradient from upper left to lower right

Pa rHorizontal t One - I nt r oduci ng C# a nd the .NET P la Specifies tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Vertical

a gradient from left to right

Specifies a gradient from top to bottom

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

To test each type, let's make use of the System.Enum class yet again, and draw a series of rectangles - C# Language Fundamentals using a LinearGradientBrush. The output is seen in Figure 14-18.

Chapter 3 Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure Gradient brushes Chapter 16 - 14-18: The Sy stem .I O Nam espaceat work Chapter 17 - Data Access w ith ADO.NET

Now the code, which I assume requires little comment at this point:

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

private MainForm_Paint(object sender, PaintEventArgs e) Chapter 19 - void ASP.NET Web Applicat ions { Chapter 20 - XML Web Ser vices Graphics g = e.Graphics; Rectangle r = new Rectangle(10, 10, 100, 100); List of Figur es // A gradient brush. List of Tables LinearGradientBrush theBrush = null; int yOffSet = 10; // Get all members of the LinearGradientMode enum. Array obj = Enum.GetValues(typeof(LinearGradientMode)); // Draw an oval with a LinearGradientMode member. for(int x = 0; x < obj.Length; x++) { // Configure Brush. LinearGradientMode temp = (LinearGradientMode)obj.GetValue(x); theBrush = new LinearGradientBrush(r, Color.GreenYellow, Color.Blue, temp); // Print name of LinearGradientMode enum. g.DrawString(temp.ToString(), new Font("Times New Roman", 10), new SolidBrush(Color.Black), 0, yOffSet); // Fill a rectangle with the correct brush. g. FillRectangle(theBrush, 150, yOffSet, 200, 50); I ndex

yOffSet += 80; C# an d th e .N ET Plat f orm , Se con d Ed it ion

}

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

}

SOURCE CODE

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer The GradientBrush application is s.included under the Chapter 14 subdirectory.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Rendering C# Images ISBN:1590590554

by Andr ew Tr oelsen

At this point you have examined how to manipulate three of the four major GDI+ types (fonts, pens, and Apr ess © 2003 (1200 pages) brushes). The final type you examine in this the Image class, and related subtypes. The abstract This compr ehensiv e text starchapter ts w ith aisbrief ov er view of the System.Drawing.Image type defines a number of methods and properties C# language and then quickly m oves to key technical and that hold various bits of ar chitectur al issues for .NET s. information regarding the underlying pixel setdeveloper it represents. For example, the Image class supplies the Width, Height, and Size properties to retrieve the dimensions of the image. Other properties allow you to gain access to the underlying palette. The Image class defines the core members shown in Table 14-26. Ta ble o f Con t en t s C# and t14-26: he .NETMembers Plat for m, of Second EditionType Table the Image I ntr oduction

in Pa rImage t One - IMember nt r oduci ng C# a ndMeaning the .NET P la tf orLife m Name1 Chapter

- The Philosophy of .NET

Chapter 2 - Building C# Applications FromFile() This static method creates an Image from the specified file. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

FromHbitmap() This static method creates a Bitmap from a Windows handle. Chapter 3 - C# Language Fundamentals Chapter 4 - Obj ect -Or iented Pr ogr static am ming w ith C# FromStream() This method creates an Image from the specified data stream. Chapter 5 - Exceptions and Obj ect Lifetim e

Height6 Chapter

These properties return information regarding the dimensions of this - I nter faces and Collections

Chapter Width7

Image. - Callback I nter faces, Delegates, and Ev ents

Chapter Size 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

PhysicalDimensions

Chapter 9

- Under standing .NET Assem blies

HorizontalResolution Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter VerticalResolution 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Palette

This property returns a ColorPalette data type that represents the underlying palette used for this Image.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

GetBounds() a kRectangle Chapter 14 - A Better Paint ing Returns Fr amew or ( GDI + ) that represents the current size of this Image. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Save()

Saves the data held in an Image-derived type to file.

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi vethat - Wthe e b Appl ica ti ons andclass X ML W e b Se rbe vi ces Given abstract Image cannot directly

created, you typically make a direct instance of the

Chapter - ASP.NET Web Pages and you Webhave Contrsome ols Bitmap18 type. For example, assume Form-derived class that renders three bitmaps into the Chapter client area. 19 - To ASP.NET begin,Web you Applicat may create ions three private Image data members, each of which is assigned to a

given *.bmp file on startup (again, be sure these files are located in the application directory): Chapter 20 - XML Web Ser vices I ndex List of Figurclass es public MainForm : System.Windows.Forms.Form List { of Tables

// The images. private Bitmap bMapImageA; private Bitmap bMapImageB; private Bitmap bMapImageC; public MainForm() { ... // Fill the images with bitmaps. bMapImageA = new Bitmap("imageA.bmp"); bMapImageB = new Bitmap("imageB.bmp"); bMapImageC = new Bitmap("imageC.bmp"); } ... }

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Rendering these items from within the context of a paint handler is easy as could be, given that the ISBN:1590590554 by Andr ew Tr oelsen Graphics class has a member named (appropriately enough) DrawImage(). This method has been Apr ess © 2003 (1200 pages) overloaded numerous times to provide various ways to place the image onto the drawing surface. For This comproptional ehensiv eImageAttributes text star ts w ith and a brief ov er view of enumerations. the example, you may specify GraphicsUnit For your purposes, all C# language and then quickly m oves to key technical and you need to do isarspecify the location at which to render each image (which may be defined using Point, chitectur al issues for .NET developer s. Rectangles, integers, or floats): Taprotected ble o f Con t envoid ts OnPaint (object sender, System.Windows.Forms.PaintEventArgs e) C# { and t he .NET Plat for m, Second Edition

Graphics g = e.Graphics; I ntr oduction Render three images. Pa r t One// - I nt r oduci ng all C# a nd the .NET P la tf or m 10, 10, 90, 90); Chapter g.DrawImage(bMapImageA, 1 - The Philosophy of .NET 10, 110, 90, 90); Chapter g.DrawImage(bMapImageB, 2 - Building C# Applications Pa r t Tw og.DrawImage(bMapImageC, - The C# Pr ogr am m ing La ngua ge 10,

210, 90, 90);

} Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

The result can be seen in Figure 14-19.

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 14-19: Rendering images Also be aware that regardless of the name given to the Bitmap type, you are able to load in images stored in any number of file formats. For example: // The Bitmap type can hold work with any number of file formats! Bitmap myBMP = new Bitmap("CoffeeCup.bmp"); Bitmap myGIF = new Bitmap("Candy.gif"); Bitmap myJPEG = new Bitmap("Clock.jpg"); Bitmap myPNG = new Bitmap("Speakers.png"); Bitmap myTIF = new Bitmap("FooFighters.tif"); // Now render each onto the Graphics context. g.DrawImage(myBMP, 10, 10); g.DrawImage(myGIF, 220, 10);

g.DrawImage(myJPEG, 280, 10); C# an d th150, e .N ET200); Plat f orm , Se con d Ed it ion g.DrawImage(myPNG, by Andr ew Tr oelsen g.DrawImage(myTIF, 300, 200);

ISBN:1590590554

Apr ess © 2003 (1200 pages)

SOURCE CODE

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. under the Chapter 14 subdirectory. The Images application is included

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , SePictureBox con d Ed it ion Dragging, Hit Testing, and the Control ISBN:1590590554

by Andr ew Tr oelsen

While you are free toess render images directly onto a Control-derived type (such as a Form), you will Apr © 2003Bitmap (1200 pages) find that you gainThis far greater control youovinstead compr ehensiv e and text functionality star ts w ith a if brief er view choose of the to create a PictureBox type to hold your image on your behalf. There are numerous reasons to do C# language and then quickly m oves to key technical so. andFirst, because the PictureBox type ar chitectur al issues for .NET s. derives from Control, you inherit a great dealdeveloper of functionality, such as the ability to capture a number of events for a particular image, assign a tool tip or context menu, and numerous other details. While you could achieve similar behaviors using a raw Bitmap, you would be required to add a fair amount of Taboilerplate ble o f Con tcode. en t s C# and t he .NET Plat for m, Second Edition

Tooduction illustrate the usefulness of the PictureBox type, let's create an application that illustrates the ability to I ntr capture MouseDown, and MouseMove Pa r t One -MouseUp, I nt r oduci ng C# a nd the .NET P la tf or m

events from a graphical image contained in a

PictureBox. Chapter 1 - The Philosophy of .NET Chapter 2

- Building C# Applications

If users click the mouse somewhere within the bounds of the image, they are in "dragging" mode and can move the image around the Form. To make things more interesting, let's monitor where they release the Chapter 3 - C# Language Fundamentals image. If it is within the bounds of a GDI+rendered rectangle, we take some additional course of action Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# (seen shortly). As you may know, the process of testing for mouse Click events within the context of a Chapter 5 the - Exceptions Obj ect e region of screen is and termed "hitLifetim testing." Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 6

- I nter faces and Collections When it7 comes to theI nter functionality provided byEv the PictureBox type, there is little to say, as all of the Chapter - Callback faces, Delegates, and ents

necessary from ruction the Control base class. Given that you have already explored a Chapter 8 - functionality Advanced C#comes Type Const Techniques number theogr members for Pa r t Thre eof- Pr am m i ng w i ththese .N ET types, Assem you bl ie scan

quickly turn your attention to the process of assigning an

image to PictureBox member variable: Chapter 9 the - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

public MainForm : Binding, System.Windows.Forms.Form Chapter 11 class - Type Reflection, Late and Attr ibute- Based Pr ogramm ing {r t Four - Le ve r a ging the .NET Libr a r ie s Pa an image smileyLay face. Chapter // 12 - This Obj ect holds Ser ialization and the of .NETaRemoting er PictureBox happyBox; Chapter private 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) MainForm() Chapter public 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter { 15 - Pr ogr am ming with Windows Form s Contr ols

// Configure the PictureBox. happyBox = new PictureBox(); Chapter 17 - Data Access w ith ADO.NET happyBox.SizeMode = PictureBoxSizeMode.StretchImage; Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces happyBox.Location = new System.Drawing.Point(64, 32); Chapter 18 - ASP.NET Web Pages and Web Contr ols happyBox.Size = new System.Drawing.Size(50, 50); Chapter 19 - ASP.NET Web Applicat ions happyBox.Cursor = Cursors.Hand; Chapter 20 - XML Web Ser vices happyBox.Image = new Bitmap("happy.bmp"); I ndex // Now add to the Form's Controls collection. List of Figur es Controls.Add(happyBox); List of Tables } ... } Chapter 16 - The Sy stem .I O Nam espace

The only point of interest is the SizeMode property, which makes use of the PictureBoxSizeMode enumeration. This type is used to control how the associated image should be rendered within the bounding rectangle of the PictureBox. Here, you assigned StretchImage, indicating that you wish to skew the image over the entire client area. Other possible values appear in Table 14-27. Table 14-27: The PictureBoxSizeMode Enumeration

PictureBoxSizeMode Meaning incon Life C# an d th e .N ET Plat f orm , Se d Ed it ion Member Name by Andr ew Tr oelsen AutoSize CenterImage

ISBN:1590590554

Apr ess © 2003 (1200 pages)

The PictureBox is sized equal to the size of the image that it

This compr ehensiv e text star ts w ith a brief ov er view of the contains. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s

The image is displayed in the center if the PictureBox is larger than the image. If the image is larger than the PictureBox, the picture is placed in the center of the PictureBox and the outside edges are clipped.

C# and t he .NET Plat for m, Second Edition I ntrNormal oduction

The image is located in the upper left corner of the PictureBox. If is smaller than the image, it will be clipped.

thePPictureBox Pa r t One - I nt r oduci ng C# a nd the .NET la tf or m Chapter 1

- The Philosophy of .NET Now that have configured the initial look and feel of the PictureBox, you need to hook up some Chapter 2 you - Building C# Applications

handlers Pa r t Tw o - for Thethe C# MouseMove, Pr ogr am m ingMouseUp, La ngua ge

and MouseDown events. This is simple, as PictureBox "is-a" Control. Thus, you can update your constructor logic as follows: Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# // Add the events. Chapter 5 handlers - Exceptions for and Obj ect following Lifetim e

happyBox.MouseDown new MouseEventHandler(happyBox_MouseDown); Chapter 6 - I nter faces and += Collections happyBox.MouseUp += newDelegates, MouseEventHandler(happyBox_MouseUp); Chapter 7 - Callback I nter faces, and Ev ents happyBox.MouseMove += new Chapter 8 - Advanced C# Type Const MouseEventHandler(happyBox_MouseMove); ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

The logic behind MouseDown stores the incoming (x,y) location of the mouse click for later use, and sets a Boolean member variable (isDragging) to true, to indicate that a drag operation is in process.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

// Mouse event handler to initiate dragging the pictureBox around. private void happyBox_MouseDown(object sender, MouseEventArgs e) Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) { Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) isDragging = true; Chapter 15 - Pr ogr am ming with Windows Form s Contr ols // Save the (x, y) of the mouse down click, Chapter // 16 - because The Sy stemwe .I O need Nam espace it as an offset when dragging the image. Chapter oldX 17 - Data Access w ith ADO.NET = e.X; Pa r t Fi veoldY - W e b =Appl ica ti ons and X ML W e b Se r vi ces e.Y; Chapter 18 ASP.NET Web Pages and Web Contr ols } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

The MouseMove handler simply relocates the position of the PictureBox (using the Top and Left I ndex properties) List of Figur esby offsetting the current cursor location with the (x, y) position captured when the mouse went down. List of Tables

// If the user clicks the image and moves the mouse, // redraw the image at the new location. private void happyBox_MouseMove(object sender, MouseEventArgs e) { if (isDragging) { // Need to figure new Y value based on where the mouse // down click happened. happyBox.Top = happyBox.Top + (e.Y - oldY); // Same deal for X (use oldX as a base line). happyBox.Left = happyBox.Left + (e.X - oldX); } }

Finally, MouseUp sets the isDragging Boolean to false, to signal the end of the drag operation. Recall C# an d th e .N ET Plat f orm , Se con d Ed it ion however, that this application has one extra point of logic. If the MouseUp event occurs when the ISBN:1590590554 by Andr ew Tr oelsen PictureBox is contained within a GDI+ Rectangle object, you can assume the user has won the game Apr ess © 2003 (1200 pages) (albeit a rather lame game...). That said, here is the remainder of the Form's logic: This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and // When the mouse goes up,forthey done ar chitectur al issues .NET are developer s. dragging.

// See if they dropped the image in the rectangle... private void happyBox_MouseUp(object sender, MouseEventArgs e) Ta{ble o f Con t en t s = Second false;Edition C# and tisDragging he .NET Plat for m, // Is the mouse within the area of the drop rect? I ntr oduction Pa r t Oneif(dropRect.Contains(happyBox.Bounds)) - I nt r oduci ng C# a nd the .NET P la tf or m MessageBox.Show("You win!", "What an amazing test of skill..."); Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

// Assume have aFundamentals private Rectangle configured as follows: Chapter 3 - C#we Language // Rectangle dropRect = new Rectangle(100, 100, 150, 150); - Obj ect -Or iented Pr ogr am ming w ith C# private void MainForm_Paint(object sender, PaintEventArgs e) Chapter 5 - Exceptions and Obj ect Lifetim e { Chapter 6 - I nter faces and Collections // Draw the drop box. Chapter 7 - Callback I nter faces, Delegates, and Ev ents Graphics g = e.Graphics; Chapter 8 - Advanced C# Type Const ruction Techniques g.FillRectangle(Brushes.AntiqueWhite, dropRect); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s // Display instructions. Chapter g.DrawString("Drag 9 - Under standing .NET Assem the blies happy guy in here...", Chapter 10 - Pr new ocesses, AppDomains, and Threads Font("Times Cont New exts, Roman", 25), Brushes.Red, dropRect); Chapter 11 Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing } Chapter 4

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

As a reminder, it is worth pointing out( Int that the Rectangle defines the Contains() method that has been Chapter 13 - Building a Bet ter Win dow roducin g Window stype For ms) overloaded test forPaint contained Rectangle, or two integer values. This member can be quite helpful Chapter 14 - to A Better ing Fr amew or k ( GDIPoint, +) when calculating if aming mouse has occurred within Chapter 15 - Pr ogr am withclick Windows Form s Contr ols a given rectangular region (as seen in the MouseUp event handler). application, you are presented with what appears in Figure 14-20. Chapter 16 - The When Sy stemyou .I O run Namthe espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 14-20: The amazing happy-dude game If you have what it takes to win the game, you are rewarded with the kudos shown in Figure 14-21.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Figure 14-21: You have nerves of steel... Ta ble o f Con t en t s

SOURCE DraggingImages application is included under the Chapter 14 subdirectory. C# and t he .NET Plat forThe m, Second Edition CODE

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

More Hit - The Testing Philosophy Details of .NET

Chapter 1 Chapter 2

- Building C# Applications

Chapter 5

- Exceptions and Obj ect Lifetim e

Validating a hit against a Control-derived Pa r t Tw o - The C#test Pr ogr am m ing La ngua ge

type (such as a PictureBox) is very simple, as each can respond to mouse events directly. However, what if you wish to perform a hit test on a geometric shape Chapter 3 - C# Language Fundamentals such as a region rendered on the screen using a raw GDI+ object? To illustrate, let's revisit the previous Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Images application, and add some additional functionality. Chapter 6 is- to I nter faces andwhen Collections The goal determine the user clicks a given image (which as you recall was not rendered within Chapter 7 Callback I nter faces, and Evimage ents was clicked, adjust the Text property of the Form, a PictureBox control). Once youDelegates, discover which Chapter 8 - Advanced C#with Type Const ruction Techniques and highlight the image a 5-pixel outline. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

The first is tostanding intercept.NET the MouseDown Chapter 9 step - Under Assem blies event for the Form itself. When the event occurs, you need to programmatically figure out if the incoming (x,and y) coordinate Chapter 10 - Pr ocesses, AppDomains, Cont exts, Threads is somewhere within the bounds of the

Rectangles used Reflection, to represent theBinding, dimension If ogramm the usering does click a given image, you set a Chapter 11 - Type Late and of Attreach ibute-Image. Based Pr private variable Pa r t FourBoolean - Le ve r a member ging the .NET Libr a(isImageClicked) r ie s

to true, and indicate which image was selected via another member variable (of type integer): Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

public MainForm System.Windows.Forms.Form Chapter 14 class - A Better Paint ing Fr : amew or k ( GDI + ) { Chapter 15 - Pr ogr am ming with Windows Form s Contr ols ... // Did they click an image? Chapter 17 - Data Access w ith ADO.NET private bool isImageClicked = false; Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces private int imageClicked; Chapter 18 - ASP.NET Web Pages and Web Contr ols protected void OnMouseDown (object sender, MouseEventArgs e) Chapter 19 - ASP.NET Web Applicat ions { Chapter 20 - XML Web Ser vices // Get (x, y) of mouse click. I ndex Point mousePt = new Point(e.X, e.Y); List of Figur es // See if the mouse is anywhere in the 3 regions... List of Tables if(rectA.Contains(mousePt)) { isImageClicked = true; imageClicked = 0; this.Text = "You clicked image A"; } else if(rectB.Contains(mousePt)) { isImageClicked = true; imageClicked = 1; this.Text = "You clicked image B"; } else if(rectC.Contains(mousePt)) { isImageClicked = true; imageClicked = 2; Chapter 16 - The Sy stem .I O Nam espace

this.Text = "You clicked image C"; } C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554 by Andr ew// Tr oelsen else Not in any shape, set defaults. Apr ess © 2003 (1200 pages) { ThisisImageClicked compr ehensiv e text star ts w ith a brief ov er view of the = false; C# language and then quickly m oves to key technical and this.Text = "Images"; ar chitectur al issues for .NET developer s. } // Redraw the client area. Invalidate(); Ta ble o f Con t en t s } C# and t he .NET Plat for m, Second Edition ... I ntr oduction } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter Building C# Applications Notice 2that- the final conditional check sets the isImageClicked member variable to false, indicating that the Pa r t Tw o -not Theclick C# Pr ogrof amyour m ingthree La ngua ge user did one images.

This is important, as you want to erase the outline of the

Chapter 3 -selected C# Language Fundamentals previously image. Once all items have been checked, invalidate the client area. Here is the Chapter 4 Paint - Objhandler: ect -Or iented Pr ogr am ming w ith C# updated Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6 - void I nter faces and Collections private MainForm_Paint(object sender, PaintEventArgs e) Chapter 7 Callback I nter faces, Delegates, and Ev ents { Chapter Graphics 8 - Advanced Type Const ruction Techniques g C# = e.Graphics; Pa r t Thre// e - Pr ogr am mall i ng w three i th .N ET images. Assem bl ie s Render

Chapter ... 9 - Under standing .NET Assem blies

outline (if clicked...) Chapter // 10 - Draw Pr ocesses, AppDomains, Cont exts, and Threads true) Chapter if(isImageClicked 11 - Type Reflection, Late == Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four{ - Le ve r a ging the .NET Libr a r ie s

Pen outline new Chapter 12 - Obj ect Ser ialization =and the Pen(Color.Red, .NET Remoting Lay er 5); switch(imageClicked) Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A { Better Paint ing Fr amew or k ( GDI + )

case 0: g.DrawRectangle(outline, rectA); Chapter 16 - The Sy stem .I O Nam espace break; Chapter 17 - Data Access w ith ADO.NET case 1: Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces g.DrawRectangle(outline, rectB); Chapter 18 - ASP.NET Web Pages and Web Contr ols break; Chapter 19 - ASP.NET Web Applicat ions case 2: Chapter 20 - XML Web Ser vices g.DrawRectangle(outline, rectC); I ndex break; List of Figur es default: List of Tables break; } } } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Hit Testing Nonrectangular Images Now, what if you wish to perform a hit test in a nonrectangular region, rather than a simple square? Assume you updated your application to render an oddball geometric shape that will also sport an outline when clicked (Figure 14-22).

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Chapter 3

- C# Language Fundamentals

Figure 14-22: Pa r t Tw o - The C# PrHit-testing ogr am m ingpolygons La ngua ge This geometric image was rendered on the Form using the FillPath() method of the Graphics type. This - Obj ect -Or iented Pr ogr am ming w ith C# method takes an instance of a GraphicsPath object, which was mentioned earlier during your examination Chapter 5 - Exceptions and Obj ect Lifetim e of the System.Drawing.Drawing2D namespace. The GraphicsPath object encapsulates a series of Chapter 6 I nter faces and Collections connected lines, curves, and (interestingly enough) strings. Adding new items to a GraphicsPath instance Chapter 7 - using Callback I nter faces, Delegates, andmethods Ev ents (Table 14-28). is achieved a number of related "add" Chapter 4

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ieGraphicsPath s Table 14-28: Add-Centric Methods of the

Chapter 9

Class

- Under standing .NET Assem blies

GraphicsPath "Add" Method

Meaning in Life

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa rAddArc() t Four - Le ve r a ging the .NET Libr a r ie Appends s

an elliptical arc to the current figure

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

AddBezier() a cubic Beziers curve Chapter 13 - Building a Bet ter Win dow ( Adds Int roducin g Window For ms)(or set of Bezier curves) to the current figure

AddBeziers() Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

AddClosedCurve()

Adds a closed curve to the current figure

Chapter 16 - The Sy stem .I O Nam espace

AddCurve() Chapter 17 - Data Access w ith ADO.NETAdds a curve to the current figure Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

AddEllipse()

Adds an ellipse to the current figure

Chapter 18 - ASP.NET Web Pages and Web Contr ols

AddLine() Chapter 19 - ASP.NET Web Applicat ions Appends a line segment to the current figure Chapter 20 - XML Web Ser vices AddLines() I ndex

AddPath()

List of Figur es ListAddPie() of Tables

Appends the specified GraphicsPath to the current figure Adds the outline of a pie shape to the current figure

AddPolygon()

Adds a polygon to the current figure

AddRectangle()

Adds one (or more) rectangle to the current figure

AddRectangles() AddString()

Adds a text string to the current figure

Assume that you have added a private GraphicsPath member variable to your current Images application. In the Form's constructor, build the set of items that represent your path as follows: public MainForm : System.Windows.Forms.Form { GraphicsPath myPath = new GraphicsPath(); public MainForm()

{ an d th ean .N ET Plat f orm , Se con d Ed it ion // C# Create interesting region. ISBN:1590590554 by Andr ew Tr oelsen myPath.StartFigure(); Apr ess © 2003 (1200 pages) myPath.AddLine(new Point(150, 10), new Point(120, 150)); This compr ehensiv e text 200, star ts w ith a brief ov er of the myPath.AddArc(200, 100, 100, 0,view 90); C# language and then quickly m oves to key technical and Point point1 = new Point(250, 250); ar chitectur al issues for .NET developer s. Point point2 = new Point(350, 275); Point point3 = new Point(350, 325); Point point4 = new Point(250, 350); Ta ble o f Con t en t s Point[] points = { point1, point2, point3, point4} ; C# and t he .NET Plat for m, Second Edition myPath.AddCurve(points); I ntr oduction myPath.CloseFigure(); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m ... Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications } Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter Obj ect iented Pr ogrand am ming w ith C# Notice 4the-calls to -Or StartFigure() CloseFigure(). When you call StartFigure(), you are able to insert a Chapter new item 5 into - Exceptions the current andpath Obj ect youLifetim are building. e A call to CloseFigure() closes the current figure and begins

a new figure (if you require one). If the figure contains a sequence of connected lines and curves (as in the Chapter 6 - I nter faces and Collections case of7the- myPath loop is closed by connecting a line from the endpoint to the starting Chapter Callback instance), I nter faces,the Delegates, and Ev ents point. 8 Chapter

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

There are more members for System.Drawing.Drawing2D.GraphicsPath, but let's keep focused on the hit- Under standing .NET Assem blies testing logic. The next step would be to update your existing MouseDown event handler to test for the Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads presence of the cursor's (x,y) position within the bounds of the GraphicsPath. Like a Region type, this can Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing be discovered using the IsVisible() member: Chapter 9

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

protected void OnMouseDown (object sender, MouseEventArgs e) { Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) // Get (x, y) of mouse click. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Point mousePt = new Point(e.X, e.Y); Chapter ... 16 - The Sy stem .I O Nam espace Chapter else 17 - Data Access w ith ADO.NET if(myPath.IsVisible(mousePt)) Pa r t Fi ve{- W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 18 - ASP.NET Web Pages and Contr ols isImageClicked = Web true; Chapter 19 - ASP.NET Web Applicat imageClicked = ions 3; Chapter 20 - XML Web Ser vices this.Text = "You clicked the strange shape..."; I ndex } ... List of Figur es } of Tables List Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Finally, you can update the Paint handler as follows: private void MainForm_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; ... // Draw the graphics path. g.FillPath(Brushes.AliceBlue, myPath); // Draw outline (if clicked...) if(isImageClicked == true) { Pen outline = new Pen(Color.Red, 5); switch(imageClicked)

{ C# an d th e .N ET Plat f orm , Se con d Ed it ion ... ISBN:1590590554 by Andr ew 3: Tr oelsen case Apr ess © 2003 (1200 pages) g.DrawPath(outline, myPath); This compr ehensiv e text star ts w ith a brief ov er view of the break; C# language and then quickly m oves to key technical and default: ar chitectur al issues for .NET developer s.

break;

} }

Ta ble o f Con t en t s

}

C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - The Philosophy of .NET Images project is included under the Chapter 14 subdirectory. SOURCE The (updated) Chapter 2 Building C# Applications CODE Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET PlatResource f orm , Se con d Ed it ion Understanding .NET Format ISBN:1590590554

by Andr ew Tr oelsen

Up to this point, each application that made use of external resources (such as bitmaps) assumed that Apr ess © 2003 (1200 pages) they were locatedThis in acompr separate stand-alone filewwithin the application For example, the Images ehensiv e text star ts ith a brief ov er view of directory. the application rendered three bitmap images, which as you recall were loaded directly from file: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

// Fill the images with bitmaps. bMapImageA = new Bitmap("imageA.bmp"); Ta ble o f Con t en t s bMapImageB = new Bitmap("imageB.bmp"); C# and t he .NET Plat for m, Second Edition bMapImageC = new Bitmap("imageC.bmp"); I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 of - The Philosophy of .NET This logic course demands that the application directory does indeed contain three files named Chapter 2 Building C# Applications "imageA.bmp," "imageB.bmp," and "imageC.bmp" (see Figure 14-23). Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t FiFigure ve - W e14-23: b Appl ica ons and X ML W ethree b Se r vi ces Antiapplication with external

resources

Chapter 18 - ASP.NET Web Pages and Web Contr ols

If any of19these files are deleted, or relocated outside the application directory, the program fails Chapter - ASP.NET Web Applicatrenamed, ions to execute a trySer just for verification's sake). Now, as you recall from Chapter 9, an assembly is a Chapter 20 - (give XML itWeb vices

collection of types and optional resources. The time has now come to learn how to bundle external resources (such as image files and strings) into the assembly itself. In this way, your .NET binary is truly List of Figur es self-contained. In a nut-shell, bundling external resources into a .NET assembly involves the following List of Tables steps: I ndex

Create an *.resx file that establishes name/value pairs for each resource in your application using XML data representation. Use the resgen.exe utility to convert your XML-based *.resx file into a binary equivalent (a *.resources file). Using the /resource: flag of the C# compiler, embed the binary *.resources file into your assembly. As you might suspect, all these steps are followed automatically when using the Visual Studio .NET IDE. You'll examine how the IDE can assist you in just a bit. For now, let's take the time to work with the .NET resource format in the raw.

C# an d th e .N ET Plat f orm , Se con d Ed it ion System.Resources Namespace ISBN:1590590554

by Andr ew Tr oelsen

The key to understanding the (1200 .NETpages) resource format is to know the types defined within the System.Resources Apr ess © 2003 namespace. ThisThis set compr of types provides programmatic to of manipulate both *.resx (XML-based) and ehensiv e textthe star ts w ith a brief means ov er view the *.resources (binary) files. Table 14-29 provides a rundown of the core types. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Table 14-29: Members of the System.Resources Namespace System.Resources Ta ble o f Con t en t s

Meaning in Life Type C# and t he .NET Plat for m, Second Edition I ntr oduction

IResourceReader

These interfaces are implemented by types that understand how to read and write .NET resources (in various formats). You do not need to IResourceWriter Chapter 1 - The Philosophy of .NET implement these interfaces yourself unless you are interested in building Chapter 2 - Building C# Applications a custom resource reader/writer. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

ResourceReader These classes provide an implementation of the IResourceReader and Chapter 3 - C# Language Fundamentals interfaces. Using the ResourceReader and Chapter 4 - Obj ect -Or iented PrIResourceWriter ogr am ming w ith C# ResourceWriter Chapter 5

types, you are able to read from and write to binary - Exceptions and ObjResourceWriter ect Lifetim e

Chapter 6

- I nter faces and Collections

*.resources files.

Chapter 7 - Callback I nter faces, Delegates, and Ev ents ResXResourceReader These classes also provide an implementation of the IResourceReader Chapter 8 - Advanced C# Typeand Const ruction Techniques IResourceWriter interfaces. Using the ResXResourceReader and

ResXResourceWriter

Pa r t Thre e - Pr ogr am m i ng w i th ResXResourceWriter .N ET Assem bl ie s

Chapter 9

types, you are able to read from, and write to, XML

- Under standing .NET *.resx Assem files. blies This file may be turned into a binary equivalent (the

*.resources file) using the resgen.exe utility. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

ResourceManager

Provides easy access to culture-specific resources (BLOBs and string resources) at runtime.

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Programmatically Creating an *.resx File

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

As mentioned, an *.resx file is a block of XML data that assigns name/value pairs for each resource in your application. The ResXResourceWriter class provides a set of members that allow you to create the *.resx file, Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces add binary and string-based resources, and commit them to storage. To illustrate, assume you have a simple Chapter 18 - you ASP.NET and Weband Contr ols application have Web built Pages a la notepad csc.exe, whose job in life is to build an *.resx file containing an Chapter 19the - ASP.NET Webimage Applicat ions earlier in this chapter, and a single string resource. The GUI is as simple entry for happy.bmp seen Chapter 20 - (Figure XML Web14-24). Ser vices as possible Chapter 17 - Data Access w ith ADO.NET

I ndex List of Figur es List of Tables

Figure 14-24: The ResX application The Click event handler for the "Add resources" button does the grunt work of adding the happy.bmp and string resource to the *.resx file. Here is the code:

protected void btnMakeResxFile_Click (object sender, System.EventArgs e) C# an d th e .N ET Plat f orm , Se con d Ed it ion { ISBN:1590590554 ew Trwriter oelsen // Make byanAndr resx & specify the file to write to. Apr ess © 2003 (1200 pages) ResXResourceWriter w = compr ehensiv e text star ts w ith a brief ov er view of the newThis ResXResourceWriter("ResXForm.resx"); C# language quickly m oves to key technical and // Add happy dudeand & then string. ar chitectur al issues for .NET developer s. Image i = new Bitmap("happy.bmp"); w.AddResource("happyDude", i); w.AddResource("welcomeString", "Hello new resource format!"); Ta ble o f Con t en t s // Commit it. C# and t he .NET Plat for m, Second Edition w.Generate(); I ntr oduction w.Close(); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m } Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr amismResXResourceWriter.AddResource(). ing La ngua ge The member of interest

This method has been overloaded a few

Chapter - C#you Language Fundamentals times to3 allow to insert binary data (as you did with the happy.bmp image), as well as textual data (as you Chapter 4 - for Objyour ect -Or iented Pr ogr am ming ith C#version takes two parameters: the name of a given resource in have done test string). Notice thatweach Chapter the *.resx 5 file - Exceptions and the data and itself. Obj ectThe Lifetim Generate() e method commits the information to file. Chapter 6

- I nter faces and Collections

Understand that you are not the one in charge of writing the raw XML that describes your resources. Rather, - Callback I nter faces, Delegates, and Ev ents the logic within the ResXResourceWriter class is responsible for building the XML description of the inserted Chapter 8 - Advanced C# Type Const ruction Techniques items. To prove the point, compile and run your application, load the new *.resx file using VS .NET, and peek Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s inside the contents (Figure 14-25). Chapter 7

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Figure Viewing *.resx file a la VS .NET Chapter 17 - 14-25: Data Access w iththe ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

If you switch to the XML view, you should be able to identify happyDude and welcomeString by name. The

Chapter 19 - ASP.NET WebtoApplicat ions your name/value pairs follows [note the (partial) binary representation of XML syntax that is used represent Chapter 20 XML Web Ser vices the happy dude bitmap...]: I ndex List of Figur es

< data name="happyDude" mimetype="text/microsoft-urt/binary-serialized/base64" >

List of Tables

AAEAAAD/////AQAAAAAAAAAMAgAAA ... AAAAAAAAAAAAAAAAAAAA=

Hello new resource format!

Programmatically Reading an *.resx File To illustrate how you can load and investigate an *.resx file programmatically let's examine the code behind the "Read *resx" button. This time, make use of a ResXResourceReader type. Once the correct file has been opened, ask the reader for a reference to its IDictionaryEnumerator interface, and loop over each name/value

pair:

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

protected void btnReadResxFile_Click (object sender, System.EventArgs e) Apr ess © 2003 (1200 pages) { This compr ehensiv e text star ts w ith a brief ov er view of the // Make C# anlanguage resx reader. and then quickly m oves to key technical and ResXResourceReader r = ar chitectur al issues for new .NET ResXResourceReader("ResXForm.resx"); developer s. // Grab the IDictionaryEnumerator interface and show everything. IDictionaryEnumerator en = r.GetEnumerator(); Ta ble o f while Con t en t (en.MoveNext()) s { C# and t he .NET Plat for m, Second Edition MessageBox.Show("Value:" + en.Value.ToString(), I ntr oduction "Key: " + en.Key.ToString()); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m } Chapter 1 - The Philosophy of .NET Chapter r.Close(); 2 - Building C# Applications }r t Tw o - The C# Pr ogr am m ing La ngua ge Pa Chapter 3

- C# Language Fundamentals

Chapter 4

Obj ect -Or iented Pr ogr am ming w ith C# When you-click the button, you see a pair of message boxes pop up, as the ResXResourceReader type loops

Chapter - Exceptions Objnamed ect Lifetim e through5 the XML file forand each value. Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Building the *.resources File Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Now that you understand how to build and manipulate an *.resx file, you can make use of the resgen.exe utility

Chapter 9 - the Under standing .NET Assem blies to produce binary equivalent. Again, VS .NET will do so automatically, but just for the love of learning, here Chapter 10 Pr ocesses, AppDomains, Cont exts, and Threads is the raw command: Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

resgen resxform.resx resxform.resources

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter Of course, 15 - you Pr ogr must am ming openwith a command Windows Form prompt s Contr in the olsdirectory containing the *.resx file before running

resgen.exe. Once you do, you are able to open the new *.resources file and check out the binary Chapter 16 - The Sy stem .I O however, Nam espace format 17 (Figure 14-26). Chapter - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 14-26: The binary *.resources file

Binding the *.resources File into a .NET Assembly Cool! At this point you are able to add this *.resources file as a command-line argument to the C# compiler. Recall that doing so also requires you to reference each external assembly (e.g., System.Drawing.dll): csc/resource:resxform.resources *.cs

If you were to now open your new assembly using ildasm.exe, you would find the entry shown in Figure 14-27 an d th e .N ET Plat f orm , Se con d Ed it ion in the assembly'sC# metadata. ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

Figure 14-27: The embedded resources

I ntr oduction

Pa r t you One can - I ntsee, r oduci ngmanifest C# a nd the P la tf orthe m As the has.NET recorded

name of the binary resources that are now contained in the

Chapter - The Philosophy owning1assembly. In just a of bit .NET you will see how to programmatically read this information from an assembly to Chapter 2 Building C# Applications make use of it in your application. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

SOURCE The Fundamentals ResXWriterReader.cs file is included under the Chapter 14 subdirectory. Chapter 3 - C# Language CODE Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Working with ResourceWriters ISBN:1590590554

by Andr ew Tr oelsen

The previous example the ResXResourceReader and ResXResourceWriter types to Apr essmade © 2003use (1200ofpages) generate an XMLThis file that contains name/value each compr ehensiv e text star ts wpairs ith a for brief ov erapplication view of the resource. The resulting *.resx file was then run through the resgen.exe utility. Finally the *.resources fileand was bound into the owning C# language and then quickly m oves to key technical ar chitectur al issues for .NET s. assembly using the /resource flag. The truth developer of the matter is that you do not need to build an *.resx file (although having an XML representation of your resources can come in handy, and is readable). TaIfble youo fdo Con not t en require ts an *.resx file, you can make use of the ResourceWriter type to directly create a binary

*.resources file.Plat Tofor illustrate, assume C# and t he .NET m, Second Editionyou have created a new application named ResourceTest (again using Notepad and csc.exe). The Main() method of the ResourceGenerator class uses the ResourceWrite I ntr oduction type to directly generate Pa r t One - I nt r oduci ng C# athe nd myResources.resources the .NET P la tf or m Chapter 1

file:

- The Philosophy of .NET

Chapter class2 ResourceGenerator - Building C# Applications Pa {r t Tw o - The C# Pr ogr am m ing La ngua ge

void Main(string[] args) Chapter static 3 - C# Language Fundamentals Chapter { 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

// Makeand a Obj new file. - Exceptions ect *.resources Lifetim e

Chapter 6

ResourceWriter rw; - I nter faces and Collections

Chapter 7

rw = Inew ResourceWriter("myResources.resources"); - Callback nter faces, Delegates, and Ev ents

// Add 1 image and 1 string. rw.AddResource("happyDude", new Bitmap("happy.bmp")); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s rw.AddResource("welcomeString", "Welcome to .NET resources."); Chapter 9 - Under standing .NET Assem blies rw.Generate(); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing } Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building Bet ter ( Int roducin Window sthe For*.resource ms) At this point, compilea and runWin thedow application to ggenerate file. Now, we can bind the Chapter 14 -binary A Better Paint ing owning Fr amew assembly or k ( GDI + )as before: contained data to the Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace csc /resource:myresources.resources *.cs Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

If you wish read theWeb rawPages name/value from Chapter 18 - to ASP.NET and Webdata Contr ols the binary *.resources file, you are free to make use of the ResourceReader class. This is almost identical to working with the ResXResourceWriter type. Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Working with ResourceManagers by Andr ew Tr oelsen

ISBN:1590590554

Rather than working with© the class directly, you will most likely use the Apr ess 2003ResourceReader (1200 pages) ResourceManager type. The reason is simple: It is easier Using the ResourceManager, you This compr ehensiv e text star ts w ith a brief to ovwork er viewwith! of the are able to extract binary and textual data from an assembly for use in your application. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

To illustrate, assume you have added a new class to the current project named MyResourceReader. This type uses a ResourceManager type to pull the happyDude and welcomeString resources from the Taassembly ble o f Conand t en tdump s them into a PictureBox and Label object using the GetObject() and GetString() members. Be very aware however, that the double quoted strings you send into these methods are case C# and t he .NET Plat for m, Second Edition sensitive. I ntr oductionHere is the code: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter - The Philosophy of .NET class1 MyResourceReader Chapter { 2

- Building C# Applications

Pa r t Tw opublic - The C# static Pr ogr am mvoid ing La ngua ReadMyResources() ge

Chapter { 3

- C# Language Fundamentals

Chapter 4

// the resources - Obj ect Open -Or iented Pr ogr am ming w ithfile. C#

Chapter 5

ResourceManager rm = - Exceptions and Obj ect Lifetim e new ResourceManager("myResources",

Chapter 6

Assembly.GetExecutingAssembly()); - I nter faces and Collections

Chapter 7

// Load resource. - Callback I nterimage faces, Delegates, and Ev ents

PictureBox p = new PictureBox(); Bitmap b = (Bitmap)rm.GetObject("happyDude"); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s p.Image = (Image)b; Chapter 9 - Under standing .NET Assem blies p.Height = b.Height; Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads p.Width = b.Width; Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing p.Location = new Point(10, 10); Pa r t Four - Le ve r a ging the .NET Libr a r ie s // Load string resource. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Label label1 = new Label(); Chapter 13 - Building a Bet ter Win dow =( Int roducin g Window s 10); For ms) label1.Location new Point(50, Chapter 14 - A label1.Font Better Paint ing Fr = amew or kFont(label1.Font.FontFamily, ( GDI + ) new 12, FontStyle.Bold); Chapter 15 - Pr label1.AutoSize ogr am ming with Windows Form s Contr ols = true; Chapter 16 - The Sy stem .I O Nam=espace label1.Text rm.GetString("welcomeString"); Chapter 17 - Data // Access Buildw ith a ADO.NET Form to show the resources. Pa r t Fi ve - W e b Form Appl icafti ons and XForm(); ML W e b Se r vi ces = new Chapter 18 - ASP.NET f.Height Web Pages = 100; and Web Contr ols f.Width 370;ions Chapter 19 - ASP.NET Web =Applicat f.Text = "These resources are embedded in the assembly!"; Chapter 20 - XML Web Ser vices // Add controls and show Form. I ndex f.Controls.Add(p); List of Figur es List of Tables f.Controls.Add(label1); f.ShowDialog(); } } Chapter 8

- Advanced C# Type Const ruction Techniques

Before you run the application, be sure to update Main() to call the ReadMyResources() method: static void Main(string[] args) { ... MyResourceReader.ReadMyResources(); }

When you run this application, you should find what appears in Figure 14-28.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the Figure 14-28: Reading (and using) embedded resources C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

SOURCE CODE

The ResourceTest project is included under the Chapter 14 subdirectory.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed Automatic Resource Configuration ait ion la Visual Studio .NET by Andr ew Tr oelsen

ISBN:1590590554

To wrap things up, look howpages) the Visual Studio .NET IDE gets you up and running with the correct Aprlet's ess © 2003at(1200 resource file configuration automatically. When a er new This compr ehensiv e text star ts wyou ith acreate brief ov viewWindows of the Forms project workspace using Visual Studio .NET, the IDE automatically defines an *.resx file for each C# language and then quickly m oves to key technical and Form in your application. ar chitectur al issues for .NET developer s. Form, the name/value pairs contained in the *.resx Furthermore, when you insert new resources to a given file are updated on your behalf. You can view a Form's *.resx file by selecting the "Show all files" option from the Solution Explorer window (Figure 14-29). Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - 14-29: Type Reflection, Late Binding, and for AttrMainForm.cs ibute- Based Pr ogramm ing Figure The underlying *.resx file Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter Once you 12 -select Obj ectthis Serfile, ialization checkand out the the .NET Properties Remoting window. Lay er You will see that the build action for this file has

been configured as "Embedded Resource" (Figure 14-30). Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 14-30: Under VS .NET, *.resx files are automatically embedded into your assembly. This option compiles the *.resx file to produce the corresponding *.resources file, which is then embedded into your assembly. To illustrate updating *.resx files using VS .NET, create a new C# Windows Application workspace named ResLoader. The Form contains two PictureHolder types, one of which has its Image property set to the happy.bmp file, the other of which is empty. In addition, a single button type will be used to dynamically read this happy dude from file, and place it into the empty PictureHolder. The GUI is shown inFigure 14-31.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Figure 14-31: GUI of the ResLoader application

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals As you insert resources (such as a bitmap) into the project, the IDE responds by creating an instance of the

Chapter 4 - Obj ect -Or iented Pr ogr ming of w ith C# InitializeComponent() method: ResourceManager type within theam scope your Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

private void InitializeComponent() - Callback I nter faces, Delegates, and Ev ents { Chapter // 8 - Note Advanced Type to Const ruction Techniques youC#need specify the name of the Form that Pa r t Thre// e - Pr ogr am m i ng w i th .N ET Assem bl resources. ie s maintains the embedded Chapter System.Resources.ResourceManager 9 - Under standing .NET Assem blies resources = Chapter 10 - Pr new ocesses, AppDomains, Cont exts, and Threads System.Resources.ResourceManager (typeof(MainForm)); Chapter ... 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t FourpictureBox1.Image - Le ve r a ging the .NET Libr = a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er (System.Drawing.Image) resources.GetObject ("pictureBox1.Image"); Chapter } 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 7

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Needless to say, you are free to add a private ResourceManager member variable (or local variables) for use throughout your application. To illustrate, here is the code behind the button's Click event:

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

// Be18sure to specify Chapter - ASP.NET Web Pages'using and Web System.Resources' Contr ols private btnLoadRes_Click(object sender, System.EventArgs e) Chapter 19 - void ASP.NET Web Applicat ions {

Chapter 20 - XML Web Ser vices

// Make a ResourceManager ResourceManager resources = new ResourceManager (typeof(MainForm)); List of Figur es // Read happy dude from assembly and place it List of Tables // into the second PictureBox object. this.pictureBox2.Image = ((System.Drawing.Bitmap)(resources.GetObject("pictureBox1.Image"))); // All done! resources.ReleaseAllResources(); } I ndex

If you were to run the application and click the button, you would find that the image has been extracted from the assembly and placed into the second PictureBox (Figure 14-32).

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

Figure 14-32: Loading resources with the ResourceManager type

I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

SOURCE The ResLoader project is included under the Chapter 14 subdirectory. Chapter 1 - The Philosophy of .NET CODE Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

That wraps up our look at GDI+. As you can guess, this .NET technology allows you to perform numerous - C# Language Fundamentals other graphical manipulations. At this point you should have a solid understanding of the technology. You Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# revisit GDI+ later in this text when you examine ASP.NET (as odd as that may seem). Until then, the next Chapter - Exceptions ect LifetimForms e chapter5 addresses the and use Obj of Windows widgets. Chapter 3

Chapter 6

- I nter faces and Collections Note are interested exploring and GDI+ (including printing support), be sure to check out Chapter 7 If- you Callback I nter faces,inDelegates, Ev further ents

Programming C# and VBTechniques .NET (Symmonds, Apress 2002). Chapter 8 GDI+ - Advanced C# Type in Const ruction Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Summary

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

GDI+ is the nameApr given a number of related .NET namespaces, each of which is used to render graphic ess ©to2003 (1200 pages) images to a Control-derived type. The chapter by examining thethe core types defined within the This compr ehensiv e text star ts began w ith a brief ov er view of System.Drawing C# namespace (including a number of useful utility types), language and then quickly m oves to key technical and and examined various manners to ar chitectur al issues for .NET developer s. intercept paint events. The bulk of this chapter was spent examining how to work with core GDI+ object types such as colors, Tafonts, ble o fgraphics Con t en t s images, pens, and brushes in conjunction with the almighty Graphics type. Along the way,

you examined details such as hit-testing, and how to drag and drop images. C# and t he .NETsome Plat forGDI+-centric m, Second Edition I ntr oduction

This chapter wrapped up by examining the new .NET resource format. As you have seen, an application does not need to bundle its external resources into the containing assembly, however, if your application Chapter 1 - The Philosophy of .NET does so, your binary image is far more portable. The *.resx file is used to describe a set of name/value Chapter 2 - Building C# Applications pairs (a la XML). This file is fed into the resgen.exe utility, resulting in a binary format (*.resources) that can Pa r t Tw o - The C# Pr ogr am m ing La ngua ge then be embedded into the owning assembly. The System.Resouces.ResourceManager type is your key Chapter 3 - C# Language Fundamentals to programmatically obtaining this information at runtime. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Chapter C# 15: Programming with ISBN:1590590554 Windows Forms by Andr ew Tr oelsen ControlsApr ess © 2003 (1200 pages)

Overview

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

This chapter is concerned with providing a roadmap of the suite of GUI widgets defined in the TaSystem.Windows.Forms ble o f Con t en t s namespace. You have already had a chance to work with some Form-level

control types such as m, MainMenu, MenuItem, StatusBar, and ToolBar (see Chapter 13); however, in this C# and t he .NET Plat for Second Edition chapter, you will be examining various types that tend to exist within the boundaries of a Form's client area I ntr oduction (e.g., Buttons, TextBoxes, Panels, andP la the like). Pa r t One - I nt r oduci ng C# a nd the .NET tf or m Chapter 1

- The Philosophy of .NET

In addition to giving you a formal grounding in the Windows Forms Control set, this chapter also details a - Building C# Applications number of related topics, such as establishing the tab order for your widgets, as well as configuring the Pa r t Tw o - The C# Pr ogr am m ing La ngua ge docking and anchoring behaviors for your family of GUI types. The chapter then investigates the process Chapter 3 - C# Language Fundamentals of building custom dialog boxes, including techniques for responding to (and validating) user input. Chapter 2

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - examine Exceptions and Obj ect Lifetim Next, you'll a new facility offerede by the .NET Windows Forms architecture: Form inheritance. As Chapter you will6see, - I nter it is faces now possible and Collections to establish "is-a" relationships between related Forms (which should make

the MFC the world insanely and happy). Finally, we wrap things up with an examination of the Chapter 7 developers - Callback Iof nter faces, Delegates, Ev ents process8 of- building custom Windows FormsTechniques controls (which should make the ATL developers of the world Chapter Advanced C# Type Const ruction insanely Pa r t Thre e happy). - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET Plat f orm , Forms Se con d EdControl it ion Understanding Windows Hierarchy ISBN:1590590554

by Andr ew Tr oelsen

The System.Windows.Forms Apr ess © 2003 namespace (1200 pages) contains a number of types that represent common GUI widgets that allow you to respond to user input in star a Windows This compr ehensiv e text ts w ith a Forms brief ovapplication. er view of theBecause .NET is a system of types built on standard OO principles, these controls are arranged in and a hierarchy of related types. Figure C# language and then quickly m oves to key technical ar chitectur al issues developer s. 15-1 illustrates the big picture (note for that.NET System.Windows.Forms.Control is the common base class for all Windows Forms widgets.) Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure The Windows Formsblies control hierarchy Chapter 9 - 15-1: Under standing .NET Assem Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter - TypeinReflection, Late Binding, and Attr ibute- Based Pr ogramm ingis the base class that provides a As you 11 learned Chapter 13, the System.Windows.Forms.Control type Pa r t Four -and Le ve r a ging the Libr a r ie s for minimal complete set.NET of behaviors

all descending widgets. This includes the ability to process

Chapter Obj ect Ser events, ializationestablish and the .NET Remoting Lay er mouse12 and- keyboard the physical dimensions of the widget using various properties Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s Forbackground ms) (Height, Width, Left, Right, Location, and so on), manipulate and foreground colors, establish Chapter the active 14 -font, A Better and so Paint forth. ing Also, Fr amew theorControl k ( GDI + base ) type also defines members that control a widget's

anchoring docking behaviors (as seen in this Chapter 15 -and Pr ogr am ming with Windows Formlater s Contr ols chapter). Chapter 16 - The Sy stem .I O Nam espace

As you read through this chapter, remember that the widgets examined in this chapter gain a good deal of their functionality from the System.Windows.Forms.Control base class. In this chapter we'll focus (more or Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces less) on a given type's unique members. Chapter 17 - Data Access w ith ADO.NET

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d thto e .N ET Plat f orm , Se con d Ed it ion Adding Controls Forms (IDE-Free) by Andr ew Tr oelsen

ISBN:1590590554

Regardless of which type of control you choose to place on a Form, you will follow a similar set of steps. Apr ess © 2003 (1200 pages) First of all, you must define member variables the GUI maintained by the Form. This compr ehensiv e text star ts that w ith represent a brief ov er view of widgets the Next, inside the Form's constructor (or within a helper method, called by the constructor), you'll configure C# language and then quickly m oves to key technical and al issues for the .NETexposed developer s. the look and feel ar ofchitectur each control using properties, methods, and events. Finally (and most important), once the control has been set to its initial state, it must be added into the Form's internal controls collection using the inherited Controls property. If you forget this final step, your widgets will not be Tavisible ble o f at Con t en t s To illustrate this process in the raw, consider the MyForm class: runtime! C# and t he .NET Plat for m, Second Edition I ntr oduction

// Don't forget to add a reference to System.Windows.Forms.dll! using System.Windows.Forms; Chapter - The Philosophy class1 MyForm : Form of .NET Chapter 2 Building C# Applications { Pa r t Tw o// - The C# Pr ogr m ing La ngua Define a am widget datage member. Chapter private 3 - C# Language Fundamentals TextBox firstNameBox = new TextBox(); Chapter public 4 - Obj ect -Or iented Pr ogr am ming w ith C# MyForm() Chapter { 5 - Exceptions and Obj ect Lifetim e Chapter 6 - I nter this.Text faces and Collections = "Controls in the raw"; // Configure the widget. Chapter 7 - Callback I nter faces, Delegates, and Ev ents firstNameBox.Text = "Chucky"; Chapter 8 - Advanced C# Type Const ruction Techniques firstNameBox.Size = bl new Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem ie s Size(150, 50); firstNameBox.Location Chapter 9 - Under standing .NET Assem blies = new Point(10, 10); Add AppDomains, new widget to the Chapter 10 - Pr // ocesses, Cont exts, andForm's Threads Controls collection. this.Controls.Add(firstNameBox); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing } - Le ve r a ging the .NET Libr a r ie s Pa r t Four ... Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

The Control$ControlCollection Type

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

While the process of adding a new widget to a Form is quite simple, I'd like to discuss the Controls property in a bit more detail. This property returns a reference to a nested class named ControlCollection Chapter 18 - ASP.NET Web Pages and Web Contr ols defined by the Control class (recall that a nested type can be denoted using the "$" token, e.g., Chapter 19 - ASP.NET Web Applicat ions Control$ControlCollection). The Control$ControlCollection type maintains an entry for each widget placed Chapter 20 - XML Web Ser vices on the Form. You can obtain a reference to this collection anytime you wish to "walk the list" of child I ndex widgets: Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

List of Figur es List of Tables

// Get access to the Control$ControlCollection type for this Form. Control.ControlCollection coll = this.Controls;

Once you have a reference to this collection, you can call any of the members described in Table 15-1. Be aware that by default controls are placed in the ControlCollection type using an (n + 1) insertion policy. Table 15-1: Nested ControlCollection Members

Control$ControlCollection Meaning C# an d th e .N ET Plat f orm , Se con d Ed it in ion Life Member ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Add() AddRange() Clear()

Used to insert a new Control-derived type (or array of

This compr ehensiv e text star ts w ith a brief ov er view of the types) in the collection C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Removes all entries in the collection

Count

Ta ble o f Con t en t s C# GetChildIndex() and t he .NET Plat for m, Second Edition I ntrSetChildIndex() oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

GetEnumerator() - The Philosophy of .NET Chapter 2 - Building C# Applications Remove() Chapter 1

Returns the number of items in the collection Returns the index value for a specified item in the collection Returns the IEnumerator interface for this collection Used to remove a control from the collection

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

RemoveAt()

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - Exceptions and Obj ect Lifetim eof this very important collection, assume you have now configured To illustrate programmatic manipulation Chapter and added 6 - aI nter newfaces Button andwidget Collections to the Form's collection (Figure 15-2). Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Figure 15-2: The Form's UI

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat Also assume you have written anions event handler for the Button's Click event. In the implementation of this Chapter method, 20you - XML loopWeb overSer each vicesitem in the Controls collection and print out some relevant information

regarding the contained members: I ndex List of Figur es List of Tables class MyForm : Form

{ private TextBox firstNameBox = new TextBox(); private Button btnShowControls = new Button(); public MyForm() { // Configure new TextBox. ... // Configure and add a new Button. btnShowControls.Text = "Examine Controls collection"; btnShowControls.Size = new Size(90, 90); btnShowControls.Location = new Point(10, 70); btnShowControls.Click += new EventHandler(btnShowControls_Clicked); this.Controls.Add(btnShowControls); }

protected void btnShowControls_Clicked(object sender, EventArgs e) C# an d th e .N ET Plat f orm , Se con d Ed it ion

{

ISBN:1590590554 by Andr ew Tr oelsen Control.ControlCollection coll = this.Controls; Apr ess © 2003 (1200 pages) string ctrs = ""; This compr ehensiv text coll) star ts w ith a brief ov er view of the foreach(Control c e in C# language and then quickly m oves to key technical and { ar chitectur al issues for .NET developer s. if(c != null) ctrs += string.Format("Index: {0}, Text: {1}\n", coll.GetChildIndex(c, false), c.Text); Ta ble o f Con t en t s } C# and t he .NET Plat for m, Second Edition MessageBox.Show(ctrs, "Index and Text values for each control"); I ntr oduction } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m ... Chapter 1 - The Philosophy of .NET }

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter Obj ect Pr ogr am ming w ith you C# to obtain the numerical index of a given widget in the Notice 4how- the call-Or toiented GetChildIndex() allows Chapter collection 5 (the - Exceptions second Boolean and Obj ect parameter Lifetim e is used to control if an exception is raised in the case that the

requested is not found). If you run the application and click the Form's Button, you are presented Chapter 6 -control I nter faces and Collections with the7 information in Figure 15-3.and Ev ents Chapter - Callback shown I nter faces, Delegates, Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - 15-3: A Better Paint ing Fr amew or k ( GDI +) Figure Interacting with a Form's Controls collection Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Given that types maintain a nested Control.ControlsCollection Chapter 16 -System.Windows.Forms.Control-derived The Sy stem .I O Nam espace type, it 17 stands to reason that you can dynamically add, hide, disable, or remove items using this collection Chapter - Data Access w ith ADO.NET atr tany a Form's lifetime can Pa Fi vepoint - W ein b Appl ica ti ons and X(which ML W e b Se rprove vi ces quite

helpful if you need to dynamically generate new

controls18on- the fly or Web restrict which should Chapter ASP.NET Pages andcontrols Web Contr ols be displayed based on user preferences/ permissions). Chapter 19 - ASP.NET Web Applicat ions

Furthermore, also understand that it is completely possible to dynamically insert (or remove) Windows widgets into any descendent of System.Windows.Forms.Control (for example, adding RadioButton types I ndex to a GroupBox, TextBox types to a Panel, and so forth). We will see examples of this technique over the List of Figur es chapter. course of this Chapter 20 - XML Web Ser vices

List of Tables

SOURCE CODE

The ControlsByHand project is included under the Chapter 15 subdirectory.

C# an d thto e .N ET Plat f orm , SeVS con d .NET) Ed it ion Adding Controls Forms (via ISBN:1590590554

by Andr ew Tr oelsen

Although you areApr always write Windows Forms code "in the raw," you will probably choose to use ess © free 2003 to (1200 pages) the Visual Studio This .NET IDE instead. When you widget from Toolbox onto the form designer, the compr ehensiv e text star ts drop w ith aabrief ov er viewthe of the IDE responds by C# automatically adding the correct member variable to the language and then quickly m oves to key technical and Form-derived class on your aryou chitectur al issues want for .NET developer behalf. Of course, will typically to change thes.name of this new variable (via the Properties window) to represent its overall functionality (e.g., "btnSubmitQuery" rather than the default "button1"). As you design the look and feel of the widget using the IDE's Properties window (Figure 15-4), the underlying Tacode ble o changes f Con t en tare s added to the InitializeComponent() member function. C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies Figure Design time property Chapter 10 - 15-4: Pr ocesses, AppDomains, Contconfiguration exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four ve rthis a ging the .NET Libr you a r ie sto Be aware- Le that window allows

configure not only the property set of a given GUI item, but the set

Chapter 12 as - Obj ect(available Ser ialization and the the .NET"lightning Remotingbolt" Lay er of events well by clicking icon). Simply select the widget from the dropChapter 13 Building a Bet ter Win dow ( Int roducin g Window For ms) down list and type in the name of the method to be calleds for the events you are interested in responding Chapter 14 -15-5). A Better Paint ing Fr amew or k ( GDI + ) to (Figure Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 15-5: Design time event handling If you examine the code generated in the InitializeComponent() method, you will find that the type has been configured based on your selections and inserted into the Control$ControlCollection automatically. For example, assume you have configured a TextBox type as follows: private void InitializeComponent() { this.firstNameBox = new System.Windows.Forms.TextBox(); this.firstNameBox.Location = new System.Drawing.Point(32, 40); this.firstNameBox.TabIndex = 0;

this.firstNameBox.Text = "Chucky"; C# an d th e .N ET Plat f orm , Se con Ed it ion this.firstNameBox.TextChanged += dnew ISBN:1590590554 by Andr ew Tr oelsen System.EventHandler(this.firstNameBox_TextChanged); Apr ess © 2003 (1200 pages) this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); This compr ehensiv e text star ts w ith a brief ov er view of the273); this.ClientSize = new System.Drawing.Size(292, C# language and then quickly m oves to key technical and this.Controls.AddRange(new System.Windows.Forms.Control[] ar chitectur al issues for .NET developer s. { this.firstNameBox}); ... }

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I here nt r oduci C#VS a nd the .NET P la tf or m Note that young use .NET to handle the

TextChanged event for the TextBox, and are thus provided

Chapter - Theevent Philosophy of as .NET with an1empty handler well as the correct event registration syntax (an obvious benefit of this Chapter 2 Building C# Applications approach is that you are not the one in charge of determining the correct delegate used to handle a Pa r t Tw o - The C# Pr ogr am m ing La ngua ge particular event):

Chapter 3

- C# Language Fundamentals

Chapter 4 - Obj ect -OrfirstNameBox_TextChanged iented Pr ogr am ming w ith C# protected void (object sender, System.EventArgs e) Chapter 5 Exceptions and Obj ect Lifetim e { Chapter // 6 - Do I nter faces and Collections whatever you need to do... Chapter 7 Callback I nter faces, Delegates, and Ev ents } Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

As you 9can- see, VS .NET IDE simply Chapter Underthe standing .NET Assem bliessaves you some typing. The remainder of this chapter focuses on a number offered by numerous Chapter 10 -ofPrbehaviors ocesses, AppDomains, Cont exts, GUI and widgets Threads by examining the "raw" code behind the scenes. If you decide to use the VS .NET IDE, be and sureAttr to ibuteexamine thePrcode generated inside the Chapter 11 - Type Reflection, Late Binding, Based ogramm ing InitializeComponent() method to gain Pa r t Four - Le ve r a ging the .NET Libr a r ie sa

true understanding of Windows Forms programming. Now that you understand the process of configuring and inserting types into a Form's Control collection, we can turn our Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er attention to the specifics of various Windows Forms widgets. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# Control an d th e .N ET Plat f orm , Se con d Ed it ion The TextBox ISBN:1590590554

by Andr ew Tr oelsen

The TextBox control is the first(1200 itempages) under investigation. This GUI widget holds some blurb of text or possibly Apr ess © 2003 multiple lines of text. TextBox controls can also read-only This compr ehensiv e text star ts wbe ithconfigured a brief ov eras view of the and may support scroll bars. The immediate base class of TextBox is TextBoxBase, which provides many C# language and then quickly m oves to key technical and common behaviors for the TextBox chitectur al issues for15-2 .NETdescribes developer s. and RichTextBoxardescendents. Table some of the core properties provided by the TextBoxBase type. TaTable ble o f 15-2: Con t en ts Members of the TextBoxBase Type C# and t he .NET Plat for m, Second Edition I ntrTextBoxBase oduction Pa rProperty t One - I nt r oduci ng

Meaning in Life C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications control itself, rather than moving the focus to the next control in the tab order.

AcceptsTab

Indicates if pressing the Tab key in a multiline TextBox control tabs within the

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

AutoSize Determines if the size of the control automatically adjusts when the assigned Chapter 3 - C# Language Fundamentals Chapter 4

is changed. - Obj ect -Or ientedfont Pr ogr am ming w ith C#

Chapter 5 - Exceptions andGet Obj ect Lifetim BackColor or set the ebackground/foreground color of the control. Chapter 6 - I nter faces and Collections

ForeColor

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

HideSelection GetsConst or sets a value indicating whether the selected text in the TextBox Chapter 8 - Advanced C# Type ruction Techniques control remains highlighted when the control loses focus. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

MaxLength

Configures the maximum number of characters that can be entered into the TextBox control.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

GetsLibr or asets Pa rModified t Four - Le ve r a ging the .NET r ie s a value

that indicates that the TextBox control has been

modified by the user since the was created or its contents were last Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay control er set. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amewiforthis k ( GDI +) Multiline Specifies TextBox can contain multiple lines of text. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

ReadOnly this TextBox as read-only. Chapter 16 - The Sy stem .I O Marks Nam espace

Chapter 17 - Data Access w ith ADO.NET SelectedText Contain the currently selected text (or some number of characters) in the Pa r t Fi ve - W e b Appl ica ti onscontrol. and X ML W e b Se r vi ces gets SelectionStart

SelectionLength

or sets the starting point of text selected in the

Chapter 18 - ASP.NET Web Pages and Web Contr ols text box. SelectionStart Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices WordWrap Indicates whether a multiline TextBox control automatically wraps words to I ndex the beginning of the next line when necessary. List of Figur es List of TextBoxBase Tables The type also defines a number of methods that allow the derived types to handle clipboard

operations (via the Cut(), Copy(), and Paste() methods), undo operations (Undo(), of course), and carry out related functionality (Clear(), AppendText(), and so on). As far as the events defined by TextBoxBase, the item of interest for this example is TextChanged (the Windows Forms equivalent of the raw EN_CHANGE message). As you may know, this event is fired whenever the content in a TextBoxBase-derived type is modified. In addition to the behavior inherited by TextBoxBase, the TextBox type grabs a good deal of functionality from the Control base class. In fact, the properties defined by TextBox alone are quite limited, as you can see in Table 15-3. Table 15-3: TextBox Properties

TextBox Property AcceptsReturn

in fLife C# an d Meaning th e .N ET Plat orm , Se con d Ed it ion Gets or sets a value indicating whether pressing Enter in a multiline TextBox

This compr ehensiv e text star ts w ith a brief ov er view of the control creates a new line of text in the control or activates the default Button C# language and then quickly m oves to key technical and for al the Formfor .NET developer s. ar chitectur issues

CharacterCasing Ta ble o f Con t en t s

ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Gets or sets whether the TextBox control modifies the case of characters as they are typed

C# PasswordChar and t he .NET Plat for m, Gets Second or sets Edition the character used to mask characters in a single-line TextBox I ntr oduction

control used to enter passwords

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

ScrollBars

Chapter 1

Gets or sets which scroll bars should appear in a multiline TextBox control

- The Philosophy of .NET

TextAlign Gets or sets how text is aligned in a TextBox control, using the Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr amHorizontalAlignment m ing La ngua ge

enumeration

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

- Exceptions and Obj ect Lifetim e Fun with TextBoxes

Chapter 5 Chapter 6

- I nter faces and Collections To illustrate some ofI the aspects Chapter 7 - Callback ntermore faces, exotic Delegates, and of Ev the entsTextBox, let's build a multiline text area that has been

configured accept Return and Tabruction keystrokes and supports a vertical scroll bar. Here is the configuration Chapter 8 - to Advanced C# Type Const Techniques code (assume you defined Pa r t Thre e - Pr ogr am have m i ng already w i th .N ET Assem a blForm-level ie s Chapter 9

member variable of type TextBox named multiLineBox):

- Under standing .NET Assem blies

Chapter // Your 10 - first Pr ocesses, TextBox. AppDomains, Cont exts, and Threads

multiLineBox.Location = Binding, new System.Drawing.Point (152, 8); Chapter 11 - Type Reflection, Late and Attr ibute- Based Pr ogramm ing multiLineBox.Text "Type some Pa r t Four - Le ve r a ging the = .NET Libr a r ie s

stuff here (and hit the return and tab keys...)";

multiLineBox.Multiline = true; Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er multiLineBox.AcceptsReturn Chapter 13 - Building a Bet ter Win dow ( = Int true; roducin g Window s For ms) multiLineBox.ScrollBars = ScrollBars.Vertical; Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) multiLineBox.TabIndex = 0; Form s Contr ols Chapter 15 - Pr ogr am ming with Windows multiLineBox.AcceptsTab = true;

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Notice that the ScrollBars property is assigned a value from the ScrollBars enumeration, which defines the

Chapter 18 values: - ASP.NET Web Pages and Web Contr ols following Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

public enum System.Windows.Forms.ScrollBars { List of Figur es Horizontal, None, Vertical Both, List of Tables } I ndex

Now assume you have placed a Button on the Form and added an event handler for the Button's Click event. The implementation of this method simply places the TextBox's text in a message box: protected void btnGetMultiLineText_Click (object sender, System.EventArgs e) { MessageBox.Show(multiLineBox.Text, "Here is your text"); }

Next, add some additional TextBoxes to the Form, this time focusing on the masking capabilities of the widget. The second TextBox (capsOnlyBox) forces all keystrokes to be converted to uppercase. The third TextBox (passwordBox) forces all keystrokes to be converted to a password character (which I have chosen to be "$," signifying how your financial life as a .NET developer should pan out).

An additional Button (btnPasswordDecoderRing) supports a Click event handler that extracts the real C# an d th e .N ET Plat f orm , Se con d Ed it ion keystrokes typed in the passwordBox TextBox widget, as shown here: by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

protected void btnPasswordDecoderRing_Click (object sender, System.EventArgs e) This compr ehensiv e text star ts w ith a brief ov er view of the { C# language and then quickly m oves to key technical and MessageBox.Show(passwordBox.Text, ar chitectur al issues for .NET developer s. "Your password is:"); } Ta ble o f Con t en t s

Here the.NET relevant code that configures these new TextBox types: C# andist he Plat for m, Second Edition I ntr oduction Pa r t One nt r oduciOnly!' ng C# a ndwidget. the .NET P la tf or m // The- I'Caps

Chapter // Note 1 - that The Philosophy CharacterCasing of .NET is established by an associated enumeration,

// which can beC#assigned Chapter 2 - Building ApplicationsUpper, Lower, or Normal. capsOnlyBox.Location = Lanew Pa r t Tw o - The C# Pr ogr am m ing nguaSystem.Drawing.Point ge

(14, 176); capsOnlyBox.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper; Chapter 3 - C# Language Fundamentals capsOnlyBox.Size = new (120, 20); Chapter 4 - Obj ect -Or iented Pr ogrSystem.Drawing.Size am ming w ith C# // The password TextBox Chapter 5 - Exceptions and Obj ect Lifetim e passwordBox.Location = new System.Drawing.Point (160, 176); Chapter 6 - I nter faces and Collections passwordBox.PasswordChar = '$'; Chapter 7 - Callback I nter faces, Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

The final GUI can be seen in Figure 15-6.

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Figure 15-6: The many faces of the TextBox type

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Chapter 19 - ASP.NET Web Applicat As mentioned, TextBoxBase has ions an additional derived type named RichTextBox. This class is a type that Chapter 20 XML Web Ser vices supports the display and manipulation of (highly) formatted text. For example, using this type you can I ndex configure support for multiple font selections, bulleted text, and so forth. I assume interested readers will List of Figur es help for further details. consult online List of Tables

SOURCE CODE

The TextBoxes application is included under the Chapter 15 subdirectory.

an d th e .N ET Plat f orm , Se con d Ed it ion The MightyC#Button Type ISBN:1590590554

by Andr ew Tr oelsen

Of all user interface widgets, Button Apr ess © 2003the (1200 pages) can be regarded as the simplest, but most well-respected GUI input device. The role of the System.Windows.Forms.Button type provide This compr ehensiv e text star ts w ith a brief ovis erto view of thea simple vehicle for user input, typically in response to a mouse click or key press. The Button class immediately derives from an abstract C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer type named ButtonBase, which provides a number of s. key behaviors for all Button-related types (CheckBox, RadioButton, and Button). Table 15-4 describes some (but by no means all) of the core properties of ButtonBase. Ta ble o f Con t en t s C# and t15-4: he .NET Plat for m, Second Edition Table ButtonBase Properties I ntr oduction

in PLife Pa rButtonBase t One - I nt r oduci ng C#Meaning a nd the .NET la tf or m Property Chapter 1 - The Philosophy of .NET Chapter 2 - Building C#Gets Applications FlatStyle or sets the flat style appearance of the Button control, using members of Pa r t Tw o - The C# Pr ogr am ing La ngua ge themFlatStyle enumeration.

Chapter 3

- C# Language Fundamentals

Image4 Chapter

Configures which - Obj ect -Or iented Pr ogr am ming (optional) w ith C# image is displayed somewhere within the bounds

Chapter 5

a Obj ButtonBase-derived type. Recall that the Control class also defines a - Exceptions of and ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

BackgroundImage property, which is used to render an image over the entire surface area of a widget.

Chapter 8 - Advanced C# Type ructionofTechniques ImageAlign Sets theConst alignment the image on the Button control, using the Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s ContentAlignment enumeration.

Chapter 9

- Under standing .NET Assem blies

ImageIndex

Work together to set the image list index value of the image displayed on the Button control from the corresponding ImageList control.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

ImageList Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa rIsDefault t Four - Le ve r a ging the .NET Libr a r ie s Specifies whether

the Button control is the default Button (i.e., receives focus in

Chapter 12 - Obj ect Ser ialization the .NET Remoting Laykey). er responseand to pressing of the Enter Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

TextAlign Gets of the text on the Button control, using the Chapter 14 - A Better Paint ing or Fr sets amewthe or kalignment ( GDI + ) ContentAlignment enumeration.

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Chapter 17 - class Data Access w ith ADO.NET The Button itself defines almost no additional functionality beyond that inherited by the ButtonBase Pa r t Fi ve - W ewith b Appl ti ons and X MLofWthe e b Se r vi ces base class, theicakey exception DialogResult

property. As you will see later in this chapter, a dialog

Chapter 18 - use ASP.NET Pages to and Web a Contr olsrepresenting which Button was clicked (e.g., OK, Cancel, box makes of thisWeb property return value Chapter ASP.NET Applicat and so 19 on)- when the Web dialog box isions terminated. Chapter 20 - XML Web Ser vices I ndex

Configuring the Content Position

List of Figur es

List of Tables Most people assume that the text contained in a Button is always placed on the middle of the Button,

equidistant from all sides. While this can be a well-established standard, the TextAlign property of the ButtonBase type makes it extremely simple to position text at just about any location. To set the position of your Button's caption, use the System.Drawing.ContentAlignment enumeration (which happens to be the same enumeration used to configure the location of any optional Button image): public enum System.Drawing.ContentAlignment { BottomCenter, BottomLeft, BottomRight, MiddleCenter, MiddleLeft, MiddleRight, TopCenter, TopLeft, TopRight }

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Fun with Buttons by Andr ew Tr oelsen

ISBN:1590590554

Apr ess © 2003 (1200 pages)

To illustrate working with this most primitive of user input widgets, the following application uses the FlatStyle, comprproperties. ehensiv e text star ts w interesting ith a brief ovaspect er view of of the the underlying code is in the Click event ImageAlign, and This TextAlign The most C# language and then quickly m oves to key technical and handler for the btnStandard type (which would be the Button in the middle of the Form). The implementation ar chitectur al issues for .NET developer s. of this method cycles through each member of the ContentAlignment enumeration and changes the Button's caption text and caption location based on the current value. Ta ble o f Con t en t s

Also, the fourth Button on the Form (btnImage) supports a background image and a small bull's-eye icon, which is also dynamically relocated based on the current value of the ContentAlignment enumeration. Here I ntr oduction is the relevant code: C# and t he .NET Plat for m, Second Edition

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

public class ButtonForm: System.Windows.Forms.Form - Building C# Applications { Pa r t Tw o - The C# Pr ogr am m ing La ngua ge // You have four Buttons on this Form. Chapter 3 - C# Language Fundamentals private System.Windows.Forms.Button btnImage; Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# private System.Windows.Forms.Button btnStandard; Chapter private 5 - Exceptions and Obj ect Lifetim e System.Windows.Forms.Button btnPopup; Chapter private 6 - I nter faces and Collections System.Windows.Forms.Button btnFlat; Chapter // 7 - Hold Callback I nter faces, Delegates, and Ev value. ents the current alignment Chapter ContentAlignment 8 - Advanced C# Type currAlignment Const ruction Techniques = ContentAlignment.MiddleCenter; Pa r t Threint e - PrcurrEnumPos ogr am m i ng w i th =.N 0; ET Assem bl ie s Chapter ... 9 - Under standing .NET Assem blies Chapter protected 10 - Pr ocesses, void AppDomains, btnStandard_Click Cont exts, and Threads (object sender, System.EventArgs e) Chapter { 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Gettheall values of the ContentAlignment enum. Pa r t Four - Le ve// r a ging .NETpossible Libr a r ie s Array values and = Enum.GetValues(currAlignment.GetType()); Chapter 12 - Obj ect Ser ialization the .NET Remoting Lay er // Bump current position ins the enum. Chapter 13 - Building a Bet the ter Win dow ( Int roducin g Window For ms) // & check for wraparound. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr currEnumPos++; ogr am ming with Windows Form s Contr ols if(currEnumPos >= values.Length) Chapter 16 - The Sy stem .I O Nam espace currEnumPos = 0; Chapter 17 - Data Access w ith ADO.NET // Change the current enum value. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces currAlignment = Chapter 18 - ASP.NET Web Pages and Web Contr ols (ContentAlignment)ContentAlignment.Parse(currAlignment.GetType(), Chapter 19 - ASP.NET Web Applicat ions values.GetValue(currEnumPos).ToString()); Chapter 20 - XML Web Ser vices // Paint enum name on Button. I ndex btnStandard.Text = currAlignment.ToString(); List of Figur es btnStandard.TextAlign = currAlignment; List of Tables // Now assign the location of the icon on btnImage... btnImage.ImageAlign = currAlignment; } ... } Chapter 2

The output can be seen in Figure 15-7.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Figure 15-7: The many faces of the Button type

Chapter SOURCE 8 - AdvancedThe C# Type Buttons Const application ruction Techniques is included under the Chapter 15 directory. Pa r t Thre CODE e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Working with CheckBoxes ISBN:1590590554

by Andr ew Tr oelsen

The other two ButtonBase-derived types of interest are CheckBox (which can support up to three possible Apr ess © 2003 (1200 pages) states) and RadioButton (which can or not selected). Like the Button, these types also This compr ehensiv e be texteither star tsselected w ith a brief ov er view of the receive most of their functionality from the Control base class. However, C# language and then quickly m oves to key technical and each class defines some ar chitectur al consider issues forthe .NET developer s. of the CheckBox widget described in Table 15-5. additional functionality. First, core properties Table 15-5: CheckBox Properties Ta ble o f Con t en t s

Life C# CheckBox and t he .NET Plat forMeaning m, Second in Edition I ntrProperty oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Appearance

Configures the appearance of a CheckBox control, using the Appearance enumeration.

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Gets sets a value Pa rAutoCheck t Tw o - The C# Pr ogr am mor ing La ngua ge

indicating whether the Checked or CheckState value and the CheckBox's appearance are automatically changed when it is clicked. Chapter 3 - C# Language Fundamentals Chapter 4 - Obj ect -OrGets ientedorPrsets ogr am w ith C#and vertical alignment of a CheckBox on a CheckAlign theming horizontal Chapter 5 - Exceptions and Obj ect Lifetim e CheckBox control, using the ContentAlignment enumeration (see the Button Chapter 6

- I nter facestype andfor Collections a full description).

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 9

- Under standing .NET Assem blies

Checked Returns a Boolean value representing the state of the CheckBox (checked or Chapter 8 - Advanced C# Type Const ruction Techniques unchecked). If the ThreeState property is set to true, the Checked property Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s returns true for either checked or indeterminately checked values. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads CheckState Gets or sets a value indicating whether the CheckBox is checked, using a Chapter 11 - Type Reflection, CheckState Late Binding, enumeration, and Attr rather ibute-than Baseda Pr Boolean ogrammvalue. ing This is very helpful Pa r t Four - Le ve r a ging when the .NET working Libr a rwith ie s

tristate CheckBoxes.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

ThreeState

Configures whether the CheckBox supports three states of selection (as specified by the CheckState enumeration), rather than two.

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm and , Se conGroupBoxes d Ed it ion Working with RadioButtons ISBN:1590590554

by Andr ew Tr oelsen

The RadioButtonApr type little comment, given that it is (more or less) just a slightly redesigned essreally © 2003requires (1200 pages) CheckBox. In fact, the members of a RadioButton almost to those of the CheckBox type. The This compr ehensiv e text star ts w ithare a brief ov eridentical view of the only notable difference is the CheckedChanged event, which is fired when the Checked value changes. C# language and then quickly m oves to key technical and ar chitectur issues .NET developer s. Also, the RadioButton type al does notfor support the ThreeState property, as a RadioButton must be on or off. Typically, multiple RadioButton objects are logically and physically grouped together to function as a Tawhole. ble o f Con For texample, en t s if you have a set of four RadioButton types representing the color choice of a given

automobile, youPlat may wish to ensure that only one of the four types can be checked at a time. Rather than C# and t he .NET for m, Second Edition writing code programmatically to do so, use the GroupBox control. Like the RadioButton, there is little to I ntr oduction say about the GroupBox givenP that Pa r t One - I nt r oduci ng C# acontrol, nd the .NET la tf oritmreceives Chapter 1

all of its functionality from the Control base class.

- The Philosophy of .NET

- Building C# Applications (and CheckBoxes) Fun with RadioButtons

Chapter 2

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

To illustrate working with Fundamentals the CheckBox, RadioButton, and GroupBox types, let's create a new Windows Chapter 3 - C# Language Forms 4Application named which Chapter - Obj ect -Or ientedCarConfig, Pr ogr am ming w ithwill C#be extended throughout this chapter. The main Form allows users to enter inand (and confirm) information about a new vehicle they intend to purchase. The order Chapter 5 - Exceptions Obj ect Lifetim e summary in a Collections Label type once the Confirm Order button has been clicked. Figure 15-8 shows Chapter 6 is - Idisplayed nter faces and the user Chapter 7 interface. - Callback I nter faces, Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t FiFigure ve - W e15-8: b Appl ica tiinitial ons and X ML e b Se r vi cesForm The UI of theWCarConfig

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Assume you have initialized a number of private member variables representing each GUI widget. First, you have your CheckBox, constructed as shown here:

Chapter 20 - XML Web Ser vices I ndex

List of Figur es

// Create your CheckBox. checkFloorMats.Location = new System.Drawing.Point (16, 16); checkFloorMats.Text = "Extra Floor Mats"; checkFloorMats.Size = new System.Drawing.Size (136, 24); checkFloorMats.FlatStyle = FlatStyle.Popup; // Add to Control collection. this.Controls.Add (this.checkFloorMats);

List of Tables

Programmatically speaking, when you wish to place a widget under the ownership of a related GroupBox, you want to add each item to the GroupBox's Controls collection (in the same way you add widgets to the Form's Controls collection). To make things a bit more interesting, respond to the Enter and Leave events sent by the GroupBox object as shown here: // Yellow RadioButton. radioYellow.Location = new System.Drawing.Point (96, 24); radioYellow.Text = "Yellow";

radioYellow.Size = new System.Drawing.Size (64, 23); C# an d thPink e .N ETRadioButtons Plat f orm , Se conconfigured d Ed it ion // Green, Red, and in a similar vein. ISBN:1590590554 by Andr ew Tr oelsen ... ess group © 2003 (1200 // Now build Apr the of pages) radio items. This compr ehensiv e text star ts w ith a brief ov er view of the groupBox1.Location = new System.Drawing.Point (16, 56); C# language and then quickly m oves to key technical and groupBox1.Text = "Exterior Color"; ar chitectur al issues for .NET developer s. groupBox1.Size = new System.Drawing.Size (264, 88); groupBox1.Leave += new System.EventHandler (groupBox1_Leave); groupBox1.Enter += new System.EventHandler (groupBox1_Enter); Ta ble o f Con t en t s groupBox1.Controls.Add (this.radioPink); C# and t he .NET Plat for m, Second Edition groupBox1.Controls.Add (this.radioYellow); I ntr oduction groupBox1.Controls.Add (this.radioRed); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m groupBox1.Controls.Add (this.radioGreen); Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - C# Fundamentals Understand, of Language course, that you do not need to capture the Enter or Leave events for a GroupBox. Chapter 4 to - Obj ect -Or iented Pr ogrhandlers am ming w ith C# the caption text of the GroupBox as shown here: However, illustrate, the event update Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6 - I nter faces and the Collections // Figure out when focus is in your group. Chapter 7 Callback I nter faces, Delegates, and Ev ents sender, System.EventArgs e) protected void groupBox1_Leave (object Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Thre e - Pr ogr am m i ng w .N ET Assem bl ie s groupBox1.Text = i th "Exterior Color:

Chapter } 9

Thanks for visiting the group...";

- Under standing .NET Assem blies

protected groupBox1_Enter (object sender, System.EventArgs e) Chapter 10 - Pr void ocesses, AppDomains, Cont exts, and Threads { Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing groupBox1.Text "Exterior Pa r t Four - Le ve r a ging the = .NET Libr a r ie s

Color: You are in the group...";

} Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

The final GUI widgets on this Form (the Label and Button types) also need to be configured and inserted in the Form's Controls collection. The Label is used to display the order confirmation, which is formatted in Chapter 16 - The Sy stem .I O Nam espace the Click event handler of the order Button, as shown here: Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

protected void btnOrder_Click (object sender, System.EventArgs e) { Chapter 19 - ASP.NET Web Applicat ions // Build a string to display information. Chapter 20 - XML Web Ser vices string orderInfo = ""; I ndex if(checkFloorMats.Checked) List of Figur es orderInfo += "You want floor mats.\n"; List of Tables if(radioRed.Checked) orderInfo += "You want a red exterior.\n"; if(radioYellow.Checked) orderInfo += "You want a yellow exterior.\n"; if(radioGreen.Checked) orderInfo += "You want a green exterior.\n"; if(radioPink.Checked) orderInfo += "Why do you want a PINK exterior?\n"; // Send this string to the Label. infoLabel.Text = orderInfo; } Chapter 18 - ASP.NET Web Pages and Web Contr ols

Notice that both the CheckBox and RadioButton support the Checked property, which allows you to investigate the state of the widget. Recall that if you have configured a tristate CheckBox, you will need to check the state of the widget using the CheckState property.

d th e .N ET Plat f orm , Se con d Ed it ion Examining C# thean CheckedListBox Control ISBN:1590590554

by Andr ew Tr oelsen

Now that you have basic Button-centric widgets, let's move on to the set of list selectionAprexplored ess © 2003the (1200 pages) centric types, specifically, CheckedListBox, ComboBox. This compr ehensiv e text starListBox, ts w ith aand brief ov er view ofThe the CheckedListBox widget allows you to group together related CheckBox options in a scrollable list control. C# language and then quickly m oves to key technical and Assume you have added such ar chitectur alapplication issues for .NET developer a control to your CarConfig that allows thes.user to configure a number of options for regarding the automobile's sound system (Figure 15-9). Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies Figure The CheckedListBox Chapter 10 - 15-9: Pr ocesses, AppDomains, Conttype exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four Le ve r a ging the .NET Libr a r ie s Like the -controls examined thus far, the

CheckedListBox type gains most of its functionality from the

Chapter - Obj ect Ser ialization andCheckedListBox the .NET Remoting Layinherits er Control12 base class type. Also, the type additional functionality from its direct base Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms) class, ListBox (examined later in this chapter). Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

To insert items in a CheckedListBox, call Add()ols for each item or use the AddRange() method and Chapter 15 new - Pr ogr am ming with Windows Form s Contr

send in an array of objects (strings, to be exact) that represent the full set of checkable items. Here is the configuration code (be sure to check out online help for details about these new properties):

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

// Configure the CheckedListBox. Chapter 18 - ASP.NET Web Pages and Web Contr ols checkedBoxRadioOptions.Location = new System.Drawing.Point (16, 48); Chapter 19 - ASP.NET Web Applicat ions checkedBoxRadioOptions.Cursor = Cursors.Hand; checkedBoxRadioOptions.Size = new System.Drawing.Size (256, 64); I ndex checkedBoxRadioOptions.CheckOnClick = true; List of Figur es // Add items to the CheckedListBox. List of Tables checkedBoxRadioOptions.Items.AddRange(new object[6] { "Front Speakers", "8-Track Tape Player", "CD Player", "Cassette Player", "Rear Speakers", "Ultra Base Thumper"} ); // As always, add the new widget to the Controls collection. this.Controls.Add (this.checkedBoxRadioOptions); Chapter 20 - XML Web Ser vices

Now update the logic behind the Click event for the Order Button. Ask the CheckedListBox which of its items are currently selected and add them to the orderInfo string. Here are the relevant code updates: protected void btnOrder_Click (object sender, System.EventArgs e) { // Build a string to display information. string orderInfo = ""; ...

// For each item in the CheckedListBox: Plat f orm , Se con d Ed it ion for(int C# i an = d0;th ei .N 5) Chapter { 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - AerrorProvider1.SetError(txtInput, Better Paint ing Fr amew or k ( GDI + ) "Can't be greater than 5!"); Chapter } 15 - Pr ogr am ming with Windows Form s Contr ols Chapter else 16 - The stem .I O Nam //SyThings areespace OK, don't show anything. Chapter 17 - Data errorProvider1.SetError(txtInput, Access w ith ADO.NET ""); Pa }r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex

SOURCE CODE

List of Figur es List of Tables

The ErrorProvider application is included under the Chapter 15 directory.

d th e .N ET Plat f orm , Se con d Ed it ion ConfiguringC#aanControl's Anchoring Behavior ISBN:1590590554

by Andr ew Tr oelsen

When you are creating containing Apr ess a© Form 2003 (1200 pages) widgets, you need to decide whether the Form should be resizable. Typically speaking, main are resizable, whereas This compr ehensiv ewindows text star ts w ith a brief ov er view ofdialog the boxes are not. To configure the resizability of yourC#Form, adjust the FormBorderStyle property to any of language and then quickly m oves to key technical andthe values described in Table 15ar chitectur al issues for .NET developer s. 15. Table 15-15: FormBorderStyle Properties Ta ble o f Con t en t s C# FormBorderStyle and t he .NET Plat for m,Property Second Edition

Meaning in Life

I ntr oduction

A nonresizable, three-dimensional border

Fixed3D

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

FixedDialog Chapter 1 - The Philosophy of .NET

A thick, nonresizable dialog box-style border

Chapter 2

A nonresizable, single-line border

- Building C# Applications

FixedSingle

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

FixedToolWindow Chapter 3 - C# Language Fundamentals

A tool window border that is not resizable

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

No border at all

None

Sizable Chapter 6 - I nter faces and Collections

A resizable border

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

A resizable tool window border

Chapter 8

- Advanced C# Type Const ruction Techniques

SizableToolWindow

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Assume that you have configured your Form to be resizable. This brings up some interesting questions

Chapter 9 the - Under standing .NET Assem regarding contained controls. For blies example, if the user makes the Form smaller than the rectangle Chapter 10 Pr ocesses, AppDomains, Contthe exts, and Threads needed to display each control, should controls adjust their size (and possibly location) to morph Chapter 11with - Type Late Binding, and Attr ibute- Based Pr ogramm ing correctly the Reflection, Form? Pa r t Four - Le ve r a ging the .NET Libr a r ie s

In the Windows Forms worldview, propertyLay is used to define a relative fixed position in which Chapter 12 - Obj ect Ser ialization andthe theAnchor .NET Remoting er the control beWin rendered. type has an Anchor property, which can be Chapter 13 - should Buildingalways a Bet ter dow ( IntEvery roducinControl-derived g Window s For ms) set to any values from the AnchorStyles Chapter 14 -ofAthe Better Paint ing Fr amew or k ( GDI + ) enumeration described in Table 15-16. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Table 15-16: AnchorStyles Values Chapter 16 - The Sy stem .I O Nam espace

Chapter 17 - Data Access w ith ADO.NET AnchorStyles Value Meaning in Life Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Bottom control is anchored to the bottom edge of its container. Chapter 18 - ASP.NET Web Pages The and Web Contr ols Chapter ionscontrol is anchored to the left edge of its container. Left 19 - ASP.NET Web ApplicatThe Chapter 20 - XML Web Ser vices

None I ndex

The control is not anchored to any edges of its container.

ListRight of Figur es

The control is anchored to the right edge of its container.

List of Tables

Top

The control is anchored to the top edge of its container.

To anchor a widget at the upper left corner, you are free to "OR" styles together (e.g., AnchorStyles.Top | AnchorStyles.Left). Again, the idea behind the Anchor property is to configure which edges of the control are anchored to the edges of its container. For example, if you configure a Button with the following Anchor value: // Anchor this widget relative to the right position. myButton.Anchor = AnchorStyles.Right;

you are ensured that as the Form is resized, this Button maintains its position relative to the right side of the Form.

d th e .N ET Plat f orm , Se conBehavior d Ed it ion ConfiguringC#aanControl's Docking ISBN:1590590554

by Andr ew Tr oelsen

Another aspect ofApr Windows Forms programming is establishing the docking behavior of your controls. If ess © 2003 (1200 pages) you so choose, you can set a widget's Dock configure This compr ehensiv e text starproperty ts w ith a to brief ov er viewwhich of theside (or sides) of a Form the widget should beC# attached to. The value you assign to a control's Dock language and then quickly m oves to key technical andproperty is honored, regardless of ar chitectur al issues for15-17 .NET developer the Form's current dimensions. Table describess.possible options. Table 15-17: DockStyle Values Ta ble o f Con t en t s

in Life C# DockStyle and t he .NET Plat for m, Meaning Second Edition I ntrValue oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Bottom

The control's bottom edge is docked to the bottom of its containing control.

Chapter 1

- The Philosophy of .NET

Fill 2 Chapter

All the control's edges are docked to all the edges of its containing control - Building C# Applications

and sized appropriately. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

None 5 Chapter

TheObj control is not - Exceptions and ect Lifetim e docked.

Chapter Right 6 Chapter 7

- I nter faces and Collections The control's right edge is docked to the right edge of its containing control. - Callback I nter faces, Delegates, and Ev ents

Top 8 Chapter

control's top edge is docked to the top of its containing control. - Advanced C#The Type Const ruction Techniques

Left

The control's left edge is docked to the left edge of its containing control.

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

So, for 9example, you want to ensure that a given widget is always docked on the left side of a Form, you Chapter - Underifstanding .NET Assem blies would write following: Chapter 10 - the Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

// This is the always located Pa r t Four - Leitem ve r a ging .NET Libr a r ie s

on the left of the Form, regardless

// of12the Form's current Chapter - Obj ect Ser ialization and size. the .NET Remoting Lay er myButton.Dock DockStyle.Left; Chapter 13 - Building=a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Using the topmost menu system, you can select from a set of AnchorStyles and DockStyles values and observe the change in behavior of the Button type (Figure 15-20).

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 15-20: The AnchoringControls application SOURCE CODE

To explore the various anchor and docking styles, check out the AnchoringControls application under the Chapter 15 directory.

C# an d thDialog e .N ET PlatBoxes f orm , Se con d Ed it ion Building Custom by Andr ew Tr oelsen

ISBN:1590590554

Now that you have solid understanding Apraess © 2003 (1200 pages) of some common Windows Forms controls, you need to examine the construction of custom boxes. good This compr ehensiv e dialog text star ts w ithThe a brief ov news er viewisofthat theeverything you have already learned about System.Windows.Forms applies directly to dialog box programming. There is no Dialog C# language and then quickly m oves to key technical and chitectur al issues for .NET developer s. Rather, a dialog box is nothing more than a base class in the ar System.Windows.Forms namespace. stylized Form. TaFirst ble oof f Con all, tunderstand en t s that dialog boxes are typically configured to be nonsizable. Therefore, you will

typically setfor the property to FormBorderStyle.FixedDialog. Also, you will want to set C# and t hewant .NETtoPlat m, BorderStyle Second Edition theoduction ControlBox, MinimizeBox, and MaximizeBox properties to false. In this way the dialog box is configured I ntr tor tbe a fixed Pa One - I nt rconstant. oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

To launch a Form as a modal dialog box (i.e., the owning Form cannot receive focus until the dialog box is - Building C# Applications dismissed), call the ShowDialog() method. Assume you have a topmost menu item that triggers the Pa r t Tw o - The C# Pr ogr am m ing La ngua ge following logic: Chapter 2 Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

// Launch a modal dialog box. - Exceptions and Obj ect Lifetim e protected void mnuModalBox_Click (object sender, System.EventArgs e) Chapter 6 - I nter faces and Collections { Chapter 7 - Callback I nter faces, Delegates, and Ev ents SomeCustomForm myForm = new SomeCustomForm(); Chapter 8 - Advanced C# Type Const ruction Techniques // Could assign in the ctor of SomeCustomForm as well. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s myForm.BorderStyle = FormBorderStyle.FixedDialog; Chapter myForm.ControlBox 9 - Under standing .NET Assem blies = false; Chapter myForm.MinimizeBox 10 - Pr ocesses, AppDomains, Cont exts, and Threads = false; Chapter myForm.MaximizeBox 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing = false; Pa r t FourmyForm.ShowDialog(this); - Le ve r a ging the .NET Libr a r ie s Chapter DoSomeMoreWork(); 12 - Obj ect Ser ialization and .NETcalled Remotinguntil Lay er dialog is closed. //theNot Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms) } Chapter 5

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Notice that directly after the ShowDialog() call, you have a private helper function named DoSomeMoreWork(). Be aware that when you show a modal dialog box, the flow of processing is stopped Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces until the ShowDialog() method returns. (After all, that is what makes it modal!) To show a modeless dialog Chapter 18 - ASP.NET Web Pages and Web Contr ols box (i.e., the launching window and dialog box can alternate focus), substitute the ShowDialog() call with a Chapter 19 - ASP.NET Web Applicat ions call to Show(), as shown here: Chapter 17 - Data Access w ith ADO.NET

Chapter 20 - XML Web Ser vices I ndex

// Launch a modeless dialog box. protected void menuShowMyDlg_Click (object sender, System.EventArgs e) List of Tables { SomeCustomForm myForm = new SomeCustomForm(); myForm.BorderStyle = FormBorderStyle.FixedDialog; myForm.ControlBox = false; myForm.MinimizeBox = false; myForm.MaximizeBox = false; myForm.Show(); DoSomeMoreWork(); // Called right after showing dialog. } List of Figur es

In this case, DoSomeMoreWork() would be hit immediately after the call to Show().

A Dialog Box Example Application Now you can put some real code behind the previous example. Assume you have a Form named

mainForm that supports a topmost menu, allowing the user to launch a modal dialog box (Figure 15-21). C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Figure 15-21: The main Form Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

When the user selects this option, a simple dialog box is displayed. The goal is to allow the user to type in Under standing .NET Assem blies some text,-which is then painted on the parent Form (but only if the OK Button is selected). Figure 15-22 Chapter 10 Prof ocesses, AppDomains, Cont exts, and Threads shows the UI your dialog box. Chapter 9

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex Figure 15-22: The dialog box Form List of Figur es List of Tables

When the user clicks the OK Button, the end result is that the string is extracted from the TextBox maintained by the custom dialog box and painted in the parent Form's client area. Moreover, if the user reactivates the dialog box, the parent Form assigns the previous text message to the dialog box's TextBox (Figure 15-23).

Figure 15-23: Obtaining information from the dialog box

C# an d th e .N ET Plat f orm , Se con d Ed it ion

by Andrthe ew custom Tr oelsendialog box should be of no ISBN:1590590554 The code representing surprise, given that a dialog box is nothing Apr ess minor © 2003 modifications. (1200 pages) more than a Form with Here is the relevant code: This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and // The dialogar chitectur box. al issues for .NET developer s.

public class SomeCustomForm : System.Windows.Forms.Form { Ta ble o f private Con t en t s System.Windows.Forms.Button btnCancel; private btnOK; C# and t he .NET PlatSystem.Windows.Forms.Button for m, Second Edition private System.Windows.Forms.Label label1; I ntr oduction private System.Windows.Forms.TextBox txtMessage; Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public SomeCustomForm() Chapter 1 - The Philosophy of .NET { Chapter 2 - Building C# Applications InitializeComponent(); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge this.StartPosition = FormStartPosition.CenterParent; Chapter 3 - C# Language Fundamentals } Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# ... Chapter private 5 - Exceptions Obj ect Lifetim e voidand InitializeComponent() Chapter { 6 - I nter faces and Collections Chapter 7 - Callback ... I nter faces, Delegates, and Ev ents Chapter 8 - Advanced Type Const ruction Techniques // OK C# Button configuration. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem=bl System.Windows.Forms.DialogResult.OK; ie s btnOK.DialogResult Chapter 9 - Under standing .NET blies btnOK.Size = Assem new System.Drawing.Size (96, 24); Chapter 10 - Pr btnOK.Text ocesses, AppDomains, = "OK"; Cont exts, and Threads // Reflection, Cancel Button configuration. Chapter 11 - Type Late Binding, and Attr ibute- Based Pr ogramm ing = System.Windows.Forms.DialogResult.Cancel; Pa r t Four - Le vebtnCancel.DialogResult r a ging the .NET Libr a r ie s btnCancel.Size (96, 24); Chapter 12 - Obj ect Ser ialization and =thenew .NETSystem.Drawing.Size Remoting Lay er btnCancel.Text = ( "Cancel"; Chapter 13 - Building a Bet ter Win dow Int roducin g Window s For ms) Form as dialog box. Chapter 14 - A // Better Paint configured ing Fr amew or k (to GDI function +) this.Text = "Some Custom Dialog"; Chapter 15 - Pr ogr am ming with Windows Form s Contr ols this.MaximizeBox = false; Chapter 16 - The Sy stem .I O Nam espace this.ControlBox = false; Chapter 17 - Data Access w ith ADO.NET this.MinimizeBox = false; Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces } Chapter 18 - ASP.NET Web Pages and Web Contr ols } Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex The first point of interest is in the constructor of the Form. Notice that you are setting the StartPosition List of Figuron es startup. Earlier, you directly called CenterToScreen() to ensure that the Form was centered property List correctly. of Tables Using the StartPosition property (and the FormStartPosition enumeration), you can gain a finer

level of granularity. Usually you should use FormStartPosition.CenterParent to ensure that the location of the dialog box is centered with regard to the parent (regardless of the parent's location on the screen), as shown here: // Place dialog box centered to parent. public SomeCustomForm() { InitializeComponent(); this.StartPosition = FormStartPosition.CenterParent; }

Another important aspect of dialog box programming is to assign the termination Buttons to a value defined by the DialogResult enumeration. As you know, most dialog boxes define an OK button that says, in effect, "I am happy with my selections. Please use them in the program." Furthermore, most dialog

boxes have a Cancel button that allows the user to back out of a selection. To configure how the dialog C# an d th e .N ET Plat f orm , Se con d Ed it ion box's button should respond with respect to dialog box processing, use the DialogResult property, as ISBN:1590590554 by Andr ew Tr oelsen shown here: Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the

private void C# InitializeComponent() language and then quickly m oves to key technical and { ar chitectur al issues for .NET developer s. ... // OK Button configuration. btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; Ta ble o f Con t en t s // Cancel Button configuration. C# and t he .NET Plat for m, Second Edition btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; I ntr oduction } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Validating Form Data with the DialogResult Property

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals What exactly does it mean a Button's DialogResult value? First of all, when a Button has been Chapter 4 - Obj ect -Or iented to Pr assign ogr am ming w ith C#

set to DialogResult.OK or DialogResult.Cancel, the Form automatically closes (meaning it is invisible but Chapter 5 - Exceptions and Obj ect Lifetim e still in memory). can query this property back in the code that launched this dialog box to see Chapter 6 - I nter Also, faces you and Collections which Button the user selected, as shown and here: Chapter 7 - Callback I nter faces, Delegates, Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

protected void Pa r t Thre e - Pr ogr am mmnuModalBox_Click i ng w i th .N ET Assem bl ie s(object

sender, System.EventArgs e) { Chapter 9 - Under standing .NET Assem blies props set inCont Form. Chapter // 10 - Style Pr ocesses, AppDomains, exts, and Threads SomeCustomForm myForm = SomeCustomForm(); Chapter 11 - Type Reflection, Late Binding, new and Attr ibute- Based Pr ogramm ing // Passing in a reference to the launching dialog box is optional. Pa r t Four - Le ve r a ging the .NET Libr a r ie s myForm.ShowDialog(this); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er if(myForm.DialogResult == DialogResult.OK) Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) { Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) // User hit OK, do whatever. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols } Chapter 16 - The Sy stem .I O Nam espace DoSomeMoreWork(); Chapter 17 - Data Access w ith ADO.NET } Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter The DialogResult 19 - ASP.NET enumeration Web Applicat specifies ions the following values: Chapter 20 - XML Web Ser vices I ndex public enum System.Windows.Forms.DialogResult List { of Figur es List of Tables Abort, Cancel, Ignore, No,

None, OK, Retry, Yes }

Grabbing Data from a Dialog Box Now that you can configure, launch, and test for a dialog box's Button click, you need to understand how to obtain the information from the dialog box. Your current dialog box allows the user to enter a custom string, which is used in the parent Form. Thus, the first step you need to take is to add some number of member variables that represent the data the dialog box is responsible for, as shown here: public class SomeCustomForm : System.Windows.Forms.Form { public SomeCustomForm() {

InitializeComponent(); C# an d th e .N ET Plat f orm , Se con d Ed it ion this.StartPosition = FormStartPosition.CenterParent; ISBN:1590590554 by Andr ew Tr oelsen } Apr ess © 2003 (1200 pages) // The dialog box's state data (and a way to get it). compr ehensiv e text star ts w ith a brief ov er view of the private This string strMessage; C# language and then public string Message quickly m oves to key technical and ar chitectur al issues for .NET developer s. { get{ return strMessage;} // The set function allows the owner to send Ta ble o f Con t en t s // in a startup string that you place in the C# and t he .NET Plat for m, Second Edition // TextBox. I ntr oduction set Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m { Chapter 1 - The Philosophy of .NET strMessage = value; Chapter 2 - Building C# Applications txtMessage.Text = strMessage; Pa r t Tw o - The C# Pr ogr am m ing La ngua ge } Chapter } 3 - C# Language Fundamentals Chapter ... 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e }

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Now, to8 transfer the value in the TextBox to Techniques this private member variable requires that you intercept the Chapter - Advanced C# Type Const ruction Click event for the OK Button. Remember that Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s the DialogResult.OK assignment already ensures that your Form is9 hidden when this Button is clicked. Chapter - Under standing .NET Assem blies This time, however, you need to do some additional work, as shown here: Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

protected Pa r t Four - Le vevoid r a ging btnOK_Click the .NET Libr a r ie(object s

sender, System.EventArgs e)

{ Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Button new smessage. Chapter // 13 - OK Building a Bet clicked! ter Win dow ( Configure Int roducin g Window For ms) = txtMessage.Text; Chapter strMessage 14 - A Better Paint ing Fr amew or k ( GDI + ) }

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17Of - Data Access w ith ADO.NET That's it! course, if you had a more elaborate dialog box (such as the CarConfig Form), you would no Pa r t Fi ve - W eab number Appl ica tiof ons and X ML W e b Se rto vi ces doubt need custom properties represent

the full set of user selections. To complete your

Chapter 18dialog - ASP.NET Web Pages and Contr olsthe code that launched this dialog box to extract the example box application, you Web can update Chapter - ASP.NET internal19message andWeb useApplicat it in theions program. Here is the complete menu selection logic: Chapter 20 - XML Web Ser vices I ndex protected void mnuModalBox_Click (object sender, System.EventArgs e) List { of Figur es List of Tables // Style props set in Form.

SomeCustomForm myForm = new SomeCustomForm(); // Assume this Form has a string variable named 'dlgMsg'. myForm.ShowDialog(this); myForm.Message = dlgMsg; if(myForm.DialogResult == DialogResult.OK) { dlgMsg = myForm.Message; Invalidate(); } DoSomeMoreWork(); }

The extracted string is then painted on the client area using standard GDI+ logic, as shown here:

protected void mainForm_Paint (object sender, PaintEventArgs e) C# an d th e .N ET Plat f orm , Se con d Ed it ion { ISBN:1590590554 Andr ew Tr oelsen obtained from the dialog // Paintby the message box. Apr ess © 2003 (1200 pages) Graphics g = e.Graphics; This compr ehensiv e new text star ts w ith a brief New ov er view of the 24), g.DrawString(dlgMsg, Font("times Roman", C# language and then quickly m oves to key technical and Brushes.Blue, this.ClientRectangle); ar chitectur al issues for .NET developer s. } Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

SOURCE

The SimpleDialog application is included under the Chapter 15 directory.

I ntr oduction CODE Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dForm th e .N ET Plat f orm , Se con d Ed it ion Understanding Inheritance ISBN:1590590554

by Andr ew Tr oelsen

As you are aware, inheritance is thepages) pillar of OOP that allows one class to extend the functionality of Apr ess © 2003 (1200 another class. Typically, when you speak of inheritance, envision This compr ehensiv e text star ts w ith a briefyou ov er view of one the non-GUI type (e.g., SportsCar) deriving from another non-GUI type (Car). However, in the world of Windows Forms, it is possible for one C# language and then quickly m oves to key technical and ar chitectur issuesand for .NET Form to derive from anotheral Form in thedeveloper process s. inherit the base class' widgets and implementation. Form-level inheritance is a very powerful technique, as this allows you to build a base Form that provides core-level functionality for a family of related dialog boxes. If you were to bundle these base-level Forms Tainto ble a o f.NET Con t en ts assembly, other members of your team could extend these types using the .NET language of C# andchoice. t he .NET Plat for m, Second Edition their I ntr oduction

For the sake of illustration, assume you Pa r t One - I nt r oduci ng C# a nd the .NET P lahave tf or mplaced

the CarConfigForm.cs file in a new C# code library

application CarConfigLib Chapter 1 - named The Philosophy of .NET(be sure to add a reference to System.Windows.Forms.dll). Once you compile2 this *.dll, create a new Windows Application project workspace. To derive one Form from another, Chapter - Building C# Applications the first set aam reference to thegeexternal Pa r t Tw o step - TheisC#to Pr ogr m ing La ngua

assembly (in this case, CarConfigLib.dll). Next, specify the base Form using standard C# syntax, as shown here: Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# // The of Obj the Form. Chapter 5 namespace - Exceptions and ect base Lifetim e

using6 CarConfig; Chapter - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

// Your new Form is really a subclass of CarConfigForm! Chapter 8 - Advanced C# Type Const ruction Techniques public class DerivedForm : CarConfig.CarConfigForm Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s { ...} Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa t Four - Le ve r aand ging reopen the .NET Libr a r ie s Ifryou now save the DerivedForm

type, you will see that the new class has inherited all the

Chapter 12Like - Obj ect inheritance Ser ializationscenario, and the .NET Remoting widgets! any be aware that Lay anyercontrols in the base Form that have been Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms)However, if you were to update the logic declared as private may not be repositioned by the derived type. Chapter 14 - A Better Paint Fr amew or k ( GDImembers, +) in the CarConfigLib.dll to ing specify protected the derived type is free to reposition these items Chapter using the 15 design - Pr ogr time am ming template. with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

At this point, you are free to extend this derived Form any way you choose. For test purposes, simply add a new MainMenu that allows the user to exit this application (Figure 15-24). Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 17 - Data Access w ith ADO.NET

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 15-24: Building the derived Form The Click event handler simply shuts down the application, as shown here: private void mnuFileExit_Click(object sender, System.EventArgs e) {

this.Close(); C# an d th e .N ET Plat f orm , Se con d Ed it ion

}

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

It is worth pointingThis outcompr that the Visual Studio provides an integrated wizard (named the ehensiv e text star.NET ts w ithIDE a brief ov er view of the C# tolanguage and then quicklyTo m access oves to key technical andactivate the Project | Add Inherited Inheritance Picker) create derived Forms. its functionality, chitectur issues for .NET developer s. class, you are asked to specify the name of the Form menu item.arOnce youalprovide a name for your new assembly that contains the base class Form. At that point, the IDE will automatically create a new class type derived from the specified base Form.

Ta ble o f Con t en t s

C# and t he .NET Plat for m, MyDerivedForm Second Edition and CarConfigLib applications are included under the Chapter 15 SOURCE The I ntr oduction CODE directory. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

At this point in the game, you should have a firm understanding of the core set of Windows Forms Chapter 1 - The Philosophy of .NET

controls. you would the remaining widgets expose their unique set of properties, methods and Chapter 2 As - Building C# expect, Applications events, I assume you willLaexamine Pa r t Tw o which - The C# Pr ogr am m ing ngua ge at

your leisure. To close this chapter, we'll now spend some time learning the process of building custom Windows Forms controls. Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d thWindows e .N ET Plat f orm , Se con d Controls Ed it ion Building Custom Forms ISBN:1590590554

by Andr ew Tr oelsen

If you have a background in classic COM, you are no doubt aware of the use of ActiveX controls. These Apr ess © 2003 (1200 pages) coclasses are simply types that implement ats (huge) ofview (quite COM interfaces that This compr ehensiv e text star w ith anumber brief ov er of complex) the provide behaviorsC#forlanguage rendering graphical content, persisting the state of the coclass, and enabling and then quickly m oves to key technical and ar chitectur al issues for(among .NET developer s. control/host container communication other duties). While ActiveX controls can now be regarded as a legacy technology, their spirit lives on under .NET. TaAs bleyou o f Con are talready en t s well aware, a class is a type that serves as a blueprint for discrete variables of this type.

In and .NET, classes can derive from other types, implement any number of interfaces, serve as C# t heyour .NETcustom Plat for m, Second Edition theoduction basis for additional types, and typically support any number of properties, methods, and events. In I ntr addition this (obvious) generic classes Pa r t One -to I nt r oduci ng C# adefinition, nd the .NET P la tf or m

are unique in that they do not support any design time

manipulation. For example,ofif .NET you have a simple C# class named Car, you are unable to interact with its Chapter 1 - The Philosophy members the VS Properties window. Furthermore, when you are programming with generic Chapter 2 -using Building C# .NET Applications class notam drag theLaitem Pa r t Twtypes, o - Theyou C# do Pr ogr m ing nguaonto ge

a Form-derived type as you would a Windows Forms Button widget. In essence, a simple class is a non-GUI type that is directly manipulated through code. Chapter 3 - C# Language Fundamentals Chapter 4

Obj ect -Or iented Pr ogr am ming w ith C# Acontrol is- also a class type, meaning it derives from a parent class (typically

Chapter 5 - Exceptions and Obj ect Lifetim e System.Windows.Forms.Control) and inherits a good deal of functionality in the process. Each of the GUI Chapter 6 I nter faces and Collections widgets you have examined during this chapter is considered a control type. Like a simple class, controls Chapter - Callback I nter faces, Delegates, andmanipulated Ev ents support7 a set of public members and can be directly by code. In addition, however, controls Chapter 8 - aAdvanced Constconfigured ruction Techniques do support GUI, andC# areType typically using various design time tools (such as the VS .NET Pa r t Thre e - window) Pr ogr am m i ng are w i th"drawn" .N ET Assem ie sowning Properties and ontoblthe

host using the Toolbox. To be sure, like any intrinsic

Chapter 9 Forms - Undercontrols, standing your .NET custom Assem blies Windows controls inherit the same set of behaviors from each class in the Chapter inheritance 10 - chain. Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Next you- have control Pa r t Four Le ve ruser a gingcontrols. the .NETLike Libr aar ie s

type, user controls also support a runtime GUI and are fully configurable at design time. The key difference is that user controls do not derive directly from Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er System.Windows.Forms.Control. Rather, user controls derive from System.Windows.Forms.UserControl, Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) which in turn derives directly from ContainerControl. Recall that ContainerControl (and its base class Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) ScrollableControl) provide additional members that allow you to configure scrolling, tab order, and focus Chapter 15 - Pr ogr am ming with Windows Form s Contr ols logic. When you wish to build a reusable GUI widget that maintains numerous related widgets that need to Chapter 16 - The Sy stem .I O Nam espace work together as a whole, you will want to derive your custom class directly from UserControl (in fact, this Chapter 17 - Data Access ith ADO.NET is the default base classwfrom which your custom controls derive). However, if you are not interested in Pa r t Fi ve W e b Appl ica ti ons X ML W e bcomposite Se r vi ces controls, you are free to change the wizard-generated building a widget that hostsand interrelated Chapter 18 ASP.NET Web Pages and Web code to derive directly from Control itself.Contr ols Chapter 19 - ASP.NET Web Applicat ions

Finally,20 you- XML haveWeb components. Chapter Ser vices Components can best be thought of as a middle-of-the-road alternative between a simple class and a full-fledged (user) control. Like a simple class, components do not support I ndex a runtime user interface. However, components can be selected from the VS .NET Toolbox window and List of Figur es

configured List of Tables using the integrated Property window at design time. For example, check out the Components tab in Figure 15-25.

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Figure 15-25: The Components tab

Chapter I nter faces Collections As you 6can- see, theseand intrinsic components are not necessarily GUI in nature, but they do lend themselves Chapter 7 Callback I nter faces, Delegates, and Ev ents well to a design time environment. If you drop a component (such as the EventLog) onto your hosting Chapter Form-derived 8 - Advanced type, you C#will Type notice Const that ruction the design Techniques time representation is placed in the designer's icon tray Pa (as r t Thre welleas - Pr a ogr member am m i ng variable w i th .NinETthe Assem Form-derived bl ie s

type being created). Once you select the component,

you are9 able to setstanding various.NET properties using the Properties window. Chapter - Under Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Programmatically speaking, what marks a type as a component is the fact that it implements the System.ComponentModel.IComponent interface. Most of the time, however, you will not directly flesh out Pa r t Four - Le ve r a ging the .NET Libr a r ie s the details of this interface by hand, but rather derive your type from Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er System.ComponentModel.Component (and thus receive the canned implementation). Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Building a Custom UserControl ISBN:1590590554

by Andr ew Tr oelsen

During the next several youpages) construct a custom UserControl named CarControl. To begin, fire up Apr ess pages, © 2003 (1200 Visual Studio .NET and select a new Windows Control Library This compr ehensiv e text star ts w ith a brief ov er workspace view of the named CarControlLibrary (Figure 15-26). When you are finished, rename the initial C# class toand CarControl (note that the base class C# language and then quickly m oves to key technical ar chitectur al issues for .NET developer s. of your type is UserControl).

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure 15-26: Creating a new Windows Control Library workspace

Chapter 9

- Under standing .NET Assem blies

Chapter Pr ocesses, AppDomains, Cont exts, Threads Before 10 we-get far along, let's establish the bigand picture of where you are going with this example. The Chapter 11 - type Type isReflection, Latefor Binding, and through Attr ibute-aBased ingthat will change based on the CarControl responsible animating seriesProfogramm bitmaps Pa r t Four state - Le veof r athe gingautomobile. the .NET Libr r ie scar's internal If athe

current speed is safely under the car's maximum speed limit,

Chapter 12 - Obj ect Serthrough ializationthree and the .NETimages Remoting Lay er the CarControl loops bitmap that render an automobile driving safely along. If the Chapter current13 speed - Building is ten amiles Bet ter below Win dow the (maximum Int roducin gspeed, Window the s For CarControl ms) loops through four images, with the

fourth image theing carFrbreaking if the car has surpassed its maximum speed, the Chapter 14 - A showing Better Paint amew or k down. ( GDI + Finally, ) CarControl over fivewith images, where the fifth image represents a doomed automobile. Chapter 15 - loops Pr ogr am ming Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# Images an d th e .N ET Plat f orm , Se con d Ed it ion Creating the by Andr ew Tr oelsen

ISBN:1590590554

Given our designApr notes, first order of business is to create a set of five *.bmp files for use by the ess ©the 2003 (1200 pages) animation loop. IfThis youcompr wish to create custom images, byeractivating ehensiv e text star ts w ith a begin brief ov view of thethe Project | Add New Item menu selection and insert five new Bitmap resources. If you would rather showcase your artistic abilities, feel C# language and then quickly m oves to key technicalnot and ar chitectur issues for .NET developer s. free to use the images that al accompany this sample application (keep in mind, I in no way consider myself a graphic artist). The first of these three images (Lemon1.bmp, Lemon2.bmp, and Lemon3.bmp) illustrates a car navigating down the road in a safe and orderly fashion. The final two bitmap images Ta(AlmostDead.bmp ble o f Con t en t s and Dead.bmp) represent a car approaching its maximum upper limit and its ultimate C# and t he .NET Plat for m, Second Edition demise. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# Design an d th e .N ET Plat f orm , Se con d Ed it ion Building the Time GUI ISBN:1590590554

by Andr ew Tr oelsen

The next step is to open design time editor for the CarControl type. As you can see, you are presented Apr ess ©the 2003 (1200 pages) with a Form-like designer that represents thetsclient the control under construction. Using the This compr ehensiv e text star w ith area a briefofov er view of the Toolbox window, C# addlanguage an ImageList type (to hold each of the bitmaps), a and then quickly m oves to key technical and Timer type (to control the chitectur al issues (to for hold .NETthe developer animation cycle),arand a PictureBox currents.image). Don't worry about configuring the size or location of the PictureBox type, as you will programmatically position this widget within the bounds of the CarControl.Figure 15-27 shows the story thus far. Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Figure 15-27: Creating the design time GUI

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - the A Better Paint ing Fr amewconfigure or k ( GDI +the ) ImageList's Images collection by adding each bitmap to Now, using Properties window, Chapter 15 Pr ogr am ming with Windows Form s Contr ols sequentially (Lemon1.bmp, Lemon2.bmp, the list. Be aware that you will want to add these items Chapter 16 - TheAlmostDead.bmp, Sy stem .I O Nam espace Lemon3.bmp, Dead.bmp) to ensure a linear animation loop. As you recall from Chapter 17 Data w ith ADO.NET Chapter 14, whenAccess you incorporate resources (such as bitmaps) into your VS .NET solutions, the Pa r t Fi ve - W*.resx e b Appl icaisti ons and X ML Wupdated. e b Se r vi ces underlying file automatically Therefore,

the images will be embedded into your assembly

Chapter - ASP.NET and Web Contr ols with no18 extra work onWeb yourPages behalf. Chapter 19 - ASP.NET Web Applicat ions

Also be20aware the default Chapter - XMLthat Web Ser vices width and height of *.bmp files inserted using VS .NET are 47×47 pixels.

Thus, the ImageSize of the ImageList should also be set to 47×47 (or else you will have some skewed rendering). Finally, configure the state of your Timer type such that the Interval property is set to 200 and is List of Figur es initially disabled. I ndex

List of Tables

C# an d th eCarControl .N ET Plat f orm , Se con d Ed it ion Implementing the by Andr ew Tr oelsen

ISBN:1590590554

With this GUI prep work of(1200 the way, Apr ess ©out 2003 pages)you can now turn to implementation of the type members. To begin, create a new public enumeration which has a member representing each item This compr ehensiv e text named star ts wAnimFrame, ith a brief ov er view of the maintained by theC#ImageList. As you will see, you make use of this enumeration to determine the current language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. frame to render into the PictureBox: // Helper enum for images. public enum AnimFrames C# and t he .NET Plat for m, Second Edition { I ntr oduction Lemon1, Lemon2, Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Lemon3, AlmostDead, Dead Chapter 1 - The Philosophy of .NET }

Ta ble o f Con t en t s

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter The CarControl 3 - C# Language type maintains Fundamentals a good number of private data points to represent the animation logic.

Here is4the- rundown eachPrmember: Chapter Obj ect -Orof iented ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6 class - I nter faces and Collections public CarControl : System.Windows.Forms.UserControl Chapter { 7 - Callback I nter faces, Delegates, and Ev ents

data. Chapter// 8 State - Advanced C# Type Const ruction Techniques private System.ComponentModel.IContainer Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

components; private AnimFrames currFrame = AnimFrames.Lemon1; Chapter 9 - Under standing .NET Assem blies AnimFrames currMaxFrame = AnimFrames.Lemon3; Chapterprivate 10 - Pr ocesses, AppDomains, Cont exts, and Threads private bool IsAnim; Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing private int the currSp = a50; Pa r t Four - Le ve r a ging .NET Libr r ie s private System.Windows.Forms.PictureBox Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er pictureBox; private int maxSp = 100; Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) private System.Windows.Forms.Timer animTimer; Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) private string carPetName= "NoName"; Chapter 15 - Pr ogr am ming with Windows Form s Contr ols private Rectangle bottomRect = new Rectangle(); Chapter 16 - The Sy stem .I O Nam espace private System.Windows.Forms.ImageList theImageList; Chapter 17 - Data Access w ith ADO.NET ... Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces } Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter As you 20 can- see, XML Web you have Ser vices data points that represent the current and maximum speed, the pet name of the

automobile, and two members of type AnimFrame. The currFrame variable is used to specify which I ndex member List of Figurof esthe ImageList is to be rendered. The currMaxFrame variable is used to mark the current upper limit the ImageList (recall that the CarControl loops through three to five images based on the current List of in Tables speed). The IsAnim data point is used to determine if the car is currently in animation mode. Finally, you have a Rectangle member (bottomRect) that is used to represent the bottom region of the CarControl type. Later, you render the pet name of the automobile into this piece of screen real estate. To divide the CarControl into two rectangular regions, create a private helper function named StretchBox(). The role of this member is to calculate the correct size of the bottomRect member as well as to ensure that the PictureBox widget is stretched out over the upper two thirds (or so) of the CarControl type. private void StretchBox() { // Configure picture box. pictureBox.Top = 0; pictureBox.Left = 0; pictureBox.Height = this.Height - 50;

pictureBox.Width = this.Width; C# an d th e = .N ET Plat f orm , Se con d Ed it ion pictureBox.Image ISBN:1590590554 by Andr ew Tr oelsen theImageList.Images[(int)AnimFrames.Lemon1]; Apr ess © 2003 (1200 pages) // Figure out size of bottom rect. This compr ehensiv e text star ts w ith a brief ov er view of the bottomRect.X = 0; C# language and then quickly m oves to key technical and bottomRect.Y = this.Height - 50; ar chitectur al issues for .NET developer s. bottomRect.Height = this.Height - pictureBox.Height; bottomRect.Width = this.Width; }

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Once you have carved out the dimensions of each rectangle, call StretchBox() from the default Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m constructor.

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Defining the Custom Events

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals The CarControl type supports two events that are fired back to the host Form based on the current speed

Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# is sent out when the CarControl's speed approaches the of the automobile. The first event, AboutToBlow, Chapter 5 Exceptions and Obj ect Lifetim e when the current speed is greater than the allowed maximum. upper limit. BlewUp is sent to the container Chapter - I nter faces leverages and Collections Each of6 these events a custom delegate (CarEventHandler) that can hold the address of any Chapter 7 Callback I nter faces, Delegates, Ev ents method returning void and taking a single and System.String as its sole parameter. You'll fire these events in Chapter 8 - Advanced ruction Techniques just a moment, but forC# theType timeConst being, add the following members to the public sector of the CarControl: Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 events - Under standing .NET Assem blies // Car / custom delegate. Chapter 10delegate - Pr ocesses, AppDomains, Cont exts, and Threads msg); public void CarEventHandler(string Chapter 11event - Type CarEventHandler Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing public AboutToBlow; Pa r t Four event - Le ve r a ging the .NET Libr a r ie s BlewUp; public CarEventHandler

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Defining the Custom Properties

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16class - Thetype, Sy stem .I O Nam espacemay define a set of properties to allow the outside world to interact Like any custom controls Chapter - Data Access w ithFor ADO.NET with the17state of the widget. your current purposes, you are only interested in defining three properties. Pa r t Fi ve e b Appl ica ti ons property and X ML enables W e b Se r vi First, you- W have Anim. This orces disables

the Timer type:

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - to ASP.NET Web Applicat // Used configure theions internal Timer type. Chapter 20 bool - XML Web public AnimSer vices I ndex { List of Figur get es{return IsAnim;}

set List of Tables { IsAnim = value; animTimer.Enabled = IsAnim; } }

The PetName property is as you would expect, and requires no comment. Do notice, however, that when the user sets the pet name, you make a call to Invalidate() to render the name of the CarControl into the bottom rectangular area of the widget (you do this step in just a moment): // Configure pet name. public string PetName { get{return carPetName;}

set {

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew=Trvalue; oelsen carPetName Apr ess © 2003 Invalidate(); (1200 pages)

} }

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Next, you have the Speed property. In addition to simply modifying the currSp data member, Speed is also the entity that fires the AboutToBlow and BlewUp events based on the current speed of the CarControl. C# and t he .NET Plat for m, Second Edition Here is the complete logic:

Ta ble o f Con t en t s I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

// Adjust currSp, currMaxFrame and fire our events. - The Philosophy of .NET public int Speed Chapter 2 - Building C# Applications { Pa r t Tw o - The C# Pr ogr am m ing La ngua ge get{return currSp;} Chapter 3 - C# Language Fundamentals set Chapter{4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - currSp Exceptions Obj ect Lifetim e = and value; Chapter 6 - currFrame I nter faces and=Collections currMaxFrame; Chapter 7 - // Callback I nter faces, Delegates, and Ev ents About to explode? Chapter 8 - if Advanced C# Type Const ruction ((maxSp - currSp) = maxSp) Chapter 12 - if Obj (currSp ect Ser ialization and the .NET Remoting Lay er Chapter 13 - {Building a Bet ter Win dow ( Int roducin g Window s For ms) currSp = Fr maxSp; Chapter 14 - A Better Paint ing amew or k ( GDI + ) BlewUp("Ug...you're toast..."); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols currMaxFrame = AnimFrames.Dead; Chapter 16 - The Sy stem .I O Nam espace } Chapter 17 - Data Access w ith ADO.NET } Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces } Chapter 1

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

I ndex As you can see, if the current speed is 10 miles below the maximum upper speed, you fire the List AboutToBlow of Figur es event and adjust the upper frame limit to AnimFrame.AlmostDead. If the user has pushed

theoflimits of your automobile, you fire the BlewUp event and set the upper frame limit to AnimFrame.Dead. List Tables

an dAnimation th e .N ET Plat f orm , Se con d Ed it ion ControllingC#the by Andr ew Tr oelsen

ISBN:1590590554

The next detail toApr attend is ensuring that the Timer type advances the current frame to render within the ess ©to 2003 (1200 pages) PictureBox. Again, recall that the number of frames loopovthrough depends on the current speed of the This compr ehensiv e text star ts w ith atobrief er view of the automobile. You C# onlylanguage want to bother adjusting the image in the PictureBox if the Anim property has been and then quickly m oves to key technical and al issues for event .NET developer s. set to true. Beginarbychitectur handling the Tick for the Timer type, and flesh out the details as follows: private void animTimer_Tick(object sender, System.EventArgs e) { C# and t he .NET Plat for m, Second Edition if(IsAnim) I ntr oduction pictureBox.Image = theImageList.Images[(int)currFrame]; Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // Bump frame. Chapterstring 1 - ThesPhilosophy of .NET = Enum.Format(typeof(AnimFrames), currFrame, "D"); Chapterint 2 - iBuilding C# Applications = int.Parse(s); Pa r t Twint o - The C# Pr ogr am= m ing nextFrame i +La ngua 1; ge ChaptercurrFrame 3 - C# Language Fundamentals = (AnimFrames)nextFrame; Chapterif 4 (currFrame - Obj ect -Or iented Pr ogr am ming w ith C# > currMaxFrames) Chapter 5 - currFrame Exceptions and ect Lifetim e = Obj AnimFrames.Lemon1; Chapter } 6 - I nter faces and Collections

Ta ble o f Con t en t s

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

d th e Name .N ET Plat f orm , Se con d Ed it ion Rendering C# theanPet by Andr ew Tr oelsen

ISBN:1590590554

Before you can take your control for a spin, you have one final detail to attend to: displaying the car's Apr ess © 2003 (1200out pages) moniker. To do this, handle the Paint event andofwithin This compr ehensiv e text starfor ts your w ith aCarControl, brief ov er view the the handler, render the CarControl's pet C# name into the bottom rectangular region of the client area: language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

private void CarControl_Paint(object sender, System.Windows.Forms.PaintEventArgs e) Ta ble o f Con t en t s { C# and t he .NET Plat for m, Second Edition // Render the petname on the bottom of the control. I ntr oduction Graphics g = e.Graphics; Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m g.FillRectangle(Brushes.GreenYellow, bottomRect); Chapterg.DrawString(PetName, 1 - The Philosophy of .NET new Font("Times New Roman", 15), Chapter 2 - Brushes.Black, Building C# Applications bottomRect); Pa r t Tw o The C# Pr ogr am m ing La ngua ge } Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# At this point, the initial crack atect theLifetim CarControl is complete. Go ahead and build your project. Chapter 5 - Exceptions and Obj e Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Testing theC#CarControl Type ISBN:1590590554

by Andr ew Tr oelsen

Like all .NET types, now able to make use of your custom control from any language targeting the Apryou ess ©are 2003 (1200 pages) CLR. For your current purposes, build a C# closing down the current This compr ehensiv e text startester ts w ithapplication. a brief ov erBegin view ofby the workspace and creating a new Windows Forms project named CarCtrlClient. To allow your current project C# language and then quickly m oves to key technical and ar chitectur al issues for .NET to reference auxiliary controls, right-click yourdeveloper Toolboxs.window and select the Add/Remove Items menu selection. Using the Browse button on the .NET Framework Components tab, navigate to your MyControlLib library, and then select the CarControl type. At this point you will find a new icon on the TaToolbox ble o f Con t en t s of course, CarControl. named, C# and t he .NET Plat for m, Second Edition

Begin building your GUI by placing a CarControl onto the Form designer. Notice that the Anim, PetName, I ntr oduction and Speed area nd all the exposed Pa r t One - I ntproperties r oduci ng C# .NET Pthrough la tf or m

the Properties window. Also be aware that the control is

"alive" at time. Thus,ofif.NET you set the Anim property to true at design time, you will find your car is Chapter 1 design - The Philosophy animating the Form Chapter 2 -on Building C# designer. Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Once you have configured the initial state of your CarControl, add additional GUI widgets that allow the - C# Language Fundamentals user to increase and decrease the speed of the automobile, and view the incoming events and speed Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# (Label widgets should do nicely for these purposes). One possible GUI design is shown in Figure 15-28. Chapter 3 Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Figure The client-side Chapter 18 - 15-28: ASP.NET Web Pages andGUI Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

The logic behind the Buttons will simply adjust the current speed by 10 MPH, and display the current speed of the CarControl in the Label widget. For example:

Chapter 20 - XML Web Ser vices I ndex List of Figur es

private void btnSpeedUp_Click(object sender, System.EventArgs e) { carControl1.Speed += 10; lblCurrSp.Text = string.Format("Speed is: {0}", carControl1.Speed.ToString()); } private void btnSlowDown_Click(object sender, System.EventArgs e) { // NOTE! We did not account for a negative current speed, // so your car may drive in reverse! carControl1.Speed -= 10; lblCurrSp.Text = string.Format("Speed is: {0}", carControl1.Speed.ToString()); }

List of Tables

Next, handle the Load event for the Form-derived type and activate the CarControl's animation:

an d th e .N ET Plat f orm , Sesender, con d Ed it ion private void C# mainForm_Load(object System.EventArgs e) ISBN:1590590554 by Andr ew Tr oelsen { Apr ess © 2003=(1200 pages) carControl1.Anim true; lblCurrSp.Text This compr =ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves tocarControl1.Speed.ToString()); key technical and string.Format("Speed is: {0}", ar chitectur al issues for .NET developer s. }

TaThe ble ofinal f Con t en t s of this client-side design is to capture the incoming events from the CarControl widget. aspect C# and t he .NET Plat for m,Forms SecondGUI Edition Like all other Windows types, you are able to handle events using the Properties window. I ntr oduction Handle the AboutToBlow and BlewUp events, and write some informative message to the output Label: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET // Client-side event handlers.

Chapter 2 - void Building C# Applications private carControl1_AboutToBlow(string msg) Pa {r t Tw o - The C# Pr ogr am m ing La ngua ge

ChapterlblEventMsg.Text 3 - C# Language Fundamentals = msg; Chapter 4 }

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - void Exceptions and Obj ect Lifetim e private carControl1_BlewUp(string msg) Chapter 6 - I nter faces and Collections { ChapterlblEventMsg.Text 7 - Callback I nter faces, = Delegates, msg; and Ev ents

} Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

At this point, you are able to run your client application and interact with the CarControl. As you can see, building and using custom controls is a fairly straight-forward task, given what you already know about Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing OOP, GDI+, and Windows Forms. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 -do Obj ect Ser ialization and the .NET Remoting Lay er the process of .NET Windows Control While you have enough information to continue exploring Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For development, there is one additional programmatic aspect to ms) contend with: design time functionality. Chapter - A Better Paint ing Fr amew or k (down GDI + )to, you need to understand the role of a key design timeBefore 14 I describe exactly what this boils Chapter - Pr ogr am ming with Windows Form s Contr ols centric 15 namespace. Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th ET Plat f orm , Se con d Ed it ion Select Members ofe .Nthe System.ComponentModel Namespace ISBN:1590590554

by Andr ew Tr oelsen

The System.ComponentModel namespace defines a number of such types that allow you to describe how Apr ess © 2003 (1200 pages) your custom controls and components should themselves time. For example, you can This compr ehensiv e text star ts display w ith a brief ov er viewatofdesign the opt to supply a textual description of each property, define a default event, or group related members into C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. a custom category (for display purposes within the Properties window). When you are interested in making the sorts of modifications previously mentioned, you will want to make use of the following core attributes (Table 15-18). Ta ble o f Con t en t s C# and t15-18: he .NETSelect Plat forMembers m, Second of Edition Table System.ComponentModel I ntr oduction Pa rSystem.ComponentModel t One - I nt r oduci ng C# a nd the .NET Applied P la tf or m

Attribute Chapter 1 - The Philosophy of .NET

to

Chapter 2 - Building C# Applications BrowsableAttribute

Properties events

Pa r t Tw o - The C# Pr ogr am m ing La nguaand ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

CategoryAttribute Properties - I nter faces and Collections and events

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Meaning in Life Specifies whether a property or an event should be displayed in the property browser. By default, all custom properties and events can be browsed. Specifies the name of the category in which to group a property or event.

Chapter 8 - Advanced C# Type Const ruction TechniquesDefines a small block of text to be displayed DescriptionAttribute Properties Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem ie s andblevents

Chapter 9

- Under standing .NET Assem blies

at the bottom of the property browser when the user selects a property or event.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

DefaultPropertyAttribute

Properties

Specifies the default property for the component. This property is selected in the Pa r t Four - Le ve r a ging the .NET Libr a r ie s property browser when a user clicks the Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er control. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

DefaultValueAttribute Chapter 14 - A Better Paint ing Fr amew orProperties k ( GDI + )

Sets a simple default value for a property that Chapter 15 - Pr ogr am ming with Windows Form s Contr olswill be applied when the control is reset to its default state. Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NETProperties LocalizableAttribute Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

DefaultEventAttribute

I ndex

List of Figur es List of Tables

Events

Specifies that a property may be localized. Any properties that have this attribute are automatically persisted into the resources file when a user chooses to localize a Form. Specifies the default event for the component. When a user double-clicks the control type, stub code is automatically written for the default event.

an d th e .N ET Plat f ormAppearance , Se con d Ed it ion of CarControl Enhancing C# the Design Time by Andr ew Tr oelsen

ISBN:1590590554

To illustrate the use of some these new attributes, assume you want to create a custom category Apr ess © 2003of (1200 pages) (called "Car Configuration") to which each property event theofCarControl belong. Also, let's supply This compr ehensiv e text star ts w ith aand brief ov erof view the a friendly description for each member and default value for each property. To do so, simply update each C# language and then quickly m oves to key technical and ar chitectur issues for .NET developer of the properties and eventsalof the CarControl type to s. support the [Category], [DefaultValue], and [Description] attributes. For example: Ta ble o f Con t en t s

using System.ComponentModel; ... I ntr oduction public class CarControl : System.Windows.Forms.UserControl Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m { Chapter... 1 - The Philosophy of .NET Chapter[Category("Car 2 - Building C# Applications Configuration"), Pa r t TwDescription("Sent o - The C# Pr ogr am m ing when La nguathe ge car is approaching terminal speed.")] Chapterpublic 3 - C# event Language Fundamentals CarEventHandler AboutToBlow; Chapter... 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter[Category("Car 5 - Exceptions and Configuration"), Obj ect Lifetim e ChapterDescription("Pet 6 - I nter faces and Collections name for your auto."), Name")] ChapterDefaultValue("No 7 - Callback I nter faces, Delegates, and Ev ents public string PetName {...} Techniques Chapter 8 - Advanced C# Type Const ruction } Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s C# and t he .NET Plat for m, Second Edition

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Now, let me make a comment on what it means to assign a default value to a property, because I can guarantee you it is not what you would (naturally) assume. Simply put, the [DefaultValue] attribute does Pa r t Four - Le ve r a ging the .NET Libr a r ie s not ensure that the underlying value of the data point wrapped by a given property will be automatically Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er initialized to the default value. Thus, although you specify a default value of "No Name" to the PetName Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) property, the carPetName member variable will not be set to "No Name" unless you do so via the type's Chapter 14 - or A Better Paint inginitialization Fr amew or k syntax: ( GDI + ) constructor via member Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

private string carPetName= "NoName";

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter ASP.NET Web Pages and comes Web Contr Rather,18the- [DefaultValue] attribute intools play when the programmer "resets" the value of a given Chapter 19using - ASP.NET Web Applicat ions To reset a property using VS .NET, select the property of interest, property the Properties window. Chapter right-click 20 the - XML description Web Ser vices pane, and click "Reset". Also note the description appears in the lower pane of

the Properties window (Figure 15-29). I ndex List of Figur es List of Tables

Figure 15-29: Resetting a property to the default value

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

The [Category] attribute only bepages) realized if the programmer selects the categorized view of the Apr ess ©will 2003 (1200 Properties window (as opposed to the default view) as of seen This compr ehensiv e text star tsalphabetical w ith a brief ov er view the in Figure 15-30. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure 15-30: The custom category

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Defining a Default Property and Default Event

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - toObj ect Ser ialization and the like .NET Remotinginto Lay a ercommon category, you may also want to In addition describing and grouping members Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s ms) configure your controls (or components) to support defaultFor behaviors. A given control may support a Chapter - A Better Paint ing define Fr amew or kdefault ( GDI + )property for a class using the [DefaultProperty] attribute as default 14 property. When you the Chapter follows:15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - the Data default Access w ithproperty ADO.NET for this control. // Mark Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces [DefaultProperty("Anim")]

Chapter 18 class - ASP.NET Web Pages and Web Contr ols public CarControl Chapter:19System.Windows.Forms.UserControl - ASP.NET Web Applicat ions Chapter {...}20 - XML Web Ser vices I ndex List of Figur es

youofensure List Tables that when the user selects this control at design time, the Anim property is automatically

highlighted in the Properties window. Likewise, when you configure your control to have a default event: // Mark the default event and property for this control. [DefaultEvent("BlewUp"), DefaultProperty("Anim")] public class CarControl : System.Windows.Forms.UserControl {...}

you ensure that when the user double-clicks the widget at design time, stub code is automatically written for the default event.

Specifying a Custom Toolbox Bitmap Another design time technique that is supported by a polished custom control is to specify a custom

toolbox bitmap image. Currently, when the user selects the CarControl, the VS .NET IDE will make show C# an d th e .N ET Plat f orm , Se con d Ed it ion this type on the ToolBox using the default "gear" icon. If you wish to specify a custom image, your first step Andrfile ew into Tr oelsen is to insert a new by *.bmp your project (CarControl.bmp)ISBN:1590590554 that is configured to be 16×16 pixels in size Apr ess © 2003 (1200 pages) (established via the Width and Height properties). This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly key and value to Embedded Resource to Once you have created the image as you see m fit oves (andtoset thetechnical Build Action chitectur al issues within for .NET s. your final task is to make use of the ensure the imageardata is contained thedeveloper assembly), [ToolboxBitmap] attribute, which is applied at the type level. The first argument is the type information for the control itself, while the second argument is the friendly name of the *.bmp file.

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

[ToolboxBitmap(typeof(CarControl), "CarControl")] [DefaultEvent("BlewUp"), DefaultProperty("Anim")] Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public class CarControl : System.Windows.Forms.UserControl Chapter 1 - The Philosophy of .NET {...} I ntr oduction

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 -doC#so, Language Fundamentals Once you you will find that when the programmer adds the widget to the toolbox, your custom Chapter 4 -be Obj ect -Or iented Pr ogr mingToolbox. w ith C# image will displayed on the VSam.NET Chapter 5

- Exceptions and Obj ect Lifetim e So, that6 wraps upfaces our examination of the process of building custom Windows Forms controls. Obviously, Chapter - I nter and Collections

complete thisfaces, topic Delegates, (especiallyand programming for design time support) would require a book all Chapter 7 coverage - Callback of I nter Ev ents

of its own.-IfAdvanced you are interested in additional details regarding developing custom Windows Forms controls, C# Type Const ruction Techniques pick up a copy of User Interfaces in C#: Windows Forms and Custom Controls (MacDonald, Apress Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s 2002). Chapter 8 Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, and Threads SOURCE The CarControl Cont and exts, CarControlTestForm projects are included under the Chapter 15 Chapter 11 Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing CODE directory. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Summary

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

This chapter rounded off© your current understanding of Windows Forms by examining the programming of Apr ess 2003 (1200 pages) numerous GUI widgets from the simple to the more exotic As you have seen, This compr ehensiv e text(Button) star ts w ith a brief ov er view (MonthCalendar). of the each and every Windows Forms control type derives from System.Windows.Forms.Control, which defines C# language and then quickly m oves to key technical and ar chitectur al issues for .NETtypes developer s. a number of members available to derived (including the all important Control.ControlCollection type). This chapter also explored the various anchoring and docking behaviors that can be used to enforce a specific layout of your GUI types, regardless of the size of the owning Form. Ta ble o f Con t en t s

In and the latter halfPlat of for thism,chapter, learned how to build custom dialog boxes using Windows Forms and C# t he .NET Second you Edition examined I ntr oductiona number of issues related to dialog boxes. Next, you learned how to derive a new Form from an using inheritance. Pa r t existing One - I ntForm r oducitype ng C# a ndForm the .NET P la tf or m

Using this technique, you are able to build a set of generic

GUIs that bePhilosophy extended of by.NET derived types. Finally, this chapter introduced you to the process of building Chapter 1 can - The custom2Windows Forms controls using the .NET platform. Chapter - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Chapter C# 16: The System.IO Namespace ISBN:1590590554 by Andr ew Tr oelsen Apr ess full-blown © 2003 (1200desktop pages) applications, the ability to save information between user When you are creating This compr ehensiv text star ts awnumber ith a briefofov er view of the sessions is imperative. This chaptere examines IO-related topics as seen through the eyes of C# language and then quickly m oves to key technical and the .NET Framework. The first order of business is to explore the core types defined in the System.IO ar chitectur al issues for .NET developer s. namespace and come to understand how to programmatically modify a machine's directory and file structure. Once you can do so, the next task is to explore various ways to read from and write to characterbinary-based, string-based, and memory-based data stores. Tabased, ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

Finally, to showcase some of these concepts using a cohesive example, I conclude this chapter with a

I ntr oductionWindows Forms application, which allows the end user to manage a collection of Car types that complete Pa r t One - I nt r oducitong C# arecovered nd the .NET P la tfaorfile m can be persisted (and from)

using various types of the System.IO namespace and .NET

Chapter 1 - The Philosophy .NETseen in Chapter 12). As an interesting bonus, the application in question object serialization servicesof(first Chapter 2 Building C# Applications also previews the use of the System.Windows.Forms.DataGrid widget (used extensively during the Pa r t Tw o - Theof C#ADO.NET). Pr ogr am m ing La ngua ge examination

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# Exploring the System.IO Namespace

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6 - I nter faces and Collections In the framework of .NET, the System.IO namespace is the region of the base class libraries devoted to Chapter 7 Callback I nter faces, Delegates, Ev ents file-based (and memory-based) input and and output services. Like any namespace, System.IO defines a set Chapter of classes, 8 - interfaces, Advanced C# enumerations, Type Const ruction structures, Techniques and delegates, most all of which are contained in Pa mscorlib.dll. r t Thre e - PrIn ogr addition am m i ngtowthe i th .N types ET Assem contained bl ie s

within mscorlib.dll, the System.dll assembly defines

additional of the .NET System.IO namespace (given that all VS .NET projects automatically set a Chapter 9 -members Under standing Assem blies reference both assemblies, you should be ready to go). Chapter 10 -toPr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

As you will see during this chapter, a key set of types within the System.IO namespace focuses on the manipulation of physical directories and files. However, additional types provide support to read data from Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er and write data to string buffers as well as to raw memory locations. To give you a roadmap of the Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) functionality in System.IO, Table 16-1 outlines the core (nonabstract) classes. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Table 16-1: Key Members of the System.IO Namespace

Chapter 16 - The Sy stem .I O Nam espace

Creatable Meaning Chapter 17 - DataIO Access w ith ADO.NETin Life Pa rType t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Directory

These types are all used to manipulate the properties for a given directory or physical file as well as create new files and extend the current directory DirectoryInfo Chapter 20 - XML Web Ser vices structure. The Directory and File types expose their functionality primarily File I ndex as static methods. The DirectoryInfo and FileInfo types expose similar ListFileInfo of Figur es functionality from a valid object variable. Chapter 19 - ASP.NET Web Applicat ions

List of Tables

FileSystemWatcher

This type allows you to monitor the external modification to a given external file.

Path

Performs operations on System.String types that contain file or directory path information in a platform-neutral manner.

StreamWriter

These types are used to store (and retrieve) textual information to (or from) a file. These types do not support random file access.

StreamReader StringWriter StringReader FileStream

Like the StreamReader/StreamWriter types, these classes also work with textual information. However, the underlying storage is a string buffer rather than a physical file. Allows for random file access (e.g., seeking capabilities) with data represented as a stream of bytes.

MemoryStreamC# an d th Random access to, streamed e .N ET Plat f orm Se con d Eddata, it ionstored in memory, rather than a physical file. ISBN:1590590554 by Andr ew Tr oelsen 2003 (1200 pages) BufferedStreamApr ess © Provides temporary storage for a stream of bytes that may be committed This compr text star tstime. w ith a brief ov er view of the to ehensiv storagee at a later

C# language and then quickly m oves to key technical and

al issues for allow .NET you developer s. and retrieve primitive data types (integers, BinaryReader ar chitectur These types to store Booleans, strings, and whatnot) as a binary value. BinaryWriter Ta ble o f Con t en t s C# t he .NET Plat for m, Second Edition In and addition to these creatable types, System.IO defines a number of enumerations, as well as a set of I ntr oduction abstract classes (Stream, TextReader, TextWriter, and so forth) that define a shared polymorphic interface Pa One - I nt r oduci ng C# will a ndread the .NET P la tf or mof tor tall descendents. You about many

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

these types in this chapter.

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con Types d Ed it ion The Directory(Info) and File(Info) by Andr ew Tr oelsen

ISBN:1590590554

System.IO provides that pages) allow you to manipulate individual files, as well as interact with a Aprfour ess ©types 2003 (1200 machine's directory structure. The first two types, Directory and File,ofexpose creation, deletion, copying, This compr ehensiv e text star ts w ith a brief ov er view the and moving operations using various static members. The closely related FileInfo and DirectoryInfo types C# language and then quickly m oves to key technical and ar chitectur al for .NET developer expose similar functionality asissues instance-level methodss.(and therefore must be "new-ed"). In Figure 16-1, notice that the Directory and File types directly extend System.Object, while DirectoryInfo and FileInfo derive from the abstract FileSystemInfo type. Generally speaking, FileInfo and DirectoryInfo are better Tachoices ble o f Con en t s for trecursive operations, as the Directory and File class members tend to return strings rather than C# t he .NET Plat for m, Second Edition fileand objects. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - 16-1: Data Access w ithand ADO.NET Figure The FileDirectory-centric types Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

The Abstract FileSystemInfo Base Class

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

I ndex The DirectoryInfo and FileInfo types receive many behaviors from the abstract FileSystemInfo type. By and

large, the es members of the FileSystemInfo class can be used to discover general characteristics (such as List of Figur time creation, various attributes, and so forth) about a given file or directory. Table 16-2 lists some core List of of Tables properties of interest. Table 16-2: FileSystemInfo Properties

FileSystemInfo Meaning in ,Life C# an d th e .N ET Plat f orm Se con d Ed it ion Property by Andr ew Tr oelsen Attributes CreationTime

ISBN:1590590554

Apr ess © 2003 (1200 pages)

Gets or sets the attributes associated to the current file that are

This compr ehensiv e text star ts w ith a brief ov er view of the represented by the FileAttributes enumeration. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Exists

Gets or sets the time of creation for the current file or directory. Can be used to determine if a given file or directory exists.

Ta ble o f Con t en t s

Extension

Used to retrieve a file's extension.

C# and t he .NET Plat for m, Second Edition I ntrFullName oduction

Gets the full path of the directory or file.

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

LastAccessTime

Chapter 1

Gets or sets the time the current file or directory was last accessed.

- The Philosophy of .NET

Chapter 2 - Building C# Applications LastWriteTime Gets or sets the time when the current file or directory was last written Pa r t Tw o - The C# Pr ogr am m ing to.La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Name

Returns the name of a given file; is a read-only property. For directories, gets the name of the last directory in the hierarchy if Chapter 5 - Exceptions and Obj ect Lifetim e possible; otherwise, retrieves the fully qualified name. Chapter 8 - Advancedtype C# also Typedefines Const ruction Techniques The FileSystemInfo the Delete() method. This is implemented by derived types to delete Pa t Thre file e - Pr am m i ng w i ththe .N ET Assem bl ieAs s argiven orogr directory from hard drive.

well, Refresh() can (and should) be called prior to obtaining

Chapter attribute 9 information - Under standing to ensure .NET that Assem theblies statistics regarding the current file (or directory) are not outdated. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Note Always get in the habit of calling Refresh() before reading data from types derived from FileSystemInfo, as the chances are quite good that the contents of the item will be altered after Four - Le ve r a ging the .NET Libr a r ie s the initial construction.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Working with the DirectoryInfo Type

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

The first creatable type you must understand is the DirectoryInfo class. This class contains a set of members used for creating, moving, deleting, and enumerating over directories and subdirectories. In Chapter 17 - Data Access w ith ADO.NET addition to the functionality provided by its FileSystemInfo base class, DirectoryInfo offers the members in Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Table 16-3. Chapter 16 - The Sy stem .I O Nam espace

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Table 16-3: Key Members of the DirectoryInfo Type

Chapter 20 - XML Web Ser vices

DirectoryInfo I ndex

Meaning in Life

ListMembers of Figur es List of Tables

Create()

Create a directory (or subdirectories) given a path name.

CreateSubdirectory() Delete()

Deletes a directory and all its contents.

GetDirectories()

Returns an array of strings that represent all subdirectories in the current directory.

GetFiles()

Gets the files in the specified directory (as an array of FileInfo types).

Parent

This property retrieves the parent directory of the specified path.

MoveTo()

Moves a directory and its contents to a new path.

You begin working with the DirectoryInfo type by specifying a particular directory path (e.g., "C:\," "D:\WinNT," "\CompanyServer\Utils," "A:\," or what have you) as a constructor parameter. If you want access to the application directory (i.e., the directory of the executing application), use the "." notation.

Here are some examples:

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

// Create a new directory bound to the current directory. Apr ess © 2003 (1200 pages) DirectoryInfo dir1 = new DirectoryInfo("."); This compr ehensiv e text star ts w ith a brief ov er view of the // Create a new directory bound to C:\Foo\Bar, note the use of the symbol @. C# language and then quickly m oves to key technical and DirectoryInfoar chitectur dir2 =al new issuesDirectoryInfo(@"C:\Foo\Bar"); for .NET developer s.

Ta ble o f Con t en t s

If you map to aSecond nonexistent C# and attempt t he .NETtoPlat for m, Editiondirectory, you are thrown a System.IO.DirectoryNotFoundException. Assuming that an exception has not been thrown, you can investigate the underlying directory contents using any of the properties inherited from FileSystemInfo. To illustrate, the following class creates a new Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m DirectoryInfo type mapped to "C:\WinNT" (adjust your letter drive and path if need be) and dumps out a Chapter 1 - The Philosophy of .NET number of interesting statistics (see Figure 16-2 for output): I ntr oduction

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

class3 MyDirectory Chapter - C# Language Fundamentals {

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

public static void Main(String[] args) - Exceptions and Obj ect Lifetim e { Chapter 6 - I nter faces and Collections DirectoryInfo dir = new DirectoryInfo(@"C:\WinNT"); Chapter 7 - Callback I nter faces, Delegates, and Ev ents // Dump directory information. Chapter 8 - Advanced C# Type Const ruction Techniques Console.WriteLine("***** Directory Info *****"); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Console.WriteLine("FullName: {0} ", dir.FullName); Chapter 9 - Under standing .NET Assem blies Console.WriteLine("Name: {0} ", dir.Name); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Console.WriteLine("Parent: {0} ", dir.Parent); Chapter 11 - Type Reflection, Late Binding, and Attr ibuteBased ogramm ing Console.WriteLine("Creation: {0} ",Pr dir.CreationTime); Pa r t Four - Le ve r a ging the .NET Libr a r ie s Console.WriteLine("Attributes: {0} ", dir.Attributes.ToString()); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Laydir.Root); er Console.WriteLine("Root: {0} ", Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Console.WriteLine("**************************\n"); Chapter}14 - A Better Paint ing Fr amew or k ( GDI + ) } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 5

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 16-2: %windir% directory information

The FileAttributes Enumeration As shown in the previous code sample, the Attributes property obtains various traits for the current directory or file, all of which are represented by the FileAttributes enumeration. Table 16-4 describes some core values. Table 16-4: Select FileAttributes Values

FileAttributes Meaning C# an d th e .N ET Plat f orm , Se in con dLife Ed it ion Enumeration byValue Andr ew Tr oelsen

ISBN:1590590554

Apr ess © 2003 (1200 pages)

Archive

Represents the archive status of the file or directory.

This compr ehensiv e text star ts w ith a brief ov er view of the Applications use this attribute to mark files for backup or C# language and then quickly m oves to key technical and removal. ar chitectur al issues for .NET developer s.

Compressed Ta ble o f Con t en t s Directory

The file or directory is compressed. The item is a directory (rather than a file).

C# and t he .NET Plat for m, Second Edition

Encrypted

I ntr oduction

The file or directory is encrypted.

Pa rHidden t One - I nt r oduci ng C# a nd the .NETThe P la tffile or m or

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Normal

directory is hidden and thus is not included in an ordinary directory listing. The file or directory is normal and has no other attributes set. This attribute is valid only if used alone.

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Offline4 Chapter

The file directory is offline. The data of the file is not - Obj ect -Or iented Pr ogr am ming w ithorC#

Chapter 5

immediately available. - Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections ReadOnly The file or directory is read only.

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

System The fileTechniques is a system file. The file is part of the operating system Chapter 8 - Advanced C# Type Const ruction or is used Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s exclusively by the operating system. Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e with .N ET Plat f orm , Se con d Ed it ion Type Enumerating Files the DirectoryInfo by Andr ew Tr oelsen

ISBN:1590590554

You can extend the MyDirectory Aprcurrent ess © 2003 (1200 pages) class to use some methods of the DirectoryInfo type. First, use the GetFiles() method to read all *.bmp under theov "C:\WinNT" directory. This method returns an This compr ehensiv e files text located star ts w ith a brief er view of the array of FileInfo types that you can iterate over using the foreach construct and thus use recursively if C# language and then quickly m oves to key technical and ar chitectur al issues for are .NETexplored developer s. in this chapter): needed (full details of the FileInfo type later class MyDirectory { C# and t he .NET Plat for m, Second Edition public static void Main(String[] args) I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m DirectoryInfo dir = new DirectoryInfo(@"C:\WinNT"); Chapter 1 - The ...Philosophy of .NET Chapter 2 - Building Applications // GetC#all files with a *.bmp extension. Pa r t Tw o - TheFileInfo[] C# Pr ogr am m ing La ngua ge bitmapFiles = dir.GetFiles("*.bmp");

Ta ble o f Con t en t s

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj -Or iented ogr am ming w ith C# //ect How manyPrwere found?

Chapter 5 Chapter 6

- Exceptions and Obj ect Lifetim e Console.WriteLine("Found {0} *.bmp files\n", bitmapFiles.Length); - I nter //faces Nowand print Collections out info for each file.

Chapter 7

foreach f in - Callback I nter(FileInfo faces, Delegates, and bitmapFiles) Ev ents

Chapter 8

{ - Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am mConsole.WriteLine("***************************\n"); i ng w i th .N ET Assem bl ie s

Chapter 9

Console.WriteLine("File name: {0} ", f.Name); - Under standing .NET Assem blies

Console.WriteLine("File size: {0} ", f.Length); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Console.WriteLine("Creation: {0} ", ing f.CreationTime); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm Pa r t Four - Le ve r a ging Console.WriteLine("Attributes: the .NET Libr a r ie s

{0} ", f.Attributes.ToString()); Console.WriteLine("***************************\n"); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er } Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 -run Data w ith ADO.NET Once you theAccess application, you see a listing something like that shown in Figure 16-3. (Your bitmaps may Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces vary!)

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 16-3: Bitmap file information

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Platwith f orm , Se conDirectoryInfo d Ed it ion Creating Subdirectories the Type by Andr ew Tr oelsen

ISBN:1590590554

You can programmatically extend directory structure using the DirectoryInfo.CreateSubdirectory() method. Apr ess © 2003 (1200 a pages) This method can This create a single subdirectory, well as multiple compr ehensiv e text star ts as w ith a brief ov er viewnested of the subdirectories. To illustrate, here is a block of code that extends the directory structure of "C:\WinNT" with some custom subdirectories: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

class MyDirectory { Ta ble o f Con t en t s public static void Main(String[] args) C# and t he .NET Plat for m, Second Edition { I ntr oduction DirectoryInfo dir = new DirectoryInfo(@"C:\WinNT"); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m ... Chapter 1 - The Philosophy of .NET try Chapter 2 - Building C# Applications { Pa r t Tw o - The C# Pr ogr amCreate m ing La ngua ge // \MyFoo off root. Chapter 3 - C# Language Fundamentals dir.CreateSubdirectory("MyFoo"); Chapter 4 - Obj ect -Or// iented Pr ogr am\MyBar\MyQaaz ming w ith C# Create off root. Chapter 5 - Exceptions and Obj ect Lifetim e dir.CreateSubdirectory(@"MyBar\MyQaaz"); Chapter 6 - I nter } faces and Collections catch(IOException e) and { Console.WriteLine(e.Message);} Chapter 7 - Callback I nter faces, Delegates, Ev ents } Chapter 8 - Advanced C# Type Const ruction Techniques }r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Pa Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

If you examine your %windir% directory using Windows Explorer, you will see the new subdirectories are present and accounted for (Figure 16-4).

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 16-4: Creating subdirectories Although you are not required to capture the return value of the CreateSubdirectory() method, be aware that a DirectoryInfo type representing the newly created item is passed back on successful execution: // CreateSubdirectory() returns a DirectoryInfo item representing the new item. try { DirectoryInfo d = dir.CreateSubdirectory("MyFoo"); Console.WriteLine("Created: {0} ", d.FullName); d = dir. CreateSubdirectory(@"MyBar\MyQaaz"); Console.WriteLine("Created: {0} ", d.FullName);

} C# an d e) th e { .N ET Plat f orm , Se con d Ed it ion catch(IOException Console.WriteLine(e.Message); } by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET , Se con d Ed itClass ion The Static Members ofPlat thef orm Directory by Andr ew Tr oelsen

ISBN:1590590554

Now that you have Aprseen ess ©the 2003DirectoryInfo (1200 pages) type in action, you can learn about the Directory type. By and large, the members of the Directory the This compr ehensiv e mimic text star ts same w ith a functionality brief ov er viewprovided of the by the instance-level members defined by DirectoryInfo, with a few notable exceptions (GetLogicalDrives() for one). They also generally C# language and then quickly m oves to key technical and ar chitectur al issues for to .NET return strings rather than objects. Due thedeveloper commons.public interface of each type, I assume you will consult online help to view each member of the Directory class. TaThis ble ofinal f Con iteration t en t s of the MyDirectory class lists the names of all drives mapped to the current computer

and uses static Directory.Delete() C# and t he the .NET Plat for m, Second Editionmethod to remove the \MyFoo and \MyBar\MyQaaz subdirectories previously I ntr oduction created: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter - The Philosophy of .NET class1 MyDirectory Chapter { 2

- Building C# Applications

Pa r t Tw opublic - The C# static Pr ogr am mvoid ing La ngua Main(String[] ge

args) { Chapter 3 - C# Language Fundamentals DirectoryInfo dir = wnew DirectoryInfo(@"C:\WinNT"); Chapter 4 - Obj ect -Or iented Pr ogr am ming ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

//faces Nowand call some static members of the Directory class. - I nter Collections

Chapter 7

// List current computer. - Callback I nterall faces,drives Delegates,on and Ev ents

string[] drives = Directory.GetLogicalDrives(); Console.WriteLine("Here are your drives:"); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s foreach(string s in drives) Chapter 9 - Under standing .NET Assem blies { Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Console.WriteLine("->{0} ", s); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing } Pa r t Four - Le ve r a ging the .NET Libr a r ie s // Delete what was created. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Console.Write("Going to delete\n->" + dir.FullName + Chapter 13 - Building"\\MyBar\\MyQaaz.\nand\n->" a Bet ter Win dow ( Int roducin g Window s + Fordir.FullName ms) + Chapter 14 - A Better"\\MyFoo.\n" Paint ing Fr amew or+"Press k ( GDI + ) a key to continue!"); Chapter 15 - Pr Console.Read(); ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace try Chapter 17 - Data { Access w ith ADO.NET Pa r t Fi ve - W e b Appl icaDirectory.Delete(@"C:\WinNT\MyFoo"); ti ons and X ML W e b Se r vi ces Chapter 18 - ASP.NET // Web The Pagessecond and Web parameter Contr ols specifies if you // wish to blow away any internal subdirectories. Chapter 19 - ASP.NET Web Applicat ions Directory.Delete(@"C:\WinNT\MyBar", true); Chapter 20 - XML Web Ser vices } I ndex List of Figur es catch(IOException e) List of Tables { Console.WriteLine(e.Message); } } } Chapter 8

- Advanced C# Type Const ruction Techniques

Great! At this point you have investigated some core behaviors of the Directory and DirectoryInfo types. Next, you need to learn how to create, open, close, and destroy the files that populate a given directory. SOURCE CODE

The MyDirectoryApp project is located under the Chapter 16 subdirectory.

an d th e .N ET Plat f orm , Se con d Ed it ion The FileInfoC#Class ISBN:1590590554

by Andr ew Tr oelsen

The role of the FileInfo to obtain Apr ess class © 2003is (1200 pages) a number of details regarding existing files on your hard drive (time created, size, file attributes, and so star forth) asithwell as aid the of creation, copying, moving, and This compr ehensiv e text ts w a brief ov erinview the destruction of files. In addition to the set of functionality inherited by FileSystemInfo, Table 16-5 describes C# language and then quickly m oves to key technical and ar chitectur al to issues for .NETclass. developer s. some core members unique the FileInfo Table 16-5: FileInfo Core Members Ta ble o f Con t en t s

Meaning in Life C# FileInfo and t he .NET Plat for m, Second Edition I ntrMember oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

AppendText()

Chapter 1

Creates a StreamWriter type (described later) that appends text to a file

- The Philosophy of .NET

CopyTo() Copies an existing file to a new file Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Create()

Chapter 3

Creates a new file and returns a FileStream type (described later) to interact with the created file

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# CreateText() Creates StreamWriter type that writes a new text file Chapter 5 - Exceptions and Obj ect aLifetim e Chapter 6 - I nter faces and Collections Delete() Deletes the file to which a FileInfo instance is bound Chapter 7 - Callback I nter faces, Delegates, and Ev ents

Directory instance the parent directory Chapter 8 - Advanced C# Gets Type an Const ructionofTechniques Pa rDirectoryName t Thre e - Pr ogr am m i ng Gets w i th .N ETfull Assem ie sa the pathblto

Chapter 9

file

- Under standing .NET Assem blies

Length Gets the size ofexts, the current file or directory Chapter 10 - Pr ocesses, AppDomains, Cont and Threads Chapter 11 - Type Reflection, LateaBinding, and Based Pr ogramm ing the option to specify a MoveTo() Moves specified fileAttr toibutea new location, providing Pa r t Four - Le ve r a ging the new .NET filename Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Name13 - Building a BetGets thedow name the file Chapter ter Win ( Int of roducin g Window s For ms) Chapter 14 - A Better PaintOpens ing Fr amew k ( GDI +) Open() a fileorwith various read/write and sharing privileges Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

OpenRead()

Creates a read-only FileStream

Chapter 16 - The Sy stem .I O Nam espace

Chapter 17 - Data Access wCreates ith ADO.NET OpenText() a StreamReader type (described later) that reads from an existing Pa r t Fi ve - W e b Appl ica ti ons and text fileX ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

OpenWrite()

Creates a read/write FileStream type

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

First, you should be aware that many methods defined by FileInfo return a specific stream-centric type (FileStream, StreamWriter, StreamReader, and so forth) that allows you to begin reading and writing data List of Figur es to (or reading from) the associated file in a variety of ways. We'll check out these types later in this List of Tables chapter; however, until then, the following code block illustrates the most generic (and least flexible) way to create a file programmatically: I ndex

public class FileManipulator { public static int Main(string[] args) { // Make a new file on the C: drive. FileInfo f = new FileInfo(@"C:\Test.txt"); FileStream fs = f.Create(); // Print some basic traits of the test.txt file. Console.WriteLine("Creation: {0} ", f.CreationTime); Console.WriteLine("Full name: {0} ", f.FullName); Console.WriteLine("Full atts: {0} ", f.Attributes.ToString()); Console.Write("Press a key to delete file"); Console.Read();

// Close the file stream and delete the file. C# an d th e .N ET Plat f orm , Se con d Ed it ion fs.Close(); ISBN:1590590554 by Andr ew Tr oelsen f.Delete(); Apr ess © 2003 (1200 pages) return 0; This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

} }

Notice that the FileInfo.Create() method returns a FileStream type that allows you to close the new file before removing it from the hard drive. (You will see additional uses of FileStream later in the chapter.) C# and t he .NET Plat for m, Second Edition When you run this application, you will be able to find your newly created *.txt file under the C drive.

Ta ble o f Con t en t s I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Examining the FileInfo.Open() Method - The Philosophy of .NET

Chapter 1 Chapter 2

- Building C# Applications

The FileInfo.Open() method can be used to open existing files as well as create new files with far more precision than FileInfo.Create(). To illustrate, ponder the following logic:

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

// Open (or create) a file with read/write attributes (no sharing), - Exceptions and Obj ect Lifetim e // and store file handle in a FileStream object. Chapter 6 - I nter faces and Collections FileInfo f2 = new FileInfo(@"C:\HelloThere.ini"); Chapter 7 - Callback I nter faces, Delegates, and Ev ents FileStream s = f2.Open(FileMode.OpenOrCreate,FileAccess.ReadWrite, Chapter 8 - Advanced C# Type Const ruction Techniques FileShare.None); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s ... Chapter 9 - Under standing .NET Assem blies s.Close(); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads f2.Delete(); Chapter 5

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

This version of the overloaded requires three parameters. The first parameter specifies Chapter 12 - Obj ect Ser ialization Open() and the method .NET Remoting Lay er the general flavor ofathe request (e.g., make a newsfile, open an existing file, append to a file, and so Chapter 13 - Building Betopen ter Win dow ( Int roducin g Window For ms) on), which using FileMode enumeration (Table 16-6). Chapter 14 - isAspecified Better Paint ing the Fr amew or k ( GDI +) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Table 16-6: FileMode Chapter 16 - The Sy stem Enumeration .I O Nam espaceValues

Chapter 17 - Data Access w ithMeaning ADO.NET in Life FileMode Pa rEnumeration t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Value Chapter 19 - ASP.NET Web Applicat ions

Append Opens the file if it exists and seeks to the end of the file. If the specified Chapter 20 - XML Web Ser vices I ndex List of Figur es ListCreate of Tables

file does not exist, a new file is created. Be aware that FileMode.Append can only be used in conjunction with FileAccess.Write. Specifies that the operating system should create a new file. Be very aware that if the file already exists, it is overwritten!

CreateNew

Specifies that the operating system should create a new file. If the file already exists, an IOException is thrown.

Open

Specifies that the operating system should open an existing file.

OpenOrCreate

Specifies that the operating system should open a file if it exists; otherwise, a new file should be created.

Truncate

Specifies that the operating system should open an existing file. Once opened, the file should be truncated so that its size is zero bytes.

The second parameter, a value from the FileAccess enumeration, is used to determine the read/write behavior of the underlying stream (Table 16-7).

Table 16-7: FileAccess Enumeration Values

C# an d th e .N ET Plat f orm , Se con d Ed it ion

FileAccess by Andr ew Tr oelsen Meaning in Life Enumeration Apr Value ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the Specifies read-only access to the file (i.e., data can only be C# language and then quickly m oves to key technical and from the s. file) ar chitectur al issues obtained for .NET developer

Read ReadWrite

Specifies read and write access to the file (i.e., data can be added to or obtained from the file)

Ta ble o f Con t en t s

C# Write and t he .NET Plat for m, Second Edition Specifies write access to the file (i.e., data can only be added to

the file)

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Finally,1you- The havePhilosophy the third parameter (FileShare), which specifies how the currently open file is to be Chapter of .NET shared2among otherC# fileApplications handlers (Table 16-8). Chapter - Building Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Table 16-8: FileShare Enumeration Chapter 3 - C# Language FundamentalsValues Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# FileShare Meaning in Life

Chapter 5 - Exceptions and Obj ect Lifetim e Enumeration Chapter 6 - I nter faces and Collections Value Chapter 7

- Callback I nter faces, Delegates, and Ev ents

None 8 - Advanced C# Type Declines sharing of the current file. Any request to open the file (by this Chapter Const ruction Techniques process or another Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s process) fails until the file is closed. Chapter Read 9

- Under standing .NET Assem blies Allows subsequent opening of the file for reading. If this flag is not

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads specified, any request to open the file for reading (by this process or Chapter 11 - Type Reflection, another Late Binding, and Attr ogramm ing process) failsibuteuntilBased the filePris closed. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

ReadWrite Allows opening Chapter 12 - Obj ect Ser ialization and subsequent the .NET Remoting Layof erthe file for reading or writing. If this flag is not specified, any request to open the file for writing or reading (by this process or another process) fails until the file is closed.

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter Windows Form s Contr ols of the file for writing. If this flag is not Write 15 - Pr ogr am ming with Allows subsequent opening Chapter 16 - The Sy stem .I O Nam specified, espace any request to open the file for writing (by this process or

process) fails until the file is closed. Chapter 17 - Data Access w ithanother ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

The FileInfo.OpenRead() and FileInfo.OpenWrite() Members

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

I ndex In addition to the Open() method, the FileInfo class also has members named OpenRead() and

OpenWrite(). List of Figur es As you would imagine, these methods return a properly configured read-only or write-only FileStream List of Tables type: // Get a FileStream object with read-only permissions. FileInfo f3 = new FileInfo(@"C:\boot.ini"); FileStream readOnlyStream = f3.OpenRead(); ... readOnlyStream.Close(); // Now get a FileStream object with write-only permissions. FileInfo f4 = new FileInfo(@"C:\config.sys"); FileStream writeOnlyStream = f4.OpenWrite(); ... writeOnlyStream.Close();

The FileInfo.OpenText(), FileInfo.CreateText(), and

FileInfo.AppendText() C# an d th e .N ET Members Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

Another "open-centric" member of the FileInfo type is OpenText(). Unlike Open(), OpenRead(), and Apr ess © 2003 (1200 pages) OpenWrite(), the OpenText() method returns an instance of the StreamReader type, rather than a This compr ehensiv e text star ts w ith a brief ov er view of the FileStream-derived type: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

// Get a StreamReader object. FileInfo f5 = new FileInfo(@"C:\bootlog.txt"); TaStreamReader ble o f Con t en t s sreader = f5.OpenText(); C# and t he .NET Plat for m, Second Edition ... I ntr sreader.Close(); oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET The final methods interest at this point are CreateText() and AppendText(), both of which return a Chapter 2 two - Building C# of Applications

StreamWriter reference, shown here: Pa r t Tw o - The C# Pr ogr am as m ing La ngua ge Chapter 3

- C# Language Fundamentals // Get StreamWriters. Chapter 4 some - Obj ect -Or iented Pr ogr am ming w ith C#

FileInfo f6 = newand FileInfo(@"D:\AnotherTest.txt"); Chapter 5 - Exceptions Obj ect Lifetim e f6.Open(FileMode.Create, FileAccess.ReadWrite); Chapter 6 - I nter faces and Collections StreamWriter swriter = f6.CreateText(); - Callback I nter faces, Delegates, and Ev ents ... Chapter 8 - Advanced C# Type Const ruction Techniques swriter.Close(); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s FileInfo f7 = new FileInfo(@"D:\FinalTest.txt"); Chapter 9 - Under standing .NET Assem blies f7.Open(FileMode.Create, FileAccess.ReadWrite); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads StreamWriter swriterAppend = f7.AppendText(); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing ... Pa r t Four - Le ve r a ging the .NET Libr a r ie s swriterAppend.Close(); Chapter 7

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter At this point, 14 - Ayou Better have Paint a good ing Frfeel amew fororthe k ( GDI functionality +) provided by the FileInfo type. (You will see exactly

what to15 do- with the StreamReader, andols StreamWriter types shortly.) Chapter Pr ogr amFileStream, ming with Windows Form s Contr Chapter 16 - The Sy stem .I O Nam espace

Note Be aware that the File type provides almost identical functionality using a number of static members. You will see the File type in action where appropriate, but be sure to check out online Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces help for an exhaustive listing of each member.

Chapter 17 - Data Access w ith ADO.NET Pa r t

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion The Abstract Stream Class by Andr ew Tr oelsen

ISBN:1590590554

In the world of IOApr manipulation, a stream ess © 2003 (1200 pages) represents a chunk of data. The abstract System.IO.Stream class defines a number of members that star provide support synchronous This compr ehensiv e text ts w ith a brieffor ov er view of the and asynchronous interactions with the storage medium (e.g., an underlying file or memory location). Figure 16-5 shows the basic stream C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. hierarchy.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Figure Stream-derived types and Attr ibute- Based Pr ogramm ing Chapter 11 - 16-5: Type Reflection, Late Binding, Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Stream descendents represent data as a raw stream of bytes (rather than text-based data). Also, some

Chapter 13 - Building a Bet ter Winseeking, dow ( Int roducin g Window s For ms) Streams-derived types support which refers to the process of obtaining and adjusting the current Chapter A Better Paint Fr amew or k ( GDI + ) the functionality provided by the Stream class, take note of position14in -the stream. Toing begin understanding Chapter 15members - Pr ogr amdescribed ming with in Windows Form s Contr ols the core Table 16-9. Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Table 16-9: Abstract Stream Members Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Stream Member

Meaning in Life

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices whether the current stream supports reading, seeking, and/or CanRead Determine I ndex writing.

CanSeek

List of Figur es

CanWrite

List of Tables

Close()

Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.

Flush()

Updates the underlying data source or repository with the current state of the buffer and then clears the buffer. If a stream does not implement a buffer, this method does nothing.

Length

Returns the length of the stream, in bytes.

Position

Determines the position in the current stream.

Read() ReadByte()

Reads a sequence of bytes (or a single byte) from the current stream and advances the current position in the stream by the number of bytes read.

Seek()

Sets the position in the current stream.

SetLength()

Sets the length of the current stream.

Write()

a sequence bytes (or a dsingle byte) to the current stream and advance C# Write an d th e .N ET Platoff orm , Se con Ed it ion

WriteByte()

position in this stream by the number of bytes written. ISBN:1590590554 by the Andrcurrent ew Tr oelsen Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Working with FileStreams

The FileStream class provides implementations for the abstract Stream members in a manner appropriate It is a fairly primitive stream; it can read or write bytes or arrays of bytes. Like the Tafor blefile-based o f Con t enstreaming. ts DirectoryInfo and FileInfo types, Edition FileStream provides the ability to open existing files as well as create new C# and t he .NET Plat for m, Second files. FileStreams are typically configured using the FileMode, FileAccess, and FileShare enumerations. I ntr oduction For example, the following logic creates a new file (test.dat) in the application directory: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET // Create a newC#file in the working directory. Chapter 2 - Building Applications

FileStream = Lanew Pa r t Tw o - The C#myFStream Pr ogr am m ing nguaFileStream("test.dat", ge FileAccess.ReadWrite); ChapterFileMode.OpenOrCreate, 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e Let's experiment with the synchronous read/write capabilities of the FileStream type. To write a stream of

Chapter I nter facescalls and to Collections bytes to6 a -file, make the inherited WriteByte() or Write() method, both of which advance the Chapter 7 Callback I nter faces, Delegates, Ev entsback from a file, simply call Read() or ReadByte(). internal file pointer automatically. To read and the bytes Chapter Advanced C# Type Const ruction Techniques Here is8an-example: Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

standing .NET Assem blies // Write- Under bytes to the *.dat file.

Chapter 10 - iPr = ocesses, Cont exts, and Threads for(int 0; i AppDomains, < 256; i++) Chapter myFStream.WriteByte((byte)i); 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the position. .NET Libr a r ie s // Reset internal

Chapter 12 - Obj ect Ser ialization myFStream.Position = 0;and the .NET Remoting Lay er Chapter 13 - bytes Buildingfrom a Bet ter Win *.dat dow ( Int file. roducin g Window s For ms) // Read the Chapter 14 - iA = Better Fr amew or k ( GDI + ) for(int 0; Paint i < ing 256; i++) Chapter Console.Write(myFStream.ReadByte()); 15 - Pr ogr am ming with Windows Form s Contr ols

myFStream.Close(); Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

SOURCE CODE

The BasicFileApp project is included under the Chapter 16 subdirectory.

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex

Working with MemoryStreams

List of Figur es List of Tables

The MemoryStream type works much like FileStream, with the obvious difference that you are now writing to memory rather than a physical file. Given that each of these types derives from Stream, you can update the previous FileStream logic to use a MemoryStream type with minor adjustments: // Create a memory stream with a fixed capacity. MemoryStream myMemStream = new MemoryStream(); myMemStream.Capacity = 256; // Write bytes to stream. for(int i = 0; i < 256; i++) myMemStream.WriteByte((byte)i); // Reset internal position. myMemStream.Position = 0; // Read bytes from stream. for(int i = 0; i < 256; i++) Console.Write(myMemStream.ReadByte());

myMemStream.Close(); C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

ess is © 2003 (1200 to pages) The output of thisApr logic identical that of the previous FileStream example. The only difference is where you store the information (toehensiv file or ememory). toov the members, MemoryStream This compr text star tsInwaddition ith a brief er inherited view of the C# language and then quickly m oves code to keyused technical and supplies other members. For example, the previous the Capacity property to specify how much chitectur issues for operation. .NET developer s. 16-10 shows the core MemoryStream type memory to carvearout for thealstreaming Table members. Ta ble o f Con t en t s

Table 16-10: MemoryStream Core Members

C# and t he .NET Plat for m, Second Edition I ntrMemoryStream oduction

Meaning in Life

Pa rMember t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Capacity

Gets or sets the number of bytes allocated for this stream

Pa rGetBuffer() t Tw o - The C# Pr ogr am m ing La nguathe ge Returns

array of unsigned bytes from which this stream was

Chapter 3

- C# Language Fundamentals created

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

ToArray()

Chapter 6

Writes the entire stream contents to a byte array, regardless of the Position property

- I nter faces and Collections WriteTo() Writes the entire Chapter 7 - Callback I nter faces, Delegates, and contents Ev ents of this MemoryStream to another streamChapter 8

derived type (such as a file) - Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Notice 9the-possible interplay between the MemoryStream and FileStream types. Using the WriteTo() Chapter Under standing .NET Assem blies method, easilyAppDomains, transfer dataCont stored memory to a file. Furthermore, you can also retrieve the Chapter 10you - Prcan ocesses, exts,inand Threads memory a byte array: Chapter 11stream - Type as Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

// Dump data to and file. Chapter 12 - memory Obj ect Ser ialization the .NET Remoting Lay er FileStream dumpFile new FileMode.Create, Chapter 13 - Building a Bet ter =Win dow FileStream("Dump.dat", ( Int roducin g Window s For ms) ChapterFileAccess.ReadWrite); 14 - A Better Paint ing Fr amew or k ( GDI + )

myMemStream.WriteTo(dumpFile); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols // Dump memory data to a byte array. byte[] bytesinMemory = myMemStream.ToArray(); Chapter 17 - Data Access w ith ADO.NET myMemStream.Close(); Chapter 16 - The Sy stem .I O Nam espace

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

Working with BufferedStreams

I ndex

List of Figur es

The final Stream-derived type to consider here is BufferedStream. This type can be used as a temporary location to read or write information, which can later be committed to permanent storage. For example, assume you have opened a data file and need to write out a large series of bytes. While you could stuff each item directly to file using FileStream.Write(), you may wish to help optimize the process by storing the new items in a BufferedStream type and making a final commit when each addition has been accounted for. In this way, you can reduce the number of times you must hit the physical file. Here is an example:

List of Tables

// Build a buffer attached to a valid FileStream. BufferedStream myFileBuffer = new BufferedStream(dumpFile); // Add some bytes to the buffer. byte[] str = { 127, 0x77, 0x4, 0x0, 0x0, 0x16}; myFileBuffer.Write(str, 0, str.Length); // Commit changes to file. myFileBuffer.Close(); // Automatically flushes.

SOURCE CODE

C# d th e .N ET Plat f illustrates orm , Se con d Ed it ion TheanStreamer project working with the FileStream, MemoryStream, and ISBN:1590590554 by Andr ew Tr oelsen BufferedStream types, and is located under the Chapter 16 subdirectory. Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , and Se conStreamReaders d Ed it ion Working with StreamWriters by Andr ew Tr oelsen

ISBN:1590590554

The StreamWriterApr and classes are useful whenever you need to read or write characteressStreamReader © 2003 (1200 pages) based data (e.g.,This strings). Both of these default compr ehensiv e text types star tswork w ith by a brief ov erwith viewUnicode of the characters; however, this can be changed by supplying a properly configured System.Text.Encoding object reference. To keep things C# language and then quickly m oves to key technical and ar chitectur al default issues for .NET developer s. fits the bill. (Be sure to check out the System.Text simple, let's assume that the Unicode encoding namespace for other possibilities.) TaStreamReader ble o f Con t en t sderives from an abstract type named TextReader, as does the related StringReader type

(discussed laterPlat in for thism,chapter). The TextReader base class provides a very limited set of functionality to C# and t he .NET Second Edition each of these descendents, specifically the ability to read and peek into a character stream. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

The StreamWriter type (as well as StringWriter, also examined later in this chapter) derives from an - The Philosophy of .NET abstract base class named TextWriter. This class defines members that allow derived types to write textual Chapter 2 - Building C# Applications data to a given character stream. The relationship between each of these new IO-centric types is shown in Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Figure 16-6. Chapter 1

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 16-6: Readers and writers To understand the writing capabilities of the StreamWriter class, you need to examine the base class functionality inherited from the TextWriter type. This abstract class defines the members described in Table 16-11. Table 16-11: Core Members of TextWriter

TextWriter C# an d thMeaning Life e .N ET Platin f orm , Se con d Ed it ion Member Name by Andr ew Tr oelsen

ISBN:1590590554

Apr ess © 2003 (1200 pages)

Close()

Closes the writer and frees any associated resources. In the process,

This compr ehensiv e text star ts w ith a brief ov er view of the the buffer is automatically flushed. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Flush()

Clears all buffers for the current writer and causes any buffered data to be written to the underlying device, but does not close the writer.

Ta ble o f Con t en t s NewLine

Used to make the new line constant for the derived writer class. The

C# and t he .NET Plat for m, Second default Edition line terminator is a carriage return followed by a line feed ("\r\n"). I ntr oduction

Write()

Writes a line to the text stream, without a new line constant.

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter WriteLine() 1 - The Philosophy of Writes .NET a line to the text stream, with a new line constant. Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

The last members of Fundamentals the TextWriter class probably look familiar to you. If you recall, the Chapter 3 two - C# Language

System.Console type has similar members that write textual data to the standard output device. (In fact - Obj ect -Or iented Pr ogr am ming w ith C# Console.In inherits from TextWriter and Console.Out from TextReader.) Here, TextWriter moves the Chapter 5 - Exceptions and Obj ect Lifetim e information to a specified file. Chapter 4 Chapter 6

- I nter faces and Collections

Chapter 7 - Callback I nter faces, andappropriate Ev ents The derived StreamWriter classDelegates, provides an implementation for the Write(), Close(), and Chapter - Advanced C# Type Const ruction Techniques Flush()8methods, as well as defines the additional AutoFlush property. This property, when set to true, Pa r t ThreStreamWriter e - Pr ogr am mto i ngflush w i thall .N ET Assem bl ie s forces data every time

you perform a write operation. Be aware that you can gain

Chapter 9 - Under standing .NETAutoFlush Assem bliesto false, provided you always call Close() when you are done better performance by setting Chapter writing 10 with- aPrStreamWriter. ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Writing to a Text File

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter Building aofBet ter Win with dow the ( Int StreamWriter roducin g Window s For ms)following class creates a new file named Now for13an- example working type. The Chapter thoughts.txt 14 - A using Better thePaint FileInfo ing Frclass. amew or Using k ( GDI the + )CreateText() method, you can obtain a valid StreamWriter.

At this point, you addming some textual dataForm to the new ols file, as shown here: Chapter 15 - Pr ogr am with Windows s Contr Chapter 16 - The Sy stem .I O Nam espace Chapter 17 class - Data Access w ith ADO.NET public MyStreamWriterReader Pa {r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter public 18 - ASP.NET static Web Pages int Main(string[] and Web Contr ols args) Chapter { 19 - ASP.NET Web Applicat ions

//Web Make a file in the application directory. Chapter 20 - XML Ser vices FileInfo f = new FileInfo("Thoughts.txt"); List of Figur es // Get a StreamWriter and write some stuff. List of Tables StreamWriter writer = f.CreateText(); writer.WriteLine("Don't forget Mother's Day this year..."); writer.WriteLine("Don't forget Father's Day this year..."); writer.WriteLine("Don't forget these numbers:"); for(int i = 0; i < 10; i++) writer.Write(i + " "); writer.Write(writer.NewLine); // Insert a carriage return. // Closing automatically flushes! writer.Close(); Console.WriteLine("Created file and wrote some thoughts..."); } } I ndex

If you locate this new file, you should be able to double-click it to open it a la Notepad. Figure 16-7 shows the content of your new file.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and chitectur al issues for *.txt .NETfile developer s. Figure 16-7:arThe contents of your

cant see, TaAs bleyou o f Con en t s the StreamWriter has indeed written your data to a file. Do be aware that the Write() and WriteLine() methods each been C# and t he .NET Plat forhave m, Second Editionoverloaded numerous times to provide a number of ways to add textual and numeric data (which defaults to Unicode encoding).

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Reading - The from Philosophy a Text of .NET File

Chapter 1 Chapter 2

- Building C# Applications

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Now understand to programmatically Pa r t Twyou o - need The C#toPr ogr am m inghow La ngua ge

read data from a file using the corresponding StreamReader type. As you probably recall, this class derives from TextReader, which offers the Chapter 3 - C# Language Fundamentals functionality described in Table 16-12. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Table 16-12: TextReader Core Members

Chapter 7 - Callback I nter faces, Delegates,in and Ev ents TextReader Member Meaning Life Chapter Name8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Peek() - Under standing .NET Returns the next available character without actually changing the Assem blies position of the reader

Chapter 9

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, Pr ogramm ing Read() Reads data and fromAttr anibuteinputBased stream Pa r t Four - Le ve r a ging the .NET Libr a r ie s

ReadBlock()

Reads a maximum of count characters from the current stream and writes the data to a buffer, beginning at index

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Chapter ReadLine() 14 - A Better Paint ing Fr Reads amew a orline k ( GDI of +characters ) from the current stream and returns the

as a string nullols string indicates EOF) Chapter 15 - Pr ogr am ming withdata Windows Form s(a Contr Chapter 16 - The Sy stem .I O Nam espace

ReadToEnd()

Reads all characters from the current position to the end of the TextReader and returns them as one string

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

If you now extend the current MyStreamWriterReader class to use a StreamReader, you can read in the

Chapter - ASP.NET Applicat ions textual 19 data from the Web thoughts.txt file, as shown here: Chapter 20 - XML Web Ser vices I ndex

public class MyStreamWriterReader { List of Tables public static int Main(string[] args) { // Writing logic as before. ... // Now read it all back in using a StreamReader. Console.WriteLine("Here are your thoughts:\n"); StreamReader sr = File.OpenText("Thoughts.txt"); string input = null; while ((input = sr.ReadLine()) != null) Console.WriteLine (input); sr.Close(); return 0; } } List of Figur es

Running the program, the output shown Figure 16-8. C# anyou d thwould e .N ETsee Plat f orm , Se con d Edin it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s

Figure 16-8: Reading from a file

C# and t he .NET Plat for m, Second Edition I ntr oduction

Here, you obtained a valid StreamReader using the static File.OpenText() method. The read logic makes use of StreamReader.Peek() to ensure that you have an additional character ahead of the reader's current Chapter 1 If -so, The Philosophy .NET position. you read the ofnext line and pump it to the console. To obtain the contents of the entire file, Chapter 2 Building C# Applications you could avoid the "peeking" and simply call ReadToEnd(), as shown here: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

// Be sure to add a reference to System.Windows.Forms.dll - Obj ect -Or iented Pr ogr am ming w ith C# // and specify a proper 'using' directive to access the Chapter 5 - Exceptions and Obj ect Lifetim e // MessageBox type. Chapter 6 I nter faces and string allOfTheDataCollections = sr.ReadToEnd(); Chapter 7 - Callback I nter faces, Delegates, "Here and Ev ents MessageBox.Show(allOfTheData, it is:"); Chapter 8 - Advanced C# Type Const ruction Techniques sr.Close(); Chapter 4

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies As you 10 can- see, the StreamReader and StreamWriter types provide a custom implementation of the Chapter Pr ocesses, AppDomains, Cont exts, and Threads

abstract defined by their respective base classes. remember that these two types are Chapter 11members - Type Reflection, Late Binding, and Attr ibuteBased Just Pr ogramm ing concerned Pa r t Four - Lewith ve r amoving ging thetext-based .NET Libr a rdata ie s

to and from a specified file.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

SOURCE CODE

The StreamWriterReaderApp project is included under the Chapter 16 subdirectory.

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Working with StringWriters by Andr ew Tr oelsen

ISBN:1590590554

Using the StringWriter StringReader Apr essand © 2003 (1200 pages) types, you can treat textual information as a stream of in-memory characters. This can prove helpful when wish character-based information to an underlying This compr ehensiv e text you star ts w ithtoaappend brief ov er view of the buffer. To gain access to the underlying buffer from an instance of a StringWriter type, you can call the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. type) or the GetStringBuilder() method, which overridden ToString() method (to receive a System.String returns an instance of System.Text.StringBuilder. TaTo bleillustrate, o f Con t en reengineer ts the previous example to write the character information to a StringWriter instance

rather a generated As you should notice, the two programs are nearly identical, given that both C# and tthan he .NET Plat for m, file. Second Edition StringWriter I ntr oduction and StreamWriter inherit the same base class functionality, as shown here: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 class - The Philosophy of .NET public MyStringWriterReader Chapter { 2 - Building C# Applications Pa r t Tw opublic - The C# static Pr ogr am mint ing La Main(string[] ngua ge

args) { Chapter 3 - C# Language Fundamentals // a StringWriter Chapter 4 - Obj ect Get -Or iented Pr ogr am ming w ithand C# write some stuff. StringWriter writer = new StringWriter(); Chapter 5 - Exceptions and Obj ect Lifetim e writer.WriteLine("Don't forget Mother's Day this year..."); Chapter 6 - I nter faces and Collections writer.WriteLine("Don't forget Father's Day this year..."); Chapter 7 - Callback I nter faces, Delegates, and Ev ents writer.WriteLine("Don't forget these numbers:"); Chapter 8 - Advanced C# Type Const ruction Techniques for(int i = 0; i < 10; i++) Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s writer.Write(i + " "); Chapter 9 - Under standing .NET Assem blies writer.Write(writer.NewLine); // Insert a carriage return. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads writer.Close(); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Console.WriteLine("Stored thoughts in a StringWriter..."); Pa r t Four - Le ve r a ging the .NET Libr a r ie s // Get a copy of the contents (stored in a string) and pump Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er // to console. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For Console.WriteLine("Contents: {0} ",ms)writer.ToString()); Chapter 14 - A return Better Paint ing Fr amew or k ( GDI + ) 0; Chapter } 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace } Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Running program, of course, dumps out textual data to the console. To gain access to the underlying Chapter 18this - ASP.NET Web Pages and Web Contr ols StringBuilder maintained the StringWriter, simply add the following logic: Chapter 19 - ASP.NET Web by Applicat ions Chapter 20 - XML Web Ser vices

// For StringBuilder type! I ndex using System.Text; List of Figur es ... List of Tables public class MyStringWriterReader { public static int Main(string[] args) { // Previous logic... ... // Get the internal StringBuilder. StringBuilder str = writer.GetStringBuilder(); string allOfTheData = str.ToString(); Console.WriteLine("StringBuilder says:\n{0} ", allOfTheData); // Insert item to buffer at position 20. str.Insert(20, "INSERTED STUFF"); allOfTheData = str.ToString(); Console.WriteLine("New StringBuilder says:\n{0} ", allOfTheData); // Remove the inserted string.

str.Remove(20, "INSERTED STUFF".Length); C# an d th e .N ET Plat f orm , Se con d Ed it ion allOfTheData = str.ToString(); ISBN:1590590554 by Andr ew Tr oelsen Console.WriteLine("Original says:\n{0} ", allOfTheData); Apr ess © 2003 (1200 pages) return 0; This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

} }

Here, you can write some character data to a StringWriter type and extract and manipulate a copy of the contents using the GetStringBuilder() member function.

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Working with StringReaders by Andr ew Tr oelsen

ISBN:1590590554

Next is the StringReader which (as you would expect) functions identically to the related Apr ess ©type, 2003 (1200 pages) StreamReader class. In fact, the StringReader class nothing This compr ehensiv e text star ts w ith a does brief ov er viewmore of thethan override the inherited members to readC# from a block of character data, rather than a file, as shown here: language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

// Now dump using a StringReader. StringReader sr = new StringReader(writer.ToString()); Ta ble o f Con t en t s string input = null; C# and t he .NET Plat for m, Second Edition while ((input = sr.ReadLine()) != null) I ntr oduction { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Console.WriteLine (input); Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications sr.Close(); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Figure 416-9 shows theiented output. Chapter - Obj ect -Or Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Figure 16-9: Manipulating the StringBuilder

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

If you were paying attention to the previous sample applications, you may have noticed one limitation of the I ndex TextReader List of Figur es and TextWriter descendents. None of these types has the ability to provide random access to its of contents List Tables (e.g., seeking). For example, StreamReader has no members that allow you to reset the

internal file cursor or jump over some number of characters and begin reading from that point. To gain this sort of functionality, you need to use various descendents of the Stream type. SOURCE CODE

The StringReaderWriterApp is included under the Chapter 16 subdirectory.

C# an d th e .N ET Plat f orm , Se con d Ed it ion Working with Binary Data (BinaryReaders and BinaryWriters) by Andr ew Tr oelsen

ISBN:1590590554

The final two coreApr classes provided by the System.IO namespace are BinaryReader and BinaryWriter, ess © 2003 (1200 pages) both of which derive directly from System.Object. These allowofyou This compr ehensiv e text star ts w ith a brieftypes ov er view theto read and write discrete data types to an underlying stream. The BinaryWriter class defines a highly overloaded method named (of C# language and then quickly m oves to key technical and chitectur al issues .NET developer s. stream. The BinaryWriter class also provides course) Write() toarplace a data type for in the corresponding some other familiar-looking members (Table 16-13). TaTable ble o f 16-13: Con t enBinaryWriter ts Core Members C# and t he .NET Plat for m, Second Edition

Member I ntrBinaryWriter oduction

Meaning in Life

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

BaseStream

Chapter 1

Represents the underlying stream used with the binary reader

- The Philosophy of .NET

Close() Closes the binary stream Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Flush()

Flushes the binary stream

Chapter 3

- C# Language Fundamentals

Seek() Chapter 4

the w position - Obj ect -Or iented Pr ogrSets am ming ith C# in the current stream

Chapter 5

Lifetim e Write() - Exceptions and Obj ectWrites a value to the current stream

Chapter 6

- I nter faces and Collections

Chapter 7 - Callbackclass I ntercomplements faces, Delegates, Ev ents The BinaryReader theand functionality offered by BinaryWriter with the members Chapter 8 -inAdvanced C# Type Const ruction Techniques described Table 16-14. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - Under standing .NET Assem blies Table 16-14: BinaryReader Core Members Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

BinaryReader Meaning in and Life Chapter 11 - Type Reflection, Late Binding, Attr ibute- Based Pr ogramm ing Pa rMember t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and access the .NETtoRemoting Lay er stream. BaseStream Enables the underlying Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Close() Closes theorbinary Chapter 14 - A Better Paint ing Fr amew k ( GDIreader. +) Chapter 15 - Pr ogr am ming with Windows Formavailable s Contr ols PeekChar() Returns the next character without actually advancing the Chapter 16 - The Sy stem .I Oposition Nam espace in the stream. Chapter 17 - Data Access w ith ADO.NET

a given setr viofces bytes or Pa rRead() t Fi ve - W e b Appl ica ti onsReads and X ML W e b Se

characters and stores them in the incoming array. Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions ReadXXXX() The BinaryReader class defines numerous ReadXXXX methods that Chapter 20 - XML Web Ser vices grab the next type from the stream (ReadBoolean(), ReadByte(), I ndex ReadInt32(), and so forth). List of Figur es List of Tables

The following class writes a number of character types to a new *.dat file created and opened using the FileStream class. Once you have a valid FileStream, pass this object to the constructor of the BinaryWriter type. Understand that the constructor of BinaryWriter takes any Stream-derived type (for example, FileStream, MemoryStream, or BufferedStream). Once the data has been written, a corresponding BinaryReader reads each byte back, as shown here: public class ByteTweaker { public static int Main(string[] args) { Console.WriteLine("Creating a file and writing binary data..."); FileStream myFStream = new FileStream("temp.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite); // Write some binary info.

BinaryWriter binWrit = new BinaryWriter(myFStream); C# an d th e .N ET Plat f ormas , Sebinary con d Ed itinfo..."); ion binWrit.Write("Hello ISBN:1590590554 by Andr ew Tr oelsen int myInt = 99; Apr ess © 2003 (1200 pages) float myFloat = 9984.82343F; ThismyBool compr ehensiv e text star ts w ith a brief ov er view of the bool = false; C# language and then m oves 'e', to key 'l', technical and 'o'} ; char[] myCharArray quickly = { 'H', 'l', ar chitectur al issues for .NET developer s. binWrit.Write(myInt); binWrit.Write(myFloat); binWrit.Write(myBool); Ta ble o f Con t en t s binWrit.Write(myCharArray); C# and t he .NET Plat for m, Second Edition // Reset internal position. I ntr oduction binWrit.BaseStream.Position = 0; Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m // Read the binary info as raw bytes. Chapter 1 - The Philosophy of .NET Console.WriteLine("Reading binary data..."); Chapter 2 - Building C# Applications BinaryReader binRead = new BinaryReader(myFStream); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge int temp = 0; Chapter 3 - C#while(binRead.PeekChar() Language Fundamentals != -1) Chapter 4 - Obj ect { -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e Console.Write(binRead.ReadByte()); Chapter 6 - I nter facestemp and Collections = temp + 1; Chapter 7 - Callback Iif(temp nter faces, Delegates, == 5) and Ev ents Chapter 8 - Advanced{C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th //.N Add ET Assem a blank bl ie s line every 5 bytes. temp = 0; Chapter 9 - Under standing .NET Assem blies Console.WriteLine(); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve}r a ging the .NET Libr a r ie s // things up. Chapter 12 - Obj ect Clean Ser ialization and the .NET Remoting Lay er binWrit.Close(); Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) binRead.Close(); Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) myFStream.Close(); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols } Chapter 16 - The Sy stem .I O Nam espace } Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions SOURCE The BinaryReaderWriter application is included under the Chapter 16 subdirectory. Chapter 20 - XML Web Ser vices CODE I ndex List of Figur es List of Tables

an d thand e .N ETDirectories Plat f orm , Se con d Ed it ion "Watching"C#Files by Andr ew Tr oelsen

ISBN:1590590554

Now that you have better handle on the use of various readers and writers, next we'll check out the role of the Apraess © 2003 (1200 pages) FileSystemWatcher class. This type can be helpful you wish This compr ehensiv e text starquite ts w ith a briefwhen ov er view of theto programmatically monitor (or "watch" files on your system. Specifically, the FileSystemWatcher type can be instructed to monitor files for any of the C# language and then quickly m oves to key technical and al issues for .NET developer s. many of these members are selfexplanatory, check actions specified ar bychitectur the NotifyFilters enumeration (while online help for further details): Ta ble o f Con t en t s

public enum System.IO.NotifyFilters { I ntr oduction Attributes, CreationTime, Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m DirectoryName, FileName, Chapter 1 - The Philosophy of .NET LastAccess, LastWrite, Chapter 2 Building C# Applications Security, Size, Pa }r t Tw o - The C# Pr ogr am m ing La ngua ge C# and t he .NET Plat for m, Second Edition

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# The first you will need to take to work Chapter 5 step - Exceptions and Obj ect Lifetim e with the FileSystemWatcher type is to set the Path property to specify

the name location) ofCollections the directory that contains the files to be monitored, as well as the Filter property that Chapter 6 (and - I nter faces and defines7the- file extension of the Delegates, files to be and monitored. Chapter Callback I nter faces, Ev ents Next, you will set the NotifyFilter property using members o the System.IO.NotifyFilters enumeration. Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

At this point, you may choose to handle the Changed, Created, and Deleted events, all of which work in - Under standing .NET Assem blies conjunction with the FileSystemEventHandler delegate. As well, the Renamed event may also be handled via th Chapter 10 - Pr ocesses, AppDomains, Cont exts, andset Threads RenamedEventHandler type. Last but not least, the EnableRaisingEvents property to true to begin spying on Chapter 11 Type Reflection, Late Binding, and Attr ibuteBased Pr ogramm ing your file set. Chapter 9

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

To illustrate, assume have and created a new directory oneryour C drive named ParanoidFolder that contains two Chapter 12 - Obj ect Seryou ialization the .NET Remoting Lay *.txt files whatever The following console will monitor the *.txt files within the Chapter 13(named - Building a Bet teryou Winwish). dow ( Int roducin g Window s Forapplication ms) ParanoidFolder, andPaint printing outFrmessages in the Chapter 14 - A Better amew or k ( GDI + ) event that the files are created, deleted, modified, or renamed: Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

public Chapter 16 class - The SyTheWatcher stem .I O Nam espace { Chapter 17 - Data Access w ith ADO.NET public static void Pa r t Fi ve - W e b Appl ica ti ons and XMain() ML W e b Se r vi ces Chapter{18 - ASP.NET Web Pages and Web Contr ols

Establish which Chapter 19 - // ASP.NET Web Applicat ions directory to watch of course you have this directory...) Chapter 20 - // XML(assume Web Ser vices FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"C:\ParanoidFolder"; List of Figur es // Set up the things to be on the look out for. List of Tables watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Only watch text files. watcher.Filter = "*.txt"; // Add event handlers. watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.Deleted += new FileSystemEventHandler(OnChanged); watcher.Renamed += new RenamedEventHandler(OnRenamed); // Begin watching the directory. watcher.EnableRaisingEvents = true; // Wait for the user to quit the program. Console.WriteLine(@"Press 'q' to quit app."); while(Console.Read()!='q'); } I ndex

// Event handlers (note the signature of the delegate targets!) C# an d thvoid e .N ETOnChanged(object Plat f orm , Se con d Ed itsource, ion private static FileSystemEventArgs e) ISBN:1590590554 by Andr ew Tr oelsen { Apr ess © 2003 (1200 pages) // Specify what is done when a file is changed, created, or deleted. This compr ehensiv e text star ts{0} w ith {1}!", a brief ov er view of the Console.WriteLine("File: e.FullPath, e.ChangeType); C# language and then quickly m oves to key technical and } ar chitectur al issues for .NET developer s. private static void OnRenamed(object source, RenamedEventArgs e) { // Specify what is done when a file is renamed. Ta ble o f Con t en t s Console.WriteLine("File: {0} renamed to\n{1}", e.OldFullPath, e.FullPath) C# and t he .NET Plat for m, Second Edition } I ntr oduction } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter - Building C# Applications Now, to2 test this program, run the application and open up the Windows Explorer. Try renaming your files, Pa r t Tw o -aThe Pr ogr m ing Laangua creating newC#*.txt file,amdeleting *.txtge file,

or whatnot. You will see the console application print out various bits

Chapter 3 - regarding C# Language information theFundamentals state of the text files (Figure 16-10). Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Figure 16-10: Watching some *.txt files

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay eris included under the Chapter 16 subdirectory. SOURCE The MyDirectoryWatcher application Chapter CODE 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET PlatAsynchronous f orm , Se con d Ed it ion IO A Brief Word Regarding by Andr ew Tr oelsen

ISBN:1590590554

You have alreadyApr seen asynchronous ess the © 2003 (1200 pages) support provided by the .NET Framework during our examination of delegates (Chapter andstar thets .NET (Chapter 12). Needless to say, This compr ehensiv e7)text w ith aRemoting brief ov er layer view of the numerous types in the System.IO namespace support asynchronous operations. Specifically, any type C# language and then quickly m oves to key technical and chitecturSystem.IO.Stream al issues for .NET developer s. BeginRead(), BeginWrite(), EndRead(), and deriving from the ar abstract type inherits EndWrite() methods. As you would expect, each of these methods works in conjunction with the IAsyncResult type: Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

public abstract class System.IO.Stream : MarshalByRefObject, Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m IDisposable Chapter 1 - The Philosophy of .NET { Chapter ... 2 - Building C# Applications Pa r t Tw opublic - The C# virtual Pr ogr am m ing La ngua ge IAsyncResult BeginRead(byte[] buffer, int offset, Chapter 3 - int C# Language count, Fundamentals AsyncCallback callback, object state); Chapter public 4 - Obj ect -Or iented IAsyncResult Pr ogr am ming w ith BeginWrite(byte[] C# virtual buffer, int offset, Chapter 5 - int Exceptions and AsyncCallback Obj ect Lifetim e count, callback, object state); Chapter public 6 - I nter virtual faces and Collections int EndRead(IAsyncResult asyncResult); virtual void EndWrite(IAsyncResult asyncResult); Chapter public 7 - Callback I nter faces, Delegates, and Ev ents } Chapter 8 - Advanced C# Type Const ruction Techniques I ntr oduction

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

The process of working with the asynchronous behavior of Stream-derived types is identical to working with asynchronous delegates and asynchronous remote method invocations. In reality, you may never Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing need to read or write to a Stream derivative asynchronously, unless perhaps you are building a .NETPa r t Four - Le ve r a ging the .NET Libr a r ie s aware photo-editing application (where the image files can be quite large indeed). Nevertheless, should Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er the need arise, just remember Stream-derived types automatically support this behavior. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , SeApplication con d Ed it ion A WindowsC#Forms Car Logger by Andr ew Tr oelsen

ISBN:1590590554

Speaking of Chapter 12©(see preceding section), as you can surely surmise, the types of the System.IO Apr ess 2003 the (1200 pages) namespace workThis naturally with the .NET object compr ehensiv e text star ts wserialization ith a brief ov model. er view ofGiven the this, the remainder of this chapter walks you through a minimal and complete Windows Forms application named CarLogApp. The C# language and then quickly m oves to key technical and ar chitectur issues for .NET CarLogApp allows the end al user to create andeveloper inventorys.of Car types (contained in an ArrayList), which are displayed in yet another Windows Forms control, the DataGrid (Figure 16-11). To keep focused on the serialization logic, this grid is read-only. Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - 16-11: Exceptions ect Lifetim e Figure Theand car Obj logger application Chapter 6 - I nter faces and Collections Chapter The topmost 7 - Callback File menu I nterprovides faces, Delegates, a numberand of choices Ev ents that operate on the underlying ArrayList. Table 16-15

describes possibleC#selections. Chapter 8 -the Advanced Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Table 16-15: Filestanding Menu Options of the CarLogApp Project Chapter 9 - Under .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

File Submenu Item

Meaning in Life

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter Make12 New - Obj Carect Ser ialization Displaysand a custom the .NETdialog Remoting box that Lay erallows the user to configure a new Car

and theroducin DataGrid. Chapter 13 - Building a Bet ter refreshes Win dow ( Int g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Clear All Cars

Empties the ArrayList and refreshes the DataGrid.

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Open16 Car- File user to open an existing *.car file and refreshes the DataGrid. This Chapter The Sy stem .IAllows O Namthe espace the result of a BinaryFormatter. Chapter 17 - Data Access file w ithis ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Save Car File

Saves all cars displayed in the DataGrid to a *.car file.

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Exit 19 - ASP.NET Web Exits the application. Chapter Applicat ions Chapter 20 - XML Web Ser vices

I will not bother to detail the menu construction logic, as you have already seen these steps during the I ndex

formal discussion of Windows Forms. The first task is to define the Car type itself. This is the class that List of Figur es

represents not only a unique row in the DataGrid, but also an item in the serialized object graph. There are numerous iterations of the Car class throughout this book, so this version is brutally bland (recall the role of the [Serializable] attribute!):

List of Tables

[Serializable] public class Car { // Make public for easy access. public string petName, make, color; public Car(string petName, string make, string color) { this.petName = petName; this.color = color; this.make = make; } }

an d th e .N ET Plat f orm , Se con d Ed it ion Next, you need toC# add a few members to the main Form class. The overall UI of the DataGrid type is ISBN:1590590554 by Andr configured using a smallew setTrofoelsen properties, all of which have been assigned using the Properties window of Apr ess © 2003 (1200 pages) the Visual Studio .NET IDE. The most important property for this example is the ReadOnly member (set to This the compr ehensiv text star ts cells w ith ainbrief ov er view ofThe theremaining configurations establish true), which prevents user fromeediting the the DataGrid. C# language and then quickly m oves to key technical and the type's color scheme and physical dimensions (which you can explore at your leisure). ar chitectur al issues for .NET developer s.

In addition, the main Form maintains a private ArrayList type, which holds each of the Car references. The Form's constructor adds a number of default cars to allow the user to view some initial items in the grid. Ta ble o f Con t en t s Once these Car types have been added to the collection, you call a helper function named UpdateGrid(), as C# and t he .NET Plat for m, Second Edition shown here: I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

public class mainForm : System.Windows.Forms.Form - The Philosophy of .NET { Chapter 2 - Building C# Applications // ArrayList for object serialization. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge private ArrayList arTheCars = null; Chapter 3 - C# Language Fundamentals ... Chapter public 4 - Obj ect -Or iented Pr ogr am ming w ith C# mainForm() Chapter { 5 - Exceptions and Obj ect Lifetim e Chapter 6 - I nter faces and Collections InitializeComponent(); Chapter 7 - Callback I nter faces, Delegates, and Ev ents CenterToScreen(); Chapter 8 - Advanced Type cars. Const ruction Techniques // AddC#some Pa r t Thre e - Pr ogr am m i ng w i th ET Assem bl ie s arTheCars = .Nnew ArrayList(); Chapter 9 - Under arTheCars.Add(new standing .NET Assem blies Car("Siddhartha", "BMW", "Silver")); Car("Chucky", Chapter 10 - Pr arTheCars.Add(new ocesses, AppDomains, Cont exts, and Threads "Caravan", "Pea Soup Green")); arTheCars.Add(new Car("Fred", "Audi TT", ing "Red")); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm Display in Pa r t Four - Le ve// r a ging the .NETdata Libr a r ie s grid. UpdateGrid(); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter } 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) ... 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 1

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t FiUpdateGrid() ve - W e b Applmethod ica ti ons is and X ML W e b Se ces The responsible forr vicreating

a System.Data.DataTable type that contains a row for

Chapter 18 in - ASP.NET Web Pages Web Contr ols each Car the ArrayList. Once and the DataTable has been populated, you then bind it the DataGrid type. Chapter 1917 - examines ASP.NET Web ionstypes (such as the DataTable) in much greater detail, so here the Chapter the Applicat ADO.NET Chapter XMLbasics Web Ser focus is20on- the forvices the time being. Here is the code: I ndex List of Figur es private void UpdateGrid() List of Tables {

if(arTheCars != null) { // Make a DataTable object named Inventory. DataTable inventory = new DataTable("Inventory"); // Create DataColumn objects that map to the fields of the Car type. DataColumn make = new DataColumn("Car Make"); DataColumn petName = new DataColumn("Pet Name"); DataColumn color = new DataColumn("Car Color"); // Add columns to data table. inventory.Columns.Add(petName); inventory.Columns.Add(make); inventory.Columns.Add(color); // Iterate over the array list to make rows. foreach(Car c in arTheCars) {

DataRow newRow; C# an d th e .N=ETinventory.NewRow(); Plat f orm , Se con d Ed it ion newRow ISBN:1590590554 by Andr ew Tr oelsen Name"] = c.petName; newRow["Pet Apr ess © 2003 (1200 pages) newRow["Car Make"] = c.make; ThisnewRow["Car compr ehensiv e text star ts w = ith c.color; a brief ov er view of the Color"] C# language and then quickly m oves to key technical and inventory.Rows.Add(newRow); ar chitectur al issues for .NET developer s.

} // Now bind this data table to the grid. carDataGrid.DataSource = inventory; Ta ble o f Con t en t s } C# and t he .NET Plat for m, Second Edition } I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 creating - The Philosophy of .NET type named Inventory. In the world of ADO.NET, a DataTable is an inBegin by a new DataTable Chapter 2 Building C# Applications memory representation of a single table of information. While you might assume that a DataTable would be Pa r t Tw o -as The C# Pr ogr am m ing La ngua ge you created a result of some SQL query,

Chapter 3

can also use this type as a stand-alone entity.

- C# Language Fundamentals

Once you a new DataTable, you need establish the set of columns that should be listed in the table. Chapter 4 -have Obj ect -Or iented Pr ogr am ming w ithtoC# The System.Data.DataColumn type represents a single column. Given that this iteration of the Car type has Chapter 5 - Exceptions and Obj ect Lifetim e three public (make, and pet name), create three DataColumns and insert them in the table Chapter 6 - Ifields nter faces and color, Collections using the DataTable.Columns property. - Callback I nter faces, Delegates, and Ev ents

Chapter 7

Chapter 8 need - Advanced Type Const ruction Next, you to addC# each row to the table.Techniques Recall that the main Form maintains an ArrayList that contains Pa r t Thre e - Pr ogr m itypes. ng w i thGiven .N ET that Assem bl ie s some number ofam Car ArrayList

implements the IEnumerable interface, you can fetch each

Chapter 9 the - Under standing .NET Assem bliesfield, and compose and insert a new DataRow in the table. Finally, Car from collection, read each public Chapter - Pr ocesses, AppDomains, ContDataGrid exts, and widget Threadsusing the DataSource property. the new10DataTable is bound to the GUI Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Now then! Ifve you run the ats this Pa r t Four - Le r a ging the application .NET Libr a r ie

point, you will find that the grid is indeed populated with the

default 12 set- of automobiles. Thisand is athe good start, but youLay can Chapter Obj ect Ser ialization .NET Remoting er do better. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Implementing the Add New Car Logic

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

The CarLogApp project another Form-derived type (AddCarDlg) that functions as a modal dialog Chapter 16 - The Sy stem .Idefines O Nam espace box (Figure Fromw ith a GUI point of view, this type is composed of a TextBox (to hold the pet name) Chapter 17 - 16-12). Data Access ADO.NET and types the Pa r t Fitwo ve -ListBox W e b Appl ica ti(to onsallow and X MLuser W e b to Seselect r vi ces

the color and make).

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 16-12: The Add a Car dialog box As far as the code behind the Form, the OK button has been assigned the DialogResult property DialogResult.OK. As you recall, this value marks a Button type to function as a standard OK button. Also, this Form maintains a public Car type (for easy access), which is configured when the user clicks the OK button. The remainder of the code is nothing more than some GUI control prep work. The relevant logic is as follows:

public class C# AddCarDlg : System.Windows.Forms.Form an d th e .N ET Plat f orm , Se con d Ed it ion { ISBN:1590590554 by Andr ew Tr oelsen // Make Apr public for easy access. ess © 2003 (1200 pages) public Car theCar = null; This compr ehensiv e text star ts w ith a brief ov er view of the ... C# language and then quickly m oves to key technical and protected void albtnOK_Click ar chitectur issues for .NET (object developer s. sender, System.EventArgs e) { // Configure a new Car when user clicks OK button. Ta ble o f Con t entheCar ts = new Car(txtName.Text, listMake.Text, listColor.Text); C# and t} he .NET Plat for m, Second Edition } oduction I ntr Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

The main Form displays this dialog box when the user selects the Make New Car menu item. Here is the - Building C# Applications code behind that object's Clicked event:

Chapter 2

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals protected void Chapter 4 - Obj ect -OrmenuItemNewCar_Click iented Pr ogr am ming w ith C# (object sender, System.EventArgs e)

{

Chapter 5

- Exceptions and Obj ect Lifetim e

// Show the dialog and check for OK click. - I nter faces and Collections AddCarDlg d = new AddCarDlg(); Chapter 7 - Callback I nter faces, Delegates, and Ev ents if(d.ShowDialog() == DialogResult.OK) Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s // Add new car to array list. Chapter 9 - Under standing .NET Assem blies arTheCars.Add(d.theCar); Chapter 10 - Pr UpdateGrid(); ocesses, AppDomains, Cont exts, and Threads Chapter } 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa }r t Four - Le ve r a ging the .NET Libr a r ie s Chapter 6

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

No surprises just theorForm Chapter 14 - A here. BetterYou Paint ing show Fr amew k ( GDIas + )a modal dialog box, and if the OK button has been clicked, you read variable, add it to the Chapter 15 the - Prpublic ogr amCar mingmember with Windows Form s Contr ols ArrayList, and refresh your grid. Chapter 16 - The Sy stem .I O Nam espace

The Serialization Logic

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

The core behindWeb the Pages Save Car File and Chapter 18 logic - ASP.NET and Web ContrOpen ols Car File Click event handlers should pose no problems at this point. When the user chooses Chapter 19 - ASP.NET Web Applicat ions to save the current inventory, you create a new file and use a BinaryFormatter to serialize Chapter 20 - XML Web Ser vicesthe object graph. However, just to keep things interesting, the user can

establish the name and location of this file using a System.Windows.Forms.SaveFileDialog type. This type I ndex is yet another standard dialog box and is illustrated in Figure 16-13.

List of Figur es List of Tables

Figure 16-13: The standard File Save dialog box

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

Notice that the SaveFileDialog is listing Apr ess © 2003 (1200 pages)a custom file extension (*.car). While I leave the task of investigating the complete functionality of the SaveFileDialog capable hands, it is worth pointing out that this has This compr ehensiv e text star ts w in ithyour a brief ov er view of the been assigned using the Filter property. This property takes an OR-delimited string that represents the text C# language and then quickly m oves to key technical and chitectur alFile issues for .NET developer s. combo boxes. Here is the full implementation: to be used in the ar drop-down name and Save as type protected void menuItemSave_Click (object sender, System.EventArgs e) { C# and t he .NET Plat for m, Second Edition // Configure look and feel of save dialog box. I ntr oduction SaveFileDialog mySaveFileDialog = new SaveFileDialog(); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m mySaveFileDialog.InitialDirectory = "."; Chapter mySaveFileDialog.Filter 1 - The Philosophy of .NET = "car files (*.car)|*.car|All files (*.*)|*.*"; Chapter mySaveFileDialog.FilterIndex 2 - Building C# Applications = 1; Pa r t Tw omySaveFileDialog.RestoreDirectory - The C# Pr ogr am m ing La ngua ge = true; Chapter mySaveFileDialog.FileName 3 - C# Language Fundamentals = "carDoc"; Chapter // 4 - Do Obj you ect -Orhave iented a Pr ogr am ming w ith C# file? Chapter if(mySaveFileDialog.ShowDialog() 5 - Exceptions and Obj ect Lifetim e == DialogResult.OK) Chapter { 6 - I nter faces and Collections Stream myStream = null; Chapter 7 - Callback I nter faces, Delegates, and Ev ents if((myStream = mySaveFileDialog.OpenFile()) != null) Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s // Save the cars! Chapter 9 - Under standing .NET Assem blies BinaryFormatter myBinaryFormat = new BinaryFormatter(); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads myBinaryFormat.Serialize(myStream, Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogrammarTheCars); ing Pa r t Four - Le ve r a ging myStream.Close(); the .NET Libr a r ie s } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er } Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) }

Ta ble o f Con t en t s

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 that - Thethe SyOpenFile() stem .I O Nam espace of the SaveFileDialog type returns a Stream that represents the Also note member Chapter 17 Data Access w ith ADO.NET specified file selected by the end user. As seen in Chapter 13, this is the very thing needed by the Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces BinaryFormatter type.

Chapter 18 - ASP.NET Web Pages and Web Contr ols

The logic the Web OpenApplicat Car File Click event handler looks very similar. This time you create an instance Chapter 19 behind - ASP.NET ions of the System.Windows.Forms Chapter 20 - XML Web Ser vices OpenFileDialog type, configure accordingly, and obtain a Stream reference based on the selected file. Next you dump the contents of the ArrayList and read in the new object graph using the BinaryFormatter.Deserialize() method, as shown here:

I ndex

List of Figur es List of Tables

protected void menuItemOpen_Click (object sender, System.EventArgs e) { // Configure look and feel of open dialog box. OpenFileDialog myOpenFileDialog = new OpenFileDialog(); myOpenFileDialog.InitialDirectory = "."; myOpenFileDialog.Filter = "car files (*.car)|*.car|All files (*.*)|*.*"; myOpenFileDialog.FilterIndex = 1; myOpenFileDialog.RestoreDirectory = true; // Do you have a file? if(myOpenFileDialog.ShowDialog() == DialogResult.OK) { // Clear current array list. arTheCars.Clear(); Stream myStream = null; if((myStream = myOpenFileDialog.OpenFile()) != null)

{ C# an th e .Nthe ET Plat f orm , Se con d Ed it ion //d Get cars! by Andr ew Tr oelsen BinaryFormatter myBinaryFormatISBN:1590590554 = new BinaryFormatter(); Apr ess © 2003 (1200 pages) arTheCars = (ArrayList)myBinaryFormat.Deserialize(myStream);

}

ThismyStream.Close(); compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and UpdateGrid(); ar chitectur al issues for .NET developer s.

} }

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr At oduction this point, the application can save and load the entire set of Car types held in the ArrayList using a Pa r t One - I nt r oduciThe ng C# a nd the .NET P la tf orself-explanatory, m BinaryFormatter. final menu items are

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

as shown here:

protected void menuItemClear_Click (object sender, System.EventArgs e) { Chapter 3 - C# Language Fundamentals arTheCars.Clear(); Chapter UpdateGrid(); 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e } Chapter 6 - I nter facesmenuItemExit_Click and Collections protected void (object sender, System.EventArgs e) Chapter 7 Callback I nter faces, Delegates, and Ev ents { Chapter 8 Application.Exit(); - Advanced C# Type Const ruction Techniques Pa }r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

This wraps ourReflection, exploration of Binding, the System.IO Over the course of this chapter you have seen Chapter 11 - up Type Late and Attrnamespace. ibute- Based Pr ogramm ing how to read and writethe data to binary, Pa r t Four - Le ve r a ging .NET Libr a r iecharacter-based, s

and memory streams. In the next chapter you will come to understand how to interact with XML-based data readers (and writers). Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building aThe Bet ter Win dow ( Int roducin g Window under s For ms) SOURCE CarLogApp project is included the Chapter 16 subdirectory. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) CODE Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Summary

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

This chapter began use of the Directory(Info) and File(Info) types. As you have seen, Aprby essexamining © 2003 (1200the pages) these classes allow you to manipulate a physical filea or directory onofyour This compr ehensiv e text star ts w ith brief ov er view the hard drive. C# language and then quickly m oves to key technical and

Next you examined a number of types from the ar chitectur al issues for derived .NET developer s. abstract Stream class, including FileStream, MemoryStream, and BufferedStream. Given that each of these types has (more or less) the same public interface, you can easily swap them in and out of your code to alter the ultimate location of your byte array. TaWhen ble o f you Conare t en tinterested s in persisting textual data, the StreamReader and StreamWriter types usually fit theand bill.t he .NET Plat for m, Second Edition C# I ntr oduction

We wrapped things up by investigating how the types of the System.IO namespace can be used in conjunction with .NET object serialization services to persist custom types to a given location.

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Chapter C# 17: Data Access with ADO.NET ISBN:1590590554 by Andr ew Tr oelsen

Overview

Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and Unless you are aarvideo chitectur game al issues developer for .NET by trade, developer you s.are probably interested in database manipulation.

As you would expect, the .NET platform defines a number of types (in a handful of related namespaces) that allow you to interact with local and remote data stores. Collectively speaking, these namespaces are Taknown ble o f Con t en t s as ADO.NET, which as you will see is a major overhaul of the classic ADO object model. C# and t he .NET Plat for m, Second Edition

This chapter begins by examining some core types defined in the System.Data namespace-specifically I ntr oduction DataColumn, DataRow, DataTable. These Pa r t One - I nt r oduci ng C# and a nd the .NET P la tf or m

classes allow you to define and manipulate a local inmemory table of data. Next, you spend a good deal of time learning about the centerpiece of ADO.NET, Chapter 1 - The Philosophy of .NET the DataSet. As you will see, the DataSet is an in-memory representation of a collection of interrelated Chapter 2 - Building C# Applications tables. During this discussion, you will learn how to programmatically model table relationships, establish Pa r t Tw o - The C# Pr ogr am m ing La ngua ge custom views based on a given DataTable, and submit queries against your in-memory DataSet. Chapter 3

- C# Language Fundamentals

Chapter 4 - Obj ect -Or to iented Pr ogr am ming w ith C# After examining how manually build and manipulate a DataSet by hand, you'll examine how to obtain a Chapter 5 Exceptions and Obj ect Lifetim e populated DataSet from a Database Management System (DBMS) such as MS SQL Server, Oracle, or Chapter 6 - IDuring nter faces Collections MS Access. theand process, you will examine the role of .NET data providers and come to understand Chapter 7 Callback I nter faces, Delegates, and Ev ents the use of ADO.NET data adapters, command objects, and command builders. Chapter 8

- Advanced C# Type Const ruction Techniques

Inr tcontrast to ogr theam intrinsically world Pa Thre e - Pr m i ng w i thdisconnected .N ET Assem bl ie s

of DataSets and data adapters, this chapter also examines the connected layer of ADO.NET and the related data reader types. As you will see, the data Chapter 9 - Under standing .NET Assem blies reader is ideal when you simply wish to obtain a result set from a data store for display purposes. We wrap Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads things up with an overview of various database-centric wizards of Visual Studio .NET, and come to see Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing how these integrated tools can be used to lessen the amount of ADO.NET code you would otherwise need Pa r t Four - Le ve r a ging the .NET Libr a r ie s to write by hand. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion The Need for ADO.NET ISBN:1590590554

by Andr ew Tr oelsen

The very first thing you Apr essmust © 2003understand (1200 pages) when approaching ADO.NET is that it is not simply the latest and greatest version of classic ADO. While true between the two systems This compr ehensiv e textit is star ts wthat ith athere brief is ovsome er viewsymmetry of the (e.g., each has the concept of connection and command objects), some familiar types (e.g., the C# language and then quickly m oves to key technical and ar chitectur issues for .NET developer s. Recordset) no longer exist. alFurthermore, there are a number of new ADO.NET types that have no direct equivalent under classic ADO (such as the data adapter). In a nutshell, ADO.NET is a brand new database access technology focused on facilitating the development of disconnected (and connected) Tasystems ble o f Con t en tthe s .NET platform. using C# and t he .NET Plat for m, Second Edition

Unlike classic ADO, which was primarily designed for tightly coupled client/server systems, ADO.NET I ntr oduction greatly thengnotion of the the .NET primitive Pa r t One extends - I nt r oduci C# a nd P la tfADO or m disconnected

Recordset with a new creature named the

DataSet. type represents a local copy of any number of related tables. Using the DataSet, the client is Chapter 1 This - The Philosophy of .NET able to 2manipulate its contents while disconnected from the data source and submit the Chapter - Buildingand C# update Applications modified back foram processing using Pa r t Tw o - data The C# Pr ogr m ing La ngua ge Chapter 3

a related data adapter.

- C# Language Fundamentals

Another major difference between classic ADO and ADO.NET is that ADO.NET has full support for XML - Obj ect -Or iented Pr ogr am ming w ith C# data representation. In fact, the data obtained from a data store is internally represented, and transmitted, Chapter 5 - Exceptions and ecttransported Lifetim e as XML. Given that XML is Obj often between layers using standard HTTP, ADO.NET is not limited Chapter 6 I nter faces and Collections by firewall constraints. Chapter 4

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

As you 8might be aware, ADOruction makesTechniques use of the COM marshaling protocol to move data between Chapter - Advanced C# classic Type Const tiers. While this was appropriate in some situations, COM marshaling poses a number of limitations. For Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s example, most firewalls are configured to reject COM RPC packets, which made moving data between Chapter 9 - Under standing .NET Assem blies machines tricky. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Perhaps the most fundamental difference between classic ADO and ADO.NET is that ADO.NET is a managed library of code and therefore plays by all the same rules as any managed library. The types that Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er comprise ADO.NET use the CLR memory management protocol, adhere to the same programming Chapter - work Building a many Bet ter languages. Win dow ( Int Therefore, roducin g Window s For(and ms) their members) are accessed in the model,13 and with the types Chapter 14 - A Better Paint ing amew.NET-aware or k ( GDI + ) language you use. same manner, regardless of Frwhich Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dof th eADO.NET .N ET Plat f orm , Se con d Ed it ion The Two Faces ISBN:1590590554

by Andr ew Tr oelsen

The ADO.NET libraries can be(1200 used in two conceptually unique manners: connected or disconnected. Apr ess © 2003 pages) When you are making use of the connected layer, will ov make use a .NET data reader. As you will This compr ehensiv e text star ts w ithyou a brief er view of of the see later in this chapter, data readers provide a way to pull records from C# language and then quickly m oves to key technical and a data store using a forward-only, ar chitectur issues .NET developer read-only approach (much al like a firefor hose cursor). As s.a given data reader pulls over records based on your SQL query, you are directly connected to the data store and stay that way until you explicitly close the connection. In addition to simply reading data via a data reader, the connected layer of ADO.NET allows Tayou ble to o f insert, Con t en ts update, or remove records using a related command object. C# and t he .NET Plat for m, Second Edition

The disconnected layer, on the other hand, allows you to obtain a set of DataTable types (typically I ntr oduction contained within a ng DataSet) a mlocal Pa r t One - I nt r oduci C# a nd that the serves .NET P laas tf or

client-side copy of information. When you obtain a

DataSet data adapter type, the connection is automatically terminated immediately after the fill Chapter 1 using - Thea Philosophy of .NET request2 (as- you would this approach helps quickly free up connects for other callers). At this point, Chapter Building C# guess, Applications the client application isam able to La manipulate Pa r t Tw o - The C# Pr ogr m ing ngua ge the

DataSet's contents without incurring any network traffic. If the client wishes to push the changes back to the data store, the data adapter (in conjunction with a set of Chapter 3 - C# Language Fundamentals SQL queries) is used once again to update the data source, at which point the connection is again closed Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# immediately. Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter - I nter faces Collections In some6 respects, this and approach may remind you of the classic ADO disconnected Recordset. The key Chapter 7 Callback I nter faces, and Ev ents difference is that a disconnectedDelegates, Recordset represents a single set of record data, whereas ADO.NET Chapter 8 can - Advanced Type Const ruction Techniques DataSets model aC#collection of related tables. In fact, it is technically possible to obtain a client-side Pa r t Thre e that - Pr ogr am m i ng all w i th ETtables Assemfound bl ie s DataSet represents of .N the

within the remote database. However, as you would expect,

Chapter 9 -will Under standing .NET Assem a DataSet more commonly containblies a reasonable subset of information. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Data Plat f orm , Se con d Ed it ion The Role ofC#ADO.NET Providers ISBN:1590590554

by Andr ew Tr oelsen

Rather than providing a ©single set of objects to communicate to a variety of data stores, ADO.NET makes use Apr ess 2003 (1200 pages) of multiple data providers. Simply put, a data is a ov seterof types (within some .NET assembly) that This compr ehensiv e text star tsprovider w ith a brief view of the understand how to communicate with a specific data source. Although C# language and then quickly m oves to key technical andthe names of these types will differ ar chitectur issues forwill .NET developer s. among data providers, eachalprovider have (at minimum) a set of class types that implement some key interfaces defined in the System.Data namespace, specifically IDbCommand, IDbDataAdapter, IDbConnection, and IDataReader. As you would guess, these interfaces define the behaviors a managed provider must support Tato ble o f Conconnected t en t s provide and disconnected access to the underlying data store (see Figure 17-1). C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Figure data access Chapter 12 - 17-1: Obj ectADO.NET Ser ialization andproviders the .NETprovide Remoting Lay er to a given DBMS. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

To better understand the core functionality of any data provider, let's check out the formal definition of each interface type (of course, numerous details are to follow).

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 16 In - The Sy stem O the Nam.NET espace Note version 1.0.Iof platform, data providers were termed managed providers. Therefore, if you Chapter 17 are - Data Access w ith ADO.NET reading earlier .NET literature (including the first edition of this text), understand that these two Pa r t Fi ve - W e b Appl ti ons and Xsynonymous ML W e b Se r viwith ces terms areicacompletely

each other.

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

The Role of the IDbConnection and IDbTransaction Interfaces

Chapter 20 - XML Web Ser vices

I ndex First we have the IDbConnection type, which is implemented by a data provider's connection object. This List of Figurdefines es interface a set of members used to connect to (and disconnect from) a specific data store, as well as List allowing of Tables you to obtain the data provider's transactional object, which (surprise, surprise) implements the

System.Data.IDbTransaction interface: public interface System.Data.IDbConnection : IDisposable { string ConnectionString { get; set; } int ConnectionTimeout { get; } string Database { get; } ConnectionState State { get; } System.Data.IDbTransaction BeginTransaction(); System.Data.IDbTransaction BeginTransaction(System.Data.IsolationLevel il); void ChangeDatabase(string databaseName); void Close(); System.Data.IDbCommand CreateCommand(); void Open(); }

C# an d th e .N ET Plat f orm , Se con d Ed it ion

As you can see, the overloaded BeginTransaction() method provides access to an IDbTransaction-compatible ISBN:1590590554 by Andr ew Tr oelsen type. Using the members defined by this interface, you are able to programmatically interact with a transactiona Apr ess © 2003 (1200 pages) session and the underlying data store: This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. public interface System.Data.IDbTransaction : IDisposable

{ IDbConnection Connection { get; } Ta ble o f IsolationLevel Con t en t s IsolationLevel { get; } C# and tvoid he .NETCommit(); Plat for m, Second Edition I ntr oduction void Rollback(); Pa }r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

The Role of the IDbCommand, IDbDataParameter, and IDataParameter - C# Language Fundamentals Interfaces Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 3 Chapter 5

- Exceptions and Obj ect Lifetim e

Next up, we have the IDbCommand interface, which will be implemented by a data provider's command object. - I nter faces and Collections Like other data access object models, command objects allow programmatic manipulation of SQL statements, Chapter 7 - Callback I nter faces, Delegates, and Ev ents stored procedures, and parameterized queries (note that each parameter object implements the Chapter 8 - Advanced C# Type Const ruction Techniques IDbDataParameter type). In addition, command objects also provide access to the data provider's data reader Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s type via the overloaded ExecuteReader() method: Chapter 6

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

public interface System.Data.IDbCommand : IDisposable { Pa r t Four - Le ve r a ging the .NET Libr a r ie s string CommandText { get; set; } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er int CommandTimeout { get; set; } Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) CommandType CommandType { get; set; } Chapter IDbConnection 14 - A Better Paint ing Fr amew or k ( GDI +) Connection { get; set; } Chapter IDataParameterCollection 15 - Pr ogr am ming with Windows Form s Contr ols Parameters { get; } Chapter IDbTransaction 16 - The Sy stem .I O Nam espace Transaction { get; set; } Chapter UpdateRowSource 17 - Data Access w ith ADO.NET UpdatedRowSource { get; set; } Pa r t Fi vevoid - W e b Cancel(); Appl ica ti ons and X ML W e b Se r vi ces Chapter System.Data.IDbDataParameter 18 - ASP.NET Web Pages and Web Contr ols CreateParameter(); Chapter int 19 - ASP.NET ExecuteNonQuery(); Web Applicat ions ExecuteReader(); Chapter System.Data.IDataReader 20 - XML Web Ser vices System.Data.IDataReader ExecuteReader(System.Data.CommandBehavior behavior); I ndex object ExecuteScalar(); List of Figur es void Prepare(); List of Tables } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Notice that the Parameters property returns a strongly typed collection that implements IDataParameterCollection. This interface provides access to a set of IDbDataParametercompliant data types (e.g., parameter objects): public interface System.Data.IDbDataParameter : System.Data.IDataParameter { byte Precision { get; set; } byte Scale { get; set; } int Size { get; set; } }

IDbDataParameter extends the IDataParameter interface to obtain the following additional behaviors: C# an d th e .N ET Plat f orm , Se con d Ed it ion

ISBN:1590590554

by Andr ew Tr oelsen

public interface System.Data.IDataParameter Apr ess © 2003 (1200 pages) { This compr ehensiv e text star ts w ith a brief ov er view of the DbType DbType { get; set; } C# language and then quickly m oves to key technical and ParameterDirection Direction { get; ar chitectur al issues for .NET developer s. set; } bool IsNullable { get; } string ParameterName { get; set; } Ta ble o f string Con t en t s SourceColumn { get; set; } DataRowVersion SourceVersion { get; set; } C# and t he .NET Plat for m, Second Edition object Value { get; set; } I ntr oduction }r t One - I nt r oduci ng C# a nd the .NET P la tf or m Pa Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

As you will see, the functionality of the IDbDataParameter and IDataParameter interfaces allow you to represen parameters within a SQL query (as well as stored procedures) via specific ADO.NET parameter objects, rather Chapter 3 - C# Language Fundamentals than hard-coded strings. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

The Role offaces theandIDbDataAdapter and IDataAdapter Interfaces - I nter Collections

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 9

- Under standing .NET Assem blies

Recall that data adapters are used to push and pull DataSets to and from a given data store. Given this, the Chapter 8 - Advanced C# Type Const ruction Techniques IDbDataAdapter interface defines a set of properties that are used to maintain the SQL statements for the Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s related SELECT, INSERT, UPDATE, and DELETE operations: Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

public interface System.Data.IDbDataAdapter : System.Data.IDataAdapter { Pa r t Four - Le ve r a ging the .NET Libr a r ie s IDbCommand DeleteCommand { get; set; } Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er IDbCommand InsertCommand { get; set; } Chapter IDbCommand 13 - Building a Bet ter Win dow ( Int roducin g Window For ms) SelectCommand { get; set;s } Chapter IDbCommand 14 - A Better Paint ing Fr amew or k ( GDI +) UpdateCommand { get; set; } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Inr taddition four properties, Pa Fi ve - Wto e bthese Appl ica ti ons and X ML an W eADO.NET b Se r vi ces

data adapter also picks up the behavior defined in the base

interface, interface defines the key function of a data adapter type: the ability to push and Chapter 18 IDataAdapter. - ASP.NET WebThis Pages and Web Contr ols pull DataSets between theApplicat caller ions and underlying data store using the Fill() and Update() methods. Also, the Chapter 19 - ASP.NET Web

IDataAdapter interface allows Chapter 20 - XML Web Ser vices you to map database column names to a more human-readable display name via the TableMappings property:

I ndex

List of Figur es

public interface System.Data.IDataAdapter List of Tables { MissingMappingAction MissingMappingAction { get; set; } MissingSchemaAction MissingSchemaAction { get; set; } ITableMappingCollection TableMappings { get; } int Fill(System.Data.DataSet dataSet); System.Data.DataTable[] FillSchema(System.Data.DataSet dataSet, System.Data.SchemaType schemaType); System.Data.IDataParameter[] GetFillParameters(); int Update(System.Data.DataSet dataSet); }

The Role of the IDataReader and IDataRecord Interfaces The next key interface to be aware of is IDataReader, which (obviously) represents the common behaviors

supported by a given data reader type. When you obtain an IDataReader-compatible type from an ADO.NET an d th e .N ET Plat f orm , Se con d Ed it ion data provider, youC#are able to iterate over the result set using a forward-only, read-only manner. by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

public interface System.Data.IDataReader : IDisposable, This compr ehensiv e text star ts w ith a brief ov er view of the System.Data.IDataRecord C# language and then quickly m oves to key technical and { ar chitectur al issues for .NET developer s. int Depth { get; } bool IsClosed { get; } { get; } Ta ble o int f Con RecordsAffected t en t s void Close(); C# and t he .NET Plat for m, Second Edition System.Data.DataTable GetSchemaTable(); I ntr oduction bool Pa r t One - I nt rNextResult(); oduci ng C# a nd the .NET P la tf or m Read(); Chapterbool 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Finally, as you can see, IDataReader extends IDataRecord, which defines an additional set of members that - Obj ect -Or iented Pr ogr am ming w ith C# allow you to extract out a strongly typed value from the stream, rather than casting the generic System.Object Chapter 5 - Exceptions Obj ectoverloaded Lifetim e retrieved from the dataand reader's indexer method: Chapter 4 Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

public interface System.Data.IDataRecord Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s int FieldCount { get; } Chapterobject 9 - Under standing .NET Assem this[ string nameblies ] { get; } Chapterobject 10 - Pr ocesses, AppDomains, exts,}and Threads this[ int i ] {Cont get; Chapterbool 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing GetBoolean(int i); Pa r t Four Le ve r a ging the .NET Libr a r ie s byte GetByte(int i); Chapterlong 12 - Obj ect Ser ialization i, and long the .NET Remoting Lay er byte[] buffer, GetBytes(int fieldOffset, Chapter 13 - int Building a Bet ter Win dow ( Int roducin g Window s For ms) bufferoffset, int length); Chapterchar 14 - AGetChar(int Better Paint ing Fr i); amew or k ( GDI + ) GetChars(int i, longForm fieldoffset, char[] buffer, Chapterlong 15 - Pr ogr am ming with Windows s Contr ols bufferoffset, int length); Chapter 16 - int The Sy stem .I O Nam espace ChapterSystem.Data.IDataReader 17 - Data Access w ith ADO.NET GetData(int i); string GetDataTypeName(int Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se i); r vi ces GetDateTime(int ChapterDateTime 18 - ASP.NET Web Pages and Web i); Contr ols GetDecimal(int ChapterDecimal 19 - ASP.NET Web Applicat ions i); double GetDouble(int i); Chapter 20 - XML Web Ser vices Type GetFieldType(int i); I ndex float GetFloat(int i); List of Figur es Guid GetGuid(int i); List of Tables short GetInt16(int i); int GetInt32(int i); long GetInt64(int i); string GetName(int i); int GetOrdinal(string name); string GetString(int i); object GetValue(int i); int GetValues(object[] values); bool IsDBNull(int i); }

Now, to be sure, a data provider will supply you with other types beyond the classes that implement the key IDataReader, IDbCommand, IDbConnection, and IDbDataAdapter interfaces. Likewise, the classes in question will certainly define additional members beyond the set specified by the related interface type.

Nevertheless, at this point better the common functionality found among all .NET C# an d thyou e .Nshould ET Plathave f orma, Se con didea Ed itof ion data providers. Recall that even though the exact names of theISBN:1590590554 implementing types will differ among data by Andr ew Tr oelsen providers, you areApr able to program against these types in a similar manner, given the beauty of interface-based ess © 2003 (1200 pages) polymorphism: This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. System.Data.OleDb.OleDbConnection c; // Implements IDbConnection!

System.Data.Odbc.OdbcConnection c2; System.Data.Oracle.OracleConnection c3; TaSystem.Data.SqlServerCe.SqlCeConnection ble o f Con t en t s c4; C# and t he .NET Plat for m, Second Edition System.Data.SqlClient.SqlConnection c5;

// // // //

Implements Implements Implements Implements

IDbConnection! IDbConnection! IDbConnection! IDbConnection!

I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET Note interface implementation (see Chapter 6) is not used by the types implementing these Chapter 2 Explicit - Building C# Applications

ADO.NET-centric interfaces. Therefore, Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

you can call the interface methods directly from an object

Chapter 3 reference. - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET Plat f orm , Namespaces Se con d Ed it ion Understanding ADO.NET ISBN:1590590554

by Andr ew Tr oelsen

.NET version 1.1 Apr ships five data providers out of the box, each of which is logically represented by a esswith © 2003 (1200 pages) specific .NET namespace. In addition, ADO.NET defines common This compr ehensiv e text star ts w ith a briefsome ov er view of the namespaces that are used by all data provider implementations. Table 17-1 gives a quick rundown of each data-centric .NET namespace. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Table 17-1: ADO.NET Namespaces ADO.NET Namespace Ta ble o f Con t en ts

Meaning in Life

C# and t he .NET Plat for m, Second Edition

System.Data

This core namespace defines types that represent tables, rows, columns, constraints, and DataSets. This namespace does not Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m define types to connect to a data source. Rather, it defines the Chapter 1 - The Philosophy of .NET types that represent the data itself. I ntr oduction

Chapter 2

- Building C# Applications

This namespace contains Pa rSystem.Data.Common t Tw o - The C# Pr ogr am m ing La ngua ge

types shared between data providers. Many of these types function as base classes to the concrete types Chapter 3 - C# Language Fundamentals defined by a given data provider. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e System.Data.OleDb This namespace defines the types that allow you to connect to an Chapter 6 - I nter faces and Collections OLE DB-compliant data source. Typically you will use this Chapter 7 Chapter 8

- Callback I nter faces, Delegates, and Ev ents namespace only if you need to communicate with a data store that - Advanced C# Type Const Techniques doesruction not have a custom data provider.

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

System.Data.Odbc

Chapter 9

This namespace defines the types that constitute the ODBC data provider.

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter System.Data.OracleClient 11 - Type Reflection, LateThis Binding, namespace and Attr ibutedefines Based the Pr types ogramm that ing constitute the Oracle data Pa r t Four - Le ve r a ging the .NET Libr provider. a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

System.Data.SqlClient

This namespace defines the types that constitute the SQL data provider.

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

System.Data.SqlServerCe This namespace defines the types that constitute the SQL CE data Chapter 15 - Pr ogr am ming with Windows Form s Contr ols provider. Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET System.Data.SqlTypes Represents native data types used by Microsoft SQL Server. Pa r t Fi ve - W e b Appl ica ti ons and XAlthough ML W e b Se r viare ces you

always free to use the corresponding CLR data

Chapter 18 - ASP.NET Web Pages types, and Web ols theContr SqlTypes are optimized to work with SQL Server. Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices The System.Data, System.Data.Common, System.Data.OleDb, System.Data.SqlClient, I ndex System.Data.Odbc, and System.Data.SqlTypes namespaces are all contained within the System.Data.dll List of Figur es assembly. However, the types of the System.Data.OracleClient namespaces are contained within a List separate of Tables assembly named System.Data.OracleClient.dll, while the SqlCe types are placed within

System.Data.Sqlservice.dll. Thus, like any .NET endeavor, be sure to set the correct external references (and C# "using" statements) for your current project.

C# an d th e .N ET Plat f orm , Se con d Ed it ion The Types of System.Data ISBN:1590590554

by Andr ew Tr oelsen

Of all the ADO.NET namespaces, System.Data is the lowest common denominator. You simply cannot Apr ess © 2003 (1200 pages) build ADO.NET applications without this in your data access applications. This This compr ehensiv e specifying text star ts w ith namespace a brief ov er view of the namespace contains types that are shared among all ADO.NET data providers, regardless of the C# language and then quickly m oves to key technical and ar chitectur al issues System.Data for .NET developer s. underlying data store. In a nutshell, contains types that represent the data you obtain from a data store, but not the types that make the literal connection. In addition to a number of database-centric exceptions (NoNullAllowedException, RowNotInTableException, MissingPrimaryKeyException, and the Talike), ble othese f Con ttypes en t s are little more than OO representations of common database primitives (tables, rows, C# and t he constraints, .NET Plat for m, Second Edition columns, and so on). Table 17-2 lists some of the core types, grouped by related functionality. I ntr oduction Pa r t One17-2: - I nt rKey oduciMembers ng C# a ndof the .NET P la tf or m Table the System.Data

Chapter 1

Namespace

- The Philosophy of .NET

System.Data Type Meaning in Life - Building C# Applications

Chapter 2

Pa rDataColumnCollection t Tw o - The C# Pr ogr am m ing La ngua ge DataColumnCollection

is used to represent all of the columns used by

Chapter 3

- C# Language Fundamentals a given DataTable.DataColumn represents a specific column in a DataColumn Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# DataTable. Chapter 5

- Exceptions and Obj ect Lifetim e

ConstraintCollection The ConstraintCollection represents all constraints (foreign key - I nter faces and Collections constrains, unique constraints) assigned to a given DataTable. Constraint Chapter 7 - Callback I nter faces, Delegates, and Ev ents Constraint represents an OO wrapper around a single constraint Chapter 8 - Advanced C# Type Const ruction Techniques assigned to one or more DataColumns. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 6

Chapter 9 - Under standing .NET Assem bliesrepresent a collection of rows for a DataTable DataRowCollection These types Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads (DataRowCollection) and a specific row of data in a DataTable

DataRow

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing (DataRow). Pa r t Four - Le ve r a ging the .NET Libr a r ie s

DataRowView DataRowView you Lay to carve out a predefined "view" from an Chapter 12 - Obj ect Ser ialization and the .NETallows Remoting er existing row.

DataView Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) DataView type Chapter 14 - A Better Paint ing The Fr amew or k ( GDI + ) represents a customized view of a DataTable that can be used for ssorting, filtering, searching, editing, and navigation. Chapter 15 - Pr ogr am ming with Windows Form Contr ols Chapter 16 - The Sy stem .I O Nam espace DataSet Represents an in-memory cache of data that may consist of multiple Chapter 17 - Data Access w ith related ADO.NET DataTables. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

ForeignKeyConstraint ForeignKeyConstraint Chapter 18 - ASP.NET Web Pages and Web Contr ols represents an action restriction enforced on a set ofions columns in a primary key/foreign key relationship. Chapter UniqueConstraint 19 - ASP.NET Web Applicat

Chapter 20 - XML Web Ser vicesThe UniqueConstraint type represents a restriction on a set of columns I ndex

in which all values must be unique.

List of Figur es

This collection represents all relationships (e.g., DataRelation types) between the tables in a DataSet.

DataRelationCollection

List of Tables

DataRelation DataTableCollection DataTable

The DataTableCollection type represents all of tables (e.g., DataTable types) for a particular DataSet.

To get the ball rolling, the first half of this chapter discusses how to manipulate these items by hand. Once you understand how to build a DataSet in the raw, you should have no problem manipulating a DataSet populated by a data provider using a related data adapter. Just as importantly, once you understand how to manually create and tweak a DataSet by hand, you will have no problems altering the wizard-generated code of VS .NET.

th e .N ET Plat f ormType , Se con d Ed it ion Examining C# thean dDataColumn ISBN:1590590554

by Andr ew Tr oelsen

The DataColumnApr type single column maintained by a DataTable. Collectively speaking, the essrepresents © 2003 (1200 apages) set of all DataColumn types bound to a given This compr ehensiv e text star tsDataTable w ith a briefrepresents ov er view ofthe thefoundation of a table's schema information. For example, assume you have a table named Employees C# language and then quickly m oves to key technical andwith three columns (EmpID, ar chitectur alProgrammatically, issues for .NET developer s. FirstName, and LastName). you would use three ADO.NET DataColumn objects to represent them in memory. As you will see in just a moment, the DataTable type maintains an internal collection (which is accessed using the Columns property) to maintain its DataColumn types. Ta ble o f Con t en t s

If you a background in relational C# and have t he .NET Plat for m, Second Editiondatabase theory, you know that a given column in a data table can beoduction assigned a set of constraints (e.g., configured as a primary key, assigned a default value, configured to I ntr contain and so Pon). Also, Pa r t One -read-only I nt r oduciinformation, ng C# a nd the .NET la tf or m

every column in a table must map to an underlying data

type (int, and so forth). For example, the Employees table's schema may demand that the EmpID Chapter 1 varchar, - The Philosophy of .NET column2 maps to an integer, while FirstName and LastName map to an array of characters. The Chapter - Building C# Applications DataColumn hasam numerous properties that Pa r t Tw o - The class C# Pr ogr m ing La ngua ge

allow you to configure these very things. Table 17-3

provides of some core properties. Chapter 3 a- rundown C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Table 17-3: Properties of the DataColumn - Exceptions and Obj ect Lifetim e

Chapter 5

Chapter 6 - I nter faces and Collections DataColumn Meaning in Life Chapter 7 - Callback I nter faces, Delegates, and Ev ents Property Chapter 8

- Advanced C# Type Const ruction Techniques

to Assem indicate if sa Pa rAllowDBNull t Thre e - Pr ogr am m i ng w Used i th .N ET bl ie

row can specify null values in this column. The default value is true. Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts,are andused Threads AutoIncrement These properties to configure the auto-increment behavior for Chapter 11 - Type Reflection,a Late Binding, and Attrcan ibuteBased Pr ogramm ingwish to ensure unique given column. This be helpful when you AutoIncrementSeed Pa r t Four - Le ve r a ging the .NET Librin a r ie values a sgiven DataColumn (such as a primary key). By default, a AutoIncrementStep Chapter 12 - Obj ect Ser ialization DataColumn and the .NET doesRemoting not support Lay er auto-incrementation. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Caption

Gets or sets the caption to be displayed for this column (for example, what the end user sees in a DataGrid).

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

ColumnMapping property determines how a DataColumn is represented when a Chapter 16 - The Sy stem .I O This Nam espace DataSet is saved as an XML document using the DataSet.WriteXml() Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons method. and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages andsets Webthe Contr ols of the column in the Columns collection (meaning ColumnName Gets or name Chapter 19 - ASP.NET Web Applicat ions how it is represented internally by the DataTable). If you do not set the Chapter 20 - XML Web Ser vices ColumnName explicitly, the default values are Column with (n+1) I ndex numerical suffixes (i.e., Column1, Column2, Column3, and so forth). List of Figur es

DataType

Defines the data type (Boolean, string, float, and so on) stored in the column.

DefaultValue

Gets or sets the default value assigned to this column when inserting new rows. This is used if not otherwise specified.

Expression

Gets or sets the expression used to filter rows, calculate a column's value, or create an aggregate column.

Ordinal

Gets the numerical position of the column in the Columns collection maintained by the DataTable.

ReadOnly

Determines if this column can be modified once a row has been added to the table. The default is false.

Table

Gets the DataTable that contains this DataColumn.

List of Tables

Unique

or sets value the values in each row of the C# an d thGets e .N ET Plat faorm , Seindicating con d Ed itwhether ion must be unique or if repeating values are permissible. If a ISBN:1590590554 by Andr ewcolumn Tr oelsen column is assigned a primary key constraint, the Unique property should Apr ess © 2003 (1200 pages) be set to true.

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Building a DataColumn Ta ble o f Con t en t s

To illustrate the basic use of the DataColumn, assume you need to model a column named FirstName, which internally maps to an array of characters. For the sake of argument, let's say this column (for I ntr oductionreason) must be read-only. Assuming you wish to build your DataColumn in the Click event whatever Pa r t One -ofI nt oduci ngtype C# awithin nd thea .NET P la tf or m handler a rButton Windows Forms application, you would write the following logic: C# and t he .NET Plat for m, Second Edition

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

protected void btnColumn_Click (object sender, System.EventArgs e) { Chapter 3 - C# Language Fundamentals // Build the FirstName column. Chapter DataColumn 4 - Obj ect -Or iented Pr ogr am=ming C# colFName neww ith DataColumn(); Chapter // 5 - Set Exceptions and Obj ect Lifetim e a bunch of values. Chapter colFName.DataType 6 - I nter faces and Collections = Type.GetType("System.String"); Chapter colFName.ReadOnly 7 - Callback I nter faces, Delegates, = true; and Ev ents Chapter colFName.Caption 8 - Advanced C# Type = Const ruction Name"; Techniques "First Pa r t ThrecolFName.ColumnName e - Pr ogr am m i ng w i th .N ET = Assem bl ie s "FirstName"; Chapter // 9 - Display Under standing DataColumn's .NET Assem blies values. temp AppDomains, = "ColumnCont type: " +Threads colFName.DataType + "\n" + Chapter string 10 - Pr ocesses, exts, and only?and " Attr + colFName.ReadOnly Chapter 11 - Type Reflection,"Read Late Binding, ibute- Based Pr ogramm ing + "\n" + "Caption: Pa r t Four - Le ve r a ging the .NET Libr a r ie s " + colFName.Caption + "\n" + "Column " + colFName.ColumnName + "\n" + Chapter 12 - Obj ect Ser ialization and theName: .NET Remoting Lay er "Nulls + colFName.AllowDBNull; Chapter 13 - Building a Bet ter Win dow allowed? ( Int roducin g "Window s For ms) Chapter MessageBox.Show(temp, 14 - A Better Paint ing Fr amew or"Column k ( GDI + ) properties"); } Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 -the Data Access w ithinADO.NET This gives result shown Figure 17-2. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 17-2: Exercising a DataColumn type Do be aware that the DataColumn provides several overloaded constructors. Given this, you can specify a number of characteristics directly at the time of creation (as opposed to discrete properties), as shown here: // Build the FirstName column (take two). DataColumn colFName = new DataColumn("FirstName", Type.GetType("System.String")); colFName.ReadOnly = true;

colFName.Caption = "First Name"; C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

Adding a DataColumn to a DataTable This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

The DataColumnartype doesalnot typically existdeveloper as a stand-alone entity, but is instead inserted into a related chitectur issues for .NET s. DataTable. To illustrate, create a new DataTable type (fully detailed later in the chapter). Next, insert each DataColumn in the DataTable.DataColumnCollection type using the Columns property. Here is an example: Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr //oduction Build the FirstName column. Pa r t One - I nt r oduci ng C# a nd=the .NET P la tf or m DataColumn myColumn new DataColumn();

Chapter ... 1

- The Philosophy of .NET

// Create a newC#DataTable. Chapter 2 - Building Applications DataTable myTable newLa ngua DataTable("MyTable"); Pa r t Tw o - The C# Pr ogr am= m ing ge // The property returns a DataColumnCollection type. Chapter 3 Columns - C# Language Fundamentals // Use method toming insert the column in the table. Chapter 4 the - Obj Add() ect -Or iented Pr ogr am w ith C# myTable.Columns.Add(myColumn); Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

- Advanced Type Const ructionto Techniques Configuring a C# DataColumn Function As a Primary Key

Chapter 8

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

One common rulestanding of database development is that a table should have at least one column that functions Chapter 9 - Under .NET Assem blies as the primary key. A primary key constraint used to uniquely identify a record (row) in a given table. In Chapter 10 - Pr ocesses, AppDomains, Cont exts,isand Threads keeping11with the current Employees example, assume you now wish toing build a new DataColumn type to Chapter - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm represent the field. This column Pa r t Four - Le veEmpID r a ging the .NET Libr a r ie s

will be the primary key of the table and thus should have the AllowDBNull and Unique properties configured as shown here: Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

// This is functioning as + a Chapter 14 - column A Better Paint ing Fr amew or k ( GDI ) primary key. DataColumn colEmpID = Windows new DataColumn(EmpID, Type.GetType("System.Int32")); Chapter 15 - Pr ogr am ming with Form s Contr ols colEmpID.Caption = "Employee ID"; colEmpID.AllowDBNull = false; Chapter 17 - Data Access w ith ADO.NET colEmpID.Unique = true; Chapter 16 - The Sy stem .I O Nam espace

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 DataColumn - ASP.NET Web Applicat Once the has been ions correctly set up to function as a primary key, the next step is to assign this Chapter 20 - XML WebDataTable's Ser vices DataColumn to the PrimaryKey property. You will see how to do in just a bit during the I ndex discussion of the DataTable, so put this on the back burner for the time being. List of Figur es List of Tables

Enabling Auto-Incrementing Fields

One aspect of the DataColumn you may choose to configure is its ability to autoincrement. Simply put, auto-incrementing columns are used to ensure that when a new row is added to a given table, the value of this column is assigned automatically, based on the current step of the incrementation. This can be helpful when you wish to ensure that a column has no repeating values (such as a primary key). This behavior is controlled using the AutoIncrement, AutoIncrementSeed, and AutoIncrementStep properties. To illustrate, build a DataColumn that supports auto-incrementation. The seed value is used to mark the starting value of the column, where the step value identifies the number to add to the seed when incrementing, as shown here: // Create a data column. DataColumn myColumn = new DataColumn(); myColumn.ColumnName = "Foo"; myColumn.DataType = System.Type.GetType("System.Int32");

// Set the auto-increment behavior. C# an d th e .N ET Plat f orm , Se con d Ed it ion myColumn.AutoIncrement = true; by Andr ew Tr oelsen myColumn.AutoIncrementSeed = 500; Apr ess © 2003 (1200 pages) myColumn.AutoIncrementStep = 12;

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET to developer Here, the Foo column has been configured ensure s. that as rows are added to the respective table, the

value in this field is incremented by 12. Because the seed has been set at 500, the first five values should be 500, 512, 524, 536, and 548.

Ta ble o f Con t en t s

C# t hethe .NET Plat for m, Second Edition Toand prove point, insert this DataColumn in a DataTable. Then add a number of new rows to the table, I ntr oduction which of course automatically bumps the value in the Foo column, as shown here: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - The Philosophy of .NET protected void btnAutoCol_Click (object sender, System.EventArgs e) Chapter 2 Building C# Applications { Pa r t Tw o// - The C# Praogr am m ing La nguathat ge Make data column

maps to an int.

Chapter DataColumn 3 - C# Language Fundamentals myColumn = new DataColumn(); Chapter myColumn.ColumnName 4 - Obj ect -Or iented Pr ogr am=ming w ith C# "Foo"; Chapter myColumn.DataType 5 - Exceptions and Obj ect = Lifetim System.Type.GetType("System.Int32"); e

behavior. Chapter // 6 - Set I nter the faces auto-increment and Collections = true; Chapter myColumn.AutoIncrement 7 - Callback I nter faces, Delegates, and Ev ents = 500; Chapter myColumn.AutoIncrementSeed 8 - Advanced C# Type Const ruction Techniques Pa r t ThremyColumn.AutoIncrementStep e - Pr ogr am m i ng w i th .N ET Assem bl ie= s

12; // Add this column to a new DataTable. Chapter 9 - Under standing .NET Assem blies myTable = new Chapter DataTable 10 - Pr ocesses, AppDomains, Cont DataTable("MyTable"); exts, and Threads myTable.Columns.Add(myColumn); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing // Add 20 new rows. Pa r t Four - Le ve r a ging the .NET Libr a r ie s DataRow r; Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er for(int i =0; i < 20; i++) Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) { Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) r = myTable.NewRow(); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols myTable.Rows.Add(r); Chapter } 16 - The Sy stem .I O Nam espace Chapter // 17 - Now Data list Access the w ith ADO.NET value in each row. Pa r t Fi vestring - W e b Appl ica ti ons and X ML W e b Se r vi ces temp = ""; Chapter DataRowCollection 18 - ASP.NET Web Pages and Web ols rows = Contr myTable.Rows; Chapter for(int 19 - ASP.NET Applicat ions i Web = 0;i < myTable.Rows.Count; i++) Chapter { 20 - XML Web Ser vices I ndex DataRow currRow = rows[i]; List of Figur es temp += currRow["Foo"] + " "; } List of Tables MessageBox.Show(temp, "These values brought ala auto-increment"); }

If you run the application (and click the corresponding Button), you see the message shown in Figure 17-3.

Figure 17-3: Auto-incrementation of a DataColumn

Configuring a Column's XML Data Representation

While many of the remaining DataColumn properties are rather self-explanatory (provided you are an d th e .N ET Plat f orm , Se con d Ed it ion comfortable with C# database terminology), I would like to discuss the ColumnMapping property. The ISBN:1590590554 by Andr ew Tr oelsen DataColumn.ColumnMapping property is used to configure how this column should be represented in Apr ess © 2003 (1200 pages) XML, if the owning DataSet dumps its contents using the WriteXml() method. The value of the compr e textusing star tsthe w ith a brief ov er view of the ColumnMapping This property isehensiv configured MappingType enumeration (Table 17-4). C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Table 17-4: Values of the MappingType Enumeration MappingType Enumeration

Meaning in Life

Ta ble o f Con t en t s Value C# and t he .NET Plat for m, Second Edition I ntrAttribute oduction

The column is mapped to an XML attribute.

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Element

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

The column is mapped to an XML element (the default).

Pa rHidden t Tw o - The C# Pr ogr am m ing La ngua ge

The column is mapped to an internal structure.

Chapter 3

The column is mapped to text.

- C# Language Fundamentals SimpleContent

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - Exceptions Obj ect Lifetim e property is MappingType.Element. Assume that you have The default value of theand ColumnMapping Chapter 6 I nter faces and Collections instructed the owning DataSet to write its contents to a new file stream as XML. Using this default setting, Chapter 7 - column Callbackwould I nter faces, Delegates, and Ev ents the EmpID appear as shown here: Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 500 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

However, DataColumn's property Chapter 12 if - the Obj ect Ser ialization ColumnMapping and the .NET Remoting Lay is er set to MappingType.Attribute, you see the following representation: Chapter 13 XML - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter

with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

This the and ADO.NET/XML Pa r t Fichapter ve - W e bexamines Appl ica ti ons X ML W e b Se rintegration vi ces

in greater detail when discussing the DataSet. Nevertheless, at this point, you understand how to create a stand-alone DataColumn type. Now for an Chapter 18 - ASP.NET Web Pages and Web Contr ols examination of the related DataRow type. Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 - XML Web The Ser vices SOURCE DataColumn application is included under the Chapter 17 subdirectory. I ndex CODE List of Figur es List of Tables

th e .N ET PlatType f orm , Se con d Ed it ion Examining C# thean dDataRow ISBN:1590590554

by Andr ew Tr oelsen

As you have seen, aess collection of DataColumn objects represents the schema of a table. A DataTable Apr © 2003 (1200 pages) maintains its columns using the internal DataColumnCollection type.ofInthe contrast, a collection of DataRow This compr ehensiv e text star ts w ith a brief ov er view types represents C# thelanguage actual data in the table. Thus, if you have 20 listings and then quickly m oves to key technical and in a table named Employees, arthese chitectur al issues for20 .NET developer s. Using the members of the DataRow class, you you can represent entries using DataRow types. are able to insert, remove, evaluate, and manipulate the values in the table. TaWorking ble o f Con with t enat s DataRow is a bit different from working with a DataColumn, because you cannot create a

direct type, but rather C# and instance t he .NET of Platthis for m, Second Editionobtain a reference from a given DataTable. For example, assume youoduction wish to insert a new row in the Employees table. The DataTable.NewRow() method allows you to I ntr obtain next slotng in C# theatable, which Pa r t Onethe - I nt r oduci nd theat .NET P la point tf or m you

can fill each column with new data via the type indexer,

as shown Chapter 1 -here: The Philosophy of .NET Chapter 2

- Building C# Applications

Pa // r t Tw Build o - TheaC#new Pr ogr Table. am m ing La ngua ge

DataTable = new DataTable("Employees"); Chapter 3 - C#empTable Language Fundamentals // Add FirstName and LastName columns to table... Chapter 4 EmpID, - Obj ect -Or iented Pr ogr am ming w ith C# ... 5 Chapter

- Exceptions and Obj ect Lifetim e // Build new record. Chapter 6 - Ia nter facesEmployee and Collections

DataRow = empTable.NewRow(); Chapter 7 - row Callback I nter faces, Delegates, and Ev ents row["EmpID"] = 102; - Advanced C# Type Const ruction Techniques row["FirstName"] = "Joe"; Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s row["LastName"] = "Blow"; Chapter 9 - Under standing .NET Assem blies // Add it to the Table's DataRowCollection. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads empTable.Rows.Add(row); Chapter 8

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter Building a Bet ter Windefines dow ( Intan roducin g Window s For Notice 13 how- the DataRow class indexer that can bems) used to gain access to a given DataColumn Chapter 14 - A position Better Paint ing Fras amew or k ( name. GDI + ) Also notice that the DataTable maintains another internal by numerical as well column Chapter collection 15 (DataRowCollection) - Pr ogr am ming with Windows to hold Form eachsrow Contr of ols data. The DataRow type defines the core members,

grouped functionality, in Table 17-5. Chapter 16by - related The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Table Key Members of the Pa r t Fi ve17-5: - Web Appl ica ti ons and X MLDataRow W e b Se r viType ces Chapter 18 - ASP.NET Web Pages and Web Contr ols

DataRow Member

Meaning in Life

Chapter 19 - ASP.NET Web Applicat ions Chapter HasErrors 20 - XML Web Ser vices The HasErrors property returns a Boolean value indicating if there are I ndex GetColumnsInError()

errors in a columns collection.

List of Figur es

If so, the GetColumnsInError() method can be used to obtain the offending members, GetColumnError() can be used to obtain the error description, while the ClearErrors() method removes each error listing for the row.

GetColumnError()

List of Tables

ClearErrors() RowError

The RowError property allows you to configure a textual description of the error for a given row. ItemArray

This property gets or sets all of the values for this row using an array of objects.

RowState

This property is used to pinpoint the current "state" of the DataRow using values of the RowState enumeration.

Table

Use this property to obtain a reference to the DataTable containing this DataRow.

AcceptChanges()

Commit (or reject) all the changes made to this row since the last time AcceptChanges() was called.

RejectChanges()

BeginEdit()

cancel an edit on a DataRow object. C# an d thBegin, e .N ETend, Plator f orm , Se con d Edoperation it ion

EndEdit()

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

CancelEdit()

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language Thisand method then quickly marks m this oves rowtotokey betechnical removedand when the AcceptChanges() ar chitecturmethod al issuesisfor .NET developer s. called.

Delete() IsNull() Ta ble o f Con t en t s

Gets a value indicating whether the specified column contains a null value.

C# and t he .NET Plat for m, Second Edition I ntr oduction

Understanding the DataRow.RowState Property

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET Most of2the- methods of Applications the DataRow class only make sense in the context of an owning DataTable. You Chapter Building C#

will see process of am inserting, Pa r t Tw o the - The C# Pr ogr m ing Laremoving, ngua ge

and updating rows in just a moment; first, however, you should get to know the RowState property. This property is useful when you need to programmatically identify the Chapter 3 - C# Language Fundamentals set of all rows in a table that have changed, have been newly inserted, and so forth. This property may be Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# assigned any value from the DataRowState enumeration (Table 17-6). Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Table 17-6: Values Iof the DataRowState Enumeration Chapter 7 - Callback nter faces, Delegates, and Ev ents Chapter 8 - Advanced C# Type Const ruction DataRowState Meaning in Techniques Life Pa rEnumeration t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - Under standing .NET Assem blies Value Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Added11 - Type Reflection, Late TheBinding, row hasand been to a DataRowCollection, and Chapter Attradded ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NETAcceptChanges() Libr a r ie s

has not been called.

Chapter 12 - Obj ect Ser ialization and thehas .NET Remoting Layvia er the Delete() method of the DataRow. Deleted The row been deleted, Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Detached

The row has been created but is not part of any DataRowCollection. A DataRow is in this state immediately after it has been created and Chapter 15 - Pr ogr am ming with Windows Form s Contr ols before it is added to a collection, or if it has been removed from a Chapter 16 - The Sy stem .I O Nam espace collection. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 17 - Data Access w ith ADO.NET

Pa rModified t Fi ve - W e b Appl ica ti ons and The X ML rowWhas e b Se been r vi ces modified,

and AcceptChanges() has not been

called. Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Unchanged

The row has not changed since AcceptChanges() was last called.

Chapter 20 - XML Web Ser vices I ndex

List Figur es the various states a DataRow may have, the following class documents the changes to the To ofillustrate List RowState of Tablesproperty as a new DataRow is created, inserted in, and removed from a DataTable:

public class DRState { public static void Main() { Console.WriteLine("***** The RowState property *****"); // Build a single column DataTable DataTable myTable = new DataTable("Employees"); DataColumn colID = new DataColumn("empID", Type.GetType("System.Int32")); myTable.Columns.Add(colID); // The DataRow. DataRow myRow; // Create a new (detached) DataRow. Console.WriteLine("Made new DataRow");

myRow = myTable.NewRow(); C# an d th e .N ET Plat f orm , Se con d Ed it ion Console.WriteLine("->Row state: {0}\n", myRow.RowState.ToString()); ISBN:1590590554 by Andr ew Tr oelsen // Now add it to table. Apr ess © 2003 (1200 pages) Console.WriteLine("Added DataRow to DataTable"); This compr ehensiv e text star ts w ith a brief ov er view of the myTable.Rows.Add(myRow); C# language and then quickly m oves to key{0}\n", technical and Console.WriteLine("->Row state: myRow.RowState.ToString()); ar chitectur al issues for .NET developer s. // Trigger an accept. Console.WriteLine("Called AcceptChanges() on DataTable"); myTable.AcceptChanges(); Ta ble o f Con t en t s Console.WriteLine("->Row state: {0}\n", myRow.RowState.ToString()); C# and t he .NET Plat for m, Second Edition // Modify it. I ntr oduction Console.WriteLine("Modified DataRow"); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m myRow["empID"] = 100; Chapter 1 - The Philosophy of .NET Console.WriteLine("->Row state: {0}\n", myRow.RowState.ToString()); Chapter 2 - Building C# Applications // Now delete it. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Console.WriteLine("Deleted DataRow"); Chapter 3 - C#myRow.Delete(); Language Fundamentals Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# state: {0}\n", myRow.RowState.ToString()); Console.WriteLine("->Row Chapter 5 - Exceptions and Obj ect Lifetim e myRow.AcceptChanges(); Chapter } 6 - I nter faces and Collections Chapter 7 - Callback I nter faces, Delegates, and Ev ents } Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

The output bestanding seen in .NET Figure 17-4. Chapter 9 - can Under Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Figure Examining row state Chapter 19 - 17-4: ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

As you can see, the ADO.NET DataRow is smart enough to remember its current state of affairs. Given this, the owning DataTable is able to identify which rows have been modified. This is a key feature of the List of Figur es DataSet, given that when it comes time to send updated information to the data store, only the modified List of Tables data is submitted. Clearly this behavior helps optimize trips between the layers of your system. I ndex

SOURCE CODE

The DataRowState is included under the Chapter 17 subdirectory.

C# an d th e .N ET Plat f orm , Se con d Ed it ion Details of the DataTable ISBN:1590590554

by Andr ew Tr oelsen

The DataTable isApr aness in-memory representation of a tabular block of data. While you can manually © 2003 (1200 pages) compose a DataTable programmatically, you will commonly This compr ehensiv e text star ts w ithmore a brief ov er view obtain of the a DataTable dynamically using a DataSet and a given data provider. Table 17-7 describes some core properties of the DataTable type. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Table 17-7: Key Members of the DataTable DataTable Ta ble o f Con t en t s

Meaning in Life Property C# and t he .NET Plat for m, Second Edition I ntr oduction

CaseSensitive

This property indicates whether string comparisons within the table are case-sensitive (or not). The default value is "false".

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET ChildRelations This property returns the collection of child relations Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m(DataRelationCollection) ing La ngua ge

for this DataTable (if any).

Chapter 3

Columns- C# Language Fundamentals As you have seen, this property returns the collection of columns that - Obj ect -Or ientedbelong Pr ogr am w ith C# toming this table.

Chapter 4 Chapter 5

- Exceptions and Obj ect Lifetim e Constraints Gets the collection of constraints maintained by the table Chapter 6 - I nter faces and Collections Chapter 7

(ConstraintCollection). - Callback I nter faces, Delegates, and Ev ents

Chapter 8 - Advanced C# Type ruction Techniques DataSet GetsConst the DataSet that contains this table (if any). Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

DefaultView GetsAssem a customized view of the table that may include a filtered view, or a Chapter 9 - Under standing .NET blies cursor position.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection,Gets Late or Binding, and Attr ibuteBased Pr ogramm MinimumCapacity sets the initial number of rows in thising table (the default is 25). Pa r t Four - Le ve r a ging the .NET Libr a r ie s

ParentRelations

Gets the collection of parent relations for this DataTable.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet terGets Win or dow ( Intan roducin s For ms)function as primary keys for the PrimaryKey sets arraygofWindow columns that Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) data table. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Rows

As you have seen, this property returns the collection of rows that belong to this table.

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Pa rTableName t Fi ve - W e b Appl ica ti ons Gets and Xor MLsets W e bthe Se rname vi ces of

the table. This same property may also be

specified as a Contr constructor parameter. Chapter 18 - ASP.NET Web Pages and Web ols Chapter 19 - ASP.NET Web Applicat ions

To help20visualize the key components of a DataTable, consider Figure 17-5. Be aware that this is not a Chapter - XML Web Ser vices traditional class hierarchy that illustrates the "is-a" relation between these types (e.g., the DataRow does I ndex notofderive from DataRowCollection). Rather, this diagram points out the logical "has-a" relationships List Figur es

between the DataTable's core items (e.g., the DataRowCollection has a number of DataRow types). List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4 - 17-5: Obj ectThe -Or iented Pr ogr w ith C#DataTable Figure structure ofam anming ADO.NET Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion Building a Complete DataTable by Andr ew Tr oelsen

ISBN:1590590554

Now that you have the basics, let's see a complete example of creating and manipulating Aprbeen ess ©exposed 2003 (1200to pages) an in-memory data table. Assume you are interested building a DataTable representing the current This compr ehensiv e text star ts w ith a in brief ov er view of the inventory in a database named Cars. The Inventory table will contain four columns: CarID, Make, Color, C# language and then quickly m oves to key technical and ar chitectur al issues for will .NETfunction developer and PetName. Also, the CarID column ass.the table's primary key (PK) and support autoincrementation. The PetName column will allow null values. (Sadly, not everyone loves their automobiles as much as we might.) Figure 17-6 shows the overall schema. Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7 - 17-6: Callback I nter faces, Delegates, and Ev ents Figure The DataTable under construction Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

The process begins by creating a newblies DataTable type. When you do so, you specify the friendly name of Chapter 9 - Under standing .NET Assem the table as a constructor parameter (as shown next). This friendly name can be used to reference this table from the containing DataSet:

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

// Create aect new DataTable. Chapter 12 - Obj Ser ialization and the .NET Remoting Lay er DataTable inventoryTable = ( new DataTable("Inventory"); Chapter 13 - Building a Bet ter Win dow Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

The next step is to programmatically insert each column using the Add() method of the

Chapter 16 - The Sy stem .I(accessed O Nam espace DataColumnCollection using the DataTable.Columns property). The following logic adds the Chapter 17 Data Access w ith ADO.NET CarID, Make, Color, and PetName columns to the current DataTable (recall that the underlying data type Pa Fi ve -column W e b Appl ica tiusing ons and ML W e b Seproperty): r vi ces ofr teach is set theXDataType

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

// DataColumn var.

Chapter 20 - XMLmyDataColumn; Web Ser vices DataColumn I ndex // Create CarID column and add to table. List of Figur es myDataColumn = new DataColumn(); List of Tables myDataColumn.DataType = Type.GetType("System.Int32");

myDataColumn.ColumnName = "CarID"; myDataColumn.ReadOnly = true; myDataColumn.AllowDBNull = false; myDataColumn.Unique = true; // Set the auto-increment behavior. myDataColumn.AutoIncrement = true; myDataColumn.AutoIncrementSeed = 1000; myDataColumn.AutoIncrementStep = 10; inventoryTable.Columns.Add(myDataColumn); // Create Make column and add to table. myDataColumn = new DataColumn(); myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "Make"; inventoryTable.Columns.Add(myDataColumn); // Create Color column and add to table.

myDataColumn = new DataColumn(); C# an d th e .N=ETType.GetType("System.String"); Plat f orm , Se con d Ed it ion myDataColumn.DataType ISBN:1590590554 by Andr ew Tr oelsen myDataColumn.ColumnName = "Color"; Apr ess © 2003 (1200 pages) inventoryTable.Columns.Add(myDataColumn); This compr ehensiv and e text add star tsto w ithtable. a brief ov er view of the // Create PetName column C# language and then quickly m oves to key technical and myDataColumn = new DataColumn(); ar chitectur al issues for .NET developer s. myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "PetName"; myDataColumn.AllowDBNull = true; Ta ble o f Con t en t s inventoryTable.Columns.Add(myDataColumn); C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One you - I ntadd r oduci C# a you nd the P la tfto ortake m Before thengrows, will.NET do well

the time to set the table's primary key. To do so, set the

Chapter 1 - The Philosophy of .NET DataTable.PrimaryKey property to whichever column necessary. Because more than a single column can Chapter 2 Building C# Applications function as a table's primary key, be aware that the PrimaryKey property requires an array of DataColumn Pa r t Tw oFor - The Pr ogr am m ing assume La ngua ge types. theC# Inventory table, the

CarID column is the only aspect of the primary key, as shown

Chapter here: 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - the Exceptions and Obj ect e // Make ID column theLifetim primary key column. Chapter 6 I nter faces and Collections DataColumn[] PK = new DataColumn[1]; Chapter Callback I nter faces, Delegates, and Ev ents PK[0]7 = - inventoryTable.Columns["CarID"]; Chapter 8 - Advanced C# Type Const = ruction inventoryTable.PrimaryKey PK; Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies Last but least, you AppDomains, need to add valid data to table. Assuming you have an appropriate ArrayList Chapter 10not - Pr ocesses, Cont exts, andthe Threads

maintaining Car types, you can the table shown Chapter 11 - Type Reflection, Latefill Binding, andas Attr ibute-here: Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

// Iterate the array list fill Lay rows Chapter 12 - Obj over ect Ser ialization and the .NETto Remoting er (remember, the ID is // auto-incremented). Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) foreach(Car c in arTheCars) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) { Chapter 15 - Pr ogr am ming with Windows Form s Contr ols DataRow newRow; newRow = inventoryTable.NewRow(); Chapter 17 - Data Access w ith ADO.NET newRow["Make"] = c.make; Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces newRow["Color"] = c.color; Chapter 18 - ASP.NET Web Pages and Web Contr ols newRow["PetName"] = c.petName; Chapter 19 - ASP.NET Web Applicat ions inventoryTable.Rows.Add(newRow); Chapter 20 - XML Web Ser vices } Chapter 16 - The Sy stem .I O Nam espace

I ndex List of Figur es List To ofdisplay Tablesyour new local in-memory table, assume you have a Windows Forms application with a main

Form displaying a DataGrid. As you saw in Chapter 11, the DataSource property is used to bind a DataTable to the GUI. The output is shown in Figure 17-7.

Figure 17-7: The visual representation of the DataTable

Here, you added rows by specifying the string name of the column to modify. However, you may also C# an d th e .N ET Plat f orm , Se con d Ed it ion specify the numerical index of the column, which can be very helpful when you need to iterate over each ISBN:1590590554 byprevious Andr ew Tr oelsen column. Thus, the code could be updated as shown here (and still achieve the same end result): Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the

foreach(Car cC#in arTheCars) language and then quickly m oves to key technical and { ar chitectur al issues for .NET developer s. // Specify columns by index. DataRow newRow; newRow Ta ble o f Con t en t s = inventoryTable.NewRow(); C# and tnewRow[1] he .NET Plat for=m,c.make; Second Edition newRow[2] = c.color; I ntr oduction Pa r t OnenewRow[3] - I nt r oduci ng =C#c.petName; a nd the .NET P la tf or m inventoryTable.Rows.Add(newRow); Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

- Obj ect -Ora iented Pr ogr am ming w ith C# Manipulating DataTable: Deleting Rows

Chapter 4 Chapter 5

- Exceptions and Obj ect Lifetim e What if6you- wish to remove a row from a data table? One approach is to call the Delete() method of the Chapter I nter faces and Collections

DataRowCollection SimplyDelegates, specify the index (or DataRow) representing the row to remove. Assume Chapter 7 - Callback type. I nter faces, and Ev ents you update- your GUI as shown in Figure 17-8. Advanced C# Type Const ruction Techniques

Chapter 8

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - 17-8: Data Access w ith rows ADO.NET Figure Removing from the DataTable Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

If you look the previous screen shot, willols notice that you specified the second row in the DataTable, Chapter 18 - atASP.NET Web Pages and Webyou Contr and therefore CarID 1020 has been Chapter 19 - ASP.NET Web Applicat ionsmarked as deleted. The following logic behind the new Button's Click event handler removes specified row from your in-memory DataTable: Chapter 20 - XML Web Serthe vices I ndex

//ofRemove List Figur es this row from the DataRowCollection. protected List of Tables void btnRemoveRow_Click (object sender, System.EventArgs e) { try { inventoryTable.Rows[(int.Parse(txtRemove.Text))].Delete(); inventoryTable.AcceptChanges(); } catch(Exception ex) { MessageBox.Show(ex.Message); } }

The Delete() method might have been better named MarkedAsDeletable() given that the row is not literally removed until the DataTable.AcceptChanges() method has been called. In effect, the Delete() method

simply sets a flag that says "I am ready to die when my table tells me." Also understand that if a row has an d th e .N ET Plat f orm , Se con d Ed it ion been marked for C# deletion, a DataTable may reject the delete operation via RejectChanges(), as shown ISBN:1590590554 by Andr ew Tr oelsen here: Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the

// Mark a rowC#as deleted, but reject the changes. language and then quickly m oves to key technical and protected void btnRemoveRow_Click (object sender, System.EventArgs e) ar chitectur al issues for .NET developer s. { inventoryTable.Rows[(int.Parse(txtRemove.Text))].Delete(); work Ta ble o f // Con Do t en t more s ... C# and t he .NET Plat for m, Second Edition inventoryTable.RejectChanges(); // Restore previous RowState value. I ntr oduction } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Manipulating a DataTable: Applying Filters and Sort Orders

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals You may a smallPrsubset of a DataTable's data, as specified by some sort of filtering criteria. Chapter 4 wish - Objto ectsee -Or iented ogr am ming w ith C#

For example, what if you to only seee a certain make of automobile from the in-memory Inventory Chapter 5 - Exceptions andwish Obj ect Lifetim table? The method of the DataTable class provides this very functionality. Update your GUI once Chapter 6 - Select() I nter faces and Collections again, this allowing specify aand string that represents the make of the automobile they are Chapter 7 -time Callback I nterusers faces, to Delegates, Ev ents interested -inAdvanced viewing (Figure 17-9). The result will be placed into a Windows Forms message box. C# Type Const ruction Techniques

Chapter 8

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t FiFigure ve - W e17-9: b Appl ica ti ons and X ML W e b Se r vi ces Specifying a filter

Chapter 18 - ASP.NET Web Pages and Web Contr ols

The Select() methodWeb has been overloaded a number of times to provide different selection semantics. At Chapter 19 - ASP.NET Applicat ions its most20basic level, sent to Select() is a string that contains some conditional operation. To Chapter - XML Webthe Serparameter vices begin, observe the following logic for the Click event handler of your new Button: I ndex List of Figur es

protected List of Tables void btnGetMakes_Click (object sender, System.EventArgs e) { // Build a filter based on user input. string filterStr = "Make='" + txtMake.Text + "'"; // Find all rows matching the filter. DataRow[] makes = inventoryTable.Select(filterStr); // Show what we got! if(makes.Length == 0) MessageBox.Show("Sorry, no cars...", "Selection error!"); else { string strMake = null; for(int i = 0; i < makes.Length; i++) { DataRow temp = makes[i];

strMake += temp["PetName"] + "\n"; } C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554 by Andr ew Tr oelsen MessageBox.Show(strMake, txtMake.Text + " type(s):"); Apr ess © 2003 (1200 pages)

}

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

}

Here, you first build a simple filter criteria based on the value in the associated TextBox. If you specify BMW, your filter is Make = 'BMW'. When you send this filter to the Select() method, you get back an array Ta ble o f Con t en t s of DataRow types that represent each row that matches the filter criteria (Figure 17-10). C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Figure 17-10: Filtered data

Chapter - Advanced C# Type Const ruction Techniques A filter 8string can be composed of any number of relational operators. For example, what if you wanted to Pa r t Thre e - Prwith ogr am w i th .N ET Assem ie s find all cars an mIDi ng greater than 1030?blYou

Chapter 9

could write the following (see Figure 17-11 for output):

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

// Now show the pet names of all cars with ID greater than 1030.

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing DataRow[] properIDs; Pa r t Four newFilterStr - Le ve r a ging the .NET Libr a> r ie '1030'"; s string = "ID

Chapter 12 - Obj Ser ialization and the .NET Remoting Lay er properIDs =ect inventoryTable.Select(newFilterStr); Chapter 13 strIDs - Building=a Bet ter Win dow ( Int roducin g Window s For ms) string null; Chapter 14 - iA = Better Fr amew or k ( GDI + ) for(int 0; Paint i < ing properIDs.Length; i++) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols { Chapter DataRow 16 - The Sytemp stem .I O = Nam properIDs[i]; espace

temp["PetName"] Chapter strIDs 17 - Data += Access w ith ADO.NET + ica " tiis + W temp["ID"] Pa r t Fi ve - W e b Appl ons ID and "X ML e b Se r vi ces

+ "\n";

} Chapter 18 - ASP.NET Web Pages and Web Contr ols MessageBox.Show(strIDs, "Pet names of cars where ID > 1030"); Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 17-11: Specifying a range of data As you can see, filtering logic is standard SQL syntax. To prove the point, assume you wish to obtain the results of the previous Select() invocation alphabetically based on pet name. In terms of SQL, this translates into a sort based on the PetName column. Luckily, the Select() method has been overloaded to send in a sort criterion, as shown here: makes = inventoryTable.Select(filterStr, "PetName");

C# an d th e .N ET Plat f orm , Se con d Ed it ion

If you want the results in descending order, call Select(), as shown here: by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

// Return results in descending order. This compr ehensiv e text star ts w ith a brief ov er view of the makes = inventoryTable.Select(filterStr, "PetName DESC"); C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

In general, the sort string contains the column name followed by "ASC" (ascending, which is the default) If need be, multiple columns can be separated by commas. Taor ble"DESC" o f Con t(descending). en t s C# and t he .NET Plat for m, Second Edition

Manipulating a DataTable: Updating Rows

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

The final of the DataTable Chapter 1 aspect - The Philosophy of .NET you should be aware of is the process of updating an existing row with new values. One approach is to first obtain the row(s) that match a given filter criterion using the Select() Chapter 2 - Building C# Applications method. have DataRow(s) Pa r t Tw o - Once The C#you Pr ogr amthe m ing La ngua ge

in question, modify them accordingly. For example, assume you have a new Button that (when clicked) searches the DataTable for all rows where Make is equal to BMW. Chapter 3 - C# Language Fundamentals Once you identify these items, you change the Make from "BMW" to "Colt": Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e // Find rowsand you want to edit with a filter. Chapter 6 - the I nter faces Collections

protected void IbtnChange_Click (object Chapter 7 - Callback nter faces, Delegates, and Ev ents sender, System.EventArgs e) { Chapter 8

- Advanced C# Type Const ruction Techniques

Build filter. Pa r t Thre// e - Pr ogr am a m i ng w i th .N ET Assem bl ie s "Make='BMW'"; Chapter string 9 - UnderfilterStr standing .NET=Assem blies string strMake = null; // Find all rows matching the filter. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing DataRow[] makes = inventoryTable. Select(filterStr); Pa r t Four - Le ve r a ging the .NET Libr a r ie s // Change all Beemers to Colts! Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er for(int i = 0; i < makes.Length; i++) Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) { Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) DataRow temp = makes[i]; Chapter 15 - Pr strMake ogr am ming += withtemp["Make"] Windows Form s Contr ols = "Colt"; Chapter 16 - The Sy stem .I O Nam espace makes[i] = temp; Chapter } 17 - Data Access w ith ADO.NET Pa }r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

The DataRow class provides the BeginEdit(), EndEdit(), and CancelEdit() methods, which allow you Chapter 20 - XML Webalso Ser vices to edit the content of a row while temporarily suspending any associated validation rules. In the previous I ndex

logic, eachesrow was validated with each assignment. (Also, if you capture any events from the DataRow, List of Figur

they fire with each modification.) When you call BeginEdit() on a given DataRow, the row is placed in edit mode. At this point you can make your changes as necessary and call either EndEdit() to commit these changes or CancelEdit() to roll back the changes to the original version. For example:

List of Tables

// Assume you have obtained a row to edit. // Now place this row in edit mode. rowToUpdate.BeginEdit(); // Send the row to a helper function, which returns a Boolean. if( ChangeValuesForThisRow(rowToUpdate) ) { rowToUpdate.EndEdit(); // OK! } else { rowToUpdate.CancelEdit(); // Forget it. }

th e .N ET Plat f orm , Se con d Ed it ion Although you areC# freeantod manually call these methods on a given DataRow, these members are by Andr ew Tr oelsen automatically called when you edit a DataGrid widget that has ISBN:1590590554 been bound to a DataTable. For example, essto© edit 2003 from (1200 pages) when you select aApr row a DataGrid, that row is automatically placed in edit mode. When you Thisrow, compr ehensiv e starautomatically. ts w ith a brief ov viewthis of behavior, the shift focus to a new EndEdit() is text called Toertest assume you have C# language and then quickly m oves to key technical and manually updated each car to be of a given Make using the DataGrid (Figure 17-12). ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e Figure Editing in a DataGrid Chapter 6 - 17-12: I nter faces and rows Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8 -request Advanced Typethe Const ruction Techniques If you now all C# BMWs, message box correctly returns all rows, as the underlying DataTable Pa r t Thre e - Pr m i ng w i th .N been ET Assem bl ie s associated toogr theam DataGrid has automatically updated

Chapter 9

(Figure 17-13).

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Figure The updated set of BMW autos Chapter 18 - 17-13: ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dthe th e .N ET Plat f orm , Type Se con d Ed it ion Understanding DataView by Andr ew Tr oelsen

ISBN:1590590554

In database nomenclature, a view object is a stylized representation of a table. For example, using Apr ess © 2003 (1200 pages) Microsoft SQL Server, you could create view current Inventory This compr ehensiv e text astar ts for w ithyour a brief ov er view of thetable that returns a new table only containing automobiles of a given color. In ADO.NET, the DataView C# language and then quickly m oves to key technical type and allows you to programmatically ar chitectur al the issues for .NET developer s. extract a subset of data from DataTable. One great advantage of holding multiple views of the same table is that you can bind these views to Tavarious ble o f Con GUIt en widgets ts (such as the DataGrid). For example, one DataGrid might be bound to a DataView

showing autos the while another may be configured to display only green automobiles. On C# and t heall .NET Platinfor m, Inventory, Second Edition a related I ntr oductionnote, the DataTable type provides the DefaultView property that returns the default DataView for the table. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

To illustrate, update the user interface of the current Windows Forms application to support two additional - Building C# Applications DataGrid types. One of these grids only shows the rows from the Inventory that match the filter Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Make='Colt'. The other grid only shows red automobiles (i.e., Color='Red'). Figure 17-14 shows the GUI Chapter 3 - C# Language Fundamentals update. Chapter 2

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - 17-14: XML Web Ser vices Figure Creating multiple views for a single DataTable I ndex List of Figur es

To ofbegin, you need to create two member variables of type DataView: List Tables public class mainForm : System.Windows.Forms.Form { // Views of the DataTable. DataView redCarsView; // I only show red cars. DataView coltsView; // I only show Colts. ... }

Next, assume you have a new helper function named CreateViews(), which is called directly after the DataTable has been fully constructed, as shown here: protected void btnMakeDataTable_Click (object sender, System.EventArgs e) {

// Make the data table. C# an d th e .N ET Plat f orm , Se con d Ed it ion MakeTable(); ISBN:1590590554 Andr ew Tr oelsen // Make byviews. Apr ess © 2003 (1200 pages) CreateViews(); This compr ehensiv e text star ts w ith a brief ov er view of the ... C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

}

Ta ble o f Con t en t s

Here is the implementation of this new helper function. Notice that the constructor of each DataView has been passed the DataTable that will be used to build the custom set of data rows:

C# and t he .NET Plat for m, Second Edition I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

private void CreateViews() - The Philosophy of .NET { Chapter 2 - Building C# Applications // Set the table that is used to construct these views. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge redCarsView = new DataView(inventoryTable); Chapter 3 - C# Language Fundamentals coltsView = new DataView(inventoryTable); Chapter // 4 - Now Obj ect -Or iented Pr ogr am ming w ithusing C# configure the views a filter. Chapter redCarsView.RowFilter 5 - Exceptions and Obj ect Lifetim e = "Color = 'red'"; Chapter coltsView.RowFilter 6 - I nter faces and Collections = "Make = 'colt'"; Chapter // 7 - Bind Callback faces, Delegates, and Ev ents toI nter grids. Chapter RedCarViewGrid.DataSource 8 - Advanced C# Type Const ruction = Techniques redCarsView; Pa r t ThreColtsViewGrid.DataSource e - Pr ogr am m i ng w i th .N ET Assem bl s =iecoltsView; Chapter } 9 - Under standing .NET Assem blies Chapter 1

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

As the DataView class Pa r t you Fourcan - Lesee, ve r a ging the .NET Libr a r iesupports s

a property named RowFilter, which contains the string representing the filtering criteria used to extract matching rows. Once you have your view established, set Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er the grid's DataSource property accordingly. That's it! Because DataGrids are smart enough to detect Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) changes to their underlying data source, if you click the Make Beemers Colts button, the ColtsViewGrid is Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) updated automatically. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 16 - toThe stem .I O Nam espaceTable 17-8 describes some other members of the DataView class. In addition theSyRowFilter property, Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve17-8: - Web Appl ica ti ons andDataView X ML W e b Se r vi ces Table Members of the Type

Chapter 18 - ASP.NET Web Pages and Web Contr ols

DataView Member

Meaning in Life

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex AddNew() List of Figur es

AllowDelete

List of Tables

AllowEdit

Adds a new row to the DataView Configure whether the DataView allows deleting, inserting, or updating of its rows

AllowNew Delete()

Deletes a row at the specified index

RowFilter

Gets or sets the expression used to filter which rows are viewed in the DataView

Sort

Gets or sets the sort column or columns and sort order for the table

Table

Gets or sets the source DataTable

SOURCE CODE

The CarDataTable project is included under the Chapter 17 subdirectory.

C# an dthe th e .N ET Plat f orm , SeDataSet con d Ed it ion Understanding Role of the by Andr ew Tr oelsen

ISBN:1590590554

You have been examining how(1200 to build Apr ess © 2003 pages)a DataTable to represent a single table of data held in memory. Although DataTables can be used stand-alone they are of more This compr ehensiv eastext star ts w ithentities, a brief ov er view the typically contained in a DataSet. Simply put, a DataSet is an in-memory representation of any number of C# language and then quickly m oves to key technical and tables (which may be just a single ar chitectur al issues for .NET developer s. DataTable) as well as any (optional) relationships between these tables and any (optional) constraints. To gain a better understanding of the relationship among these core types, consider the logical hierarchy shown in Figure 17-15. Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - 17-15: Exceptions Obj ectof Lifetim e Figure Theand anatomy a DataSet Chapter 6 - I nter faces and Collections

The Tables propertyI of the DataSet allowsand youEvtoents access the DataTableCollection that contains the Chapter 7 - Callback nter faces, Delegates, individual Another important used by the DataSet is the DataRelationCollection. Chapter 8 DataTables. - Advanced C# Type Const ructioncollection Techniques Given that version Pa r t Thre e -a PrDataSet ogr am m iis ngawdisconnected i th .N ET Assem bl ie s

of a database schema, it can programmatically represent the parent/child relationships between its tables. Chapter 9 - Under standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

For example, a relation can be created between two tables to model a foreign key constraint using the DataRelation type. This object can then be added to the DataRelationCollection through the Relations Pa r t Four - Le ve r a ging the .NET Libr a r ie s property. At this point, you can navigate between the connected tables as you search for data. You will see Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er how this is done a bit later in the chapter. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter The ExtendedProperties 14 - A Better Paint property ing Fr amew provides or k ( GDI access +) to the PropertyCollection type, which allows you to

associate extra to the DataSet as name/value pairs. This information can literally be Chapter 15 any - Pr ogr am information ming with Windows Form s Contr ols anything if it.Ihas no espace bearing on the data itself. For example, you can associate your company's Chapter 16at- all, Theeven Sy stem O Nam name to which can then function as in-memory metadata, as shown here: Chapter 17a-DataSet, Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter // Make 18 - aASP.NET DataSet Web and Pagesadd and some Web Contr metadata. ols

DataSet = new DataSet("MyDataSet"); Chapter 19 - ds ASP.NET Web Applicat ions ds.ExtendedProperties.Add("CompanyName", "Intertech, Inc"); Chapter 20 - XML Web Ser vices // Print out the metadata. I ndex Console.WriteLine(ds.ExtendedProperties["CompanyName"].ToString()); List of Figur es List of Tables

Other examples of extended properties might include an internal password that must be supplied to access the contents of the DataSet, a number representing a data refresh rate, and so forth. Be aware that the DataTable itself also supports the ExtendedProperties property.

Members of the DataSet Before exploring too many other programmatic details, take a look at the public interface of the DataSet. The properties defined by the DataSet are centered on providing access to the internal collections, producing XML data representations and providing detailed error information. Table 17-9 describes some core properties of interest. Table 17-9: Properties of the Mighty DataSet

DataSet Property CaseSensitive DataSetName

Life C# an d thMeaning e .N ET Platin f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Indicates whether string comparisons in DataTable objects are case

This compr ehensiv e text star ts w ith a brief ov er view of the sensitive (or not). C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s DefaultViewManager

Represents the friendly name of this DataSet. Typically this value is established as a constructor parameter. Establishes a custom view of the data in the DataSet.

C# and t he .NET Plat for m, Second Edition

EnforceConstraints

I ntr oduction

Gets or sets a value indicating whether constraint rules are followed when attempting any update operation.

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter HasErrors 1 - The Philosophy of Gets .NET a value indicating whether there are errors in any of the rows in any Chapter 2

of the tables of this DataSet. - Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Relations

Chapter 3

Gets the collection of relations that link tables and allows navigation from parent tables to child tables.

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# Tables Provides access Chapter 5 - Exceptions and Obj ect Lifetim e to the collection of tables maintained by the DataSet. Chapter 6

- I nter faces and Collections The methods of the DataSet mimic some and of the provided by the aforementioned properties. In Chapter 7 - Callback I nter faces, Delegates, Ev functionality ents

addition8 to-interacting withType XMLConst streams, other methods exist to allow you to copy the contents of your Chapter Advanced C# ruction Techniques DataSet, asmestablish Pa r t Thre e as - Prwell ogr am i ng w i th the .N ETbeginning Assem bl ieand s

ending points of a batch of updates. Table 17-10

describes methods. Chapter 9 -some Undercore standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Table 17-10: Methods of the Mighty DataSet

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa rDataSet t Four - Le ve r a ging the .NET Libr a r ie sin Method Meaning

Life

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

AcceptChanges() Commits changes made to this Chapter 13 - Building a Bet ter Win dow all ( Intthe roducin g Window s For ms) DataSet since it was loaded or the last time AcceptChanges() was called. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows clears Form s the Contr ols Clear() Completely DataSet data by removing every row in each Chapter 16 - The Sy stem .I O table. Nam espace Chapter 17 - Data Access w ith ADO.NET

Clone()

Clones the structure of the DataSet, including all DataTables, as well as all relations and any constraints.

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Chapter 19 - ASP.NET Web Applicat Copy() Copiesions both the structure and data for this DataSet. Chapter 20 - XML Web Ser vices

GetChanges()

I ndex

List of Figur es ListGetChildRelations() of Tables

Returns a copy of the DataSet containing all changes made to it since it was last loaded, or since AcceptChanges() was called. Returns the collection of child relations that belong to a specified table.

GetParentRelations()

Gets the collection of parent relations that belong to a specified table.

HasChanges()

Overloaded. Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows.

Merge()

Overloaded. Merges this DataSet with a specified DataSet.

ReadXml()

These methods allow you to read XML data from a valid stream (filebased, memory-based, or network-based) into the DataSet.

ReadXmlSchema() RejectChanges()

Rolls back all the changes made to this DataSet since it was created, or the last time DataSet.AcceptChanges was called.

WriteXml()

These methods allow you to write out the contents of a DataSet into a valid stream.

WriteXmlSchema()

Now that you have a better understanding of the role of the DataSet (and some idea what you can do with C# an d th e .N ET Plat f orm , Se con d Ed it ion one), let's run through some specifics. Once this discussion of the ADO.NET DataSet is complete, the ISBN:1590590554 Andr ew Tr oelsen remaining bulk ofbythis chapter will focus on how to obtain DataSet types from external sources (such as a Apr ess © 2003 (1200 pages) relational database) using the types defined by the System.Data.SqlClient and System.Data.OleDb namespaces. This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Building an In-Memory DataSet TaTo bleillustrate o f Con t en thet suse of a DataSet, create a new Windows Forms application that maintains a single

DataSet, three DataTable objects named Inventory, Customers, and Orders. The columns for C# and t hecontaining .NET Plat for m, Second Edition each table will be minimal but complete, with one column marking the primary key for each table. Most I ntr oduction importantly, can between Pa r t One - I nt ryou oduci ng model C# a ndthe theparent/child .NET P la tf or relationships m

the tables using the DataRelation type.

Your goal to build the database Chapter 1 -is The Philosophy of .NET shown in Figure 17-16 in memory. Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le17-16: ve r a ging theCars .NETdatabase Libr a r ie s Figure The

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Here, the is the table to the Orderss table, Chapter 13 Inventory - Building table a Bet ter Winparent dow ( Int roducin g Window For ms)which maintains a foreign key (CarID) column. the Customers parent Chapter 14Also, - A Better Paint ing Frtable amewisorthe k ( GDI + ) table to the Orders table. (Again note the foreign key, CustID.) you soon with see, Windows when youForm adds DataRelation types to your DataSet, they may be used to Chapter 15As - Pr ogrwill am ming Contr ols navigate to espace obtain and manipulate the related data. Chapter 16between - The Sy the stemtables .I O Nam Chapter 17 - Data Access w ith ADO.NET

To begin, assume you have added a set of member variables to your main Form, representing the individual DataTables and containing DataSet, as shown here:

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

public class mainForm : System.Windows.Forms.Form { I ndex // Inventory DataTable. List of Figur es private DataTable inventoryTable = new DataTable("Inventory"); List of Tables // Customers DataTable. private DataTable customersTable = new DataTable("Customers"); // Orders DataTable. private DataTable ordersTable = new DataTable("Orders"); // Our DataSet! private DataSet carsDataSet = new DataSet("CarDataSet"); ... } Chapter 20 - XML Web Ser vices

Now, to keep things as OO as possible, build some (very) simple wrapper classes to represent a Car and Customer in the system. Note that the Customer class maintains a field that identifies the car a customer is interested in buying, as shown here: public class Car {

// Make public for easy access. C# an d thpetName, e .N ET Plat make, f orm , Secolor; con d Ed it ion public string by Andr ew Tr oelsen public Car(string petName, string make, ISBN:1590590554 string color) Apr ess © 2003 (1200 pages) { This compr ehensiv e text star ts w ith a brief ov er view of the this.petName = petName; C# language and then quickly m oves to key technical and this.color = color; ar chitectur al issues for .NET developer s. this.make = make; } }

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

public class Customer { Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m public Customer(string fName, string lName, int currentOrder) Chapter 1 - The Philosophy of .NET { Chapter 2 - Building C# Applications this.firstName= fName; Pa r t Tw o - The C# Pr ogr am m ing La ngua ge this.lastName = lName; Chapter 3 - C#this.currCarOrder Language Fundamentals = currentOrder; Chapter } 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter // 5 - Make Exceptions and Obj ect easy Lifetim e public for access. Chapter public 6 - I nter string faces and firstName, Collections lastName; Chapter public 7 - Callback faces, Delegates, and Ev ents intI nter currCarOrder; Chapter } 8 - Advanced C# Type Const ruction Techniques I ntr oduction

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies The main maintains two ArrayList thatThreads hold a set of cars and customers, which are populated Chapter 10 Form - Pr ocesses, AppDomains, Conttypes exts, and

with some sample data in the scope of the Form's constructor. Next, the constructor calls a number of private helper functions to build the tables and their relationships. Finally, this method binds the Inventory Pa r t Four - Le ve r a ging the .NET Libr a r ie s and Customer DataTables to their corresponding DataGrid widgets. Notice that the following code binds a Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er given DataTable in the DataSet using the SetDataBinding() method: Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

// Your list of Cars and Customers. private ArrayList arTheCars, arTheCustomers;

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

public mainForm() { Chapter 18 - ASP.NET Web Pages and Web Contr ols // Fill the car array list with some cars. Chapter 19 - ASP.NET Web Applicat ions arTheCars = new ArrayList(); Chapter arTheCars.Add(new 20 - XML Web Ser vices Car("Chucky", "BMW", "Green")); I ndex ... List of Figur // esFill the other array list with some customers. List of Tables arTheCustomers = new ArrayList(); arTheCustomers.Add(new Customer("Dave", "Brenner", 1020)); ... // Make data tables (using the same techniques seen previously). MakeInventoryTable(); MakeCustomerTable(); MakeOrderTable(); // Add relation (seen in just a moment). BuildTableRelationship(); // Bind to grids (Param1 = DataSet, Param2 = name of table in DataSet). CarDataGrid.SetDataBinding(carsDataSet, "Inventory"); CustomerDataGrid.SetDataBinding(carsDataSet, "Customers"); } Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Each DataTable is constructed using the techniques examined earlier in this chapter. To keep focused on

the DataSet logic, I will not repeat every detail of the table-building logic here. However, be aware that C# an d th e .N ET Plat f orm , Se con d Ed it ion each table is assigned a primary key that is autoincremented. Here is some partial table-building logic ISBN:1590590554 by Andr ew Tr (check out the source code foroelsen complete details): Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the

private void C# MakeOrderTable() language and then quickly m oves to key technical and { ar chitectur al issues for .NET developer s. ... // Add table to the DataSet. carsDataSet.Tables.Add(customersTable); Ta ble o f Con t en t s Create CustID, CarID columns and add to table... C# and t// he .NET Plat forOrderID, m, Second Edition // Make the ID column the primary key column... I ntr oduction // Add some orders. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m i = 0; ofi .NET < arTheCustomers.Count; i++) Chapter for(int 1 - The Philosophy { Chapter 2 - Building C# Applications DataRow Pa r t Tw o - The C# Pr ogr amnewRow; m ing La ngua ge newRow = ordersTable.NewRow(); Chapter 3 - C# Language Fundamentals Customer c = (Customer)arTheCustomers[i]; Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# newRow["CustID"] = i; Chapter 5 - Exceptions and Obj ect Lifetim e newRow["CarID"] = c.currCarOrder; Chapter 6 - I nter faces and Collections carsDataSet.Tables["Orders"].Rows.Add(newRow); Chapter 7 - Callback I nter faces, Delegates, and Ev ents } Chapter 8 - Advanced C# Type Const ruction Techniques } Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter The MakeInventoryTable() 10 - Pr ocesses, AppDomains, and MakeCustomerTable() Cont exts, and Threads helper functions behave almost identically (again,

check source code for full details). Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Using Plat f orm ,the Se con d Ed it ion ExpressingC#Relations DataRelation Type ISBN:1590590554

by Andr ew Tr oelsen

The really interesting work happens in the BuildTableRelationship() helper function. Once a DataSet has Apr ess © 2003 (1200 pages) been populated with a number of tables, youtscan optionally to the programmatically model their This compr ehensiv e text star w ith a brief ovchoose er view of parent/child relationships. Be aware that this is not mandatory. You can C# language and then quickly m oves to key technical andhave a DataSet that does little else ar chitectur al issues for .NET developer than hold a collection of DataTables in memory (evens.a single DataTable). However, when you do establish the interplay between your DataTables, you can navigate between them on the fly, maintain data integrity, and collect any sort of information you may be interested in obtaining, all while disconnected from Tathe ble data o f Con t en t s source. C# and t he .NET Plat for m, Second Edition

The System.Data.DataRelation type is an OO wrapper around a table-to-table relationship. When you I ntr oduction create DataRelation specify friendly name, Pa r t Onea- new I nt r oduci ng C# a ndtype, the .NET P la a tf or m

followed by the parent table (for example,

Inventory) related child table (Orders). For a relationship to be established, each table must have Chapter 1 -and Thethe Philosophy of .NET an identically namedC#column (CarID) of the same data type (Int32 in this case). In this light, a DataRelation Chapter 2 - Building Applications isr tbasically bound rules Pa Tw o - The C# Prby ogrthe am same m ing La nguaas gea

relational database. Here is the complete implementation of the

BuildTableRelationship() helper function: Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

private BuildTableRelationship() Chapter 5 - void Exceptions and Obj ect Lifetim e { Chapter 6

- I nter faces and Collections DataRelation Chapter // 7 - Create Callback Ianter faces, Delegates, obj. and Ev ents

DataRelation dr = new DataRelation("CustomerOrder", - Advanced C# Type Const ruction Techniques carsDataSet.Tables["Customers"].Columns["CustID"], Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s carsDataSet.Tables["Orders"].Columns["CustID"]); Chapter 9 - Under standing .NET Assem blies // Add to the DataSet. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads carsDataSet.Relations.Add(dr); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing // Create another DataRelation obj. Pa r t Four - Le ve r a ging the .NET Libr a r ie s dr = new DataRelation("InventoryOrder", Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er carsDataSet.Tables["Inventory"].Columns["CarID"], Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) carsDataSet.Tables["Orders"].Columns["CarID"]); Chapter // 14 - Add A Better Fr amew or k ( GDI + ) to Paint the ing DataSet. Chapter carsDataSet.Relations.Add(dr); 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace } Chapter 8

// Parent. // Child.

// Parent. // Child.

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

As you 18 can- see, a given is held Chapter ASP.NET WebDataRelation Pages and Web Contrin olsthe DataRelationCollection maintained by the DataSet. The DataRelation type offers a number of properties that allow you to obtain a reference to the child Chapter 19 - ASP.NET Web Applicat ions

and/or 20 parent table participating in the relationship, specify the name of the relationship, and so on, Chapter - XML Webthat Seris vices and these are listed in Table 17-11.

I ndex

List of Figur es

Table 17-11: Properties of the DataRelation Type

List of Tables

DataRelation Property

Meaning in Life

ChildColumns

Obtain information about the child table in this relationship as well as the table itself

ChildKeyConstraint ChildTable DataSet

Gets the DataSet to which the relations' collection belongs

ParentColumns

Obtain information about the parent table in this relationship as well as the table itself

ParentKeyConstraint ParentTable RelationName

Gets or sets the name used to look up this relation in the parent data set's DataRelationCollection

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Navigating by Between Related Tables Andr ew Tr oelsen

ISBN:1590590554

Apr ess © 2003 (1200 pages)

To illustrate how a DataRelation allows you to move between related tables, extend your GUI to include a This compr ehensiv e text star ts w ith a brief ov er view of the new Button type and a relatedand TextBox. The end usertoiskey abletechnical to enterand the ID of a customer and obtain all C# language then quickly m oves the information about that customer's which is placed in a simple message box (Figure 17-17). The ar chitectur al issues fororder, .NET developer s. Button's Click event handler is as shown here (error checking removed for clarity): Taprotected ble o f Con t envoid ts btnGetInfo_Click (object sender, System.EventArgs e) C# and t he .NET Plat for m, Second Edition { I ntr oduction string strInfo = ""; Pa r t OneDataRow - I nt r oducidrCust ng C# a nd=the .NET P la tf or m null;

Chapter DataRow[] 1 - The Philosophy of .NET= null; drsOrder Chapter // 2 - Get Building C# Applications the specified CustID from the TextBox. Pa r t Tw oint - ThetheCust C# Pr ogr am ing La ngua ge = mint.Parse(this.txtCustID.Text);

Chapter // 3 - Now C# Language based on Fundamentals CustID, get the correct row in Customers table.

= -Or carsDataSet.Tables["Customers"].Rows[theCust]; Chapter drCust 4 - Obj ect iented Pr ogr am ming w ith C# += "Cust #" Lifetim + drCust["CustID"].ToString() + "\n"; Chapter strInfo 5 - Exceptions and Obj ect e from customer table to order table. Chapter // 6 - Navigate I nter faces and Collections drCust.GetChildRows(carsDataSet.Relations["CustomerOrder"]); Chapter drsOrder 7 - Callback=I nter faces, Delegates, and Ev ents order Chapter // 8 - Get Advanced C# number. Type Const ruction Techniques drsOrder) Pa r t Threforeach(DataRow e - Pr ogr am m i ng w i th r.N in ET Assem bl ie s strInfo += "Order Number: " + r["OrderID"] + "\n"; - Under standing .NET Assem blies // Now navigate from order table to inventory table. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads DataRow[] drsInv = Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing drsOrder[0].GetParentRows(carsDataSet.Relations["InventoryOrder"]); Pa r t Four - Le ve r a ging the .NET Libr a r ie s // Get Car info. Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er foreach(DataRow r in drsInv) Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) { Chapter 14 - A strInfo Better Paint += ing Fr amew or k"( GDI +) "Make: + r["Make"] + "\n"; Chapter 15 - Pr strInfo ogr am ming += with"Color: Windows Form s Contr ols " + r["Color"] + "\n"; Chapter 16 - The Sy stem .I O espace strInfo +=Nam "Pet Name: " + r["PetName"] + "\n"; Chapter } 17 - Data Access w ith ADO.NET Pa r t Fi veMessageBox.Show(strInfo, - W e b Appl ica ti ons and X ML W e b Se r vi ces based on cust ID"); "Info Chapter 18 ASP.NET Web Pages and Web Contr ols } Chapter 9

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 17-17: Navigating data relations As you can see, the key to moving between data tables is to use a handful of methods defined by the DataRow type. Let's break this code down step by step. First, you obtain the correct customer ID from the text box and use it to grab the correct row in the Customers table (using the Rows property, of course), as shown here: // Get the specified CustID from the TextBox.

int theCust = int.Parse(this.txtCustID.Text); d th e .N ETget Platthe f orm ,correct Se con d Edrow it ion in the Customers table. // Now based C# onanCustID, ISBN:1590590554 by Andr ew Tr oelsen DataRow drCust = null; Apr ess © 2003 (1200 pages) drCust = carsDataSet.Tables["Customers"].Rows[theCust]; This compr e text star ts w ith a brief ov er view of +the"\n"; strInfo += "Cust #" ehensiv + drCust["CustID"].ToString() C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Next, you navigate from the Customers table to the Orders table, using the CustomerOrder data relation. Notice that the DataRow.GetChildRows() method allows you to grab rows from your child table, and once C# and t he .NET Plat for m, Second Edition you do, you can read information out of the table, as shown here:

Ta ble o f Con t en t s I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

// Navigate from customer table to order table. - The Philosophy of .NET DataRow[] drsOrder = null; Chapter 2 - Building C# Applications drsOrder = drCust.GetChildRows(carsDataSet.Relations["CustomerOrder"]); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge // Get order number. Chapter 3 - C# Language Fundamentals foreach(DataRow r in drsOrder) Chapter 4 - += Obj "Order ect -Or iented Pr ogr am ming ith C# strInfo Number: " + wr["OrderID"] + "\n"; Chapter 1

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections Your final is to navigate from the Orders to its parent table (Inventory), using the Chapter 7 step - Callback I nter faces, Delegates, and table Ev ents

GetParentRows() method. At this point, youTechniques can read information from the Inventory table using the Make, Chapter 8 - Advanced C# Type Const ruction PetName, Color here: Pa r t Thre e - and Pr ogr am m icolumns, ng w i th .Nas ET shown Assem bl ie s Chapter 9

- Under standing .NET Assem blies

Chapter // Now 10 navigate - Pr ocesses, from AppDomains, orderCont table exts, and to Threads inventory table.

DataRow[] drsInv = Late Binding, and Attr ibute- Based Pr ogramm ing Chapter 11 - Type Reflection, Pa r t Four drsOrder[0].GetParentRows(carsDataSet.Relations["InventoryOrder"]); - Le ve r a ging the .NET Libr a r ie s

foreach(DataRow r in drsInv) Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er { Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) +=Paint "Make: " + orr["Make"] + "\n"; Chapter strInfo 14 - A Better ing Fr amew k ( GDI + ) +=ming "Color: " + r["Color"] Chapter strInfo 15 - Pr ogr am with Windows Form s Contr ols + "\n"; strInfo += "Pet Name: " + r["PetName"] + "\n";

Chapter 16 - The Sy stem .I O Nam espace

}

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 example - ASP.NETofWeb Pages and Web Contr ols As a final navigating relations programmatically, the following code prints out the values in the Chapter - ASP.NET Web Applicat ions using the InventoryOrders relationship: Orders19 table that is obtained indirectly Chapter 20 - XML Web Ser vices I ndex

protected void btnGetChildRels_Click (object sender, System.EventArgs e)

List { of Figur es List of Tables // Ask the CarsDataSet for the child relations of the inv. table.

DataRelationCollection relCol; DataRow[] arrRows; string info = ""; relCol = carsDataSet.Tables["inventory"].ChildRelations; info += "\tRelation is called: " + relCol[0].RelationName + "\n\n"; // Now loop over each relation and print out info. foreach(DataRelation dr in relCol) { foreach(DataRow r in inventoryTable.Rows) { arrRows = r.GetChildRows(dr); // Print out the value of each column in the row. for (int i = 0; i < arrRows.Length; i++) { foreach(DataColumn dc in arrRows[i].Table.Columns)

{ C# an d th e .N ET info Plat f orm con d+EdarrRows[i][dc]; it ion +=, Se "\t" by Andr ew } Tr oelsen Apr ess © 2003 (1200 += pages) info "\n";

ISBN:1590590554

This}compr ehensiv e text star ts w ith a brief ov er view of the } C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

MessageBox.Show(info, "Data in Orders Table obtained by child relations");

}

Ta ble o f Con t en t s

}

C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One 17-18 - I nt r oduci ngthe C# output. a nd the .NET P la tf or m Figure shows

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies Figure Navigating parent/child relations Chapter 10 - 17-18: Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Hopefully, this last example has you convinced of the usefulness of the DataSet type. Given that a DataSet is completely disconnected from the underlying data source, you can work with an in-memory copy of data Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er and navigate around each table to make any necessary updates, deletes, or inserts. Once this is done, Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) you can submit your changes to the data store for processing. Of course you don't yet know how to get Chapter 14 - There A Betteris Paint amew k ( GDI +regarding ) connected! one ing finalFritem oforinterest the DataSet before addressing this issue. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# Writing an d th e .N ET Plat f orm , Se conDataSets d Ed it ion Reading and XML-Based by Andr ew Tr oelsen

ISBN:1590590554

A major design goal of ADO.NET to apply a liberal use of XML infrastructure. Using the DataSet type, Apr ess © 2003 (1200was pages) you can write an This XMLcompr representation of your relations, and other schematic details ehensiv e textthe starcontents ts w ith a of brief ov tables, er view of the to a given streamC# (such as a file). To do so, simply call the WriteXml() method, as shown here: language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

protected void btnToXML_Click (object sender, System.EventArgs e) { Ta ble o f Con t en t s // Write your entire DataSet to a file in the app directory. C# and t he .NET Plat for m, Second Edition carsDataSet.WriteXml("cars.xml"); I ntr oduction MessageBox.Show("Wrote CarDataSet to XML file in app directory"); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m btnReadXML.Enabled = true; Chapter 1 - The Philosophy of .NET } Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals If you now your new file in the VisualwStudio Chapter 4 -open Obj ect -Or iented Pr ogr am ming ith C# .NET IDE (Figure 17-19), you will see that the entire

DataSet been transformed to Lifetim XML. e Chapter 5 has - Exceptions and Obj ect Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Figure 17-19: The Cars database as XML

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

To test the ReadXml() method of the DataSet, perform a little experiment. The CarDataSet application has

Chapter 19that - ASP.NET Web ions DataSet completely (including all tables and relations). After the ina Button will clear outApplicat the current Chapter 20 XML Web Ser vices memory representation has been gutted, instruct the DataSet to read in the cars.xml file, which as you I ndex would guess restores the entire DataSet, as shown here: List of Figur es List of Tables void btnReadXML_Click (object sender, System.EventArgs e) protected

{ // Kill current DataSet. carsDataSet.Clear(); carsDataSet.Dispose(); MessageBox.Show("Just cleared data set..."); carsDataSet = new DataSet("CarDataSet"); carsDataSet.ReadXml("cars.xml"); MessageBox.Show("Reconstructed data set from XML file..."); btnReadXML.Enabled = false; // Bind to grids. CarDataGrid.SetDataBinding(carsDataSet, "Inventory"); CustomerDataGrid.SetDataBinding(carsDataSet, "Customers"); }

Figure 17-20 shows your final product.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - 17-20: Exceptions ectupdate Lifetim e Figure Theand finalObj GUI Chapter 6 - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

In addition the abilityC#toType persist theruction contents of a DataSet as XML, be aware that the WriteXmlSchema() Chapter 8 - toAdvanced Const Techniques and ReadXmlSchema() methods may also be Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s used to generate and read an *.xsd file that represents the overall structure of the DataSet type. Once you have the data and structure of a DataSet persisted to file, Chapter 9 - Under standing .NET Assem blies you are able to manipulate the contents using the types of the System.Xml.dll assembly (see Chapter 18). Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Furthermore, once you have generated your schema file from a given DataSet, you are able to view Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing and/or tweak the type definitions using VS .NET (Figure 17-21). Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 17-21: The Cars XML schema file SOURCE CODE

The CarDataSet application is included under the Chapter 17 subdirectory.

C# an d th eTest .N ET Plat f orm , Se con d Ed it ion Building a Simple Database ISBN:1590590554

by Andr ew Tr oelsen

Now that you understand how(1200 to create Apr ess © 2003 pages) and manipulate a DataSet in memory, you can get down to the business of making a data connection and seeing to obtain a populated DataSet from a specific data This compr ehensiv e text star ts w ithhow a brief ov er view of the provider. In keeping with the automotive theme used throughout this text, I have included two versions of a C# language and then quickly m oves to key technical and ar chitectur issues the for .NET developer s. sample Cars database thatalmodels Inventory, Orders, and Customers tables examined during the chapter. TaThe ble ofirst f Con version t en t s is a SQL script that builds the tables (including their relationships) and is intended for

users (and greater). C# and of t heSQL .NETServer Plat for7.0 m, Second Edition To create the Cars database, begin by opening the Query Analyzer utility that ships with SQL Server. Next, connect to your machine and open the cars.sql file. Before you run I ntr oduction the script, ber oduci sure ng thatC#the path Pa r t One - I nt a nd thelisted .NET in P lathe tf orSQL m

file points to your installation of MS SQL Server. Thus, be

sure you thePhilosophy following DDL (in bold) as necessary (be aware that SQL Server 2000 has a unique Chapter 1 edit - The of .NET directory using SQL 7.0 . . . don't ask): Chapter 2 structure. - BuildingI'm C# still Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

CREATE [Cars] ON (NAME = N'Cars_Data', FILENAME Chapter 3 DATABASE - C# Language Fundamentals =N'C:\MSSQL7\Data \Cars_Data.MDF' , Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# SIZE = FILEGROWTH 10%) Chapter 5 2, - Exceptions and Obj=ect Lifetim e Chapter 6

- I nter faces and Collections LOG ON = IN'Cars_Log', FILENAME Chapter 7 (NAME - Callback nter faces, Delegates, and Ev ents

= N' C:\MSSQL7\Data\Cars_Log.LDF' , - Advanced C# Type Const ruction Techniques SIZE = 1, FILEGROWTH = 10%) Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s GO Chapter 8 Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11your - Type Reflection, Latedo, Binding, andthe AttrSQL ibuteBased Enterprise Pr ogramm ing Now run script. Once you open up Server Manager. You should see the Cars Pa r t Four - Le ve rall a ging theinterrelated .NET Libr a rtables ie s database with three

(with some sample data to boot) as well as a single stored

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er procedure. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

The second of theingCars database is for Chapter 14 - Aversion Better Paint Fr amew or k ( GDI + ) users of MS Access. Under the Access DB folder you will find the15 cars.mdb file, which same information and underlying structure as the SQL Server Chapter - Pr ogr am ming withcontains Windowsthe Form s Contr ols version.16During remainder this chapter, I will assume that you are connecting to the SQL Server Chapter - The the Sy stem .I O Namof espace

Cars database rather than the Access equivalent. In just a bit, however, you will see how to configure an ADO.NET connection object to hook into an *.mdb file. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 17 - Data Access w ith ADO.NET

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Selecting aC#Data Provider ISBN:1590590554

by Andr ew Tr oelsen

As mentioned earlier in © this chapter, .NET 1.1 ships with five data providers. The first of these is the OleDb Apr ess 2003 (1200 pages) data provider, which is composed of the in the namespace. The OleDb This compr ehensiv e text types star ts defined w ith a brief ov System.Data.OleDb er view of the provider allows you to access data located in any data store that supports the classic OLE DB protocol. C# language and then quickly m oves to key technical and ar chitectur issues foruse .NET s. data provider to access SQL Server, Oracle, or Thus, like with classic ADO,alyou may thedeveloper ADO.NET MS Access databases. Because the types in the System.Data.OleDb namespace must communicate with unmanaged code (e.g., the OLE DB providers), you need to be aware that a number of .NET to COM Tatranslations ble o f Con t en t s behind the scenes, which can affect performance. By and large, this namespace is occur C# and twhen he .NET forattempting m, Second to Edition useful youPlat are communicate with a data source that does not have a specific data I ntr oduction provider assembly. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

The SQL offers direct access to MS SQL Server data stores, and only SQL Server data Chapter 1 data - Theprovider Philosophy of .NET stores (version 7.0 and The System.Data.SqlClient namespace contains the types used by the Chapter 2 - Building C# greater). Applications SQL andPrprovides the La same Pa r t Twprovider o - The C# ogr am m ing nguafunctionality ge

as the OleDb provider. In fact, for the most part, both namespaces have similarly named items. The key difference is that the SQL provider does not use the Chapter 3 - C# Language Fundamentals OLE DB or classic ADO protocols and thus offers numerous performance benefits. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 interested - Exceptions Obj ect If you are in and making useLifetim of thee System.Data.Oracle, System.Data.Odbc, or Chapter 6 I nter faces and Collections System.Data.SqlServerCe namespaces, I will assume you will check out the details as you see fit. Chapter 7 as - Callback I nter faces,once Delegates, and Ev ents However, you would hope, you are comfortable with one data provider, you can easily manipulate Chapter 8 - Advanced Type Const Techniques other providers. RecallC#that while theruction exact names of the types will differ between namespaces (for Pa r t Thre e -OleDbConnection Pr ogr am m i ng w i thvs. .N ET Assem bl ie s example, SqlConnection

vs. OdbcConnection), semantically related types can be

Chapter Under standingmanner .NET Assem treated9in a- polymorphic givenblies the IDbCommand, IDbConnection, IDbDataAdapter, and Chapter IDataReader 10 - Printerfaces ocesses, AppDomains, et al. Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

To we'll connect Pa r t begin, Four - Le ve rexamine a ging the how .NETto Libr a r ie s

to a data source using the OleDb data provider, therefore don't forget to specify the proper using directives (recall this data provider is contained within the Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er System.Data.dll assembly): Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

// Using the OleDb data provider. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols using System.Data; using System.Data.OleDb;

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 have - ASP.NET Webout Pages Web Contr olsa data store using the OleDb data provider, we will see Once we checked howand to interact with Chapter - ASP.NET Webtypes Applicat ionsthe System.Data.SqlClient namespace. how to 19 make use of the within Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d thSystem.Data.OleDb e .N ET Plat f orm , Se con d Ed it Namespace ion The Types of the ISBN:1590590554

by Andr ew Tr oelsen

Table 17-12 provides a© walkthrough of the core types of the System.Data.OleDb namespace. Note that Apr ess 2003 (1200 pages) each type sports This an "OleDb-" prefix. compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and chitectur issues for .NET developer s.Namespace Table 17-12: KeyarTypes ofalthe System.Data.OleDb

System.Data.OleDb Type Ta ble o f Con t en t s

Meaning in Life

C# and t he .NET Plat for m, Second Edition

OleDbCommand

I ntr oduction

Represents a SQL query command to be made to a data source.

Pa rOleDbConnection t One - I nt r oduci ng C# a nd the .NET Represents P la tf or man

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

OleDbDataAdapter

open connection to a data source.

Represents a set of data commands and a database connection used to fill and update the contents of a DataSet.

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

OleDbDataReader Provides a way of reading a forward-only stream of data records Chapter 3 - C# Language Fundamentals Chapter 4

from a data - Obj ect -Or iented Pr ogr am ming w ith source. C#

Chapter 5

- Exceptions and Obj ect Lifetim e OleDbErrorCollection OleDbErrorCollection maintains a collection of warnings or errors - I nter faces and Collections returned by the data source, each of which is represented by an OleDbError Chapter 7 - Callback I nter faces, Delegates, andtype. Ev ents OleDbError When an error is encountered, an exception of OleDbException Chapter 8 - Advanced C# Type Const ruction Techniques is thrown. type OleDbException Chapter 6

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

OleDbParameterCollection Muchblies like classic ADO, the OleDbParameterCollection collection Chapter 9 - Under standing .NET Assem holds onto the parameters sent to a stored procedure in the database. Each parameter is of type OleDbParameter.

OleDbParameter Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d thConnected e .N ET Plat f orm , Layer Se con d Ed Working with the ofit ion ADO.NET ISBN:1590590554

by Andr ew Tr oelsen

The first step to take when working with the OleDb data provider is to establish a session with the data source Apr ess © 2003 (1200 pages) using the OleDbConnection type (which, as you implements IDbConnection interface). Much like the This compr ehensiv e text star ts wrecall, ith a brief ov er view the of the classic ADO Connection object, OleDbConnection types are provided with a formatted connection string, C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. semicolons. This information is used to identify the name containing a number of name/value pairs separated by of the machine you wish to connect to, required security settings, the name of the database on that machine, and, most importantly, the name of the OLE DB provider. (See online help for a full description of each Taname/value ble o f Con t en ts pair.) C# and t he .NET Plat for m, Second Edition

The connection string may be set using the OleDbConnection.ConnectionString property or including it as a I ntr oduction constructor wish toorconnect Pa r t One - I ntargument. r oduci ng C#Assume a nd theyou .NET P la tf m

to the Cars database on your local machine using the SQL

OLE DB The following logic does the trick: Chapter 1 provider. - The Philosophy of .NET Chapter 2

- Building C# Applications

Pa // r t Tw Build o - TheaC#connection Pr ogr am m ing string. La ngua ge

OleDbConnection cn Fundamentals = new OleDbConnection(); Chapter 3 - C# Language cn.ConnectionString "Provider=SQLOLEDB.1;" + Chapter 4 - Obj ect -Or iented = Pr ogr am ming w ith C# ID=sa;Pwd=;Initial Chapter "User 5 - Exceptions and Obj ect Lifetim e Catalog=Cars;" + Source=(local);"; Chapter "Data 6 - I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

As you can infer from the preceding code comments, the Initial Catalog name refers to the database you are attempting to establish a session with (Pubs, Northwind, Cars, and so on). The Data Source name identifies the Chapter 9 - Under standing .NET Assem blies name of the machine that maintains the database (for simplicity, I have assumed no specific password is require Chapter 10system - Pr ocesses, AppDomains, exts, and for local administrators). TheCont final point of Threads interest is the Provider segment, which specifies the name of Chapter 11 Type Reflection, Late Binding, and Attr ibuteBased Pr ogramm ing the OLE DB provider that will be used to access the data store. Table 17-13 describes some possible values. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Table 17-13: Core OLE DB Providers Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Provider Segment Meaning Chapter 14 - A Better Paint ing Fr amew or k ( GDIin + ) Life Value

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Microsoft.JET.OLEDB.4.0 You want to use the Jet OLE DB provider to connect to an Access Chapter 17 - Data Access w ith ADO.NET database. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

MSDAORA YouWeb wantContr to use Chapter 18 - ASP.NET Web Pages and ols the OLE DB provider for Oracle. Chapter 19 - ASP.NET Web ApplicatYou ions want to use the OLE DB provider for MS SQL Server. Once you have SQLOLEDB Chapter 20 - XML Web Ser vices configured the connection string, the next step is to open a session with I ndex List of Figur es

the data source, do some work, and release your connection to the data source, as shown in the code snippet following this table.

List of Tables

// Build a connection string. OleDbConnection cn = new OleDbConnection(); cn.ConnectionString = "Provider=SQLOLEDB.1;" + "User ID=sa;Pwd=;Initial Catalog=Cars;" + "Data Source=(local);"; cn.Open(); // Do some interesting work here... cn.Close();

In addition to the ConnectionString, Open(), and Close() members, the OleDbConnection class provides a number of members that let you configure attritional settings regarding your connection, such as timeout setting and transactional information. Table 17-14 gives a partial rundown.

Table 17-14: Members of the OleDbConnection Type

C# an d th e .N ET Plat f orm , Se con d Ed it ion

OleDbConnection Meaning in Life by Andr ew Tr oelsen Member Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the

BeginTransaction() Used to programmatically commit, abort, or roll back a transaction. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. CommitTransaction() RollbackTransaction() Ta ble o f Con t en t s Close()

Closes the connection to the data source.

C# and t he .NET Plat for m, Second Edition

ConnectionString

I ntr oduction

Gets or sets the string used to open a session with a data store.

Pa rConnectionTimeout t One - I nt r oduci ng C# a nd the This .NETread-only P la tf or m

Chapter 1 Chapter 2

property returns the amount of time to wait while

- The Philosophy of .NET establishing a connection before terminating and generating an error (the - Building C# Applications default value is 15 seconds). If you wish to change this default, specify a

Pa r t Tw o - The C# Pr ogr am m ing La"Connect ngua ge

Timeout" segment in the connection string (e.g., Connect Timeout=30). Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Database

Gets the name of the database maintained by the connection object.

DataSource Gets the location of the database maintained by the connection object. Chapter 6 - I nter faces and Collections Chapter 7

and Ev ents Open() - Callback I nter faces, Delegates, Opens a database connection with the current property settings.

Chapter 8

- Advanced C# Type Const ruction Techniques

Obtains Pa rGetOleDbSchemaTable() t Thre e - Pr ogr am m i ng w i th .N ET Assemschema bl ie s

information from the data source.

Chapter 9

blies Provider - Under standing .NET Assem Gets the name of the provider maintained by the connection object.

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

State 11 - Type Reflection, Late Gets the and current state Based of the Pr connection, Chapter Binding, Attr ibuteogramm ingrepresented by the ConnectionState enumeration. Pa r t Four - Le ve r a ging the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

As you can see, the properties of the OleDbConnection type are typically read-only in nature, and are only usefu when you wish to obtain the characteristics of a connection at runtime. When you wish to override default Chapter 15 - Pr ogr am ming with Windows Form s Contr ols settings, you must alter the construction string itself. For example, ponder the following code, which changes the Chapter - The Sy stem .I O Nam espace default 16 connection timeout setting from 15 seconds to 30 seconds (via the Connect Timeout segment of the Chapter 17 Data Access w ith ADO.NET connection string): Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

OleDbConnection cn = new OleDbConnection(); cn.ConnectionString = "Provider=SQLOLEDB.1;" + Chapter "User 20 - XMLID=sa;Pwd=;Initial Web Ser vices Catalog=Cars;" + I ndex "Data Source=(local);Connect Timeout=30"; List of Figur es cn.Open(); List of Tables Console.WriteLine("***** Info about your connection *****"); Console.WriteLine("Database location: {0}", cn.DataSource); Console.WriteLine("Database name: {0}", cn.Database); Console.WriteLine("Provider: {0}", cn.Provider); Console.WriteLine("Timeout: {0}", cn.ConnectionTimeout); Console.WriteLine("Connection state: {0}", cn.State.ToString()); cn.Close(); Console.WriteLine("Connection state: {0}", cn.State.ToString()); Chapter 19 - ASP.NET Web Applicat ions

Notice that this connection is explicitly opened and closed each time before making a call to the State property. As mentioned in the previous table, this property may take any value of the ConnectionState enumeration: public enum System.Data.ConnectionState { Broken, Closed,

Connecting, Executing, an d th e .N ET Plat f orm , Se con d Ed it ion Fetching,C#Open ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

}

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quicklyof m asking oves to akey technical type and if it is currently in the process of While it may be enticing to ponder the notion connection ar chitectur al issues for .NET developer s. querying data (e.g., ConnectionState.Executing), do understand that with the current release of the .NET Framework, the only valid ConnectionState values are ConnectionState.Open and ConnectionState.Closed (the remaining members of this enum are reserved for future use and are basically no-ops as of .NET 1.1). Also, Ta ble o f Con t en t s understand that it is always safe to close a connection whose connection state is currently C# and t he .NET Plat for m, Second Edition ConnectionState.Closed. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Connecting to an ofAccess Database - The Philosophy .NET

Chapter 1 Chapter 2

- Building C# Applications

Much like classic ADO, the process of connecting to an Access database using ADO.NET requires little more than retrofitting your construction string. First, set the Provider segment to the JET engine, rather than Chapter 3 - C# Language Fundamentals SQLOLEDB. Beyond this adjustment, set the data source segment to point to the path of your *.mdb file, as Chapter - Obj ect -Or iented Pr ogr am ming w ith C# shown 4here: Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

// Be sure to update the data source segment if necessary! - Callback I nter faces, Delegates, and Ev ents OleDbConnection cn = new OleDbConnection(); Chapter 8 - Advanced C# Type Const ruction Techniques cn.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0;" + Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assemsource bl ie s @"data = C:\cars.mdb"; Chapter 9 - Under standing .NET Assem blies cn.Open(); Chapter 7

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Once the- Le connection has.NET beenLibr made, Pa r t Four ve r a ging the a r ie syou

can read and manipulate the contents of your data table.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Obtaining Database Schema Information Using Connection Types

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Connection objects used toForm obtain schema Chapter 15 - Pr ogr am can mingalso withbe Windows s Contr ols information from a given database through the GetOleDbSchemaTable() As you are most likely aware, "schema information" is little more than Chapter 16 - The Sy stem .I O method. Nam espace metadata describes Chapter 17 that - Data Access wthe ith database ADO.NET itself, rather than the tabular data it is maintaining. The GetOleDbSchemaTable() two Pa r t Fi ve - W e b Appl ica ti ons method and X MLtakes W e b Se r viparameters, ces

the first of which is a member of the

OleDbSchemaGuid type. This typeContr exposes Chapter 18 - ASP.NET class Web Pages and Web ols a number of read-only fields that map to the sort of metadata you are19interested in Web obtaining (table Chapter - ASP.NET Applicat ions names, stored procedure names, views, and whatnot). Chapter 20 - XML Web Ser vices

The second parameter is an array of System.Object types that represents what (if any) restrictions should be

I ndex placed on the schema information returned by the call. Be aware that the exact format of this array of List of Figur es System.Object types will vary based on the specified value of the OleDbSchemaGuid parameter. Upon List of Tables the GetOleDbSchemaTable() method returns a DataTable type that contains the schema completion,

information. Rather than pound out all of the possible parameter combinations (as they are documented within online help), the following example illustrates how you can make use of an OleDbConnection type to obtain basic schema information regarding each table in the Cars database: DataTable dtSchemaInfo = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] {null, null, null, "TABLE"}); // Print the DataTable. for(int curRow = 0; curRow < dtSchemaInfo.Rows.Count; curRow++) { for(int curCol= 0; curCol< dtSchemaInfo.Columns.Count; curCol++) { Console.Write(dtSchemaInfo.Rows[curRow][curCol].ToString().Trim()+ " ") }

Console.WriteLine(); C# an d th e .N ET Plat f orm , Se con d Ed it ion

}

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

As you will see, itThis is also possible schema foreraview specific compr ehensivtoe obtain text star ts w ith details a brief ov of thetable in a database using data reader C# to language types (more details come). and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Building a SQL Command via OleDbCommand Ta ble o f Con t en t s

Now that you better understand the role of the OleDbConnection type, the next order of business is to check out how to submit SQL queries to the database in question. The OleDbCommand type (which as you recall I ntr oduction implements the IDbCommand interface) is an OO representation of a SQL query, table name, or stored Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m procedure that is specified using the CommandType property. This property may take any value from the Chapter 1 - The Philosophy of .NET CommandType enum: C# and t he .NET Plat for m, Second Edition

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

public enum System.Data.CommandType - C# Language Fundamentals { Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# StoredProcedure, Chapter 5 - Exceptions and Obj ect Lifetim e TableDirect, Chapter 6 - I nter faces and Collections Text // Default value. Chapter 7 - Callback I nter faces, Delegates, and Ev ents } Chapter 3

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - Under standing Assem blies a SQL query, the CommandText property can be used to get or set If the command type does .NET indeed represent Chapter the query 10 text. - Pr ocesses, When creating AppDomains, an OleDbCommand Cont exts, and Threads type, you may establish the SQL query as a constructor

parameter directly via theLate CommandText Chapter 11 - or Type Reflection, Binding, and property. Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Also, when you are creating an OleDbCommand type, you will need to specify the OleDbConnection to be used Again, you may do so as a constructor parameter or via the Connection property. To illustrate, ponder the two Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) (functionally equivalent) ways to build an OleDbCommand type that associates a SQL SELECT statement with Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) an OleDbConnection variable named "cn": Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

// Specify SQL command and connection as constructor parameters. string strSQL1 = "Select Make from Inventory where Color='Red'"; Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces OleDbCommand myCommand1 = new OleDbCommand(strSQL1, cn); Chapter 18 - ASP.NET Web Pages and Web Contr ols // Specify SQL command and connection via properties. Chapter 19 - ASP.NET Web Applicat ions string strSQL2 = "Select Make from Inventory where Color='Red'"; Chapter 20 - XML Web Ser vices OleDbCommand myCommand2 = new OleDbCommand(); I ndex myCommand.Connection = cn; List of Figur es myCommand.CommandText = strSQL2; Chapter 17 - Data Access w ith ADO.NET

List of Tables

Realize that at this point, you have not literally submitted the SQL query to the Cars database, but rather preppe the state of the command type for future use. Table 17-15 highlights some additional members of the OleDbCommand type. Table 17-15: Members of the OleDbCommand Type

OleDbCommand C# an d th eMeaning .N ET Plat fin ormLife , Se con d Ed it ion Member by Andr ew Tr oelsen CommandText

ISBN:1590590554

Apr ess © 2003 (1200 pages)

Gets or sets the SQL command text or the provider-specific syntax to run

This compr ehensiv e text star ts w ith a brief ov er view of the against the data source. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

CommandTimeout Ta ble o f Con t en t s CommandType

Gets or sets the time to wait while executing the command before terminating the attempt and generating an error. The default is 30 seconds. Gets or sets how the CommandText property is interpreted via the

C# and t he .NET Plat for m, Second CommandType Edition enumeration. The default value is CommandType.Text, which I ntr oduction

represents a SQL query.

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Connection

Gets or sets the OleDbConnection used by this instance of the OleDbCommand.

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Gets the collection Pa rParameters t Tw o - The C# Pr ogr am m ing La ngua ge

of OleDbParameter types used for a parameterized query.

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Cancel()

Cancels the execution of a command.

ExecuteReader() Returns an instance of an OleDbDataReader, which provides forward-only, Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

read-only access to the underlying data. - I nter faces and Collections

Chapter 7 - Callback I nter faces, and Evthe entscommand text to the data store, without returning an ExecuteNonQuery() ThisDelegates, method issues Chapter 8 - Advanced C# Type Const ruction Techniques OleDbDataReader type. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

ExecuteScalar() A lightweight Chapter 9 - Under standing .NET Assem bliesversion of the ExecuteNonQuery() method, designed specifically for singleton queries as obtaining a record count). Chapter 10 - Pr ocesses, AppDomains, Cont exts, and(such Threads

Chapter 11 - Type Reflection, Creates Late Binding, and Attr(or ibuteBased Prversion ogrammof ingthe command on the data Prepare() a prepared compiled) Pa r t Four - Le ve r a ging the .NET Libr a r ie s source.

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d thOleDbDataReader e .N ET Plat f orm , Se con d Ed it ion Working with the by Andr ew Tr oelsen

ISBN:1590590554

Once you have established the(1200 active connection and SQL command, the next step is to truly submit the Apr ess © 2003 pages) query to the dataThis source. As you would number compr ehensiv e textguess, star ts there w ith a are briefa ov er view of of ways the to do so. The OleDbDataReader type (which implements IDataReader) is the simplest and fastest way to C# language and then quickly m oves to key technical and obtain information from a data store. ar chitectur al issuesforward-only for .NET developer s. of data returned one record at a time. Given this, it This class represents a read-only, stream should stand to reason that data readers are useful only when submitting SQL selection statements to the underlying data store. Ta ble o f Con t en t s

The OleDbDataReader usefulEdition when you need to iterate over large amounts of data very quickly and have C# and t he .NET Plat for m, is Second nooduction need to work an in-memory DataSet representation. For example, if you request 20,000 records from a I ntr table to -store in a text file,a nd it would be rather intensive Pa r t One I nt r oduci ng C# the .NET P la tf or memory m

to hold this information in a DataSet. A better

approach be to create data reader that spins over each record as rapidly as possible. Be aware, Chapter 1 would - The Philosophy of a .NET however, DataReaders (unlike data adapter types) maintain an open connection to their data source Chapter 2 that - Building C# Applications until you the session. Pa r t Tw o - explicitly The C# Prclose ogr am m ing La ngua ge Chapter 3

- C# Language Fundamentals

To illustrate, the following example issues a simple SQL query against the Cars database, using the - Obj ect -Or iented Pr ogr am ming w ith C# ExecuteReader() method of the OleDbCommand type. Using the Read() method of the returned Chapter 5 - Exceptions Obj ect Lifetim e OleDbDataReader, youand dump each member to the standard IO stream: Chapter 4 Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

public class OleDbDR Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s static void Main(string[] args) Chapter { 9 - Under standing .NET Assem blies Chapter 10 - Pr // ocesses, Cont exts, and Threads MakeAppDomains, a connection. Chapter 11 - Type Reflection, Late Binding, Attr OleDbConnection(); ibute- Based Pr ogramm ing OleDbConnection cn =and new Pa r t Four - Le vecn.ConnectionString r a ging the .NET Libr a r ie s = "Provider=SQLOLEDB.1;" + Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er "User ID=sa;Pwd=;Initial Catalog=Cars;" + Chapter 13 - Building"Data a Bet ter Source=(local);Connect Win dow ( Int roducin g Window s For ms) Timeout=30"; Chapter 14 - A cn.Open(); Better Paint ing Fr amew or k ( GDI + ) ... 15 - Pr ogr am ming with Windows Form s Contr ols Chapter //SyCreate a SQL command. Chapter 16 - The stem .I O Nam espace string = "SELECT Make FROM Inventory WHERE Color='Red'"; Chapter 17 - Data Access strSQL w ith ADO.NET Pa r t Fi ve - W e b OleDbCommand Appl ica ti ons and XmyCommand ML W e b Se r vi = cesnew OleDbCommand(strSQL, cn); // Obtain a data reader a la ExecuteReader(). Chapter 18 - ASP.NET Web Pages and Web Contr ols OleDbDataReader myDataReader; Chapter 19 - ASP.NET Web Applicat ions myDataReader = myCommand.ExecuteReader(); Chapter 20 - XML Web Ser vices // Loop over the results. I ndex Console.WriteLine("***** Red cars obtained from a DataReader *****"); List of Figur es while (myDataReader.Read()) List of Tables { Console.WriteLine("-> Red car: " + myDataReader["Make"].ToString()); } // Don't forget this! myDataReader.Close(); cn.Close(); } }

The result is the listing of all red automobiles in the Cars database (Figure 17-22).

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Figure 17-22: Reading records with the OleDbDataReader Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Recall 1that- DataReaders read-only streams of data. Given this, there is no way to navigate Chapter The Philosophyare of forward-only, .NET around2the- contents of the OleDbDataReader. All you can do is read the current record in memory and use it Chapter Building C# Applications inr tyour Pa Tw oapplication: - The C# Pr ogr am m ing La ngua ge Chapter 3

- C# Language Fundamentals

Chapter // Get 4 the - Obj value ect -Or iented in the Pr ogr am 'Make' ming w ith column. C#

Console.WriteLine("Red car: {0} ", myDataReader["Make"].ToString()); Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

When you are finished using the DataReader, make sure to terminate the session using the appropriately Chapter 8 - Advanced C# Type Const ruction Techniques named method, Close(). Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - toUnder standingand .NET Assemmethods, blies In addition the Read() Close() there are a number of other methods that allow you to obtain Chapter 10 -typed Pr ocesses, AppDomains, Contcolumn exts, and Threads a strongly value from a specified in a given format (e.g., GetBoolean(), GetByte(), and so Chapter 11 - Type Based to Pr ogramm forth). Thus, if youReflection, know thatLate the Binding, column and you Attr areibuteattempting access ing has been typed as a Boolean data Pa r t Four Le veavoid r a gingan the .NET Libr ie smaking type, you- can explicit casta rby

a call to GetBoolean(). Finally, understand that the FieldCount

Chapter 12returns - Obj ect ialization the .NET Remoting er property theSer number of and columns in the currentLay record. Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Specifying the Data Reader's Command Behavior

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter - The stem .I O the NamOleDbCommand.ExecuteReader() espace As you 16 may haveSynoticed, method has been overloaded. One version Chapter of this member 17 - Datatakes Access a value w ith ADO.NET from the CommandBehavior enumeration. This type supports the following Pa values: r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 enum - ASP.NET Web Applicat ions public System.Data.CommandBehavior Chapter 20 - XML Web Ser vices { I ndex CloseConnection, Default,

KeyInfo, SchemaOnly, List of Figur es SequentialAccess, List of Tables SingleResult, SingleRow, }

One value of interest is CommandBehavior.CloseConnection. If you specify this value, the underlying connection maintained by the connection object will be automatically closed once you close the data reader type (check out online help for details on the remaining values): // Auto close the connection. OleDbDataReader myDataReader; myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection); ... myDataReader.Close();

// No need to do this anymore! cn.Close(); C# an d th e .N ET of Platconnection f orm , Se con d Ed it ion Console.WriteLine("State is: {0}", cn.State); by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the

Obtaining Multiple Setsm Using OleDbDataReader C# language Result and then quickly oves to keyatechnical and ar chitectur al issues for .NET developer s.

Data reader types are able to obtain multiple result sets from a single command object. For example, if you are interested in obtaining all rows from the Inventory table as well as all rows from the Customers table, you to tspecify Taare ble able o f Con en t s both SQL SELECT statements using a semicolon delimiter: C# and t he .NET Plat for m, Second Edition I ntr oductiontheSQL = "SELECT * From Inventory;SELECT * from Customers"; string Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET Once you theC# data reader, you are able to iterate over each result set via the NextResult() method. Do Chapter 2 -obtain Building Applications

be thatC# youPrare always the Pa r t aware Tw o - The ogr am m ingreturned La ngua ge

first result set automatically. Thus, if you wish to read over the rows of each table, you would be able to build the following iteration construct: Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

do Chapter 5

- Exceptions and Obj ect Lifetim e

{ Chapter 6

- I nter faces and Collections

Chapterwhile(myDataReader.Read()) 7 - Callback I nter faces, Delegates, and Ev ents

{

Chapter 8

- Advanced C# Type Const ruction Techniques

// Read the info of the current result set. } Chapter 9 - Under standing .NET Assem blies }while(myDataReader.NextResult()); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Obtaining Schema Information Using a OleDbDataReader

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

A final point to be made regarding ADO.NET data reader types is that they also provide a manner to obtain schema information. However, unlike the connection types (which allow you to obtain schema information for Chapter 15 - Pr ogr am ming with Windows Form s Contr ols the entire database), the OleDbDataReader.GetTableSchema() method returns a DataTable that describes Chapter 16 - The Sy stem .I O Nam espace the characteristics of the table specified by the SQL SELECT statement: Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

DataTable dt = myDataReader.GetSchemaTable();

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List ofSOURCE Figur es List ofCODE Tables

The OleDbDataReaderApp application is included under the Chapter 17 subdirectory.

C# an d th e .N and ET PlatDeleting f orm , Se con dRecords Ed it ion Inserting, Updating, Using OleDbCommand ISBN:1590590554

by Andr ew Tr oelsen

As you have just Apr seen, ExecuteReader() method allows you to examine the results of a SQL SELECT essthe © 2003 (1200 pages) statement using aThis forward-only, read-only flow ofithinformation. compr ehensiv e text star ts w a brief ov erHowever, view of thewhen you wish to submit SQL commands that result in the modification of a given table, you make C# language and then quickly m oves to key technical use and of the ar chitectur al issues formethod. .NET developer s. OleDbCommand.ExecuteNonQuery() This single method will perform inserts, updates, and deletes based on the format of your command text. Be very aware that when you are making use of the OleDbCommand.ExecuteNonQuery() method, you are operating within the connected layer of ADO.NET, Tameaning ble o f Con t enmethod ts this has nothing to do with obtaining populated DataSet types via a data adapter. C# and t he .NET Plat for m, Second Edition

Tooduction illustrate modifying a data source via ExecuteNonQuery(), assume you wish to insert a new record into the I ntr Inventory of the Cars database. Once Pa r t One - Itable nt r oduci ng C# a nd the .NET P la tf oryou m

have configured your connection type, the remainder of your

task is as as authoring the correct SQL: Chapter 1 simple - The Philosophy of .NET Chapter 2

- Building C# Applications

Pa class r t Tw o -UpdateWithCommandObj The C# Pr ogr am m ing La ngua ge

{ Chapter 3

- C# Language Fundamentals void Main(string[] args) Chapter static 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter { 5

- Exceptions and Obj ect Lifetim e

Chapter 6

//faces Open connection to Cars db. - I nter andaCollections

Chapter 7

OleDbConnection cn = and newEv OleDbConnection(); - Callback I nter faces, Delegates, ents

cn.ConnectionString = "Provider=SQLOLEDB.1;" + "User ID=sa;Pwd=;Initial Catalog=Cars;" + Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s "Data Source=(local);Connect Timeout=30"; Chapter 9 - Under standing .NET Assem blies cn.Open(); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads // SQL INSERT statement. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing string sql = "INSERT INTO Inventory" + Pa r t Four - Le ve r a ging the .NET Libr a r ie s "(CarID, Make, Color, PetName) VALUES" + Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er "('777', 'Honda', 'Silver', 'NoiseMaker')"; Chapter 13 - Building a Bet ter the Win dow ( Int roducin g Window s For ms) // Insert record. Chapter 14 - A OleDbCommand Better Paint ing Fr amew GDI + OleDbCommand(sql, ) cmd or=k (new cn); Chapter 15 - Pr try ogr am ming with Windows Form s Contr ols Chapter 16 - The stem .I O Nam espace { Sy cmd.ExecuteNonQuery(); } Chapter 17 - Data Access w ith ADO.NET catch(Exception ex) Pa r t Fi ve - W e b {Appl ica ti ons and X ML W e b Se r vi ces Console.WriteLine(ex.Message); } Chapter 18 - ASP.NET cn.Close(); Web Pages and Web Contr ols Chapter } 19 - ASP.NET Web Applicat ions } Chapter 20 - XML Web Ser vices Chapter 8

- Advanced C# Type Const ruction Techniques

I ndex List of Figur es

Updating or removing a record is just as easy:

List of Tables

// UPDATE existing record. sql = "UPDATE Inventory SET Make = 'Hummer' WHERE CarID = '777'"; cmd.CommandText = sql; try {cmd.ExecuteNonQuery();} catch(Exception ex) {Console.WriteLine(ex.Message);} // DELETE a record. sql = "Delete from Inventory where CarID = '777'"; cmd.CommandText = sql; try {cmd.ExecuteNonQuery();} catch(Exception ex)

{Console.WriteLine(ex.Message);} C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

Apr ess © 2003 pages) Although you do not bother to (1200 obtain the value returned from the ExecuteNonQuery() method, do understand that this memberThis returns a System.Int32 affected records: compr ehensiv e text that star tsrepresents w ith a briefthe ov number er view ofofthe C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

try {

Console.WriteLine("Number of rows effected: {0}", cmd.ExecuteNonQuery()); Ta ble o f Con t en t s }

C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Finally, do be aware that the ExecuteNonQuery() method of a given command object is the only way to issue

Chapter 1 - TheLanguage Philosophy (DDL) of .NET Data Definition commands to a data source (e.g., CREATE, ALTER, DROP, and so forth). Chapter 2 - Building C# Applications Pa r t Tw SOURCE o - The C# Pr ogr The am UpdateDBWithCommandObj m ing La ngua ge

application is included under the Chapter 17

CODE subdirectory. Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

- Exceptions and Obj ect Lifetim e Working with Parameterized Queries

Chapter 5 Chapter 6

- I nter faces and Collections The previous insert, update, andDelegates, delete logic Chapter 7 - Callback I nter faces, andworked Ev ents as expected; however, you are able to tighten things up

just a bit. you may C# know, a parameterized query can be useful when you wish to treat SQL parameters as Chapter 8 As - Advanced Type Const ruction Techniques objects, than aw value a hard-coded Pa r t Thre erather - Pr ogr am mas i ng i th .Nwithin ET Assem bl ie s

string. Typically, parameterized queries execute much faster than a literal block of text, in that they are parsed exactly once (rather than each time the SQL string is Chapter 9 - Under standing .NET Assem blies assigned to the CommandText property). Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Like classic ADO, ADO.NET command objects maintain a collection of discrete parameter types. While it is initially more verbose to configure the parameters used for a given SQL query, the end result is a more Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er convenient manner to tweak SQL statements programmatically. When you wish to map a textual parameter Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) to a member in the command object's parameters collection, simply create a new OleDbParameter type and Chapter - AOleDbCommand's Better Paint ing Fr amew or k collection ( GDI + ) add it to14the internal using the Parameters property. In addition, make use of Chapter - Pr ogrinam ming withitself. Windows Contr olsto make use of this technique whenever a SQL query is the "@"15symbol the string WhileForm yousare free Chapter 16 it- isThe Sy stem .I O when Nam espace involved, most helpful you wish to trigger a stored procedure. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .NProcedure ET Plat f orm , SeUsing con d Ed itOleDbCommand ion Executing aC#Stored by Andr ew Tr oelsen

ISBN:1590590554

Astored procedure a named block of SQL code stored at the database. Stored procedures can be Aprisess © 2003 (1200 pages) constructed to return a set of rows (or native data the calling and may take any This compr ehensiv e text star ts w ithtypes) a brieftoov er view of component the number of optional parameters. The end result is a unit of work that behaves like a typical function, with C# language and then quickly m oves to key technical and ar chitectur al issues for .NET s. rather than a binary business object. the obvious differences of being located on adeveloper data store Let's add a simple stored procedure to the existing Cars database called GetPetName, which takes an Tainput ble o parameter f Con t en t s of type integer. (If you ran the supplied SQL script, this stored proc is already defined.)

This numerical the car for which you are interested in obtaining the pet name, which is returned C# andist the he .NET Plat for ID m, of Second Edition as oduction an output parameter of type char. Here is the syntax: I ntr Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 PROCEDURE - The Philosophy of .NET CREATE GetPetName Chapter@carID 2 - Building int,C# Applications Pa r t Tw@petName o - The C# Prchar(20) ogr am m ing output La ngua ge

AS Chapter 3

- C# Language Fundamentals SELECT = PetName fromw ith Inventory where CarID = @carID Chapter 4 @petName - Obj ect -Or iented Pr ogr am ming C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Now that you have a stored procedure in place, let's see the code necessary to execute it. Begin as always - Callback I nter faces, Delegates, and Ev ents by creating a new OleDbConnection, configure your connection string, and open the session. Next, create Chapter 8 - Advanced C# Type Const ruction Techniques a new OleDbCommand type, making sure to specify the name of the stored procedure and set the Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s CommandType property accordingly, as shown here: Chapter 7

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

// Open connection to data store. OleDbConnection cn = new OleDbConnection(); Pa r t Four - Le ve r a ging the .NET Libr a r ie s cn.ConnectionString = "Provider=SQLOLEDB.1;" + Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er "User ID=sa;Pwd=;Initial Catalog=Cars;" + Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) "Data Source=(local);Connect Timeout=30"; Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) cn.Open(); Chapter 15 - aPr command ogr am ming object with Windows Contr ols proc. // Make for Form thes stored Chapter 16 The Sy stem .I O Nam espace OleDbCommand myCommand = new OleDbCommand("GetPetName", cn); Chapter 17 - Data Access w ith ADO.NET myCommand.CommandType = CommandType.StoredProcedure; Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Specifying Parameters Using the OleDbParameter Type

Chapter 20 - XML Web Ser vices

I ndex The next task is to establish the parameters used for the call. To illustrate the syntax of parameterized List of Figur es will use the OleDbParameter type. This class maintains a number of properties that allow you queries, you List of Tables to configure the name, size, and data type of the parameter, as well as its direction of travel. Table 17-16

describes some key properties of the OleDbParameter type. Table 17-16: Key Members of the OleDbParameter Type

OleDbParameter Meaning C# an d th e .N ET Plat f ormin , SeLife con d Ed it ion Property by Andr ew Tr oelsen DataType DbType

ISBN:1590590554

Apr ess © 2003 (1200 pages)

Establishes the type of the parameter, in terms of .NET

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and thenorquickly m oves to data key technical Gets sets the native type fromand the data source, represented ar chitectur al issues for .NET developer s.

as a CLR data type

Direction Ta ble o f Con t en t s

Gets or sets whether the parameter is input-only, output-only, bidirectional, or a return value parameter

C# and t he .NET Plat for m, Second Edition

IsNullable

I ntr oduction

Gets or sets whether the parameter accepts null values

Pa rOleDbType t One - I nt r oduci ng C# a nd the Gets .NET or P lasets tf or m the

native data type from the data source represented

Chapter 1

- The Philosophy of .NET by the OleDbType enumeration

Chapter 2

- Building C# Applications

ParameterName

Gets or sets the name of the OleDbParameter

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter Precision 3 - C# Language Fundamentals Gets or sets the maximum number of digits used to represent the Chapter 4

property - Obj ect -Or iented Pr ogrValue am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Scale

Gets or sets the number of decimal places to which the Value property is resolved

Size 8 - Advanced C# Type Const Getsruction or setsTechniques the maximum parameter size of the data Chapter Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Value

Chapter 9

Gets or sets the value of the parameter

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter Given that 11 -you Type have Reflection, one input Late and Binding, one output and Attr parameter, ibute- Based youPrcan ogramm configure ing your types as follows. Note Pa that r t Four you -then Le veadd r a ging these the items .NET Libr to the a r ieOleDbCommand s

type's ParametersCollection (which is, again,

accessed the Chapter 12 via - Obj ectParameters Ser ializationproperty): and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A the Betterparameters Paint ing Fr amew or k (the GDI + call. ) // Create for Chapter OleDbParameter 15 - Pr ogr am ming theParam with Windows = newForm OleDbParameter(); s Contr ols

// Input param. Chapter 16 - The Sy stem .I O Nam espace theParam.ParameterName = "@carID"; Chapter 17 - Data Access w ith ADO.NET theParam.OleDbType OleDbType.Integer; Pa r t Fi ve - W e b Appl ica ti ons =and X ML W e b Se r vi ces theParam.Direction = ParameterDirection.Input; Chapter 18 - ASP.NET Web Pages and Web Contr ols theParam.Value 1;Applicat // ions Car ID = 1. Chapter 19 - ASP.NET = Web myCommand.Parameters.Add(theParam); Chapter 20 - XML Web Ser vices // Output param. theParam = new OleDbParameter(); List of Figur es theParam.ParameterName = "@petName"; List of Tables theParam.OleDbType = OleDbType.Char; theParam.Size = 20; theParam.Direction = ParameterDirection.Output; myCommand.Parameters.Add(theParam); I ndex

The final step is to issue the command using (once again) OleDbCommand.ExecuteNonQuery(). Notice that the Value property of the OleDbParameter type is accessed to obtain the returned pet name, as shown here: // Execute the stored procedure! myCommand.ExecuteNonQuery(); // Display the result. Console.WriteLine("Stored Proc Info:"); Console.WriteLine("Car ID: {0}", myCommand.Parameters["@carID"].Value);

Console.WriteLine("PetName: {0}", myCommand.Parameters["@petName"].Value); C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

SOURCE CODE

ISBN:1590590554

OleDbStoredProc included under ThisThe compr ehensiv e text starproject ts w ith is a brief ov er view of the the Chapter 17 subdirectory. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e Layer .N ET Platand f orm , Se conOleDbDataAdapter d Ed it ion The Disconnected the Type ISBN:1590590554

by Andr ew Tr oelsen

At this point you should understand how to connect to a data source using the OleDbConnection type, Apr ess © 2003 (1200 pages) issue a commandThis (using the OleDbCommand and iterate over a result set compr ehensiv e text star ts and w ith OleDbParameter a brief ov er view of types), the using the OleDbDataReader. As you have just seen, these types allow you to obtain and alter data using C# language and then quickly m oves to key technical and ar chitectur al issuesHowever, for .NET developer the connected layer of ADO.NET. when yous.are using these techniques, you are not receiving your data via DataSets, DataTables, DataRows, or DataColumns. Given that you spend a good deal of time in this chapter getting to know these types, you are right in assuming that there is more to the story of Tadata ble oaccess f Con t en t s the forward-only, read-only world of the data reader. than C# and t he .NET Plat for m, Second Edition

Tooduction shift gears, we now need to examine the role of the OleDbDataAdapter type and understand how it is I ntr our vehicle obtaining Pa r t One - I ntto r oduci ng C# aapopulated nd the .NETDataSet. P la tf or m In

a nutshell, data adapters pull information from a data

store and a DataTable or DataSet type using the OleDbDataAdapter.Fill() method. As you can Chapter 1 populate - The Philosophy of .NET see, this hasC#been overloaded a number of times (FYI, the integer return type holds the number of Chapter 2 method - Building Applications records Pa r t Tw o -returned): The C# Pr ogr am m ing La ngua ge Chapter 3

- C# Language Fundamentals // Fills the set with records Chapter 4 - Obj ect data -Or iented Pr ogr am ming w ith C# from a given source table.

public Fill(DataSet string tableName); Chapter 5 int - Exceptions and Obj ect yourDS, Lifetim e Chapter 6

- I nter faces and Collections // Fills the data the and records Chapter 7 - Callback I nterset faces,with Delegates, Ev ents located between

// the given bounds from a given source table. - Advanced C# Type Const ruction Techniques public int Fill(DataSet yourDS, int startRecord, Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s int maxRecord, string tableName); Chapter 8 Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET method Libr a r ie shas The OleDbDataAdapter.Fill()

also been overloaded to return to you a populated DataTable

Chapter 12 - Obj ecta Ser ializationDataSet: and the .NET Remoting Lay er type, rather than full-blown Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 int - A Better Paint ing Fr amew or k ( GDI + ) public Fill(System.Data.DataTable dataTable); Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

It eisb also pointing outWthat one version Pa r t FiNote ve - W Appl worth ica ti ons and X ML e b Se r vi ces

of the Fill() method will automatically populate a

ADO Recordset type with theols contents of a given ADO.NET DataTable. Chapter 18 classic - ASP.NET Web Pages and Web Contr Chapter 19 - ASP.NET Web Applicat ions

Before you can call this method, you obviously need a valid OleDbDataAdapter object reference. The constructor has also been overloaded a number of times, but in general you need to supply the I ndex connection information and the SQL SELECT statement used to populate the DataTable/DataSet type at List of Figur es the time Fill() is called. Once the initial SQL Select has been established via the constructor parameter, it List of be Tables may obtained (and modified) via the SelectCommand property: Chapter 20 - XML Web Ser vices

// Whenever you call Fill(), the SQL statement // contained within the SelectCommand property // will be used to populate the DataSet. myDataAdapter.Fill(myDS, "Inventory");

The OleDbDataAdapter type not only fills the tables of a DataSet on your behalf, but also is in charge of maintaining a set of core SQL statements used to push updates back to the data store. When you call the Update() method of a given data adapter, it will read the SQL contained within the DeleteCommand, InsertCommand, and UpdateCommand properties to push the changes within a given DataTable back to the data source: // Whenever you call Update(), the SQL statements // contained within the InsertCommand,

// DeleteCommand, and UpdateCommand properties C# anto d thupdate e .N ET Plat f orm , Se con d Ed it ion // will be used the data source ISBN:1590590554 by Andr ew Tr oelsen // given a DataTable in the DataSet. Apr ess © 2003 (1200 pages) myDataAdapter.Update(myDS, "Inventory"); This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and al issues for .NET developer s. Now, if you have ar a chitectur background in classic ADO, you should already be able to see the huge conceptual

change at hand: Under ADO.NET, you are the individual in charge of specifying the SQL commands to use during the updating of a given database.

Ta ble o f Con t en t s

C# t he .NET Plat for m, key Second Edition (SelectCommand, UpdateCommand, DeleteCommand, and In and addition to these four properties I ntr oduction InsertCommand), Table 17-17 describes some additional members of the OleDbDataAdapter type. Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - The Philosophy of .NET Table 17-17: Core Members of the OleDbDataAdapter Chapter 2 - Building C# Applications

OleDbDataAdapter Member

Meaning in Life

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# SQL commands that will be issued to the data DeleteCommand Used to establish Chapter 5 - Exceptions and Obj ect Lifetim e the Fill() and Update() methods are called. Each of these store when

InsertCommand

Chapter 6

- I nter faces and Collections properties is set using an OleDbCommand type.

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

SelectCommand

UpdateCommand Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Fill()

Fills a given table in the DataSet with some number of records

Chapter 9

- Under standing .NETbased Assemon blies the current SELECT command. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

GetFillParameters() Returns parameters used when performing the select command. Chapter 11 - Type Reflection, Late Binding,alland Attr ibute- Based Pr ogramm ing Pa rUpdate() t Four - Le ve r a ging the .NET Libr a r ie s Calls the

respective INSERT, UPDATE, or DELETE statements for

Chapter 12 - Obj ect Ser ialization each and the .NET Remoting inserted, updated,Lay or er deleted row for a given table in the Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) DataSet. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Filling a DataSet Using the OleDbDataAdapter Type

Chapter 17 - Data Access w ith ADO.NET

Pa r t understand Fi ve - W e b Appl ti ons and Xof ML W edata b Se adapter r vi ces To the ica functionality the

types, let's begin by learning how to use a data adapter

Chapter - ASP.NET Web Pages andThe Webfollowing Contr ols code populates a DataSet (containing a single table) to fill a 18 DataSet programmatically. Chapter 19OleDbDataAdapter: - ASP.NET Web Applicat ions using an Chapter 20 - XML Web Ser vices I ndex public static int Main(string[] args) List { of Figur es List of Tables // Open a connection to Cars db.

OleDbConnection cn = new OleDbConnection(); cn.ConnectionString = "Provider=SQLOLEDB.1;" + "User ID=sa;Pwd=;Initial Catalog=Cars;" + "Data Source=(local);Connect Timeout=30"; cn.Open(); // Create data adapter using the following SELECT. string sqlSELECT = "SELECT * FROM Inventory"; OleDbDataAdapter dAdapt = new OleDbDataAdapter(sqlSELECT, cn); // Create and fill the DataSet (connection closed automatically). DataSet myDS = new DataSet("CarsDataSet"); dAdapt.Fill(myDS, "Inventory"); // Private helper function. PrintTable(myDS); return 0; }

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Notice that unlike your work during the first half of this chapter,ISBN:1590590554 you did not manually create a DataTable by Andr ew Tr oelsen type and add it to the DataSet. Also, you did not call ExecuteReader() from a command object to stream Apr ess © 2003 (1200 pages) over the result set. Rather, you specified the Inventory table as the second parameter to the Fill() method, This compr ehensiv e text star ts w ith a brief ov er view of the which functions as the friendly name of the newly populated table. Do be aware that if you do not specify a C# language and then quickly m oves to key technical and friendly name, theardata adapter will simply the table "Table": chitectur al issues for .NETname developer s. // This DataSet has a single table called 'Table'. Ta ble o f dAdapt.Fill(myDS); Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction

Internally, Fill() builds thea DataTable, given Pa r t One - I nt r oduci ng C# nd the .NET P la tf orthe m

name of the table in the data store using the SELECT

command. this iteration, of the.NET connection between the given SQL SELECT statement and the Chapter 1 - In The Philosophy OleDbDataAdapter established as a constructor parameter: Chapter 2 - Building was C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

// Create SELECT Fundamentals command as string type. Chapter 3 - C#a Language string = "SELECT * FROM Inventory"; Chapter 4 sqlSELECT - Obj ect -Or iented Pr ogr am ming w ith C# OleDbDataAdapter dAdapt newe OleDbDataAdapter(sqlSELECT, cn); Chapter 5 - Exceptions and Obj ect =Lifetim Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

As an alternative, you can associate the OleDbCommand to the OleDbDataAdapter, using the Chapter 8 - Advanced C# Type Const ruction Techniques SelectCommand property, as shown here: Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

// Create a SELECT command object. OleDbCommand selectCmd = new OleDbCommand("SELECT * FROM Inventory", cn); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing // Make a data adapter and associate commands. Pa r t Four - Le ve r a ging the .NET Libr a r ie s OleDbDataAdapter dAdapt = new OleDbDataAdapter(); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er dAdapt.SelectCommand = selectCmd; Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am mingmethod with Windows Contrsome ols formatting razzle-dazzle: The PrintTable() helper is little Form mores than Chapter 16 - The Sy stem .I O Nam espace Chapter 17 static - Data Access ADO.NET public voidw ith PrintTable(DataSet ds) Pa {r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter // 18 - Get ASP.NET Web Pagestable and Web ContrDataSet. ols Inventory from Chapter Console.WriteLine("Here 19 - ASP.NET Web Applicat ions is what we have right now:\n"); Chapter DataTable 20 - XML Web invTable Ser vices = ds.Tables["Inventory"]; I ndex

// Print the Column names.

for(int curCol= 0; curCol< invTable.Columns.Count; curCol++) List of Figur es { List of Tables Console.Write(invTable.Columns[curCol].ColumnName.Trim() + "\t"); } Console.WriteLine(); // Print each cell. for(int curRow = 0; curRow < invTable.Rows.Count; curRow++) { for(int curCol= 0; curCol< invTable.Columns.Count; curCol++) { Console.Write(invTable.Rows[curRow][curCol].ToString().Trim() + "\t"); } Console.WriteLine(); } }

Altering Column C# an d th Names e .N ET Plat Using f orm , Se the con d OleDbDataAdapter Ed it ion Type ISBN:1590590554

by Andr ew Tr oelsen

The default behavior of © a 2003 data(1200 adapter Apr ess pages)type is to map column names from the data source to the DataColumn collection without modification. However, oftentimes you wish to map the underlying column This compr ehensiv e text star ts w ith a brief ov er view of the name (e.g., LName) to a more friendly display (e.g., Name). C# language and then quickly mname oves to key Last technical and When you wish to do so, you will need to establisharspecific chitectur column al issues mappings for .NET developer for the table s. you will be filling with the corresponding data adapter. To do so, you must first obtain the data adapter's underlying System.Data.Common.DataTableMapping type (and thus need to specify that you are using the TaSystem.Data.Common ble o f Con t en t s namespace). Once you have a reference to this entity, you are able to establish C# and t he .NET Plat for m,for Second Edition unique column names a specific table. For example, the following code alters the display names for I ntr theoduction CarID, Make, and PetName columns of the Inventory table: Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - reference The Philosophy of .NET // Must this namespace Chapter - Building C# Applications // to2 get definitions of DataTableMapping! Pa r t Tw o -System.Data.Common; The C# Pr ogr am m ing La ngua ge using

Chapter ... 3

- C# Language Fundamentals

Chapter // Establish 4 - Obj ect column -Or iented mappings Pr ogr am mingfor w ith the C# Inventory table

// by5 adding new and DataColumnMapping types Chapter - Exceptions Obj ect Lifetim e // to6 the DataTableMapping Chapter - I nter faces and Collections type. DataTableMapping tblMapper = and Ev ents Chapter 7 - Callback I nter faces, Delegates, Chapter dAdapt.TableMappings.Add("Table", 8 - Advanced C# Type Const ruction Techniques"Inventory");

tblMapper.ColumnMappings.Add("CarID", Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

"ID"); tblMapper.ColumnMappings.Add("Make", "Brand"); Chapter 9 - Under standing .NET Assem blies tblMapper.ColumnMappings.Add("PetName", "Friendly name of Car"); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads // Create and fill the DataSet. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing dAdapt.Fill(myDS); Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 -explicitly Buildingalter a Betthe ter internal Win dow DataColumnMappingCollection ( Int roducin g Window s For ms) Here, you type before making the call to Fill(). Chapter 14 - A note Betterthat Paint ingspecify Fr amewthe or kfriendly ( GDI + ) name of the table to interact with at the time you add in your Furthermore, you Chapter - Prmapping, ogr am ming with than Windows Form Contrcall ols the Fill() method (recall that by default, the name of unique 15 table rather at the times you Chapter 16 populated - The Sy stem .I O Nam espace the newly DataTable is simply "Table"). Chapter 17 - Data Access w ith ADO.NET

Ifryou run this now output Pa t Fi ve - W e b application, Appl ica ti onsyou andwill X ML W e find b Se rthe vi ces

shown in Figure 17-23.

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 17-23: Mapping database column names to unique display names SOURCE CODE

The FillSingleTableDSWithAdapter project is under the Chapter 17 subdirectory.

C# an d th SQL e .N ET Plat f ormProvider , Se con d Ed it ion Working with the Data ISBN:1590590554

by Andr ew Tr oelsen

Before you see the of inserting, updating, and removing records using a data adapter, I would like Aprdetails ess © 2003 (1200 pages) to introduce the SQL data provider. As you recall, OleDb provider you to access any OLE DBThis compr ehensiv e text star ts w iththe a brief ov er view of allows the compliant data store, but incurs overhead via the COM interoperability layer lurking in the background. C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

When you know that the data source you need to manipulate is MS SQL Server, you will find performance gains if you use the System.Data.SqlClient namespace directly. Collectively, these classes constitute the Tafunctionality ble o f Con t en oftthe s SQL data provider, which should look very familiar, given your work with the OleDb provider 17-18). C# and t he(Table .NET Plat for m, Second Edition I ntr oduction

Table CorengTypes ofthe the.NET System.Data.SqlClient Pa r t One17-18: - I nt r oduci C# a nd P la tf or m Chapter 1

Namespace

- The Philosophy of .NET

System.Data.SqlClient Meaning in Life Type - Building C# Applications

Chapter 2

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter SqlCommand 3 - C# Language Fundamentals Represents a Transact-SQL query to execute at a SQL Server Chapter 4

data source. - Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

SqlConnection

Represents an open connection to a SQL Server data source.

SqlDataAdapter Represents set of data commands and a database Chapter 7 - Callback I nter faces, Delegates, and Ev a ents Chapter 8

used to fill the DataSet and update the SQL Server - Advanced C# Type Const connection ruction Techniques

data source. Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9 - Under standing .NET Assem blies SqlDataReader Provides a way of reading a forward-only stream of data Chapter 10 - Pr ocesses, AppDomains, Cont exts,from and a Threads records SQL Server data source. Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

SqlErrors Pa rSqlErrors t Four - Le ve r a ging the .NET Libr a r ie s

maintains a collection of warnings or errors returned by SQL Server, of which is represented by a SQLError Chapter SqlError 12 - Obj ect Ser ialization and the .NET Remotingeach Lay er type. When an error is encountered, an exception of type Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) SqlException SQLException is thrown. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols SqlParameterCollection SqlParametersCollection holds onto the parameters sent to a Chapter 16 The Sy stem .I O Nam espace stored procedure held in the database. Each parameter is of SqlParameter

type SQLParameter. Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Given that these types almost to working with the OleDb data provider, you should Chapter 18 -working ASP.NETwith Web Pages and is Web Contridentical ols already19know what toWeb do with them, Chapter - ASP.NET Applicat ionsas they have a similar public interface. To help you get comfortable with this20new set Web of types, the remainder of the examples use the SQL data provider (don't forget to specify Chapter - XML Ser vices you are using the System.Data.SqlClient namespace!) I ndex List of Figur es

The System.Data.SqlTypes Namespace

List of Tables

On a quick related note, when you use the SQL data provider, you also have the luxury of using a number of managed types that represent native SQL server data types. Table 17-19 gives a quick rundown. Table 17-19: Types of the System.Data.SqlTypes Namespace

System.Data.SqlTypes SQL C# an d th e .NWrapper ET Plat f orm , Native Se con d Ed it ionServer by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

SqlBinary SqlInt64

ISBN:1590590554

binary, varbinary, timestamp, image

This compr ehensiv e text star ts bigint w ith a brief ov er view of the C# language and then quickly m oves to key technical and bit ar chitectur al issues for .NET developer s.

SqlBit SqlDateTime Ta ble o f Con t en t s SqlNumeric

C# and t he .NET Plat for m, Second Edition

SqlDouble

I ntr oduction

datetime, smalldatetime decimal float

Pa rSqlInt32 t One - I nt r oduci ng C# a nd the .NET P la tf or mint

Chapter 1

- The Philosophy of .NET

SqlMoney - Building C# Applications Pa rSqlString t Tw o - The C# Pr ogr am m ing La ngua ge Chapter 2 Chapter 3

money, smallmoney nchar, ntext, nvarchar, sysname, text, varchar, char

- C# Language Fundamentals

SqlNumeric numeric - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e SqlSingle real Chapter 4 Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

SqlInt16

smallint

Chapter 8 - Advanced C# Type Const ruction Techniques System.Object sql_variant Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

SqlByte

Chapter 9

- Under standing .NET Assem blies

tinyint

Chapter 10 - Pr ocesses, AppDomains, Cont exts, uniqueidentifier and Threads SqlGuid Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Inserting Records Using the SqlDataAdapter

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Chapter 14 you - A have Betterflipped Paint ing Fr amew or k ( GDI +) Now that from the OleDb provider to the realm of the SQL provider, you can return to the Chapter - Pr ogr am ming Form s Contr olsexamine how to insert new records into a given table task of 15 understanding thewith role Windows of data adapters. Let's Chapter using the 16 SqlDataAdapter - The Sy stem .I O (which Nam espace is nearly identical to using the OleDbDataAdapter, OdbcDataAdapter,

and OracleDataAdapter As always, begin by creating an active connection, as shown here: Chapter 17 - Data Access wtypes). ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 class - ASP.NET Web Pages and Web Contr ols public MySqlDataAdapter Chapter 19 - ASP.NET Web Applicat ions { Chapter public 20 - XML Web static Ser vices void Main() I ndex

{

List of Figur es // Create a connection and adapter (with select command). List of Tables

SqlConnection cn = new SqlConnection("server=(local);User ID=sa;Pwd=;database=Cars"); SqlDataAdapter dAdapt = new SqlDataAdapter("SELECT * FROM Inventory", cn); // Kill record inserted on the last run of this app. cn.Open(); SqlCommand killCmd = new SqlCommand("Delete from Inventory where CarID = '1111'", cn); killCmd.ExecuteNonQuery(); cn.Close();

} }

You can see that the connection string has been cleaned up quite a bit. In particular, notice that you do not need to define a Provider segment (as the SQL data provider only talks to SQL server! ). Next, note that you create a new SqlDataAdapter and specify the value of the SelectCommand property as a constructor

parameter (just like with the OleDbDataAdapter).

C# an d th e .N ET Plat f orm , Se con d Ed it ion

ISBN:1590590554 ewmore Tr oelsen The deletion logicbyisAndr really of a good housekeeping chore for the current application. Here, you Apr ess © 2003 (1200 pages) create a new SqlCommand type that will destroy the record you are about to enter (to avoid a primary key violation). This compr ehensiv e text star ts w ith a brief ov er view of the

C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer If you wish to make use of parameterized queries, thes.next step is a bit more involved. Your goal is to create a new SQL statement that will function as the SqlDataAdapter's InsertCommand. First, create the new SqlCommand and specify a standard SQL insert, followed by SqlParameter types describing each Tacolumn ble o f Con t enInventory ts in the table, as shown here (and yes, you could avoid the use of the parameter objects if C# and t heand .NET Plat for m, Second Edition you wish directly hard code the INSERT statement): I ntr oduction Pa r t One - Istatic nt r oduci ng C# a nd the .NET P la tf or m public void Main()

Chapter 1 {

- The Philosophy of .NET

Chapter ... 2 - Building C# Applications Pa r t Tw o// - The C# Pr ogr aminsert m ing La ngua ge Build the command!

Chapter 3 dAdapt.InsertCommand - C# Language Fundamentals = new SqlCommand("INSERT INTO Inventory" + Chapter 4 - Obj ect -Or ientedMake, Pr ogr amColor, ming w ithPetName) C# "(CarID, VALUES" + - Exceptions "(@CarID, and Obj @Make, ect Lifetim @Color, e @PetName)", cn)"; Chapter SqlParameter 6 - I nter faces andworkParam Collections = null; Chapter 5

Chapter // 7 - CarID. Callback I nter faces, Delegates, and Ev ents

= dAdapt.InsertCommand.Parameters.Add(new Chapter 8 workParam - Advanced C# Type Const ruction Techniques SqlParameter("@CarID", Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s SqlDbType.Int)); = "CarID"; Chapter workParam.SourceColumn 9 - Under standing .NET Assem blies DataRowVersion.Current; Chapter workParam.SourceVersion 10 - Pr ocesses, AppDomains, Cont = exts, and Threads // Make. workParam = dAdapt.InsertCommand.Parameters.Add(new Pa r t Four - Le ve r a ging the .NET Libr a r ie s SqlParameter("@Make", SqlDbType.VarChar)); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er workParam.SourceColumn = "Make"; Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) workParam.SourceVersion = DataRowVersion.Current; Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) // Color. Chapter 15 - Pr ogr am ming with Windows Form s Contr ols workParam = dAdapt.InsertCommand.Parameters.Add(new Chapter 16 - The Sy stem .I O Nam espace SqlParameter("@Color", SqlDbType.VarChar)); ChapterworkParam.SourceColumn 17 - Data Access w ith ADO.NET = "Color"; Pa r t Fi ve - W e b Appl ica ti ons and X ML W e= b Se r vi ces workParam.SourceVersion DataRowVersion.Current; Chapter// 18 PetName. - ASP.NET Web Pages and Web Contr ols ChapterworkParam 19 - ASP.NET=Web Applicat ions dAdapt.InsertCommand.Parameters.Add(new Chapter 20 - XML Web Ser vices SqlParameter("@PetName", SqlDbType.VarChar)); I ndex workParam.SourceColumn = "PetName"; workParam.SourceVersion = DataRowVersion.Current; List of Figur es } of Tables List Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Now that you have formatted each of the parameters, the final step is to fill the DataSet and add your new row (note that the PrintTable() helper function has carried over to this example): public static void Main() { ... // Fill data set with initial data. DataSet myDS = new DataSet(); dAdapt.Fill(myDS, "Inventory"); PrintTable(myDS); // Add new row to the DataTable. DataRow newRow = myDS.Tables["Inventory"].NewRow(); newRow["CarID"] = 1111;

newRow["Make"] = "SlugBug"; C# an d th e = .N ET Plat f orm , Se con d Ed it ion newRow["Color"] "Pink"; ISBN:1590590554 by Andr ew Tr oelsen newRow["PetName"] = "Cranky"; Apr ess © 2003 (1200 pages) myDS.Tables["Inventory"].Rows.Add(newRow); compr e text star ts w ith a brief ov er view of the // Send This back toehensiv database and reprint. C# language and then quickly m oves to key technical and try ar chitectur al issues for .NET developer s. { dAdapt.Update(myDS, "Inventory"); myDS.Dispose(); Ta ble o f Con t en t s myDS = new DataSet(); C# and t he .NET Plat for m, Second Edition dAdapt.Fill(myDS, "Inventory"); I ntr oduction PrintTable(myDS); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m } Chapter 1 - The Philosophy of .NET catch(Exception e){ Console.Write(e.ToString()); } Chapter 2 - Building C# Applications } Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4 -run Objthe ect -Or iented Pr ogr amsee ming C# shown in Figure 17-24. When you application, you thew ith output Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 17-24: Inserting new records using a data adapter SOURCE CODE

The InsertRowsWithSqlAdapter project can be found under the Chapter 17 subdirectory.

Updating Existing Using SqlDataAdapter C# an d th e Records .N ET Plat f orm , Se con dthe Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

Now that you can insert new rows, let's look at how you can update existing rows, which you might guess Apr ess © 2003 (1200 pages) will look quite similar to the process of inserting new rows (as well as the process of deleting existing This compr ehensiv e text star ts w ith a brief ov er view of the rows). Again, start the process by obtaining a connection and creating a new SqlDataAdapter. Next, set C# language and then quickly m oves to key technical and the value of the UpdateCommand the s.same general approach as when setting the value of ar chitectur al issuesproperty, for .NET using developer the InsertCommand. Here is the relevant code in Main(): Tapublic ble o f Con t en t s static void Main() C# { and t he .NET Plat for m, Second Edition I ntr oduction // Create a connection and adapter (same as previous code). Pa r t One... - I nt r oduci ng C# a nd the .NET P la tf or m

the UpdateCommand. Chapter // 1 - Establish The Philosophy of .NET Chapter dAdapt.UpdateCommand 2 - Building C# Applications = new SqlCommand

("UPDATE Pa r t Tw o - The C# Pr ogr am mInventory ing La ngua ge SET

Make = @Make, Color = " + "@Color, PetName = @PetName " + Chapter 3 - C# Language Fundamentals "WHERE CarID = @CarID" , cn); Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# parameters for each column in Inventory table. Chapter // 5 - Build Exceptions and Obj ect Lifetim e // Same as before, but now you are populating the ParameterCollection Chapter 6 - I nter faces and Collections // of the UpdateCommand: Chapter 7 - Callback I nter faces, Delegates, and Ev ents SqlParameter workParam = null; Chapter 8 - Advanced C# Type Const ruction Techniques workParam = dAdapt.UpdateCommand.Parameters.Add(new Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s SqlParameter("@CarID", SqlDbType.Int)); Chapter 9 - Under standing .NET Assem blies workParam.SourceColumn = "CarID"; Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads workParam.SourceVersion = DataRowVersion.Current; Chapter // 11 - Do Type Reflection, Late Binding, and Attr ibute- and BasedColor Pr ogramm ing the same for PetName, Make, params Pa r t Four... - Le ve r a ging the .NET Libr a r ie s Chapter // 12 - Fill Obj ect initial Ser ialization and the .NET Remoting Lay er data set. Chapter DataSet 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) myDS = new DataSet(); Chapter dAdapt.Fill(myDS, 14 - A Better Paint ing Fr amew or k ( GDI + ) "Inventory"); Chapter PrintTable(myDS); 15 - Pr ogr am ming with Windows Form s Contr ols Chapter // 16 - Change The Sy stem columns .I O Nam espace in second row to 'FooFoo'. changeRow = myDS.Tables["Inventory"].Rows[1]; Chapter DataRow 17 - Data Access w ith ADO.NET Pa r t Fi vechangeRow["Make"] - W e b Appl ica ti ons and X=ML"FooFoo"; W e b Se r vi ces = "FooFoo"; Chapter changeRow["Color"] 18 - ASP.NET Web Pages and Web Contr ols changeRow["PetName"] Chapter 19 - ASP.NET Web Applicat ions= "FooFoo"; back to database and reprint. Chapter // 20 - Send XML Web Ser vices try I ndex { List of Figur es dAdapt.Update(myDS, "Inventory"); List of Tables myDS.Dispose(); myDS = new DataSet(); dAdapt.Fill(myDS, "Inventory"); PrintTable(myDS); } catch(Exception e) { Console.Write(e.ToString()); } }

Figure 17-25 shows the output.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - 17-25: Pr ogr amUpdating ming withexisting Windows Form susing Contra olsdata adapter Figure records Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

As you may be guessing, if you wish to inform a data adapter how it should handle rows marked as deleted, you need to build yet another command type and assign it to the data adapter's DeleteCommand Chapter 18 - ASP.NET Web Pages and Web Contr ols property. While having absolute control over the SQL used to insert, update, and delete records does Chapter 19 - ASP.NET Web Applicat ions allow a great deal of flexibility, you may agree that it can be a bit of a bother to constantly build verbose Chapter 20 - XML Web Ser vices SQL commands by hand. You are, however, provided with some helper types. Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

I ndex List ofSOURCE Figur es List ofCODE Tables

The UpdateRowsWithSqlAdapter project is found under the Chapter 17 subdirectory.

C# an d thSQL e .N ET Commands Plat f orm , Se con d Using Ed it ion CommandBuilder Types Auto-Generating ISBN:1590590554

by Andr ew Tr oelsen

Each ADO.NET data provider that pages) ships with .NET 1.1 provides a command builder type. Using this type, Apr ess © 2003 (1200 you are able to automatically obtain objects thatovcontain correct INSERT, DELETE, and This compr ehensiv e command text star ts w ith a brief er view the of the UPDATE command types based on the initial SELECT statement. For example, the SqlCommandBuilder C# language and then quickly m oves to key technical and ar chitectur issues contained for .NET developer s. SqlDataAdapter's InsertCommand, automatically generates thealvalues within the UpdateCommand,and DeleteCommand properties based on the initial SelectCommand. The obvious benefit is that you have no need to build all the SqlCommand and SqlParameter types by hand. Ta ble o f Con t en t s

Anand obvious question pointEdition is how a command builder is able to build these SQL commands on the C# t he .NET Plat forat m,this Second fly.oduction The short answer is metadata. At runtime, when you call the Update() method of a data adapter, the I ntr related builder willthe read thePdatabase's Pa r t One command - I nt r oduci ng C# a nd .NET la tf or m

schema data to autogenerate the underlying INSERT,

DELETE, logic. If you are interested in seeing these SQL statements first-hand, you may call Chapter 1 and - TheUPDATE Philosophy of .NET the SqlCommandBuilder.GetInsertCommand(), GetUpdateCommand(), and GetDeleteCommand() Chapter 2 - Building C# Applications methods. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Chapter 3

- C# Language Fundamentals

Consider the following example, which deletes a row in a DataSet using the auto-generated SQL - Obj ect -Or iented Pr ogr am ming w ith C# statements. Furthermore, this application will print out the underlying command text of each command Chapter 5 object: - Exceptions and Obj ect Lifetim e Chapter 4 Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

static void Main(string[] args) Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s DataSet theCarsInventory = new DataSet(); Chapter// 9 Make - Underconnection. standing .NET Assem blies ChapterSqlConnection 10 - Pr ocesses, AppDomains, cn = newCont exts, and Threads Chapter 11 - SqlConnection("server=(local);User Type Reflection, Late Binding, and Attr ibute- BasedID=sa;Pwd=;database=Cars"); Pr ogramm ing Pa r t Four Le ve r a ging the .NET Libr a r ie s // Autogenerate INSERT, UPDATE, and DELETE commands Chapter// 12 based - Obj ect on Ser ialization the .NETcommand. Remoting Lay er exitingandSELECT ChapterSqlDataAdapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) da = new SqlDataAdapter("SELECT * FROM Inventory", cn); ChapterSqlCommandBuilder 14 - A Better Paint ing Fr invBuilder amew or k ( GDI + = ) new SqlCommandBuilder(da); out values of the command objects. Chapter// 15 Print - Pr ogr am ming with Windows Formgenerated s Contr ols command: {0}", ChapterConsole.WriteLine("SELECT 16 - The Sy stem .I O Nam espace Chapter 17 - da.SelectCommand.CommandText); Data Access w ith ADO.NET Console.WriteLine("UPDATE command: {0}", Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces Chapter 18 - invBuilder.GetUpdateCommand().CommandText); ASP.NET Web Pages and Web Contr ols command: {0}", ChapterConsole.WriteLine("INSERT 19 - ASP.NET Web Applicat ions invBuilder.GetInsertCommand().CommandText); Chapter 20 - XML Web Ser vices Console.WriteLine("DELETE command: {0}", I ndex invBuilder.GetDeleteCommand().CommandText); List of Figur es // Fill data set. List of Tables da.Fill(theCarsInventory, "Inventory"); PrintTable(theCarsInventory); // Delete a row and update database. try { theCarsInventory.Tables["Inventory"].Rows[6].Delete(); da.Update(theCarsInventory, "Inventory"); } catch(Exception e) { Console.WriteLine(e.Message); } // Refill and reprint Inventory table. theCarsInventory = new DataSet(); da.Fill(theCarsInventory, "Inventory"); PrintTable(theCarsInventory);

} C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Based on the initial SQL SELECT SqlCommandBuilder type generates the following This compr ehensivstatement, e text star tsthe w ith a brief ov er view of the C# and language and parameterized then quickly m oves to key technical and UPDATE, INSERT, DELETE queries: ar chitectur al issues for .NET developer s.

UPDATE Inventory SET CarID = @p1 , Make = @p2 , Color = @p3 , PetName = @p4 ( (CarID = @p5) AND TaWHERE ble o f Con t en t s ((@p6 = 1 AND Make IS NULL) OR (Make = @p7)) AND C# and t he .NET Plat for m, Second Edition ((@p8 =1 AND Color IS NULL) OR (Color = @p9)) AND I ntr oduction ((@p10 = 1 AND PetName IS NULL) OR (PetName = @p11)) ) Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m INSERT INTO Inventory( CarID , Make , Color , PetName ) VALUES Chapter 1 - The Philosophy of .NET ( @p1 , @p2 , @p3 , @p4 ) Chapter 2 - Building C# Applications DELETE FROM Inventory WHERE ( (CarID = @p1) AND Pa r t Tw o - The C# Pr ogr am m ing La ngua ge ((@p2 = 1 AND Make IS NULL) OR (Make = @p3)) AND Chapter 3 - C# Language Fundamentals ((@p4 = 1 AND Color IS NULL) OR (Color = @p5)) AND Chapter ect -Or iented Pr ogr ming w ith ((@p64 = - 1Obj AND PetName ISamNULL) OR C# (PetName = @p7)) ) Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections Now, while may Ilove the idea of getting something Chapter 7 - you Callback nter faces, Delegates, and Ev ents for nothing, do understand that command builders

do come some very restrictions. Specifically, a command builder is only able to auto-generate Chapter 8 with - Advanced C# critical Type Const ruction Techniques SQL commands formuse a data Pa r t Thre e - Pr ogr am i ng by w i th .N ET adapter Assem bl if ie all s Chapter 9

of the following conditions are true:

- Under standing .NET Assem blies

The SELECT command only interacts with a single table (e.g., no joins).

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11single - Type Reflection, Lateattributed Binding, and ibute- Based The table has been withAttr a primary key. Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

The representing thethe primary key is accounted for in your SQL SELECT statement. Chapter 12column(s) - Obj ect Ser ialization and .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

To wrap up our examination of the raw details of ADO.NET, allow me to provide two Windows Forms applications that tie together the topics discussed thus far. After this point, I'll wrap up with an overview of Chapter 15 - Pr ogr am ming with Windows Form s Contr ols the data-centric tools provided by VS .NET and discuss strongly typed DataSets. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 16 - The Sy stem .I O Nam espace

Chapter 17 - Data Access ith ADO.NET SOURCE ThewMySqlCommandBuilder project is found under the Chapter 17 subdirectory. Pa r t FiCODE ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Windows Plat f orm , Se con d Ed it ionExample A CompleteC#ADO.NET Forms ISBN:1590590554

by Andr ew Tr oelsen

Now assume youApr have Windows ess a© new 2003 (1200 pages) Forms example that allows the user to edit the values in a DataGrid (e.g., add new records, and update records). This compr ehensiv e text star tsand w ithdelete a briefexisting ov er view of the When finished, the user may submit the modified DataSet back to the database using a Button type. C# language and then quickly m oves to key technical andFirst, assume the following constructor logic:ar chitectur al issues for .NET developer s. public class mainForm : System.Windows.Forms.Form { C# and t he .NET Plat for m, Second Edition private SqlConnection cn = new I ntr oduction SqlConnection("server=(local);uid=sa;pwd=;database=Cars"); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m private SqlDataAdapter dAdapt; Chapter private 1 - The Philosophy of .NET SqlCommandBuilder invBuilder; Chapter private 2 - Building C# Applications DataSet myDS = new DataSet(); Pa r t Tw oprivate - The C# Pr ogr am m ing La ngua ge System.Windows.Forms.DataGrid dataGrid1; Chapter private 3 - C# Language Fundamentals System.Windows.Forms.Button btnUpdateData; Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# ... Chapter public 5 - Exceptions and Obj ect Lifetim e mainForm() Chapter { 6 - I nter faces and Collections InitializeComponent(); Chapter 7 - Callback I nter faces, Delegates, and Ev ents // Create the initial SELECT SQL statement. Chapter 8 - Advanced C# Type Const ruction Techniques dAdapt = new SqlDataAdapter("SELECT * FROM Inventory", cn); Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s // Autogenerate the INSERT, UPDATE, Chapter 9 - Under standing .NET Assem blies and AppDomains, DELETE statements. Chapter 10 - Pr // ocesses, Cont exts, and Threads invBuilder = new SqlCommandBuilder(dAdapt); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing // Fill and bind. Pa r t Four - Le ve r a ging the .NET Libr a r ie s dAdapt.Fill(myDS, "Inventory"); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er dataGrid1.DataSource = myDS.Tables["Inventory"].DefaultView; Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) ... Chapter 15 - Pr ogr am ming with Windows Form s Contr ols }

Ta ble o f Con t en t s

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa Fi vepoint, - W e bthe Appl ica ti ons and X ML W all e b the Se r vi ces Atr t this SqlDataAdapter has information

it needs to submit changes back to the data store.

Chapter 18 - ASP.NET Pages and Web Contr Now assume that youWeb have the following logic ols behind the Button's Click event: Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - void XML Web Ser vices private btnUpdateData_Click(object sender, System.EventArgs e) I ndex { List of Figur tryes List of Tables {

dataGrid1.Refresh(); dAdapt.Update(myDS, "Inventory"); } catch(Exception ex) { MessageBox.Show(ex.Message); } }

As usual, you call Update() and specify the table within the DataSet you wish to update. If you take this out for a test run, you see something like Figure 17-26 (be sure you exit out of edit mode on the DataTable before you submit your results! ).

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Figure 17-26: All good things do come ... Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET SOURCE TheApplications WinFormsExample project is included under the Chapter 17 subdirectory. Chapter 2 - Building C#

CODE Pa r t Tw o - The C# Pr ogr am m ing La ngua ge Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .NDataSet ET Plat f orm ,(and Se con dAdding Ed it ion Filling a Multitabled DataRelations) by Andr ew Tr oelsen

ISBN:1590590554

Let's come full circle and an additional Windows Forms example that mimics the application you Apr ess © build 2003 (1200 pages) created during the first half of this chapter. The simple In Figure 17-27 you can see three This compr ehensiv e text star ts wGUI ith aisbrief ov erenough. view of the DataGrid types that hold the data retrieved from the Inventory, Orders, and Customers tables of the Cars C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. all changes back to the data store. database. In addition, the single Button pushes any and

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - 17-27: Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Figure Viewing related DataTables Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

To keep things even simpler, you will use auto-generated commands for each of the three SqlDataAdapters (one for each table). First, here is the Form's state data:

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

public class mainForm : System.Windows.Forms.Form { Chapter 17 - Data Access w ith ADO.NET private System.Windows.Forms.DataGrid custGrid; Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces private System.Windows.Forms.DataGrid inventoryGrid; Chapter 18 - ASP.NET Web Pages and Web Contr ols private System.Windows.Forms.Button btnUpdate; Chapter 19 - ASP.NET Web Applicat ions private System.Windows.Forms.DataGrid OrdersGrid; Chapter 20 - XML Web Ser vices ... I ndex // Here is the connection. List of Figur es private SqlConnection cn = new List of Tables SqlConnection("server=(local);uid=sa;pwd=;database=Cars"); // Our data adapters (for each table). private SqlDataAdapter invTableAdapter; private SqlDataAdapter custTableAdapter; private SqlDataAdapter ordersTableAdapter; // Command builders (for each table). private SqlCommandBuilder invBuilder = new SqlCommandBuilder(); private SqlCommandBuilder orderBuilder = new SqlCommandBuilder(); private SqlCommandBuilder custBuilder = new SqlCommandBuilder(); // The dataset. DataSet carsDS = new DataSet(); ... } Chapter 16 - The Sy stem .I O Nam espace

The Form's constructor does the grunge work of creating your data-centric member variables and filling an d th e .N ET Plat f orm , Se con d Ed it ion the DataSet. AlsoC# note that there is a call to a private helper function, BuildTableRelationship(), as shown ISBN:1590590554 by Andr ew Tr oelsen here: Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the

public mainForm() C# language and then quickly m oves to key technical and { ar chitectur al issues for .NET developer s. InitializeComponent(); adapters. Ta ble o f // Con Create t en t s

= new SqlDataAdapter("Select * from Inventory", cn); C# and tinvTableAdapter he .NET Plat for m, Second Edition custTableAdapter = new SqlDataAdapter("Select * from Customers", cn); I ntr oduction = new Pa r t OneordersTableAdapter - I nt r oduci ng C# a nd the .NET P la tfSqlDataAdapter("Select or m

* from Orders", cn); // Autogenerate commands. Chapter 1 - The Philosophy of .NET new SqlCommandBuilder(invTableAdapter); Chapter invBuilder 2 - Building C#= Applications orderBuilder newLa ngua SqlCommandBuilder(ordersTableAdapter); Pa r t Tw o - The C# Pr ogr am= m ing ge custBuilder = new SqlCommandBuilder(custTableAdapter); Chapter 3 - C# Language Fundamentals // Add tables to DS. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# invTableAdapter.Fill(carsDS, "Inventory"); Chapter 5 - Exceptions and Obj ect Lifetim e custTableAdapter.Fill(carsDS, "Customers"); Chapter 6 - I nter faces and Collections ordersTableAdapter.Fill(carsDS, "Orders"); Chapter 7 - Callback I nter faces, Delegates, and Ev ents // Build relations between tables. Chapter BuildTableRelationship(); 8 - Advanced C# Type Const ruction Techniques Pa }r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

The BuildTableRelationship() helper function does justBased what Pr you woulding expect. Recall that the Cars Chapter 11 - Type Reflection, Late Binding, and Attr ibuteogramm database expresses number of parent/child Pa r t Four - Le ve r a ging athe .NET Libr a r ie s

relationships. The code looks identical to the logic seen

earlier in chapter, as shownand here: Chapter 12 this - Obj ect Ser ialization the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter private 14 - void A Better BuildTableRelationship() Paint ing Fr amew or k ( GDI + )

{ Chapter 15 - Pr ogr am ming with Windows Form s Contr ols a .IDR obj. Chapter // 16 - Create The Sy stem O Nam espace = new DataRelation("CustomerOrder", Chapter DataRelation 17 - Data Access wdr ith ADO.NET Pa r t Fi ve - W e b carsDS.Tables["Customers"].Columns["CustID"], Appl ica ti ons and X ML W e b Se r vi ces

carsDS.Tables["Orders"].Columns["CustID"]); Chapter 18 - ASP.NET Web Pages and Web Contr ols relation to ions the DataSet. Chapter // 19 - Add ASP.NET Web Applicat carsDS.Relations.Add(dr); // Create another DR obj. I ndex dr = new DataRelation("InventoryOrder", List of Figur es carsDS.Tables["Inventory"].Columns["CarID"], List of Tables carsDS.Tables["Orders"].Columns["CarID"]); // Add relation to the DataSet. carsDS.Relations.Add(dr); // Fill the grids! inventoryGrid.SetDataBinding(carsDS, "Inventory"); custGrid.SetDataBinding(carsDS, "Customers"); OrdersGrid.SetDataBinding(carsDS, "Orders"); } Chapter 20 - XML Web Ser vices

Now that the DataSet has been filled and disconnected from the data source, you can manipulate each table locally. To do so, simply insert, update, or delete values from any of the three DataGrids. When you are ready to submit the data back for processing, click the Form's Update button. The code behind the Click event should be clear at this point, as shown here: private void btnUpdate_Click(object sender, System.EventArgs e)

{ try {

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) invTableAdapter.Update(carsDS, "Inventory"); This compr ehensiv e text star ts w ith a brief "Customers"); ov er view of the custTableAdapter.Update(carsDS, C# language and then quickly m oves to key and ordersTableAdapter.Update(carsDS, technical "Orders"); ar chitectur al issues for .NET developer s.

} catch(Exception ex) { Ta ble o f Con t en t s MessageBox.Show(ex.Message); C# and t he .NET Plat for m, Second Edition } I ntr oduction } Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2 -update, Buildingyou C# will Applications Once you find each table in the Cars database correctly altered. Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

SOURCE The WinFormsMultiTableDataSet project is included under the Chapter 17 Chapter 3 - C# Language Fundamentals CODE Chapter 4 - Obj ect -Orsubdirectory. iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Bring In theC#Wizards! ISBN:1590590554

by Andr ew Tr oelsen

To wrap up this chapter, like to offer Apr ess ©I'd 2003 (1200 pages)a guided tour of select integrated data-centric wizards provided by VS .NET. Now, let me preface the following byasaying the of goal This compr ehensiv e text sections star ts w ith brief ovthat er view thehere is not to detail each and every option of each and every wizard. Doing so would require at least two additional (large) chapters. Rather, I will C# language and then quickly m oves to key technical and al issues .NET s. illustrate the use ar ofchitectur a number of keyfor tools in developer order to prime the pump for further exploration on your own terms. you wish to follow along, create a brand new C# Windows Forms application named WinFormsVsNetWizardsApp. Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

Revisiting the Solutions Explorer

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Back in Chapter 2, you were introduced to the Server Explorer utility of VS .NET. As you recall, this tool allows

Chapter 1 - Thewith Philosophy of .NET you to interact a number of server-side services (such as MS SQL Server) using a familiar tree-view GUI. Chapter 2 Building C# Applications This view of the world can be quite helpful when working with ADO.NET, given that you are able to add any Pa r t Tw o -ofThe C# Pr ogr am ing La ngua ge number connections tomyour design time

view. To do so, simply right-click the Data Connections node and

Chapter 3 - Connection C# Language Fundamentals select Add (Figure 17-28). Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Figure Adding a new ions data connection Chapter 19 - 17-28: ASP.NET Web Applicat Chapter 20 - XML Web Ser vices I ndex At this point you are provided with the Data Link Properties dialog box, which allows you to specify the name and List of Figur location ofesthe database you wish to communicate with. For this example, connect to your local Cars database List of Tables (Figure 17-29).

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4 - 17-29: Obj ect -Or iented Pr ogr amnew mingdata w ithconnection C# Figure Configuring the Chapter 5 - Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Once you have added a SQL connection, you are then able to view the underlying data source (Figure 17-30). A - Callback I nter faces, Delegates, and Ev ents you would guess, each database item (tables, views, stored procedures, and whatnot) can be opened from with Chapter 8 - Advanced C# Type Const ruction Techniques VS .NET by simply double-clicking the item of interest. To take things out for a test drive, double-click the Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Inventory table and GetPetName stored procedure. Chapter 7

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 17-30: Interacting with the Cars database via VS .NET Note Many of the advanced (read: really cool and helpful) features of the Solution Explorer (such as the ability to create, edit, and delete various database objects) require Visual Studio .NET Enterprise Edition or higher.

Creating a SQL Connection at Design Time As you have seen earlier in this chapter, the System.Data.SqlClient.SqlConnection type defines a ConnectionString property, which contains information regarding a programmatic connection to a given data source. While it is not too difficult to build a connection string by hand, the IDE provides a number of tools to assist you in this regard. To illustrate one such approach, activate the Data tab from the Toolbox window (Figure 17-31), and place a SqlConnection component onto your design time Form.

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Figure 17-31: Design time connection configuration

Chapter 6

- I nter faces and Collections Once you doneI nter so, select this item from Icon Tray, and using the Properties window, select the name o Chapter 7 -have Callback faces, Delegates, and the Ev ents

your Cars from theConst ConnectionString property drop-down list. At this point, you should be pleased to Chapter 8 -connection Advanced C# Type ruction Techniques see thatea- valid string been created Pa r t Thre Pr ogrconnection am m i ng w i th .N EThas Assem bl ie s

and configured on your behalf (within the #region code

block): 9 - Under standing .NET Assem blies Chapter

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

public Form1 : Late System.Windows.Forms.Form Chapter 11 class - Type Reflection, Binding, and Attr ibute- Based Pr ogramm ing {r t Four - Le ve r a ging the .NET Libr a r ie s Pa sqlConnection1; Chapter private 12 - Obj ect System.Data.SqlClient.SqlConnection Ser ialization and the .NET Remoting Lay er ... 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter private void InitializeComponent() { Chapter 15 - Pr ogr am ming with Windows Form s Contr ols this.sqlConnection1 = new System.Data.SqlClient.SqlConnection(); Chapter 16 - The Sy stem .I O Nam espace this.sqlConnection1.ConnectionString = " " Chapter 17 - Data Access w ith ADO.NET ... Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces } Chapter 18 - ASP.NET Web Pages and Web Contr ols } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex You are now able to program against you new SqlConnection type using all of the techniques presented in this

chapter. Command objects can be dragged onto the Forms designer in a similar manner. Once you do, you ma List of Figur es editofyour SQL queries using an integrated query editor (activated via the CommandText property). List Tables

Building a Data Adapter at Design Time The VS .NET IDE also provides an integrated wizard that takes care of the grunge work that is necessary to buil SELECT, UPDATE, INSERT, and DELETE commands for a given data adapter type (as you have seen, writing this code by hand can be a bit on the tedious side). To illustrate, delete your current SqlConnection component and place a SqlDataAdapter component onto your Icon Tray. This action will launch the Data Adapter Configuration Wizard. Once you click past the initial Welcome screen, you will be asked which data connection should be used to configure the data adapter (Figure 17-32). Again, pick your Cars connection.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Figure- 17-32: Specifying the connection for the new SqlDataAdapter Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 4 Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6 step - I nter facesyou andtoCollections The next allows configure how the data adapter should submit data to the data store (Figure 17-33). Chapter 7 - Callback I nter faces, Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex Figure 17-33: Specifying data store updates List of Figur es List of Tables

As you can see from Figure 17-37, you have three choices. If you want to move data between the data store and the DataSet using stored procedures, you may instruct the wizard to generate new INSERT, UPDATE, and DELETE functions based on an initial SELECT statement or, as an alternative, choose prefabricated stored procedures. Your final option is to have the wizard build SQL queries. I'll assume you will check out the generated stored procedures at your leisure, so simply select Use SQL Statements for the time being.

The next step of the tool asks you to specify the SQL SELECT statement that will be used to build the set of SQ queries. Although you may type in the SQL SELECT statement by hand, you can also activate the Query Builder tool (which should look familiar to many Visual Basic developers). Figure 17-34 shows the crux of this integrated SQL editor.

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals Figure Creating the SELECT logic Chapter 4 - 17-34: Obj ect -Or iented Pr ogrinitial am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Once you are finished with the data adapter configuration tool, open your code window and check out the - I nter faces and Collections InitializeComponent() method. As you can see, the new SqlCommand data members are configured Chapter 7 - Callback I nter faces, Delegates, and Ev ents automatically. I won't bother to list each aspect of the generated code, as you have already manually written the Chapter 8 - Advanced C# Type Const ruction Techniques same syntax by hand during the chapter. However, here is a partial snapshot: Chapter 6

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

public class Form1 : System.Windows.Forms.Form { Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing private System.Data.SqlClient.SqlConnection sqlConnection1; Pa r t Four - Le ve r a ging the .NET Libr a r ie s private System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1; Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er private System.Data.SqlClient.SqlCommand sqlSelectCommand1; Chapter private 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) System.Data.SqlClient.SqlCommand sqlInsertCommand1; Chapter private 14 - A Better Paint ing Fr amew or k ( GDI + ) System.Data.SqlClient.SqlCommand sqlUpdateCommand1; Chapter private 15 - Pr ogr am ming with Windows Form s Contr ols System.Data.SqlClient.SqlCommand sqlDeleteCommand1; Chapter private 16 - The Syvoid stem .I O Nam espace InitializeComponent() Chapter { 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b this.sqlDataAdapter1.DeleteCommand Appl ica ti ons and X ML W e b Se r vi ces = this.sqlDeleteCommand1; Chapter 18 - ASP.NET this.sqlDataAdapter1.InsertCommand Web Pages and Web Contr ols = this.sqlInsertCommand1; this.sqlDataAdapter1.SelectCommand = this.sqlSelectCommand1; Chapter 19 - ASP.NET Web Applicat ions this.sqlDataAdapter1.TableMappings.AddRange Chapter 20 - XML Web Ser vices (new System.Data.Common.DataTableMapping[] { I ndex List of Figur es new System.Data.Common.DataTableMapping("Table", "Inventory", new System.Data.Common.DataColumnMapping[] { List of Tables new System.Data.Common.DataColumnMapping("CarID", "CarID"), new System.Data.Common.DataColumnMapping("Make", "Make"), new System.Data.Common.DataColumnMapping("Color", "Color"), ... // // sqlInsertCommand1 // this.sqlInsertCommand1.CommandText = "INSERT INTO Inventory(CarID, Make, Color, PetName)" + "VALUES (@CarID, @Make, @Color," + " @PetName); SELECT CarID, Make, Color, PetName FROM " + "Inventory WHERE (CarID = @CarID)"; this.sqlInsertCommand1.Connection = this.sqlConnection1; this.sqlInsertCommand1.Parameters.Add( new System.Data.SqlClient.SqlParameter("@CarID", Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

System.Data.SqlDbType.Int, 4, "CarID")); C# an d th e .N ET Plat f orm , Se con d Ed it ion

...

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

} }

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and chitectur issues for .NET developer s. Hopefully, things ar look quite alfamiliar. Once you have generated the basic look and feel of your data adapter, you

may continue to alter its behavior using the Properties window. For example, if you were to select the TableMappings property, you could assign display names to each column of the underlying data table (Figure Ta ble o f Con t en t s 17-35). C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Figure names at design Chapter 13 - 17-35: BuildingAltering a Bet tercolumn Win dowdisplay ( Int roducin g Window s Fortime ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Using the Configured Data Adapter

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

At this point you are free to make use of any of the tricks you have learned about during the chapter to obtain an manipulate a DataSet. By way of a simple test, place a DataGrid widget onto the main Form, and show the Chapter 18 - ASP.NET Web Pages and Web Contr ols contents of the Inventory table via a Button Click event: Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

private void btnLoadInventory_Click(object sender, System.EventArgs e) { List of Figur es DataSet myDS = new DataSet(); List of Tables sqlConnection1.Open(); sqlDataAdapter1.Fill(myDS); dataGrid1.DataSource = myDS.Tables["Inventory"]; } I ndex

Design Time Connections and Data Adapters, Take Two The previous example illustrated how you can gain design time assistance for connection and data adapter type by dragging and dropping the related components from the Data tab of the Toolbox onto the forms designer. If you are looking for the optimal short cut, try the following: First, delete all items from the Form's icon tray. Next, switch to the Server Explorer view and select the Inventory icon of the Cars database from the Data Connection node. Now, drag the Inventory table icon directly onto the Form. Once you do, you will be given SqlConnection and SqlDataAdapter types that are automatically preconfigured to communicate with the Cars database! Understand that everything shown via the Server Explorer is "drag-and-droppable." To check things out further,

select the GetPetName stored procedure and drag it onto the Form. As you can see, the result is a new C# an d th e .N ET Plat f orm , Se con d Ed it ion SqlCommand type that is preconfigured to trigger the underlying stored proc: by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

this.sqlCommand1.CommandText = "dbo.[GetPetName]"; This compr ehensiv e text star ts w ith a brief ov er view of the this.sqlCommand1.CommandType = System.Data.CommandType.StoredProcedure; C# language and then quickly m oves to key technical and this.sqlCommand1.Connection = this.sqlConnection1; ar chitectur al issues for .NET developer s. this.sqlCommand1.Parameters.Add( new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", 4, Ta ble o System.Data.SqlDbType.Int, f Con t en t s System.Data.ParameterDirection.ReturnValue, false, C# and t he .NET Plat for m, Second Edition ((System.Byte)(0)), ((System.Byte)(0)), "", I ntr oduction System.Data.DataRowVersion.Current, null)); Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m this.sqlCommand1.Parameters.Add( Chapter 1 - The Philosophy of .NET Chapternew 2 - System.Data.SqlClient.SqlParameter("@carID", Building C# Applications System.Data.SqlDbType.Int, 4)); Pa r t Tw o - The C# Pr ogr am m ing La ngua ge this.sqlCommand1.Parameters.Add( Chapter 3 - C# Language Fundamentals new System.Data.SqlClient.SqlParameter("@petName", Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# System.Data.SqlDbType.VarChar, 20, Chapter 5 - Exceptions and Obj ect Lifetim e System.Data.ParameterDirection.Output, false, Chapter 6 - I nter faces and Collections ((System.Byte)(0)), ((System.Byte)(0)), "", Chapter 7 - Callback I nter faces, Delegates, and Ev ents System.Data.DataRowVersion.Current, null)); Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - Under standing .NETgenerated Assem bliesthe initial code, you are free to tweak and change things to your liking. Again, once the wizards have Chapter By way10 of -example, Pr ocesses, select AppDomains, one of theCont SqlCommand exts, and Threads types and check out the Parameters property of the

Properties As you would guess, the editor allows Chapter 11 - window. Type Reflection, Late Binding, and resulting Attr ibute-dialog Based Pr ogramm ing you to edit parameter objects at desig time. Pa r t Four - Le ve r a ging the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat , Se con dTime Ed it ion Working with DataSets atf orm Design ISBN:1590590554

by Andr ew Tr oelsen

In the previous code samples, you pages) directly created and allocated a DataSet type in your code base. As you Apr ess © 2003 (1200 would guess, VSThis .NET also offers design time for the In fact, VS .NET allows you compr ehensiv e text star ts support w ith a brief ov ermighty view of DataSet. the to generate two types of DataSets: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Untyped DataSets: This corresponds to the DataSets examined thus far in the chapter. Untyped DataSets are simply variables of type System.Data.DataSet. Ta ble o f Con t en t s

Typed DataSets: This optionEdition allows you to generate a new .NET class type that derives from the C# and t he .NET Plat for m, Second

DataSet class. Using this wrapper class, you can interact with the underlying data using objectoriented property syntax, rather than having to directly interact with the Rows and Columns collections. One - I nt r oduci ng C# a nd the .NET P la tf or m

I ntr oduction Pa r t

Chapter 1 - to The Philosophy of .NET If you wish add an uptyped DataSet to your project, use the Data tab of the VS .NET Toolbox and place Chapter 2 Building C# Applications a new DataSet onto your design time template. When you do so, you will find that a new member variable Pa Tw o DataSet - The C# has Pr ogr am madded ing La ngua ge ofr ttype been and allocated

to a new instance, which can then be manipulated in your

Chapter code. 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e Working with Typed DataSets at Design Time - I nter faces and Collections

Chapter 6

Chapter 7 -wrap Callback I nter faces, by Delegates, and ents Now, let's up this chapter checking outEvthe role of typed DataSets. First of all, understand the Chapter 8 - Advanced C# the Type Const ruction as Techniques typed DataSets perform same function an untyped DataSet (they contain a client-side cache of Pa r t Thre e -are Pr ogr am m i ng w i th updated .N ET Assem s data) and populated and via bl a iecorresponding

data adapter. The key difference is, simply put,

Chapter - Under standing .NET bliesuntyped DataSets, you are required to drill into the internal ease of9 use. For example, whenAssem you use Chapter structure 10 of - the Pr ocesses, DataTable AppDomains, type using Cont theexts, Rows and and Threads Columns properties. While nothing is horribly wrong

with this11approach, it would be to build wrapper class that hides ing the internal complexities from view. Chapter - Type Reflection, Latenice Binding, anda Attr ibute- Based Pr ogramm For example, writing this: Pa r t Four - Le verather r a gingthan the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) // A basic untyped DataSet. Chapter lblCarID.Text 14 - A Better=Paint myDS.Tables["Inventory"].Rows[0]["CarID"]; ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

you can write the following:

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

// A typed DataSet. Chapter 18 - ASP.NET Web Pages and Web Contr ols lblCarID.Text myDS.Inventory[0].CarID; Chapter 19 - ASP.NET=Web Applicat ions Chapter 20 - XML Web Ser vices I ndex

In a nutshell, strongly typed DataSets are classes that derive from DataSet, and define numerous properties that interact with the underlying structure on your behalf.

List of Figur es List of Tables

To generate a strongly typed DataSet using VS .NET, right-click the related data adapter and select Generate DataSet (Figure 17-36).

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# Figure Creating a typed DataSet at design time Chapter 5 - 17-36: Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

From the dialog box simply supply a name (such as CarsDataSet) and reconfirm the tables to wrap. At this - Callback I nter faces, Delegates, and Ev ents point, you can make use of your new DataSet-derived type as follows:

Chapter 7 Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

private - void btnLoadInventory_Click(object sender, System.EventArgs e) Under standing .NET Assem blies { Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads sqlConnection1.Open(); Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing sqlDataAdapter1.Fill(carsDataSet1); Pa r t Four - Le ve r a ging the .NET Libr a r ie s dataGrid1.DataSource = carsDataSet1.Inventory; Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er } Chapter 9

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 you - Pr ogr mingneed with to Windows Formofs the Contr ols Note that no am longer make use Tables property to gain access to the contained Inventory Chapter table. Using 16 - The a strongly Sy stem typed .I O Nam DataSet, espace you simply reference the Inventory property. Chapter 17 - Data Access w ith ADO.NET

Under the Hood of the Typed DataSets

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Chapter - ASP.NET Applicat Activate19the Solution Web Explorer andions click the Show all Files button. You will find that your strongly typed Chapter DataSet 20is- represented XML Web Serby vices two related files. First you have an XML schema file (*.xsd) that represents the

overall structure of the DataSet in terms of XML. Behind this schema file is a related *.cs class file (Figure I ndex 17-37). List of Figur es List of Tables

Figure 17-37: Typed DataSets have a related "code behind" file C# an d th e .N ET Plat f orm , Se con d Ed it ion

ISBN:1590590554 ewView, Tr oelsen If you switch overby to Andr Class you will find that the newly generated CarsDataSet class defines a ess © 2003 (1200 pages)the rows and tables it is responsible for maintaining (Figure 17-38). number of nestedApr classes to represent

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - 17-38: Type Reflection, Late Binding, type and Attr ibute- Based Figure The DataSet-derived maintains a set Profogramm nesteding classes. Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

While I will assume you will check out the generated code at your leisure, it is worth pointing out that strongly typed DataSets are automatically configured as serializable, which, as you recall from Chapter Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) 12, allows you to persist the state data to some storage medium (as well as marshal the type by value): Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

[Serializable()] ... Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces public class CarsDataSet : DataSet {...} Chapter 17 - Data Access w ith ADO.NET

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 - to XML Web out Ser the vicesnested InventoryDataTable type, you would see that in addition to deriving If you were check I ndex from System.Data.DataTable, this new type is enumerable, and contains a number of private DataColumn List of Figur types that es are exposed via class properties (which are in turn exposed via the strongly typed DataRowList of Tables derived class). Thus, if you wish to access the stats of the first row in the Inventory table, you can write the

following: private void btnGetStats_Click(object sender, System.EventArgs e) { string info = "Color: " + carsDataSet1.Inventory[0].Color; info += "\n" + "Make: " + carsDataSet1.Inventory[0].Make; info += "\n" + "Pet Name: " + carsDataSet1.Inventory[0].Friendly_Name_of_Car; MessageBox.Show(info, "First Car Info"); }

Again, the bonus is that the exposed properties are already mapped into CLR data types based on the underlying schema information. It is worth pointing out that while strongly typed DataSets are quite programmer friendly, the additional layers of indirection could be a potential performance drain. When you

want to ensure your ADO.NET DataSets are operated on as quickly as possible, simple untyped DataSets C# an d th e .N ET Plat f orm , Se con d Ed it ion tend to offer better performance. by Andr ew Tr oelsen

ISBN:1590590554

Apr ess up © 2003 pages) Well, that wraps things for (1200 this chapter. Obviously there is much more to say about ADO.NET than I had time to present If ehensiv you areelooking a ith solid complement to this Thishere. compr text starfor ts w a brief ov er view of the chapter, I recommend checking C# Guide language and then quickly m oves to key technical and 2002). outA Programmer's to ADO.NET in C# by Mahesh Chand (Apress, ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Summary

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen

ISBN:1590590554

ADO.NET is a new technology developed with the disconnected n-tier application firmly in Aprdata ess ©access 2003 (1200 pages) mind. The System.Data namespace contains the core typesofyou This compr ehensiv e text star tsmost w ith of a brief ov er view the need to programmatically interact with rows, columns, tables, and views. As you have seen, the System.Data.SqlClient and C# language and then quickly m oves to key technical and ar chitectur al issues for .NET System.Data.OleDb namespaces define thedeveloper types yous.need to establish an active connection. The centerpiece of ADO.NET is the DataSet. This type represents an in-memory representation of any Tanumber ble o f Con of tables t en t s and any number of optional interrelationships, constraints, and expressions. The beauty

of and establishing your Edition local tables is that you are able to programmatically navigate between C# t he .NET relations Plat for m, on Second them while disconnected from the remote data store. I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Here you examined the role of the data adapter (OleDbDataAdapter and SqlDataAdapter). Using this type - The Philosophy of .NET (and the related SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand properties), Chapter 2 - Building C# Applications the adapter can resolve changes in the DataSet with the original data store. Also, you learned about the Pa r t Tw o - The C# Pr ogr am m ing La ngua ge connected layer of ADO.NET, and came to understand the role of data reader types. Chapter 1

Chapter 3

- C# Language Fundamentals

Chapter 4 - Obj ect -Or iented Pr ogr am out minga w ith C# of the tools available from VS .NET. As you have seen, We wrapped things up by checking subset Chapter 5 - Exceptions andwizards Obj ect do Lifetim e the numerous integrated indeed help you with mundane and repetitive coding details. Like any Chapter code generation 6 - I nter faces tool, you and may Collections find that a given wizard does not bring you all the way home. However,

given your throughout this Delegates, chapter, you Chapter 7 - work Callback I nter faces, andshould Ev entsbe able to tweak the wizard-generated code to suit your needs. Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Part Five:C# Web Applications andISBN:1590590554 XML Web Services by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Chapter List This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Chapter 18: ASP.NET Web Pages and Web Controls Ta ble o f Con t en t s

Chapter 19: ASP.NET Web Applications

C# and t he .NET Plat for m, Second Edition I ntr oduction Chapter 20: XML Web Services

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion Chapter C# 18: ASP.NET Web Pages and Web Controls ISBN:1590590554 by Andr ew Tr oelsen Aprexample ess © 2003applications (1200 pages) in this text have focused on Windows Forms and console-based Until now, all of the This compr ehensiv text explore star ts w ith a the brief.NET ov er view of thefacilitates the construction of front ends. In the next two chapters,e you how platform C# language and then quickly m oves to key technical and browser-based presentation layers. To begin, you'll quickly review a number of key Web-centric atoms ar chitectur al issues for .NET developer s. (HTTP, HTML, client-side, and server-side code bases) as well as the role of commercial Web servers (such as Microsoft IIS). During this process, you will create a simple Web application using HTML and ASP. Oft scourse, if you are already "Web aware," feel free to skim or skip these initial sections Taclassic ble o f Con t en entirely. On the other hand, if you come to ASP.NET with limited Web development experience, this primer C# and t he .NET Plat for m, Second Edition will provide a valuable frame of reference for the chapters that follow. I ntr oduction

Pa r t One I nt r oduci ng C# a nd the the .NETremainder P la tf or m With this- Web primer complete,

of this chapter will concentrate upon the composition of

Chapter 1 -pages The Philosophy of .NET ASP.NET and the related topic of ASP.NET Web controls. As you will see, ASP.NET provides a far Chapter 2 Building C# Applications superior programming model than classic (COM-based) ASP. For example, you can now partition your Pa r t Tw o - The logic C# Prand ogr am m ing Lalogic nguainto ge presentation business

discrete files using a technique called code behind. Also be very

Chapter 3 - ASP.NET C# Language Fundamentals aware that demands that you to use "real" programming languages for your server-side logic Chapter 4 C#, - Obj ect.NET, -Or iented Pr ogr am ming C#interpreted scripting languages (such as VBScript). Given (such as VB MC++, etc.), ratherw ith than Chapter this last5 point, - Exceptions it is critical and toObj understand ect Lifetimthat e you simply cannot build ASP.NET applications without solid

knowledge OOP, interfaces, and attributes. Chapter 6 - of I nter faces and Collections Chapter 7

- Callback I nter faces, Delegates, and Ev ents

- Advanced C# Type Const ruction Techniques The Role of HTTP

Chapter 8

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Web applications are very .NET different animals Chapter 9 - Under standing Assem blies than traditional desktop applications (to say the least). The first obvious10difference is that a production-level will always involve at least two networked Chapter - Pr ocesses, AppDomains, Cont exts,Web and application Threads machines course, duringLate development it isAttr entirely possible to haveing a single machine play the role of Chapter 11 -(of Type Reflection, Binding, and ibute- Based Pr ogramm both client and this afact, Pa r t Four - Le ve r aserver). ging theGiven .NET Libr r ie s

the machines in question must agree upon a particular wire

protocol how to send receive data. The wire protocol that connects the computers in Chapter 12to- determine Obj ect Ser ialization and and the .NET Remoting Lay er question Hypertext Transfer Protocol (HTTP). Chapter 13is- the Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

When a client machine launches a Web browser (such as Netscape Navigator or Microsoft Internet

Chapter 15 -an PrHTTP ogr am ming withis Windows s Contr ols Explorer), request made to Form access a particular resource (such as an *.aspx file or *.htm file) Chapter 16 The Sy stem .I O Nam espace located on a server machine. HTTP is a text-based protocol that is built upon a standard request/response Chapter 17 -For Data Access wifith ADO.NET paradigm. example, you navigate to http://www.intertech-inc.com, the browser software Pa r t Fi ve - WaeWeb b Appl ica ti ons and X ML WDomain e b Se r vi Name ces leverages technology termed

System (DNS), which converts the registered URL into

Chapter 18 -numerical ASP.NET Web Web Contr olsAt this point, the browser opens a socket connection afour-part valuePages (aka and an IP address). Chapter 19 via - ASP.NET ionsHTTP request to the default page at the Intertech-inc.com Web site. (typically port 80),Web andApplicat sends the Chapter 20 - XML Web Ser vices

Once the hosting Web server receives the incoming HTTP request, the specified resource may contain I ndex

logic that scrapes out any client-supplied input values (such as values within a text box) in order to format a proper HTTP response. Web programmers may leverage any number of technologies (CGI, ASP, List of Tables ASP.NET, Java Servlets, etc.) to dynamically generate the content to be emitted into the HTTP response. At this point, the client-side browser renders the HTML emitted from the Web server. Figure 18-1 illustrates the basic HTTP request/response cycle. List of Figur es

Figure 18-1: The HTTP request and response cycle Another aspect of Web development that is markedly different from traditional desktop programming is the fact that HTTP is a stateless wire protocol. As soon as the Web server emits a response to the client browser, everything about the previous interaction is forgotten. Therefore, as a Web developer, it is up to

you take specific steps to "remember" information (such as items in a shopping cart) about the clients who C# an d th e .N ET Plat f orm , Se con d Ed it ion are currently logged onto your site. As you will see in the next chapter, ASP.NET provides numerous ways by Andr Tr oelsen to handle state, many of ew which are commonplace to any Web ISBN:1590590554 platform (session variables, cookies, and Apr ess © 2003 (1200 pages) application variables) as well as some new techniques (such as view state and the application cache). This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an dWeb th e .N ET Plat f orm , Se con dand Ed it ion Understanding Applications Web Servers ISBN:1590590554

by Andr ew Tr oelsen

Now that you better thepages) role of HTTP and the underlying request/response cycle of the Web, Aprunderstand ess © 2003 (1200 we need to qualify some further terminology. begin, a Web application This compr ehensiv e text star tsTo w ith a brief ov er view of the can be understood as a collection of files C# (*.htm, *.asp, *.aspx, image files, and so on) and related language and then quickly m oves to key technical and components (.NET or classic ar chitectur for .NET developer COM binaries) stored withinalaissues particular directory (ands.optional subdirectories) on a given Web server. As you will see in the next chapter, Web applications have a specific life cycle and provide numerous events (such as initial startup or final shutdown) that you can hook into. Ta ble o f Con t en t s

AWeb a software product in charge of hosting your Web applications and typically provides a C# and tserver he .NETisPlat for m, Second Edition number of related services such as integrated security, File Transfer Protocol (FTP) support, mail I ntr oduction exchange services, forth. Internet Pa r t One - I nt r oduci ngand C# so a nd the .NET P la tfInformation or m

Server (IIS) is Microsoft's enterprise-level Web server

product, as Philosophy you would of guess, Chapter 1 and - The .NET has intrinsic support for classic ASP as well as ASP.NET Web applications. Chapter 2 - Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Note It is perfectly fine to have a single installation of IIS host classic ASP and ASP.NET Web - C# Language Fundamentals applications. Because both Web platforms make use of distinct file extensions (for example, Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# *.asp versus *.aspx), IIS will load the correct host process based on the incoming HTTP request. Chapter 3 Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter When you 6 -build I nterASP.NET faces and Collections Web applications, you will be required to interact with IIS. Be aware, however,

that IIS7is not automatically selected whenand youEv install Chapter - Callback I nter faces, Delegates, ents the Windows OS 2000 or XP Professional Edition (you can't ASP.NET theConst "Home" editions of Windows). Therefore, depending on the configuration Chapter 8 -run Advanced C# on Type ruction Techniques ofr tyour may be required Pa Thredevelopment e - Pr ogr am m imachine, ng w i th .Nyou ET Assem bl ie s

to manually install IIS before proceeding through this chapter. To do so, simply access the Add/Remove Program applet from the Control Panel folder and Chapter 9 - Under standing .NET Assem blies select "Add/Remove Windows Components." Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Note Ideally, your development machine will have IIS installed before you install the .NET Framework. If you install IIS after you install the .NET Framework, none of your ASP.NET Web applications Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er will execute correctly (you will simply get back a blank page). Luckily, you can reconfigure IIS to Chapter 13 host - Building Bet ter Win dow ( Int roducin Window s For ms) command line tool (using the /i flag). .NET aapplications by running thegaspnet_regiis.exe Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Assuming have IIS properly installed on syour workstation, you can interact with IIS from the Chapter 15 -you Pr ogr am ming with Windows Form Contr ols Administrative folder (located in the Control Panel folder). For the purposes of this chapter, we are Chapter 16 - TheTools Sy stem .I O Nam espace only concerned the wDefault Web Site node (Figure 18-2). Chapter 17 - Datawith Access ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Figure 18-2: The IIS applet

Working with IIS Virtual Directories A single IIS installation is able to host numerous Web applications, each of which resides in a virtual directory. Each virtual directory is mapped to a physical directory on the local hard drive. Therefore, if you create a new virtual directory named CarsAreUs, the outside world can navigate to this site using a URL such as http://www.CarsAreUs.com (assuming your site's IP address has been registered with the world at large). Under the hood, the virtual directory maps to a physical root directory such as C:\TheCarsSite, which contains the set of files (and optional subdirectories) that constitutes the Web

application.

C# an d th e .N ET Plat f orm , Se con d Ed it ion

ISBN:1590590554 Andr ew Tr oelsen When you createby ASP.NET Web applications using VS .NET, you will automatically receive a new virtual Apr ess © 2003 (1200 pages) as you would guess, you are able to manually create a virtual directory for the current project. However, directory by hand.This Forcompr the sake of illustration, you ov wish to create ehensiv e text star tsassume w ith a brief er view of the a simple Web application named C# islanguage thenfolder quicklyonmyour oves machine to key technical Cars. The first step to createand a new to holdand the collection of files that constitute chitecturC:\CarsWebSite). al issues for .NET developer s. this new site (for ar example,

Next, you need to create a new virtual directory to host the Cars site. Simply rightclick the Default Web Site Tanode ble o fofCon en t sselect New | Virtual Directory from the context menu. This menu selection launches an IIS tand C# and t he .NET PlatSkip for m,past Second Edition integrated wizard. the welcome screen and give your Web site a name (Cars). Next, you are I ntr oduction asked to specify the physical folder on your hard drive that contains the various files and images that Pa r t One - I this nt r oduci nd theC:\CarsWebSite). .NET P la tf or m represent site ng (in C# thisacase,

Chapter 1

- The Philosophy of .NET The final of the C# wizard prompts you for some basic traits about your new virtual directory (such as Chapter 2 step - Building Applications

read/write access the it La contains, Pa r t Tw o - The C# Prto ogr amfiles m ing ngua ge the

ability to view these files from a Web browser, the ability to launch executables [e.g., CGI applications], and so on). For this example, the default selections are just Chapter 3 - C# Language Fundamentals fine (be aware that you can always modify your selections after running this tool using various "right-click" Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Property dialog boxes integrated within IIS). When you are finished, you will see that your new virtual Chapter 5 - Exceptions and Obj ect Lifetim e directory has been registered with IIS (Figure 18-3). Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Figure 18-3: The Cars virtual directory

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion The Role ofC#HTML ISBN:1590590554

by Andr ew Tr oelsen

Once you have configured a virtual directory to host your Web application, you need to create the content Apr ess © 2003 (1200 pages) itself. Recall that This Webcompr application is term to er the setofofthe files that constitute the functionality ehensiv e simply text starthe ts w ith agiven brief ov view of the site. To be C# sure, a vast number of these files will contain syntactic language and then quickly m oves to key technical and tokens defined by the Hypertext ar chitectur issuesisfor .NET developer s. language used to describe how literal text, Markup Language (HTML).alHTML a standard markup images, external links, and various HTML-based GUI widgets are rendered by the client-side browser. TaThis ble oparticular f Con t en taspect s of Web development is one of the major reasons that many programmers dislike

building Web-based C# and t he .NET Plat forprograms. m, Second While Editionit is true that modern IDEs (including Visual Studio .NET) and Web development platforms (such as ASP.NET) hide much of the raw HTML tokens from view, you will do well I ntr oduction tor thave knowledge of HTML astf you Pa One -a I working nt r oduci ng C# a nd the .NET P la or m

work with ASP.NET. While this chapter will most certainly

not cover aspects of HTML (by any means), let's check out some basics. Chapter 1 all - The Philosophy of .NET Chapter 2

- Building C# Applications

The Basic Structure of an HTML Document

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals An HTML consists of a set of am tags thatwdescribe the look and feel of a given Web page. As you would Chapter 4 file - Obj ect -Or iented Pr ogr ming ith C#

expect,5the- basic structure of an tends to remain the same. For example, *.htm files (or Chapter Exceptions and Obj ectHTML Lifetimdocument e alternatively, *.html files) and close with and tags, typically define a section, Chapter 6 - I nter faces andopen Collections

and so 7forth. Keep inI nter mind that Delegates, HTML is not case sensitive. Therefore, in the eyes of the hosting browser, Chapter - Callback faces, and Ev ents , , and are identical. - Advanced C# Type Const ruction Techniques

Chapter 8

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

To illustrate some HTML basics, open Visual Studio .NET, insert an empty HTML file using the File | New |

Chapter 9 -selection, Under standing .NETthis Assem File menu and save file blies under your physical directory as default.htm. If you examine the new Chapter 10 Pr ocesses, AppDomains, and Threads *.htm file created by the IDE, you willCont findexts, something like the following: Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Chapter 16 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 - XML Web Ser vices Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

I ndex List of Figur es

The and tags are used to mark the beginning and end of your document. As you may guess, Web browsers use these tags to understand where to begin applying the rendering formats specified in the body of the document.

List of Tables

The and tags are used to hold any metadata about the document itself. Here the HTML header uses some tags that describe the origin of this file (VS .NET) and general bits of information. These tags will have no effect for the examples in this text, so feel free to delete them. Finally, note that a tag is set (currently empty) that may be modified as follows:

This Is the Cars Web Site



As you would guess, C# an the d th e .N ET tags Plat aref orm used , Se tocon specify d Ed it the iontext string that should be placed in the title bar of the Web browser application. ISBN:1590590554 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion HTML FormC#Development by Andr ew Tr oelsen

ISBN:1590590554

The real action ofApr aness *.html file(1200 occurs within the scope of the elements. Nestled within these tags © 2003 pages) are any number of additional tags used render various widgets. Simply put, an HTML form is This compr ehensiv e texttostar ts w ith a briefuser ov er input view of the simply a named group of related UI elements used to gather user input, which is then transmitted to the C# language and then quickly m oves to key technical and ar chitectur for .NETan developer s. Web application via HTTP. al Doissues not confuse HTML form with the entire display area shown by a given browser. In reality, an HTML form is more of a logical grouping of widgets placed in the and tag set: Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 17 - Data Access w ith ADO.NET

User Name: Pa r t

Chapter 18 ASP.NET Web Pages and Web

Password: Contr ols Chapter

Chapter 20 - XML Web Ser vices

I ndex List of

List of Tables

Chapter 16 - The Sy stem .I O Nam espace

Notice that you have assigned relevant names and IDs to each widget (txtUserName, txtPassword, btnSubmit, and btnReset). Of greater importance, note that each input button has an extra attribute named type, which marks these buttons as UI items that automatically clear all fields to their initial values (type = Reset) or send the form data to the recipient (type = Submit). Figure 18-6 illustrates your creation thus far.

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction

Figure initial at the Pa r t One - I nt18-6: r oduciThe ng C# a ndcrack the .NET P ladefault.htm tf or m Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

page

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an d th e .N ET Plat f orm , Se con d Ed it ion The Role ofC#Client-Side Scripting by Andr ew Tr oelsen

ISBN:1590590554

Now that you have better understanding of how to construct an HTML form, the next issue is to examine Apraess © 2003 (1200 pages) the role of client-side scripting. A given *.html may contain script code that will be emitted in This compr ehensiv e text star tsfile w ith a brief ov erblocks view of of the the response stream and processed by the requesting browser. There are two major reasons that clientC# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s. side scripting is used: To validate user input before posting back to the Web server Ta ble o f Con t en t s

Tot he interact withforthe Object Model (DOM) of the target browser C# and .NET Plat m, Document Second Edition I ntr oduction

Regarding the first point, understand that the inherent evil of a Web application is the need to make frequent round-trips (aka postbacks) to the server machine to update the HTML rendered into the Chapter 1 While - The postbacks Philosophy are of .NET browser. unavoidable, you should always be mindful of ways to minimize travel Chapter 2 Building C# Applications across the wire. One technique that saves round-trips is to use client-side scripting to validate user input Pa r t Tw osubmitting - The C# Prthe ogrform am m data ing Lato ngua before the ge Web server. If an error is found (such as not specifying data within a Chapter 3 field), - C# you Language Fundamentals required can prompt the user of the error without incurring the cost of posting back to the Web Chapter - Obj ectnothing -Or iented Pr ogr am ming w ith C# user than posting back on a slow connection, only to server. 4(After all, is more annoying to the Chapter - Exceptions and Obj ect Lifetim e ) receive5instructions to address input errors! Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 6

- I nter faces and Collections In addition validating user input, client-side Chapter 7 - toCallback I nter faces, Delegates, andscripts Ev ents can also be used to interact with the underlying object

model (termed the Document Object Model, or DOM) of the browser itself. Most commercial browsers - Advanced C# Type Const ruction Techniques expose a set of objects that can be leveraged to control how the browser should behave. One major Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s annoyance is the fact that different browsers tend to expose similar, but not identical, object models. Thus, Chapter 9 - Under standing .NET Assem blies if you emit a block of client-side script code that interacts with the DOM, it may not work identically on all Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads browsers. Chapter 8

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four ve r a gingprovides the .NETthe LibrHttpRequest.Browser a r ie s Note- Le ASP.NET

property, which allows you to determine at runtime

Chapter 12 the - Obj ect Ser ialization and the .NET Remoting Lay er request. capacities of the browser that sent the current Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

There are scripting languages that can+ be Chapter 14 -many A Better Paint ing Fr amew or k ( GDI ) used to author client-side script code. Two of the more

popular15are VBScript andwith JavaScript. is a ols subset of the Visual Basic 6.0 programming language. Chapter - Pr ogr am ming WindowsVBScript Form s Contr Be aware that Microsoft Internet Explorer (IE) is the only Web browser that has built-in support for clientside VBScript support. Thus, if you wish your HTML pages to work correctly in any commercial Web Chapter 17 - Data Access w ith ADO.NET browser, do not use VBScript for your client-side scripting logic. Chapter 16 - The Sy stem .I O Nam espace

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 -popular ASP.NET Web Pages and Web Contr ols The other scripting language is JavaScript. Be very aware that JavaScript is in no way, shape, or Chapter - ASP.NET Web Applicat ions While JavaScript and Java have a somewhat similar syntax, form a 19 subset of the Java language. Chapter 20 - isXML Ser vices programming language, and thus is far less powerful than Java itself. The JavaScript notWeb a full-fledged I ndex good news is that all modern day Web browsers support JavaScript, which makes it a natural candidate List for ofclient-side Figur es scripting logic. List of Tables

Note To further confuse the issue, recall that JScript .NET is a full-blown managed language that can be used to build valid .NET assemblies and is not used to author client-side script code!

A Client-Side Scripting Example To illustrate the role of client-side scripting, we will first examine how to intercept events sent from clientside HTML GUI widgets. Assume you have added an additional HTML Button (btnHelp) type to your default.html page that allows the user to view help information. To capture the Click event for this button, activate the HTML view and select your button from the left drop-down list. Using the right drop-down list box, select the onclick event (Figure 18-7).

C# an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction

Figure widget Pa r t One - I nt18-7: r oduciCapturing ng C# a ndHTML the .NET P la tf events or m Chapter 1

a la VS .NET

- The Philosophy of .NET

Once you do so, VS .NET will create an empty JavaScript function that will be called when the user clicks Building C# Applications the button.- Within this stub, simply make use of the alert() method to display a client-side message box:

Chapter 2

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5 - Exceptions and Obj ect Lifetim e This Is the Cars Web Site Chapter 6 - I nter faces and Collections

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er BGCOLOR="#66ccff"> Chapter Chapter 17 - Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) ...

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith In this case, the form data is ADO.NET not appended to the query string, but instead is written to a separate line Pa r t Fi ve - W e b Appl ica ti ons and X ML W e the b Seform r vi cesdata within the HTTP header. Using POST,

is not directly visible to the outside world and is

Chapter 18 a- wee ASP.NET Web secure Pages and Webimportantly, Contr ols therefore bit more (more POST data is not limited by character length). For the Chapter 19 - make ASP.NET Applicat ionsto send the form data to the receiving *.asp page. time being, useWeb of HTTP GET Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e Active .N ET Plat fServer orm , Se conPage d Ed it ion Building a Classic by Andr ew Tr oelsen

ISBN:1590590554

A classic Active Server a hodgepodge of HTML and server-side script code. If you have never Apr ess Page © 2003 is (1200 pages) worked with classic ASP, understand that the goal is to dynamically This compr ehensiv e text star ts w ithof a ASP brief ov er view of the build HTML on the fly using server-side scriptC# logic and a small set of classic COM objects and related COM libraries. For example, language and then quickly m oves to key technical and ar chitectur alVBScript issues for(or .NET developerblock s. you may have a server-side JavaScript) that reads a table from a data source using classic ADO and returns the rows as a generic HTML table. TaFor ble this o f Con example, t en t s the ASP page uses the intrinsic ASP Request COM object to read the values of the

incoming (appended the query string) and echo them back to the caller (not terribly exciting, C# and t he form .NET data Plat for m, Second to Edition butoduction it makes the point). The server-side script logic will make use of VBScript (as denoted by the I ntr "language" Pa r t One - I ntdirective). r oduci ng C# a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

To do so, create a new HTML file using Visual Studio .NET and save this file under the name - Building C# Applications ClassicAspPage.asp into the folder to which your virtual directory has been mapped. Next, update your Pa r t Tw o - The C# Pr ogr am m ing La ngua ge *.asp file with the following HTML and scripting logic: Chapter 2 Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

- Exceptions and Obj ect Lifetim e

Chapter 6 - I nter faces and Collections

Chapter 7 - Callback I nter faces, Delegates, and Ev ents The Cars Page Chapter 8 - Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

ChapterHere Under standing .NET Assem blies is what you sent me: Chapter

- Pr ocesses, AppDomains, Cont exts, and Threads User Name:

Chapter Pr ogramm
ing Pa r t Four Le ve r a ging the .NET Libr a r ie s Password: Chapter
Chapter

13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter

14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 5

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

The first thing to be aware of is that an *.asp file begins and ends with the standard , , and tag pairs. Here, you use the classic ASP Request COM object, which like any COM type supports Chapter 18 - ASP.NET Web Pages and Web Contr ols a number of properties, methods, and events. You call the Request.QueryString() method to examine the Chapter 19 - ASP.NET Web Applicat ions values contained in each HTML widget submitted via method = "GET". Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 20 - XML Web Ser vices

I ndex Also note that the notation is a shorthand way of saying "Insert the following directly into the List of Figur es HTTP response." To gain a finer level of flexibility, you could interact with the ASP Response COM object List within of Tables a full script block (denoted using the notation). You have no need to do so here; however,

here is a simple example:

...



Here, the C# code block is not only triggering the GetDateTime() method in the code behind file, but also making use of the inherited Response property defined by the System.Web.UI.Page base class. To build a more compact *.aspx file, you could make reference to the inherited Page members directly in your code behind class. Thus, you could also write the following: public class SomeWebForm : System.Web.UI.Page {

... C# an dGetDateTime() th e .N ET Plat f orm , Se con d Ed it ion public void ISBN:1590590554 by Andr ew Tr oelsen { Apr ess © 2003 (1200 pages) Response.Write("It is now " + DateTime.Now.ToString()); This compr ehensiv e text star ts w ith a brief ov er view of the } C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

}

And then simply call:

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition





w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e

Chapter Chapter 7 - Callback I nter faces, Delegates, and Ev ents

Chapter 8 - Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

As you 11 can- see, documents tend to quite verbose. The gooding news is that you can lead a productive a Chapter Type WSDL Reflection, Late Binding, andbeAttr ibuteBased Pr ogramm happy asvear a.NET WebLibr service Pa r t Fourlife - Le ging XML the .NET a r ie s

developer without becoming an expert in the nuances of WSDL syntax. Although you are always free to create a *.wsdl document by hand, the chances that you will do so are extreme Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er rare. However, having a basic understanding of WSDL will serve you well, especially if you need to tweak the Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) default element definitions emitted by IIS. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 Recall - Pr ogr that am ming with Windows Form s Contr ols Note the System.Web.Services.Description namespace contains a plethora of types that allow y Chapter 16 to - The Sy stem .I O Namread espace programmatically and manipulate raw WSDL (so check it out if you are so interested). Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET PlatLine f orm , Se con d Ed it ion The wsdl.exe Command Utility by Andr ew Tr oelsen

ISBN:1590590554

Now that you have better understanding of WSDL's place in the world, you are ready to check out a Apraess © 2003 (1200 pages) command-line tool that ships with the .NET named wsdl.exe. In a nutshell, this tool This compr ehensiv e text starSDK ts w ith a brief(surprise, ov er view surprise) of the performs two major tasks: C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Generates a server-side file that functions as a skeleton for implementing the XML Web service Generates Ta ble o f Con t en t sa client-side file that functions as the proxy to the remote XML Web service C# and t he .NET Plat for m, Second Edition

Wsdl.exe supports a number of command-line flags. While you may view all possible options by typing wsdl -? at the command prompt, Table 20-5 points out some of the more common arguments (do note Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m that each flag supports a shorthand notation as well, which can also be seen via command prompt help). I ntr oduction Chapter 1

- The Philosophy of .NET

Chapter 2 - Building C# Applications Table 20-5: Select Flags of wsdl.exe Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Wsdl.exe Meaning in Life Chapter 3 - C# Language Fundamentals Command-Line Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Flag5 Chapter

- Exceptions and Obj ect Lifetim e

Chapter 6 - I nter faces and Collections /appsettingurlkey This option instructs wsdl.exe to build a proxy that does not make use of Chapter 7 - Callback I nter faces, Delegates,URLs. and Ev ents hard-coded Instead, the proxy class will be configured to read the Chapter 8

- Advanced C# Type Const ruction Techniques URL from a client-side *.config file.

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

/language Specifies the language to use for the generated proxy class: Chapter 9 - Under standing .NET Assem blies CS (C#;Cont default) Chapter 10 - Pr ocesses, AppDomains, exts, and Threads Chapter 11 - Type Reflection, Late Binding,Basic and Attr ibute- Based Pr ogramm ing VB (Visual .NET) Pa r t Four - Le ve r a ging the .NET Libr a r ie s

JS (JScript)

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

(Visual J#). The default sisFor C#. Chapter 13 - Building a Bet ter VJS Win dow ( Int roducin g Window ms) Chapter 14 - A Better Paint ing Specifies Fr amew orthe k ( GDI +) /namespace namespace for the generated proxy or template. By Chapter 15 - Pr ogr am ming with Windows Contr olsbe defined within a namespace definition! default yourForm types will not Chapter 16 - The Sy stem .I O Nam espace

/out

Specifies the file in which to save the generated proxy code. If not specified, the file name is based on the XML Web service name.

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web ols to use within the proxy code. SOAP is the default. /protocol Specifies theContr protocol Chapter 19 - ASP.NET Web Applicat However, ions you can also specify HttpGet or HttpPost to create a proxy that

communicates using simple HTTP GET or POST verbs. Chapter 20 - XML Web Ser vices I ndex

/server

List of Figur es

Generates an abstract class for an XML Web service based on the WSDL document.

List of Tables

Transforming WSDL into an XML Web Service Skeleton One interesting use of the wsdl.exe utility is to generate a skeleton class definition in the language of your choice. Once this source code file has been generated, you have a solid starting point to provide the actual implementation of each Web method. To illustrate, open a command window and specify the /server flag, followed by the name of the WSDL document you wish to process. Note that the WDSL document may be contained in a physical *.wsdl file: wsdl /server SimpleHelloWS_wsdl.wsdl

or can be obtained dynamically from a given URL via the ?WSDL suffix:

wsdl /server http://localhost/helloWS/HelloWorldWS.asmx?WSDL C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

In either case, once wsdl.exe tool hasstar processed elements, Thisthe compr ehensiv e text ts w ith a the briefWSDL ov er view of the you will end up with a C# source C# language then quickly m oves to key managed technical and code file (if you wish to receiveand a file written with a different language, simply make use of the /language flag): ar chitectur al issues for .NET developer s. System.Diagnostics; Tausing ble o f Con t en t s using System.Xml.Serialization; using System; I ntr oduction using System.Web.Services.Protocols; Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m using System.ComponentModel; Chapter 1 - The Philosophy of .NET using System.Web.Services; Chapter 2 - Building C# Applications [System.Web.Services.WebServiceBindingAttribute Pa r t Tw o - The C# Pr ogr am m ing La ngua ge (Name="HelloClassSoap", Namespace="http://tempuri.org/")] Chapter 3 - C# Language Fundamentals public abstract class HelloClass : System.Web.Services.WebService Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# { Chapter[System.Web.Services.WebMethodAttribute()] 5 - Exceptions and Obj ect Lifetim e Chapter[System.Web.Services.Protocols.SoapDocumentMethodAttribute 6 - I nter faces and Collections Chapter("http://tempuri.org/HelloWorld", 7 - Callback I nter faces, Delegates, and Ev ents Chapter RequestNamespace="http://tempuri.org/", 8 - Advanced C# Type Const ruction Techniques Pa r t ThreResponseNamespace="http://tempuri.org/", e - Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter Use=System.Web.Services.Description.SoapBindingUse.Literal, 9 - Under standing .NET Assem blies Chapter ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] 10 - Pr ocesses, AppDomains, Cont exts, and Threads abstract HelloWorld(); Chapterpublic 11 - Type Reflection, string Late Binding, and Attr ibute- Based Pr ogramm ing }r t Four - Le ve r a ging the .NET Libr a r ie s Pa C# and t he .NET Plat for m, Second Edition

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Again, note that the generated class type is simply a shell that you can use to implement the methods of the XML Web service. Notice, for example, that the HelloClass type and HelloWorld() method have both been Chapter 15 - Pr ogr am ming with Windows Form s Contr ols defined as abstract entities. Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 16 - The Sy stem .I O Nam espace

Chapter 17 this - Data w ith ADO.NET Although is aAccess very interesting feature of the wsdl.exe utility, the chances are that you would rather have Pa r t Fi ve -go W einb the Appl ica ti ons and X ML e b Se r vi ces this tool other direction andWgenerate a client-side

proxy type that will communicate with the

Chapter remote18 Web - ASP.NET service.Web You Pages see how andtoWeb do Contr this very ols thing in just a moment. But first, let's dive a bit deeper into

the wire19protocols. Chapter - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex

SOURCE CODE

List of Figur es List of Tables

The SimpleHelloWS_WSDL.wsdl and proxy skeleton files can be found under the Chapter 20 subdirectory.

C# anXML d th e .N ET PlatService f orm , Se con d Ed it ion Revisiting the Web Wire Protocols ISBN:1590590554

by Andr ew Tr oelsen

As you know, theApr purpose of a(1200 Webpages) service is to return XML-based data to a consumer, using the HTTP ess © 2003 protocol. Specifically, a Web server bundles this data into the This compr ehensiv e text star ts w ith a brief ov erbody view of of an the HTTP request and transmits it to the consumer using one of three specific techniques (Table 20-6). C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Table 20-6: Web Service Wire Protocols Transmission Ta ble o f Con t en t s

Meaning in Life Protocol C# and t he .NET Plat for m, Second Edition I ntr oduction

HTTP GET

GET submissions append parameters to the query string of the current URL.

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET HTTP2POST POST transmissions embed the data points into the header of the Chapter - Building C# Applications

HTTP message Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

rather than appending them to the query string.

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w iththe C# wire using XML. methods across - Exceptions and Obj ect Lifetim e

SOAP

Chapter 5

SOAP is a wire protocol that specifies how to submit data and invoke

Chapter 6

- I nter faces and Collections While each leads to the same result (invoking a Web method), your choice of wire protocol Chapter 7 - approach Callback I nter faces, Delegates, and Ev ents

determines types of (and return types) that can be sent between each interested party. Chapter 8 - the Advanced C# parameters Type Const ruction Techniques The SOAP protocol form Pa r t Thre e - Pr ogr am moffers i ng w iyou th .Nthe ET greatest Assem bl ie s

of flexibility, given that SOAP messages allow you to pass complex data types between the caller and XML Web service (as well as binary files). However, for Chapter 9 - Under standing .NET Assem blies completion let's check out the role of standard GET and POST. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

HTTP GET and HTTP POST Messages

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Although and POST verbs may(be familiarg constructs, you Chapter 13 GET - Building a Bet ter Win dow Int roducin Window s For ms)must be aware that this method of transportation is not Paint rich enough to represent complex items as structures or classes. When you use Chapter 14 - A Better ing Fr amew or k ( GDI + such ) GET and you canWindows only interact Web Chapter 15 POST - Pr ogrverbs, am ming with Form swith Contr ols methods using the types listed in Table 20-7. Chapter 16 - The Sy stem .I O Nam espace

Table 20-7: Supported POST and GET Data Types

Chapter 17 - Data Access w ith ADO.NET

Pa rSupported t Fi ve - W e b Appl ica ti ons and X ML W ein b SeLife r vi ces Meaning

Chapter 18 - ASP.NET GET/POST Data Web Pages and Web Contr ols Chapter Type19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

Enumerations

I ndex

List of Figur es ListSimple of Tables Arrays

Strings

GET and POST verbs support the transmission of .NET System.Enum types, given that these types are represented as a static constant string. You can construct arrays of any primitive type. GET and POST transmit all numerical data as a string token. String really refers to the string representation of CLR primitives such as Int16, Int32, Int64, Boolean, Single, Double, Decimal, and so forth.

If you make use of standard HTTP GET or HTTP POST, you are not able to build Web methods that take complex types as parameters or return values (for example, an ADO.NET DataSet or custom structure type). For simple Web services, this limitation may be acceptable. However, if you make use of SOAP messages, you are able to build much more elaborate XML Web services.

SOAP Messages Although a complete examination of SOAP is outside the scope of this text, understand that SOAP itself does not define a specific protocol and can thus be used with any number of existing Internet protocols (HTTP, SMTP, and others). The general role of SOAP, however, remains the same: Provide a mechanism

to invoke methods using complex types in a language- and platform-neutral manner. To do so, SOAP C# an d th e .N ET Plat f orm , Se con d Ed it ion encodes each complex method using SOAP messages. ISBN:1590590554

by Andr ew Tr oelsen

Apr ess © 2003 (1200 pages) two core sections. First we have the SOAP envelope, which can In a nutshell, a SOAP message defines be understood asThis the compr conceptual information. ehensivcontainer e text starfor ts the w ithrelevant a brief ov er view of theSecond, we have the rules that C# language and then m oves to(placed key technical are used to describe the information in quickly said message into theand SOAP body). An optional third ar chitectur issues for .NET developer s. section (the SOAP header) almay be used to specify general information regarding the message itself such as security or transactional information. Ta ble o f Con t en t s

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - The Philosophy of .NET

Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5 - Exceptions and Obj ect Lifetim e

C# and t he .NET Plat for m, Second Edition

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8 - aAdvanced Type Const ruction Techniques Viewing SOAP C# Message Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Like other of WSDL, you are not Chapter 9 -aspects Under standing .NET Assem bliesrequired to understand the inner details of SOAP to build XML Web services with the .NET platform. However, you use the makeshift client browser, you are able Chapter 10 - Pr ocesses, AppDomains, Cont exts, andwhen Threads

to view 11 the- format of the SOAP for each exposed method. Chapter Type Reflection, Latemessage Binding, and Attr ibuteBasedWeb Pr ogramm ing For example, if you were to click the link for the Pa r t Four - Lethe ve rAdd() a ging method the .NET of Libr a rCalcWebService, ie s

you would find the following SOAP request:

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 17 - Data Access w ith ADO.NET int Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces int Chapter 18 - ASP.NET Web Pages and Web Contr ols

Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 - XML Web Ser vices

Chapter 16 - The Sy stem .I O Nam espace

I ndex List of Figur es List of Tables

The corresponding SOAP response looks like this:

int



C# an d th e .N ET Plat fC# orm ,Code Se con d (Generating Ed it ion Transforming WSDL into a Proxy) ISBN:1590590554

by Andr ew Tr oelsen

At this point, you Apr areess ready to build custom clients that can consume your XML Web services. Although © 2003 (1200 pages) undesirable, it is completely possible to construct a client-side base This compr ehensiv e text star ts w ith a brief ov er code view of the that manually requests a WSDL definition and manually parses each XML node to establish a connection C# language and then quickly m oves to key technical and to the remote service. A muchar chitectur al issues for .NETto developer s. a proxy class that maps to the Web methods defined preferred approach is to leverage wsdl.exe generate by a given *.asmx file. To do so, specify the name of proxy file to be generated (via the /out flag) and the URL where the WSDL can be obtained: Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition

wsdl.exe /out:c:\MyCalcWSProxy.cs http://localhost/CSharpBookSE/CalcWebService/CalcWS.asmx?WSDL

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2 - wsdl.exe Building C# By default, willApplications generate proxy code written in C#. However, if you wish to obtain proxy code in an Pa r t Tw o - The C# language, Pr ogr am m ing La ngua alternative .NET make use ge of

the /language flag. You should also be aware that by default,

Chapter wsdl.exe 3 will - C# generate Language a proxy Fundamentals that communicates with the remote XML Web service using SOAP. If you wish

to build4a proxy that leverages straight HTTP Chapter - Obj ect -Or iented Pr ogr am ming w ith GET C# or HTTP POST, you may make use of the /protocol flag. Chapter 5

- Exceptions and Obj ect Lifetim e

- I nter facesthe and Collections Investigating Proxy Code

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

If you opened up the generated *.cs ruction file, youTechniques would find that you are given a class type that derives from Chapter 8 - Advanced C# Type Const System.Web.Services.Protocols.SoapHttpClientProtocol. This base class defines a number of helper Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s functions that will be leveraged within the implementation of the proxy type. Table 20-8 describes some Chapter 9 - Under standing .NET Assem blies interesting inherited members. Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Table 20-8: Core Members the SoapHttpClientProtocol Pa r t Four - Le ve r a ging the .NETof Libr a r ie s

Type

Chapter 12 - Obj ect Ser ialization and thein .NET Remoting Lay er Inherited Meaning Life Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Member Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

BeginInvoke() Starts an asynchronous invocation of the Web method Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam EndInvoke() Endsespace an asynchronous invocation of the Web method Chapter 17 - Data Access w ith ADO.NET Pa rInvoke() t Fi ve - W e b Appl ica ti ons Synchronously and X ML W e b Seinvokes r vi ces

a method of the Web service

Chapter Webproxy Contrinformation ols Proxy18 - ASP.NET Web Pages Gets and or sets for making a Web service request through a Chapter 19 - ASP.NET Web Applicat firewallions Chapter 20 - XML Web Ser vices

Timeout I ndex

Gets or sets the timeout (in milliseconds) used for synchronous calls

ListUrl of Figur es

Gets or sets the base URL to the server to use for requests

List of Tables

UserAgent

Gets or sets the value for the user agent header sent with each request

The constructor of this proxy class hard codes the URL of the remote Web service and stores it in the inherited Url property: [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute( Name="MyWayCoolWebCalculatorSoap", Namespace="http://www.intertech-inc.com/WebServices")] public class MyWayCoolWebCalculator : System.Web.Services.Protocols.SoapHttpClientProtocol { public MyWayCoolWebCalculator()

{ C# an d th=e "http://localhost/CSharpBookSE/CalcWebService/CalcWS.asmx"; .N ET Plat f orm , Se con d Ed it ion this.Url

} ... }

by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

The generated proxy code defines synchronous and asynchronous members for each Web method defined in the Web service. As you are aware, synchronous method invocations are blocked until the call returns. Ta ble o f Con t en t s Asynchronous method inoculations return control to the calling client immediately after sending the invocation C# and t he .NET Plat for m, Second Edition request. When the processing has finished, the runtime makes a callback to the client. Here is the I ntr oduction synchronous implementation of the Add() method which takes two System.Int32 types (recall that we Pa r t One - I ntthis r oduci ng C# a nd the .NET P la tf or m overloaded method): Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

[System.Web.Services.Protocols.SoapDocumentMethodAttribute( "http://www.intertech-inc.com/WebServices/Add", Chapter 3 - C# Language Fundamentals RequestNamespace="http://www.intertech-inc.com/WebServices", Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# ResponseNamespace="http://www.intertech-inc.com/WebServices", Chapter 5 - Exceptions and Obj ect Lifetim e Use=System.Web.Services.Description.SoapBindingUse.Literal, Chapter 6 - I nter faces and Collections ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] Chapter 7 int - Callback I nter faces, Delegates, public Add(int x, int y) and Ev ents Chapter 8 - Advanced C# Type Const ruction Techniques { Pa r t Threobject[] e - Pr ogr am results m i ng w i th .N Assem bl ie s =ETthis.Invoke("Add", Chapter 9 - Under newstanding object[] .NET Assem {x, y}); blies ((int)(results[0])); Chapter return 10 - Pr ocesses, AppDomains, Cont exts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

The asynchronous version of this Add() method is represented by the now familiar BeginXXXX() / EndXXX() method pair:

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

public System.IAsyncResult BeginAdd(int x, int y, System.AsyncCallback callback, object asyncState) Chapter 17 - Data Access w ith ADO.NET { Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces return this.BeginInvoke("Add", Chapter 18 - ASP.NET Web Pages and Web Contr ols new object[] {x, y}, callback, asyncState); Chapter 19 - ASP.NET Web Applicat ions } Chapter 20 - XML Web Ser vices public int EndAdd(System.IAsyncResult asyncResult) I ndex { List of Figur es object[] results = this.EndInvoke(asyncResult); List of Tablesreturn ((int)(results[0])); } Chapter 16 - The Sy stem .I O Nam espace

The remaining proxy methods are implemented more or less the same way. In a nutshell, each synchronous method packages any incoming parameters into a generic array of System.Object types and passes them into the inherited Invoke() method. The return value (if any) is cast into a .NET specific type. The asynchronous methods take a similar approach, however they make use of the inherited BeginInvoke() and EndInvoke() methods.

Wrapping the Proxy Type Within a .NET Namespace One update you will want to make for the generated proxy file is to wrap the class in a namespace definition, as shown here: namespace CalcWSClient

{ C# an d MyWayCoolWebCalculator th e .N ET Plat f orm , Se con d Ed it:ion public class ISBN:1590590554 by Andr ew Tr oelsen System.Web.Services.Protocols.SoapHttpClientProtocol Apr ess © 2003 (1200 pages) {...} This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

}

By default, wsdl.exe will not define a specific namespace unless you explicitly specify the /n flag at the command prompt. For example:

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

wsdl.exe /out:c:\MyCalcWSProxy.cs /n:CalcWSClient http://localhost/CSharpBookSE/CalcWebService/CalcWS.asmx?WSDL

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an dProxy th e .N ET(Synchronous Plat f orm , Se con d Ed itInvocations) ion LeveragingC#the by Andr ew Tr oelsen

ISBN:1590590554

Once you have your proxy file,(1200 you pages) can either compile the type into a stand-alone .NET assembly (via csc.exe) o Apr ess © 2003 simply include theThis *.cscompr file directly in yourstar client ehensiv e text ts wapplication. ith a brief ovInereither view ofcase, the you need to explicitly set a reference the System.Web.Services.dll assembly (given that the proxy code makes C# language and then quickly m oves to key technical and use of numerous types defined within ar chitectur al issues for .NET developer s. this binary). At this point the client will simply create an instance of the proxy type and call the methods of interest. All of the Tagrunge ble o f Con work t en oft sopening an HTTP channel, formatting the SOAP message, and mapping XML to and from .NET

data is handled on Second your behalf. C# andtypes t he .NET Plat for m, Edition I ntr oduction

Assume you have created a new C# console application project that directly includes the *.cs proxy file and wraps it into the client's namespace. The client code is straightforward:

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

// Don't angua reference Pa r t Tw o - Theforget C# Pr ogrto am mset ing La ge

to // System.Web.Services.dll! Chapter 3 - C# Language Fundamentals using System; Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# namespace CalcWSClient Chapter 5 - Exceptions and Obj ect Lifetim e { Chapter 6 - I nter faces and Collections class TheClient Chapter 7 - Callback I nter faces, Delegates, and Ev ents { Chapter 8 - Advanced C# Type Const ruction Techniques static void Main(string[] args) Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s { Chapter 9 - Under// standing .NET Assem Exercise the blies proxy! Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Console.WriteLine("***** The amazing Web Service Client App *****\n") Chapter 11 - Type MyWayCoolWebCalculator Reflection, Late Binding, and Attr ws ibuteogramm ing = Based new Pr MyWayCoolWebCalculator(); Pa r t Four - Le ve r a ging the .NET Libr a r ie s Console.WriteLine("2 + 3 = {0}", ws.Add(2, 3)); Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er = {0}", ws. Add(23.4F, 33.1F)); Console.WriteLine("23.4 + 33.1 Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window For ms) is: {0}", Console.WriteLine("My random snumber Chapter 14 - A Better Paint ws.GetMyRandomNumber()); ing Fr amew or k ( GDI + ) value of PI is: {0}", Chapter 15 - Pr ogrConsole.WriteLine("Simple am ming with Windows Form s Contr ols ws.GetSimplePI()); Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Console.WriteLine(); Access w ith ADO.NET Pa r t Fi ve - W} e b Appl ica ti ons and X ML W e b Se r vi ces Chapter}18 - ASP.NET Web Pages and Web Contr ols } Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex

Regarding Overloaded Web Methods

List of Figur es List of Tables

One point of interest is the fact that the overloaded Add() method defined by the Web service indeed is realized by the client as an overloaded method. Recall that WSDL demands a unique name for each method it is describing (therefore, we are required to make use of the MessageName property when applying the [WebService] attribute). However, if you look at the proxy code, you will find that the System.Web.Services.Protocols.SoapDocumentMethodAttribute type maps the overloaded method to the corre underlying WSDL name, for example: [System.Web.Services.Protocols.SoapDocumentMethodAttribute ("http://www.intertech-inc.com/WebServices/Add", RequestNamespace="http://www.intertech-inc.com/WebServices", ResponseNamespace="http://www.intertech-inc.com/WebServices", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int Add(int x, int y) {...}

[System.Web.Services.WebMethodAttribute(MessageName="Add1")] C# an d th e .N ET Plat f orm , Se con d Ed it ion [System.Web.Services.Protocols.SoapDocumentMethodAttribute ISBN:1590590554 by Andr ew Tr oelsen ("http://www.intertech-inc.com/WebServices/AddFloats", Apr ess © 2003 (1200 pages) RequestElementName="AddFloats", This compr ehensiv e text star ts w ith a brief ov er view of the RequestNamespace="http://www.intertech-inc.com/WebServices", C# language and then quickly m oves to key technical and ResponseElementName="AddFloatsResponse", ar chitectur al issues for .NET developer s. ResponseNamespace="http://www.intertech-inc.com/WebServices", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] Ta ble o f Con t en t s [return: System.Xml.Serialization.XmlElementAttribute("dddFloatsResult")] C# and t he .NET Plat for m, Second Edition public System.Single Add(System.Single x, System.Single y) I ntr oduction {...} Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

an dProxy th e .N ET(Asynchronous Plat f orm , Se con d Ed it ion LeveragingC#the Invocations) by Andr ew Tr oelsen

ISBN:1590590554

As you have seenApr atess numerous points throughout this text, the .NET platform has native support for © 2003 (1200 pages) asynchronous method invocations. The of wasynchronously invoking This compr ehensiv e texttask star ts ith a brief ov er view of thea method exposed from a given XML Web serviceC#under .NET is once again based on the delegate Thus, if you wish to language and then quickly m oves to key technicalpattern. and ar chitectur for .NETexposed developer asynchronously invoke any alofissues the methods bys. the Calculator XML Web Service, simply leverage the BeginXXX() and EndXXXX() methods. TaRecall ble o f that Con twhen en t s you wish to invoke a method asynchronously, the IAsyncResult interface allows you to

gather method's valueEdition as well as determine if the call has completed. Thus, you may call Add() C# and t the he .NET Plat forreturn m, Second asynchronously as follows: I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - The Philosophy IAsyncResult result of= .NET ws.BeginAdd(30, 21, null , null); Chapter ... 2 - Building C# Applications Pa if(result.IsCompleted) r t Tw o - The C# Pr ogr am m ing La ngua ge

+ 32 = {0}", ws.EndAdd(result)); Chapter Console.WriteLine("30 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

If you would rather have the XML Web service call back to the client-side code base (rather than poll the - I nter faces and Collections method via the IsCompleted property), you can make use of the AsyncCallback delegate:

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

// Assume 'ws' a i th static instance Pa r t Thre e - Pr ogr am mis i ng w .N ET Assem bl ie s

of the Calc proxy. AsyncCallback cb = new AsyncCallback(AdditionDone); Chapter 9 - Under standing .NET Assem blies IAsyncResult result = ws.BeginAdd(30, 21, cb, null); Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads ... Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing public static void AdditionDone(IAsyncResult result) Pa r t Four - Le ve r a ging the .NET Libr a r ie s { Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Console.WriteLine("30 + 32 = {0}", ws.EndAdd(result)); Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) } Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

can be Pa r t FiSOURCE ve - W e b Appl icaThe ti onsCalcWSClient and X ML W e b project Se r vi ces CODE Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

found under the Chapter 20 subdirectory.

C# an d th e .N ET Proxy Plat f orm ,Logic Se con d Ed it ion Avoiding Hard-Coded by Andr ew Tr oelsen

ISBN:1590590554

The default behavior of © wsdl.exe ispages) to hard code the URL of the Web service within the proxy's constructor. The Apr ess 2003 (1200 obvious drawbackThis to this situation is thets URL renamed or relocated, the proxy class must be updated an compr ehensiv e that text if star w ith is a brief ov er view of the recompiled. To build a more flexible proxy type, wsdl.exe provides the /appsettingurlkey flag (which may be C# language and then quickly m oves to key technical and ar chitectur al issues for .NET s. command line, the proxy's constructor will contain logic abbreviated to /urlkey). When you specify thisdeveloper flag at the that reads the URL using a key contained within a client-side *.config file. TaTo bleillustrate, o f Con t en generate ts a proxy file for the HelloWS Web service created earlier in this chapter (note that HelloUR

is just that will beEdition placed in the *.config file): C# and an t hearbitrary .NET Platkey for m, Second I ntr oduction Pa r t One - I nt r/urlkey:HelloUrl oduci ng C# a nd the .NET P la tf or m C:\>wsdl http://localhost/helloWS/helloworldWS.asmx?WSDL

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Ifryou check out Pa t Tw now o - The C# Pr ogrthe amdefault m ing Laconstructor ngua ge

of the proxy, you will find the following logic (note that if the correct cannot be found, the hard-coded URL will be used as a backup): Chapter 3 - C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C# public Chapter 5 HelloClass() - Exceptions and Obj ect Lifetim e

{ Chapter 6

- I nter faces and Collections urlSetting = Chapter string 7 - Callback I nter faces, Delegates, and Ev ents

System.Configuration.ConfigurationSettings.AppSettings["HelloUrl"]; - Advanced C# Type Const ruction Techniques if ((urlSetting Pa r t Thre e - Pr ogr am m i ng w i th != .N ETnull)) Assem bl ie s this.Url = urlSetting; Chapter 9 - Under standing .NET Assem blies else Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads this.Url = "http://localhost/helloWS/helloworldWS.asmx"; Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing } Chapter 8

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet terwould Win dow ( Int roducin The client-side *.config file look like this: g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter - Pr ogr am ming with Windows Form s Contr ols

Chapter 16 - The Sy stem .I O Nam espace

Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica tikey="HelloUrl" ons and X ML W e b Se value="http://localhost/helloWS/helloworldWS.asmx" r vi ces operator, 364 AppDomains, Cont exts, and Threads Chapter 10 - Pr ocesses,

* and & parameters, 363 field access via pointers, 364 Pa r t Four - Le ve r a ging the .NET Libr a r ie s fixed keyword, 365–366 Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er stackalloc keyword, 365 Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) swap function, unsafe and safe, 363–364 Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) unsafe keyword, 361–363

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

untyped DataSets, defined, 927

Chapter 16 - The Sy stem .I O Nam espace

Up/Down 774–776 Chapter 17 Controls, - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl848 ica ti ons and X ML W e b Se r vi ces Update() method,

Chapter 18 - ASP.NET Web Pages and Web Contr ols

UPDATE SQL statements, 848

Chapter 19 - ASP.NET Web Applicat ions

UpdateGrid() method, 836

Chapter 20 - XML Web Ser vices

updating records I ndex with OleDbCommand, 897–898 List of Figur es with SqlDataAdapter, 910–912 List of Tables UpDownBase properties, 774 user controls, defined, 789–790 user-defined types (UDTs), 20 User Interfaces in C# (Apress, 2002), 802 User Strings tokens, 503–504 using keyword, 31–32,48,172,265–266

Index V

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and valid overloadable operators, 385 ar chitectur al issues for .NET developer s.

validation controls, 1005–1014 custom validation, 1010–1012 Ta bleproject o f Conexample, t en t s 1006–1010 properties 1006 C# and t he .NETof, Plat for m, Second Edition validation summaries, 1012–1014 I ntr oduction Pa r t One - I nt rand oducireference-based ng C# a nd the .NET P la tf109–114 or m value-based types,

Chapter 1 - The of, Philosophy comparison 113–114of .NET Chapter 2 types - Building C# Applications value containing reference types, 112–113 Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

value-based semantics, 119,125,168–169

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

value keyword, 194–195

value semantics, 118 and Obj ect Lifetim e Chapter 5 - Exceptions Chapter 6 - Iand nterreference faces and Collections value types types, 128–132 Chapter - Callback Isyntax nter faces, Delegates, variable7 initialization (C#), 104–105and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

variable scope and default assignments, 102–104

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

VB .NET Chapter 9 - Under standing .NET Assem blies C# indexer from, 374–375 Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

calculator, 15 Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Chapter 11 - Type 409–411 Pa r t client Four - application, Le ve r a ging the .NET Libr a r ie s

snap-in, building, 531–532 special names from, 384–385 Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) VB .NET and the .NET Platform (Apress, 2002), 412 Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

VBCalculator applications, 14–15 Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter VbNetSnapIn.dll, 16 - The Sy 530 stem .I O Nam espace Chapter 17 944, - Data Access 950 w ith ADO.NET VBScript, 947–948, Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

verbatim strings and escape characters, 161–162

Chapter 18 - ASP.NET Web Pages and Web Contr ols

versionable and self-describing Chapter 19 - ASP.NET Web Applicatentities ions (assemblies), 403 Chapter versioning 20 - XML Web Ser vices I ndexclass members, 220–222

shared assemblies, 437–438 List of Figur es List of objects, Tables defined, 871 view

view state, ASP.NET, 1026–1029 custom view state data, 1029 definition and basics, 1026 demonstrating (example), 1027–1029 _VIEWSTATE form field, 951 virtual directories, IIS, 938,1066 virtual keyword, 214,228 virtual members, defined, 22 virtual System.Object.Finalize() method, 260 visibility traits (CTS members), 22 type and method, 184–186 Visual Basic (VB)

default method names Item, 374 C# an d th e .N ET Plat f orm , Se con d Ed it ion runtime module, 25 ISBN:1590590554 VB 6 IDE, 57 by Andr ew Tr oelsen Apr ess © 2003 (1200 pages) VB 6.0 Object Browser utility, 520 This compr VB 6.0 programming, 4 ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and VB 6.0 Set keyword, 374 ar chitectur al issues for .NET developer s.

volatile keyword, 366 VS .NET Ta bleAdd o f Con t en t s References dialog box, 449 C# and t he .NET Plat for m, utility, Second1095 Edition Add Web Reference I ntr oduction Add Web Reference wizard, 1063 Pa r t adding One - I nt r oduci ng a nd the P la tf or m controls to C# Forms with,.NET 747–749

Chapter 1 - Thestructure, Philosophy application 62of .NET Chapter 2 - Building C# AssemblyInfo.cs file,Applications 527 Pa r t configuration Tw o - The C# files Pr ogrand, am m428–429 ing La ngua ge

Chapter debugging 3 - C# system Language exceptions Fundamentals with, 253–256

editing 942 Chapter 4 -HTML Obj ectdocuments -Or iented Prwith, ogr am ming w ith C# Enterprise edition, 921 Chapter 5 - Exceptions and Obj ect Lifetim e handling with, 255–256 Chapter 6 - Icustom nter facesexceptions and Collections implementing interfaces with, 288–290and Ev ents Chapter 7 - Callback I nter faces, Delegates,

integrated debugger, Chapter 8 - Advanced C# 56 Type Const ruction Techniques 358 Pa r t overflow Thre e - Prchecking, ogr am m i ng w i th .N ET Assem bl ie s

project -workspace, building, 612–615 Under standing .NET Assem blies Dispose() method, 614–615 Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads InitializeComponent(), 614–615 Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing referencing external assemblies via, 67–68 Pa r t Four - Le ve r a ging the .NET Libr a r ie s resource configuration with, 739–742 Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er test application, building, 61–70 Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) adding code, 67 Chapter configuring 14 - A Better Paint ing Fr amew or k ( GDI + ) a C# project, 64–65 Chapter inserting 15 - Pr ogr am ming with Windows s Contr ols new C# type definitions,Form 68–69 Chapter outlining 16 - The code, Sy stem .I O Nam espace 69–70 Chapter properties 17 - Data Access w ith window, 66 ADO.NET Pa r t Fi vereferencing - W e b Applexternal ica ti ons and X ML W e b67–68 Se r vi ces assemblies, Chapter solution 18 - ASP.NET Web Pages and Web explorer window, 62–64 Contr ols Chapter threads 19 - window, ASP.NET 483 Web Applicat ions UDDI 1103–1105 Chapter 20 interaction - XML Webwith, Ser vices I ndexunsafe compilation, 361 VS .NET List of Figur es 2003, 45 Chapter 9

List Tables VSof.NET IDE

database manipulation tools, 73–74 debugging with, 70–71 default namespace of, 175–176 features of, 71–76 HTML and, 939 Inheritance Picker, 788 integrated help, 74–76 object browser utility, 73 project solution, creating, 60–61 server explorer window, 71–72 start page, 58–59 using,57–61 writing Windows Forms code, 747 XML-related editing tools, 72–73 wizards.Seewizards

XML Web services, building with, 1069–1072

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Ta ble o f Con t en t s C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

Index W

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and warnings and errors, issuing, 86 ar chitectur al issues for .NET developer s.

Watcher class (FileSystemWatcher). SeeFileSystemWatcher class Web applications. See alsoASP.NET Web applications Ta blecreating o f Con t manually, en t s 953–958 C# and t*.aspx he .NET Plat for m, Second Edition file, coding, 954–958 I ntr oduction directive, 955 Pa r t One - I nt r oduci ngdirective, C# a nd the .NET P la tf or m 955–956

Chapter script 1 - The Philosophy of .NET blocks, 956–957 Chapter widget 2 - Building C# Applications declarations, 957–958 Pa r t creating Tw o - The C# VS Pr ogr am m961–966 ing La ngua ge with .NET,

Chapter code 3 - C# behind Language file, 965–966 Fundamentals

*.aspx file, 964–965 Chapter initial 4 - Obj ect -Or iented Pr ogr am ming w ith C# defined, 939 and Obj ect Lifetim e Chapter 5 - 936, Exceptions shutdown, 1037 Chapter 6 - I nter faces and Collections and7Web servers,I nter 936–938 Chapter - Callback faces, Delegates, and Ev ents Chapter Web controls, 8 - Advanced ASP.NET C# Type Const ruction Techniques Pa r t overview Thre e - Prof, ogr982–985 am m i ng w i th .N ET Assem bl ie s

property, Chapter AutoPostBack 9 - Under standing .NET 984–985 Assem blies event handling, 983–984 Chapter server-side 10 - Pr ocesses, AppDomains, Cont exts, and Threads System.Web.UI.Control members, Chapter 11 - Type Reflection, type Late Binding, and985–990 Attr ibute- Based Pr ogramm ing adding removing controls, Pa r t Four - Le veand r a ging the .NET Libr a r ie s988–990 986–988 Chapter contained 12 - Obj ectcontrols, Ser ialization and the .NET Remoting Lay er

System.Web.UI.WebControl type(members, Chapter 13 - Building a Bet ter Win dow Int roducin g990–991 Window s For ms) toolbox,966 validation controls, 1005–1014 Chapter 15 - Pr ogr am ming with Windows Form s Contr ols custom validation, 1010–1012 Chapter 16 - The Sy stem .I O Nam espace project example, 1006–1010 Chapter 17 - Data Access w ith ADO.NET properties of, 1006 Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces validation summaries, 1012–1014 Chapter 18 - ASP.NET Web Pages and Web Contr ols WebForm controls, examples of, 991–1005 Chapter DataGrids. 19 - ASP.NET ApplicatADO.NET ions SeeWeb DataGrids, Chapter feature-rich 20 - XML Web Ser vices controls, 995–997 I ndex HTML tables, building, 994–995 List of Figur es controls, 992 ListBox List of Tables radio button types, 992–993 scrollable, multiline TextBoxes, 993 Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Web Forms, 607–608 Web methods documenting with Description property, 1073–1074 exposing custom types from, 1096–1097 invoking CalcWS, 1071–1072 overloaded,1092–1093 types, arrays of, 1096–1097 [WebMethod] attribute ASP.NET runtime and, 1066 Description property, 1073–1074 EnableSession property, 1075–1077 MessageName property, 1074–1075 stateful Web services, building, 1075–1077 WSDL name clashes, 1074–1075

Web pages, ASP.NET. C# an dSee th eASP.NET .N ET PlatWeb f ormpages , Se con d Ed it ion Web servers ISBN:1590590554 by Andr ew Tr oelsen defined, 936–937 Apr ess © 2003 (1200 pages) GDI+ on, 1016–1019 This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and Web services, XML. SeeXML Web services ar chitectur al issues for .NET developer s.

Web sites .NET and non-Microsoft OS, 40–41 Ta ble.NET-aware o f Con t en t sprogramming languages, 10 ASP .NET C# and t he .NETIDE PlatWeb for m, Matrix, Second90 Edition C# compiler (csc.exe) download, 43 I ntr oduction support article, 1063 Pa r t DISCO One - I nt r oduci ng C# a nd the .NET P la tf or m Dotnetfx.exe package (Microsoft), 40 Chapter 1 - The Philosophy of .NET hyperthreading, 453 Chapter 2 - Building C# Applications 89m ing La ngua ge Pa r t SharpDevelop Tw o - The C# PrIDE, ogr am WebService behaviors article, 1061 Chapter 3 - C# Language Fundamentals web.config 1050–1057 Chapter 4 - file, Obj ect -Or iented Pr ogr am ming w ith C# configuring session and stateObj with, 1077 e Chapter 5 - Exceptions ect Lifetim custom , 1057 Chapter 6 - Web I nter settings faces andwith Collections

elements of, 1052I nter faces, Delegates, and Ev ents Chapter 7 - Callback

error output with , 1053–1054 - Advanced C# Type Const ruction Techniques storing state with , 1054–1056 Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s tracing with , 1052–1053 Chapter 8 Chapter 9

- Under standing .NET Assem blies

WebControl base classAppDomains, properties, 990–991 Chapter 10 - Pr ocesses, Cont exts, and Threads Chapter 11 -controls, Type Reflection, Late and Attr ibute- Based Pr ogramm ing WebForm examples of,Binding, 991–1005 Pa r t DataGrids. Four - Le veSee r a ging the .NET ADO.NET Libr a r ie s DataGrids,

Chapter feature-rich 12 - Obj ect controls, Ser ialization 995–997 and the .NET Remoting Lay er

HTML building, 994–995 Chapter 13 tables, - Building a Bet ter Win dow ( Int roducin g Window s For ms) ListBox 992 ing Fr amew or k ( GDI + ) Chapter 14 - controls, A Better Paint radio types, 992–993 Chapter 15button - Pr ogr am ming with Windows Form s Contr ols scrollable, multiline 993 Chapter 16 - The Sy stem .ITextBoxes, O Nam espace Chapter [WebService] 17 - Data attribute, Access 1077–1078 w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

directive, 1066

Chapter 18 - ASP.NET Web Pages and Web Contr ols

while and do/while looping constructs, 136–137

Chapter 19 - ASP.NET Web Applicat ions

widget 20 declarations, Chapter - XML WebASP.NET, Ser vices 957–958 I ndex wildcard character (*), 50 List of Figur es Win32 List of Tables and processes under, 451–453 threads

WIN32API,260 wincv.exe desktop application, 39 Windows DNA (Distributed iNternet Architecture) programming, 6 Windows file header, 397–398 Windows Forms, 607–669 applications, building extendible, 532–534 building menus with, 644–646 Menu type members, 645 Menu$MenuItemCollection type, 645–646 Car Logger application, 834–841 Add New Car logic, 837–838 serialization logic, 838–840 client, building (XML Web services), 1097 Component class, 622

ContainerControl class, 637 an d th e .N ET Plat f orm , Se con d Ed it ion Control class,C# 623–627, 633–636 ISBN:1590590554 by Andr ew Tr oelsen Control class example, 634–635 Apr ess © 2003 (1200 pages) control methods, 634 This compr 624–626 ehensiv e text star ts w ith a brief ov er view of the Form styles, setting, C# language and then quickly m oves to key technical and members of, 624 ar chitectur al issues for .NET developer s. painting basics, 635–636 properties of, 623,633 Control Ta ble o f Con tevents, en t s 627–631 control class example, 627–628 C# and t he .NET Plat for m, Second Edition Mouse events, responding to, 628–631 I ntr oduction MouseEventArgs type properties, 629 Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m controls,683–684 Chapter 1 - The Philosophy of .NET example,914–916 Chapter 2 - Building C# Applications Form class, 637–640 Pa r t Tw o - The C# Pr ogr am m ing La ngua ge example,639–640 Chapter 3 - C# Language Fundamentals key methods of, 638–639 Chapter properties 4 - Obj ectof, -Or638 iented Pr ogr am ming w ith C# Chapter select 5 - Exceptions events of,and 639Obj ect Lifetim e Chapter 6 I nter faces and Collections Form level events, handling with VS .NET, 643–644 Chapter 7 Callback I nter faces, Forms, anatomy of, 621–622Delegates, and Ev ents Chapter - Advanced C# Type Const ruction Techniques GUI8namespaces, 607–608 Pa r t Keyboard Thre e - Pr ogr am m iresponding ng w i th .N ETto, Assem bl ie s events, 631–633 Chapter MDI9applications, - Under standing building, .NET666–669 Assem blies 668 AppDomains, Cont exts, and Threads Chapter child 10 - Form, Pr ocesses, 668–669 Chapter child 11 - windows, Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing parent Pa r t Four - Le veForm, r a ging666–667 the .NET Libr a r ie s menus Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er with VS .NET, 654–655 Chapter building 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) menu system, building, 646–649 Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) MenuItem type properties, 651–653 Chapter 15 - Pr ogr am ming with Windows Form s Contr ols pop-up, creating, 649–651 Chapter 16 - The Sy stem .I O Nam espace ScrollableControl class, 636–637 Chapter 17 - Data Access w ith ADO.NET Status bars, 655–660 Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces building,656–657 Chapter 18 - ASP.NET Web Pages and Web Contr ols menu selection prompts, 659–660 Chapter 19 - ASP.NET Web Applicat ions select properties of, 655 Chapter StatusBarPanel 20 - XML Web Ser vices type properties, 656 I ndex Timer type, 658–659 List of Figur es System.Windows.Forms namespace overview, 608 List of Tables System.Windows.Forms.Application class, 615–621 Application class example, 617–618 ApplicationExit event, 619 core properties of, 616–617 events of, 617 methods,616 preprocessing messages with, 619–621 Tool bars, building, 660–664 adding images to Tool bar buttons, 663–664 ToolBar type properties, 660–661 ToolBarButton type properties, 661 Tool bars, building at design time, 664–666 types, interacting with, 609–612 Main window, building, 610–612 project work space, preparing, 609 VS .NET project workspace, building, 612–615

Dispose() method, 614–615 C# an d th e .N ET Plat f orm , Se con d Ed it ion InitializeComponent(), 614–615 ISBN:1590590554 by type Andrlife-cycle, ew Tr oelsen Windows Form 640–643 Apr ess © 2003 (1200 pages) Form life time events, 640–641 Thisexample, compr ehensiv e text star ts w ith a brief ov er view of the Form lifetime 642–643 C# language and then quickly m oves to key technical and

Windows Forms Controls, ar chitectur743–803 al issues for .NET developer s. adding to Forms, 744–747 adding to Forms with VS .NET, 747–749 Ta bleanchoring o f Con t enbehavior, ts configuring, 779–780 animation, 796 C# and t he .NET Plat for m, Second Edition assigning ToolTips to, 769–770 I ntr oduction type, 752–755 Pa r t Button One - I nt r oduci ng C# a nd the .NET P la tf or m configuring, Chapter content 1 - Theposition, Philosophy of .NET 753 754–755 Chapter example, 2 - Building C# Applications Pa r t CarControl Tw o - The C# Pr ogr am m ing La ngua ge defining, 794 Chapter custom 3 - C# events, Language Fundamentals custom properties, defining, 794–796 Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C# design time appearance of, 800–803 Chapter 5 - Exceptions and Obj ect Lifetim e implementing, 792–796 Chapter 6 - I nter faces and Collections testing,797–798 Chapter 7 - Callback I nter faces, Delegates, and Ev ents CheckBoxes, 755–756 Chapter 8 - Advanced C# Type Const ruction Techniques custom dialog boxes, building, 781–787 Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s application example, 782–785 Chapter DialogResult 9 - Under standing .NET Assem blies property, 785 Chapter grabbing 10 - Pr ocesses, AppDomains, data from, 785–787Cont exts, and Threads Chapter 11 Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing custom UserControl, building, 790–791 Pa r t custom Four - LeWindows ve r a ging Forms the .NET Libr a r ie s Controls, building, 789–790 Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er DateTime type, 766–767 Chapter 13 -input Building a Bet767 ter Win dow ( Int roducin g Window s For ms) default Button, Chapter design 14 -time A Better GUI, Paint building, ing Fr792 amew or k ( GDI + ) docking configuring, 780–781 Chapter 15 - behavior, Pr ogr am ming with Windows Form s Contr ols DomainUpDown and NumericUpDown Controls, 774–776 Chapter 16 - The Sy stem .I O Nam espace ErrorProvider type, 776–778 Chapter 17 - Data Access w ith ADO.NET 787–789 Pa r t Form Fi ve - inheritance, W e b Appl ica ti ons and X ML W e b Se r vi ces hierarchy of, 743–744 Chapter 18 - ASP.NET Web Pages and Web Contr ols images, 791 Applicat ions Chapter 19 - creating, ASP.NET Web ListBoxes and ComboBoxes, 761–763 Chapter 20 - XML Web Ser vices MonthCalendar Control, 763–766 I ndex Panel Controls, 773 List of Figur es pet name rendering, 796 List of Tables RadioButtons and GroupBoxes, 756–760 CheckedListBox Control, 758–760 example,756–758 System.ComponentModel namespace, 798–799 tab order, configuring, 768 TextBox control, 749–752 TrackBar Control, 770–772 Up/Down Controls, 774–776 Windows OS 2000 and XP Professional, 937 Windows service and hosting remote objects, 597–598 wire protocols, 1086–1089 HTTP GET and HTTP POST messages, 1087 SOAP messages, 1088–1089 wizards Add Member, 228

Add Web Reference, 1063 an d th e .N ET Plat f orm , Se con d Ed it ion Data Adapter C# Configuration, 922–926 ISBN:1590590554 by Andr ew Tr oelsen Data Adapters and design time connections, 926–927 Apr ess © 2003 (1200 pages) Property Builder, 1000 This compr ehensiv e text star ts w ith a brief ov er view of the Solutions Explorer, 919–921 C# language and then quickly m oves to key technical and SQL connection, 921–922 ar chitectur al issues for .NET developer s. Tab Order, 768 WKO (Well Known Object) types Ta bleactivation o f Con t en mode ts of, 576–577

CAO/WKO-singleton objects,Edition 589–595 C# and t he .NET Plat for m, Second characteristics of, 587 I ntr oduction of, Pa r t configuration One - I nt r oduci ng565 C# a nd the .NET P la tf or m defined, Chapter 1 - 564 The Philosophy of .NET Chapter 2 - Building C# Applications WM_LBUTTONDOWN message, 619–621 Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

WNDCLASSEX structure, 624

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

worker threads, 452–453

write-only read-only properties, 197–198 Chapter 5 and - Exceptions and Obj ect Lifetim e Chapter 6 method, - I nter faces WriteTo() 821and Collections Chapter 7 Callback I nter faces, Delegates, and Ev ents WriteXml() method, 883 Chapter 8

- Advanced C# Type Const ruction Techniques

WriteXmlSchema() method, 885

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Writing9Add-Ins forstanding VS .NET (Apress, 2002), 534 Chapter - Under .NET Assem blies Chapter - PrService ocesses,Description AppDomains, Cont exts, and Threads WSDL 10 (Web Language) Chapter contract, 11 - Type 1068Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t defined, Four - Le1063 ve r a ging the .NET Libr a r ie s

document Chapter 12 - Objformat, ect Ser 1079–1082 ialization and the .NET Remoting Lay er element, Chapter 13 - Building a Bet ter1082 Win dow ( Int roducin g Window s For ms) Chapter 14 - A Betterelement, Paint ing 1081 Fr amew or k ( GDI + )

1081 Chapter 15 - Pr ogr amelement, ming with Windows Form s Contr ols element, Chapter 16 - The Sy stem .I O 1082 Nam espace

element, 1080 fundamentals of, 1078–1079 Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces name clashes, 1074–1075 Chapter 18 - ASP.NET Web Pages and Web Contr ols transforming into C# code, 1089–1091 Chapter 19 - ASP.NET Web Applicat ions proxy code, 1089–1091 Chapter 20 - XML Web Ser vices wrapping proxy type in .NET namespace, 1091 I ndex wsdl.exe command line utility, 1079,1084–1086 Chapter 17 - Data Access w ith ADO.NET

List of Figur es List of Tables

Index X

C# an d th e .N ET Plat f orm , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

ISBN:1590590554

This compr ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and XML (Extension Markup Language) ar chitectur al issues for .NET developer s.

configuration files, 426–429 data representation Ta ble o f configuring Con t en t s in DataColumns, 857–858 passing information with, 1060 C# and t he .NET Plat for m, Second Edition documenting source code via, 76–79 I ntr oduction files, viewing generated, 79–81 Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m format characters, 80 Chapter 1 - The Philosophy of .NET formatter (serialization), 548 Chapter 2 - Building C# Applications XML-based DataSets, 883–885 Pa r t Tw o - The C# Pr ogr am m ing La ngua ge XML-related editing tools, 72–73 Chapter 3

- C# Language Fundamentals

XML Web -services, 1059–1105 Obj ect -Or iented Pr ogr am ming w ith C# arrays of Web method types, 1096–1097 Chapter 5 - Exceptions and Obj ect Lifetim e building manually, 1065–1066 Chapter 6 - I nter faces and Collections building with VS .NET, 1069–1072 Chapter 7 - Callback I nter faces, Delegates, and Ev ents adding functionality, 1071 Chapter 8 - Advanced C# Type Const ruction Techniques CalcWS Web methods, 1071–1072 Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s code behind file (*.asmx.cs), 1070–1071 Chapter 9 - Under standing .NET Assem blies CarSalesInfoWS project, 1100–1102 Chapter 10 Pr ocesses, AppDomains, Cont exts, and Threads custom types Chapter consuming, 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing 1099–1100 Pa r t Four Le ve r a ging the .NET Libr a r ie s exposing,1098–1099 Chapter 12 - Objservice, ect Ser ialization description 1063 and the .NET Remoting Lay er Chapter 13 Building a Bet ter Win dow ( Int roducin g Window s For ms) discovery service, 1062–1063 Chapter generating 14 - A Better proxy Paint with VS ing Fr .NET, amew1095 or k ( GDI + ) hard-coded proxy logic, 1094 Chapter 15 - Pr ogr am ming with Windows Form s Contr ols HelloWS WSDL document, 1082–1084 Chapter 16 - The Sy stem .I O Nam espace invocations Chapter 17 - Data Access w ith ADO.NET Pa r t Fi veasynchronous, - W e b Appl ica1093–1094 ti ons and X ML W e b Se r vi ces Chapter synchronous, 18 - ASP.NET1092–1093 Web Pages and Web Contr ols namespaces, 1064 Chapter 19 - ASP.NET Web Applicat ions overview of, 1059–1061 Chapter 20 - XML Web Ser vices System.Web.Services namespace, 1064–1065 I ndex System.Web.Services.WebService base class, 1072–1073 List of Figur es testing,1066–1069 List of Tables compiled .NET assembly, viewing, 1068–1069 WSDL contract, viewing, 1068 transport protocol, 1063 UDDI (Discovery Service Protocol), 1102–1105 [WebMethod] attribute, 1073–1077 Description property, 1073–1074 EnableSession property, 1075–1077 MessageName property, 1074–1075 stateful Web services, building, 1075–1077 WSDL name clashes, 1074–1075 [WebService] attribute, 1077–1078 Windows Forms client, building, 1097 wire protocols, 1086–1089 HTTP GET and HTTP POST messages, 1087 SOAP messages, 1088–1089 WSDL document format, 1079–1082 Chapter 4

element, 1082 C# an d th e .N ET Plat f orm , Se con d Ed it ion

element, 1081 ISBN:1590590554 byelement, Andr ew Tr oelsen

1081 Apr ess © 2003 (1200 pages) element, 1082 This compr element, 1080ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and WSDL fundamentals, 1078–1079 ar chitectur al issues for .NET developer s. WSDL, transforming into C# code, 1089–1091 proxy code, 1089–1091 Ta ble o f wrapping Con t en t sproxy type in .NET namespace, 1091 wsdl.exe command line utility, 1084–1086 C# and t he .NET Plat for m, Second Edition XMLSerializer data type, 1098–1099 I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables

C# an d th e .N ET Plat f orm , Se con d Ed it ion List of Figures by Andr ew Tr oelsen

ISBN:1590590554

Apr ess © 2003 (1200 pages)

Chapter 1: This Thecompr Philosophy ofts .NET ehensiv e text star w ith a brief ov er view of the C# language and then quickly m oves to key technical and ar chitectur al issues .NET developer Figure 1-1: The CLR, CTS, CLSfor base class librarys.relationship

Figure 1-2: All .NET-aware compilers emit IL instructions and metadata. Ta ble o f Con t en t s

Figure 1-3: Plat mscoree.dll in action C# and t he .NET for m, Second Edition I ntr oduction

Figure 1-4: The base class libraries

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - 1-5: The Your Philosophy of .NET Figure new best friend, ildasm.exe Chapter 2 - Building C# Applications

Figure 1-6: the underlying CIL Pa r t Tw o - The C#Viewing Pr ogr am m ing La ngua ge Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Figure 1-7: Dumping namespace information to file

Chapter 5 - 1-8: Exceptions andCIL Objto ectfile Lifetim e Figure Dumping Chapter 6

- I nter faces and Collections

Figure Viewing metadata viaand ildasm.exe Chapter 7 - 1-9: Callback I ntertype faces, Delegates, Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Figure 1-10: Double click here to view the assembly manifest.

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - 1-11: UnderViewing standingtypes .NET using Assemthe bliesClassViewer Web application Figure Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Figure wincv.exe Chapter 11 - 1-12: Type Working Reflection,with Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 2: Building C# Applications

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - 2-1: A Better Paint ing the Fr amew ( GDI + ) Figure Establishing pathortok csc.exe Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure TestApp in espace action Chapter 16 - 2-2: The The Sy stem .I O Nam Chapter 17 - Data Access w ith ADO.NET

Figure 2-3: Your first Windows Forms application

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - 2-4: ASP.NET Webthe Pages and response Web Contrfile ols Figure Behold, default Chapter 19 - ASP.NET Web Applicat ions

Figure Chapter 20 - 2-5: XMLDocumenting Web Ser vices the bug I ndex

Figure 2-6: The entire bug report

List of Figur es

List ofFigure Tables 2-7: Debugging at the command line

Figure 2-8: The Projects tab of the VS .NET Start Page Figure 2-9: The My Profile tab of the VS .NET Start Page Figure 2-10: The New Project dialog box Figure 2-11: The Solution Explorer Figure 2-12: Class View Figure 2-13: Type sorting options Figure 2-14: Configuring your C# project starts here. Figure 2-15: File names may be changed using the Properties window.

Figure 2-16: Class names can also be changed using the Properties window. C# an d th e .N ET Plat f orm , Se con d Ed it ion

ewReferences Tr oelsen Figure 2-17: by TheAndr Add dialog box

ISBN:1590590554

Apr ess © 2003 (1200 pages)

Figure 2-18: This Collapsing the SayHi() compr ehensiv e text method star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

Figure 2-19: ar Setting breakpoints chitectur al issues for .NET developer s. Figure 2-20: The Server Explorer window Ta ble o f Con t en t s

Figure 2-21: The integrated XML editor

C# and t he .NET Plat for m, Second Edition

I ntr oduction Figure 2-22: The integrated Object Browser Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Figure Integratedofdatabase editors Chapter 1 - 2-23: The Philosophy .NET Chapter 2

- Building C# Applications

Figure 2-24: Visual Studio .NET Integrated Help

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - 2-25: C# Language Fundamentals Figure Remember, F1 is your friend. Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C#

Figure Again,and F1 Obj is your friend.e Chapter 5 - 2-26: Exceptions ect Lifetim Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Figure 2-27: Specifying the XML documentation file via VS .NET

Chapter 8 - 2-28: Advanced C# Type Const ruction Techniques Figure XmlCarDoc.xml Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure yourblies HTML-based documentation Chapter 9 - 2-29: UnderConfiguration standing .NET of Assem Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Figure 2-30: The generated XmlCarDoc online documentation

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le2-31: ve r a ging the .NET Libr a r ie s Figure Regions at work

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Figure Configuring debug Chapter 13 - 2-32: Building a Bet ter Win dow or ( Intrelease roducin builds g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Figure 2-33: Setting project-wide symbols

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - 2-34: The Sy stem .I Oline Nam espace within VS .NET Figure Viewing numbers Chapter 17 - Data Access w ith ADO.NET

Obtaining various Pa r t FiFigure ve - W 2-35: e b Appl ica ti ons and X MLenvironment W e b Se r vi cesvariables Chapter 18 - ASP.NET Web Pages and Web Contr ols

Chapter 3: C# Language Fundamentals

Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices

I ndex Figure 3-1: Supplying and processing command line arguments List of Figur es

Figure 3-2: Setting command arguments via VS .NET

List of Tables

Figure 3-3: Simple constructor logic Figure 3-4: Viewing default values for member data Figure 3-5: Basic IO using System.Console Figure 3-6: Simple format characters Figure 3-7: String format flags in action Figure 3-8: Assignment of value types results in a verbatim copy of each field. Figure 3-9: Assignment of reference types copies the reference. Figure 3-10: The internal references point to the same object! Figure 3-11: Default implementation of select System.Object members

Figure 3-12: C# Overridden initaction an d th e System.Object .N ET Plat f orm ,members Se con d Ed ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Figure 3-13: The hierarchy of System types

ISBN:1590590554

comprteenager ehensiv e chatter text star ts w ith a brief ov er view of the Figure 3-14: This Random C# language and then quickly m oves to key technical and chitectur foramong .NET developer s. Figure 3-15: ar Static dataalisissues shared like objects.

Figure 3-16: Passing reference types by value locks the reference in place. Ta ble o f Con t en t s

Figure 3-17: Passing reference types by reference allows the reference to be redirected. C# and t he .NET Plat for m, Second Edition I ntr oduction

Figure 3-18: A multidimensional array

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - 3-19: The Philosophy of .NET Figure Jagged arrays Chapter 2

- Building C# Applications

Figure 3-20: Fun Pa r t Tw o - The C# Pr ogrwith am mSystem.Array ing La ngua ge Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Figure 3-21: Configuring the default namespace

Chapter 4: faces Object-Oriented Programming with C# - I nter and Collections

Chapter 6 Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Figure A simple definition Chapter 8 - 4-1: Advanced C# class Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure 4-2: Internal and public types

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - 4-3: Pr ocesses, AppDomains, Cont exts, and Threads Figure The "is-a" relationship Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Figure relationship Pa r t Four - Le4-4: ve r aThe ging"has-a" the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Figure 4-5: Classical polymorphism

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - 4-6: A Better Paint ing Fr amew or k ( GDI + ) Figure Ad hoc polymorphism Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure value "value" when setting EmpID to 81 Chapter 16 - 4-7: The The Sy stem .I O of Nam espace Chapter 17 - Data Access w ith ADO.NET

Figure 4-8: Properties map to hidden get_ and set_ methods.

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - 4-9: ASP.NET Web Pageshierarchy and Web Contr ols Figure The employee Chapter 19 - ASP.NET Web Applicat ions

Figure The Ser extended Chapter 20 - 4-10: XML Web vices employee hierarchy I ndex

Figure 4-11: The contained Radio in action

List of Figur es

List ofFigure Tables 4-12: The current employee hierarchy does not honor polymorphism.

Figure 4-13: A better bonus system (thanks to polymorphism) Figure 4-14: Our current shapes hierarchy Figure 4-15: Virtual methods do not have to be overridden. Figure 4-16: Better! Abstract members must be overridden. Figure 4-17: Versioning the Draw() method Figure 4-18: Adding a new class via VS .NET Figure 4-19: The Add Class Wizard Figure 4-20: Specifying the base class

Figure 4-21: Implementing (not inheriting) select interfaces C# an d th e .N ET Plat f orm , Se con d Ed it ion

ewMember Tr oelsenWizard Figure 4-22: by TheAndr Add

ISBN:1590590554

Apr ess © 2003 (1200 pages) compr ehensiv eand text star ts w ith a brief ov er view of the Chapter 5: This Exceptions Object Lifetime C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Figure 5-1: Dealing with the error using structured exception handling Ta ble Figure o f Con t5-2: en t sObtaining detailed error information C# and t he .NET Plat for m, Second Edition

Figure 5-3: Identifying the exceptions thrown from a given method

I ntr oduction Pa r t One - I nt5-4: r oduci ng C# a ndand thesystem .NET P la tf or m Figure Application exceptions

Chapter 1

- The Philosophy of .NET Figure You C# have just entered no-man's land. Chapter 2 - 5-5: Building Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Figure 5-6: Preparing to enable VS .NET exception handling

Chapter 3

- C# Language Fundamentals

Chapter 4 - 5-7: Obj ect -OrCLR iented Pr ogr am set ming w ith C# Figure The exception Chapter 5

- Exceptions and Obj ect Lifetim e Figure VS .NET exception support for a given exception Chapter 6 - 5-8: I nterSpecifying faces and Collections Chapter 7

Callback I nter faces, Delegates, and Ev ents Figure- 5-9: Enabling your custom application exceptions via VS .NET

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w iyour th .N custom ET Assem bl ie s Figure 5-10: Handling application

Chapter 9

exceptions via VS .NET

- Under standing .NET Assem blies

Figure Reference types are allocated the managed heap. Chapter 10 - 5-11: Pr ocesses, AppDomains, Cont exts, andonThreads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Figure 5-12: Finalizers are called automatically upon application shutdown.

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - 5-13: Obj ectThe Serinterplay ialization of andfinalization the .NET Remoting Lay er Figure and disposal Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Figure Influencing anamew object's Chapter 14 - 5-14: A Better Paint ing Fr or k (current GDI + ) generation Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 6: Interfaces and Collections

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Pa r t FiFigure ve - W 6-1: e b Appl Theicaupdated ti ons and shapes X ML Whierarchy e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Figure 6-2: Dynamically determining implemented interfaces

Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 - 6-3: XMLInterfaces Web Ser vices Figure as parameters I ndex List ofFigure Figur es6-4: A versioned interface hierarchy List of Tables

Figure 6-5: Implementing interfaces via VS .NET Figure 6-6: Specifying interfaces for new types Figure 6-7: MemberwiseClone() copies references, not values. Figure 6-8: Now you have a true deep copy. Figure 6-9: Comparing automobiles based on car ID Figure 6-10: Sorting automobiles by pet name Figure 6-11: The System.Collections interface hierarchy Figure 6-12: Fun with System.Collections.ArrayList Figure 6-13: System.Collections.Queue at work

Figure 6-14: System.Collections.Stack type at work

C# an d th e .N ET Plat f orm , Se con d Ed it ion

ew Tr oelsen Figure 6-15: by TheAndr updated Cars container

ISBN:1590590554

Apr ess © 2003 (1200 pages) compr ehensiv e text star ts w ith a brief ov er viewand of theEvents Chapter 7: This Callback Interfaces, Delegates, C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Figure 7-1: An interface-based event protocol Ta ble Figure o f Con t7-2: en t sThe C# "delegate" keyword represents a sealed type deriving from

System.MulticastDelegate.

C# and t he .NET Plat for m, Second Edition I ntr oduction Figure 7-3: Dynamically "pointing to" various methods Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter Figure 1 - 7-4: The Remember! Philosophy ofC# .NET delegate types alias System.MulticastDelegate Chapter 2

- Building C# Applications

Figure 7-5: buck Pa r t Tw o - The C#Passing Pr ogr amthe m ing La ngua ge Chapter 3

C# Language Fundamentals Figure- 7-6: Passing the buck yet again

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter Figure 5 - 7-7: Exceptions Asynchronous and Obj ect invocations Lifetim e increase program responsiveness. Chapter 6

- I nter faces and Collections

Figure- 7-8: Asynchronous invocations via callbacks Callback I nter faces, Delegates, and Ev ents

Chapter 7

Chapter 8 - 7-9: Advanced C# into Typethe Const ruction Techniques Figure Hooking engine events Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 8: Advanced C# Type Construction Techniques

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Figure 8-1: Enabling VS .NET overflow checking

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - 8-2: Obj ect Ser ialization and unsafe the .NET Remoting Lay er Figure Enabling VS .NET compilation Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Figure Internal of+ overloaded operators Chapter 14 - 8-3: A Better PaintCIL ing representation Fr amew or k ( GDI ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure 8-4: CIL representation of user-defined conversion routines

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Chapter 9: Understanding .NET Assemblies

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Figure Assembly Win32 ions header file information Chapter 19 - 9-1: ASP.NET Web Applicat Chapter 20 - XML Web Ser vices I ndex

Figure 9-2: A single file assembly

List ofFigure Figur es9-3: A multifile assembly List of Tables

Figure 9-4: The physical view of a .NET assembly Figure 9-5: The logical view of a .NET assembly Figure 9-6: Creating a C# code library (e.g., a managed *.dll) Figure 9-7: Referencing external .NET assemblies begins here. Figure 9-8: Local copies of (non-shared) assemblies are placed in your Debug folder. Figure 9-9: Selecting a VB .NET Windows Forms Application Figure 9-10: A painfully simple GUI Figure 9-11: Cross-language inheritance in action Figure 9-12: An MC++ project workspace

Figure 9-13: Your car library as seen via ildasm.exe

C# an d th e .N ET Plat f orm , Se con d Ed it ion

ISBN:1590590554 Andr ew Tr oelsen Figure 9-14: by Type metadata for the types within carlibrary.dll

Apr ess © 2003 (1200 pages)

Figure 9-15: This Yourcompr multifile assembly ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

Figure 9-16: ar The ufo.netmodule chitectur al issues for .NET developer s.

Figure 9-17: A single module of the multifile assembly Ta ble o f Con t en t s

Figure 9-18: *.netmodules are loaded on demand.

C# and t he .NET Plat for m, Second Edition

I ntr oduction Figure 9-19: Relocating CarLibrary.dll into a specific subdirectory Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Figure Working with the app.config file Chapter 1 - 9-20: The Philosophy of .NET Chapter 2

- Building C# Applications

Figure 9-21: Preventing automatic re-copying of private assemblies

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - 9-22: C# Language Fundamentals Figure The Global Assembly Cache Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C#

Figure Using and sn.exe to generate Chapter 5 - 9-23: Exceptions Obj ect Lifetim e the public/private key pair file Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Figure 9-24: A strongly named assembly documents the public key in the manifest.

Chapter 8 - 9-25: Advanced C# Type named, Const ruction Techniques Figure Our strongly shared assembly (version 1.0.0.0) Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure the current version of SharedAssembly.dll Chapter 9 - 9-26: UnderFreezing standing .NET Assem blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Figure 9-27: Side-by-side execution

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le9-28: ve r a ging .NETGAC Libr asubdirectory r ie s Figure The the hidden

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Figure Inside the subdirectory Chapter 13 - 9-29: Building a Bet terhidden Win dow\SharedAssembly ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Figure 9-30: Behold! The GAC's internal copy of sharedassembly.dll

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - 9-31: The Sy stem .I O Nam espace Figure Our publisher policy assembly Chapter 17 - Data Access w ith ADO.NET

The .NET administration Pa r t FiFigure ve - W 9-32: e b Appl ica ti ons and X ML W e b Seutility r vi ces Chapter 18 - ASP.NET Web Pages and Web Contr ols

Figure 9-33: Declaratively building a *.config file

Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 - 9-34: XML Web Ser vicesCarLibrary.dll to VS .NET developers Figure Suggesting I ndex

Chapter 10: Processes, AppDomains, Contexts, and Threads

List of Figur es List of Tables

Figure 10-1: The Windows Task Manager Figure 10-2: The Win32 process / thread relationship Figure 10-3: Enumerating running processes Figure 10-4: Enumerating the threads within a running process Figure 10-5: Enumerating the loaded modules within a running process Figure 10-6: Enumerating assemblies within a given app domain (within a given process) Figure 10-7: A single process with two application domains Figure 10-8: The AppDomainManipulator.exe process under the hood Figure 10-9: Processes, application domains, and context boundaries

Figure 10-10:C#Investigating an d th e .Nan ET object's Plat f ormcontext , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Figure 10-11: Your first multithreaded application

ISBN:1590590554

ehensiv e text star ts w ith a brief ov er view of the Figure 10-12:This Thecompr VS .NET Threads window C# language and then quickly m oves to key technical and chitectur al issues .NET developer Figure 10-13:arTwo threads eachfor performing a units.of work

Figure 10-14: Possible output of the MultiThreadSharedData application Ta ble o f Con t en t s

Figure 10-15: possible output of the MultiThreadSharedData application C# and t he .NET PlatAnother for m, Second Edition I ntr oduction

Figure 10-16: Consistent output of the MultiThreadSharedData application

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - 10-17: The Philosophy of not .NET Figure Many (but all) .NET types are already thread-safe . Chapter 2 - Building C# Applications

Figure 10-18: (very useful) console-based Pa r t Tw o - The C# PrThe ogr am m ing La ngua ge Chapter 3

clock application

- C# Language Fundamentals

- Obj ect -Or iented Reflection, Pr ogr am ming w ithLate C# Chapter 11: Type Binding, and Attribute-Based Chapter 5 - Exceptions and Obj ect Lifetim e Programming Chapter 6 - I nter faces and Collections Chapter 4

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Figure 11-1: Viewing an assembly's metadata

Pa r t Thre e - Pr ogr am m i ng w i th ET Assem bl ie s Figure 11-2: Reflecting on.NFoo

Chapter 9

- Under standing .NET Assem blies

Figure Reflecting on a private Chapter 10 - 11-3: Pr ocesses, AppDomains, Cont assembly exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Figure 11-4: Late bound method invocation

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - 11-5: Obj ectAttributes Ser ialization and the .NET Remoting Lay er Figure in action Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Figure Attributes via ildasm.exe Chapter 14 - 11-6: A Better Paint ingseen Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure 11-7: Metadata value

Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - 11-8: Data Access w ith ADO.NET Figure Input for a snap-in module Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Figure Snapping in external assemblies Chapter 18 - 11-9: ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Chapter 12: Object Serialization and the .NET Remoting Layer

Chapter 20 - XML Web Ser vices I ndex

List ofFigure Figur es12-1: A simple object graph List of Tables

Figure 12-2: The Serializable and NonSerialized attributes Figure 12-3: JamesBondCar serialized using a BinaryFormatter Figure 12-4: JamesBondCar serialized using a SoapFormatter Figure 12-5: The serialization process Figure 12-6: Custom serialization Figure 12-7: A high-level view of the default .NET Remoting architecture Figure 12-8: The server's output Figure 12-9: The client's output Figure 12-10: Enumerating client-side channels

Figure 12-11: Server-side statistics

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Andr ew Tr oelsenare shared among remote ISBN:1590590554 Figure 12-12:bySingleton WKOs clients. Apr ess © 2003 (1200 pages)

Figure 12-13:This Single call WKOs maintain relationship with their remote clients. compr ehensiv e text star tsawone-to-one ith a brief ov er view of the C# language and then quickly m oves to key technical and

Figure 12-14:arThe default lease for information for CarProvider chitectur al issues .NET developer s.

Figure 12-15: Altering lease timing via a server-side *.config file Ta ble o f Con t en t s

Figure 12-16: Creating a new Windows Service project workspace

C# and t he .NET Plat for m, Second Edition

I ntr oduction Figure 12-17: Including an installer for the custom Windows Service Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Figure The Windows Services Applet Chapter 1 - 12-18: The Philosophy of .NET Chapter 2

- Building C# Applications

Chapter 13: Building a Better Window (Introducing Windows Forms)

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4 - 13-1: Obj ectThe -Or iented Pr ogr w ith C# Figure minimal setam of ming assembly references Chapter 5

- Exceptions and Obj ect Lifetim e Figure A simple main window a la Windows Forms Chapter 6 - 13-2: I nter faces and Collections Chapter 7

Callback I nter faces, Delegates, and Ev ents Figure- 13-3: Specifying /t—winexe within VS .NET

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m iWindows ng w i th .NForms ET Assem bl ie s Figure 13-4: The project

Chapter 9

workspace

- Under standing .NET Assem blies

Figure The Form DesignerCont exts, and Threads Chapter 10 - 13-5: Pr ocesses, AppDomains, Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Figure 13-6: The Properties window provides design time editing support.

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - 13-7: Obj ectReading Ser ialization and the Remoting Lay er Figure attributes via.NET the Application type Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Figure ThePaint derivation of a or custom Chapter 14 - 13-8: A Better ing Fr amew k ( GDI Form +)

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure 13-9: ControlStyles.ResizeRedraw = false

Chapter 16 - The Sy stem .I O Nam espace Chapter Figure 17 - 13-10: Data Access ControlStyles.ResizeRedraw w ith ADO.NET = true Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Figure Intercepting Chapter 18 - 13-11: ASP.NET Web Pageskey andpresses Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Figure 13-12: Scroll Form GUI

Chapter 20 - XML Web Ser vices I ndex Figure 13-13: Form events List of Figur es

Figure 13-14: Form events

List of Tables

Figure 13-15: Menu-centric types of Windows Forms Figure 13-16: A more elaborate main menu Figure 13-17: Check-marking a menu item Figure 13-18: The integrated menu editor of VS .NET Figure 13-19: Handing menu-centric events using VS .NET Figure 13-20: A custom status bar Figure 13-21: A custom tool bar Figure 13-22: Toolbars a la VS .NET Figure 13-23: Assigning an ImageList via VS .NET

Figure 13-24:C#Assigning to fToolBar an d th e images .N ET Plat orm , Se buttons con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Figure 13-25: The parent window's menu system

ISBN:1590590554

compr ehensiv e text star ts w ith a brief ov er view of the Figure 13-26:This Spawning child windows C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Chapter 14: A Better Painting Framework (GDI+) Ta ble Figure o f Con t14-1: en t s A simple GDI+ application C# and t he .NET Plat for m, Second Edition

Figure 14-2: The default coordinate system of GDI+ I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Figure 14-3: Rendering via pixel units

Chapter 1

- The Philosophy of .NET

Chapter 2 - 14-4: Building C# Applications Figure Rendering via inch units Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Figure The result of applying page offsets Chapter 3 - 14-5: C# Language Fundamentals Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Figure 14-6: Altering coordinate and measurement modes

Chapter 6 - 14-7: I nter faces and Collections Figure The stock .NET color dialog Chapter 7 - Callback I nter faces, Delegates, and Ev ents

Figure Gathering statistics of the Verdana font family Chapter 8 - 14-8: Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure 14-9: Font metrics

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - 14-10: Pr ocesses, AppDomains, exts, and Threads Figure Menu layout of theCont FontApp project Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Figure Thethe FontApp application in Pa r t Four - Le14-11: ve r a ging .NET Libr a r ie s

action

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Figure 14-12: The stock .NET Font dialog

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - 14-13: A Better Paint ingwith Fr amew k ( GDI + ) Figure Working Pen or types Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure withespace pen caps Chapter 16 - 14-14: The Sy Working stem .I O Nam Chapter 17 - Data Access w ith ADO.NET

Figure 14-15: Working with Brush types

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - 14-16: ASP.NET Web Pages and Web Contr ols Figure The hatch styles Chapter 19 - ASP.NET Web Applicat ions

Figure Bitmaps as brushes Chapter 20 - 14-17: XML Web Ser vices I ndex

Figure 14-18: Gradient brushes at work

List of Figur es

List ofFigure Tables 14-19: Rendering images

Figure 14-20: The amazing happy-dude game Figure 14-21: You have nerves of steel... Figure 14-22: Hit-testing polygons Figure 14-23: An application with three external resources Figure 14-24: The ResX application Figure 14-25: Viewing the *.resx file a la VS .NET Figure 14-26: The binary *.resources file Figure 14-27: The embedded resources

Figure 14-28: Reading (and using) embedded resources C# an d th e .N ET Plat f orm , Se con d Ed it ion

Andr ew Tr oelsen Figure 14-29:byThe underlying *.resx file for MainForm.cs

ISBN:1590590554

Apr ess © 2003 (1200 pages)

Figure 14-30:This Under VSehensiv .NET, e*.resx filestsare embedded compr text star w ithautomatically a brief ov er view of the into your assembly. C# language and then quickly m oves to key technical and

Figure 14-31:arGUI of the application chitectur al ResLoader issues for .NET developer s.

Figure 14-32: Loading resources with the ResourceManager type Ta ble o f Con t en t s

Chapter 15: Programming with Windows Forms Controls

C# and t he .NET Plat for m, Second Edition I ntr oduction

Pa r t One - I nt15-1: r oduci ng C# a nd theForms .NET Pcontrol la tf or m hierarchy Figure The Windows

Chapter 1

- The Philosophy of .NET

Figure TheC#Form's UI Chapter 2 - 15-2: Building Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Figure 15-3: Interacting with a Form's Controls collection

Chapter 3

- C# Language Fundamentals

Chapter 4 - 15-4: Obj ectDesign -Or iented Pr property ogr am ming w ith C# Figure time configuration Chapter 5

- Exceptions and Obj ect Lifetim e

Figure Design event handling Chapter 6 - 15-5: I nter faces andtime Collections Chapter 7

Callback I nter faces, Delegates, and Ev ents Figure- 15-6: The many faces of the TextBox type

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m imany ng w i th .N ETof Assem bl ie s Figure 15-7: The faces the Button

Chapter 9

type

- Under standing .NET Assem blies

Figure The initial UI of theCont CarConfig Form Chapter 10 - 15-8: Pr ocesses, AppDomains, exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Figure 15-9: The CheckedListBox type

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - 15-10: Obj ect Multicolumn Ser ialization and the .NET Remoting Figure CheckedListBox type Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Figure The ListBox type or k ( GDI + ) Chapter 14 - 15-11: A Better Paint ing Fr amew

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure 15-12: The ComboBox type

Chapter 16 - The Sy stem .I O Nam espace Chapter Figure 17 - 15-13: Data Access The MonthCalendar w ith ADO.NET type Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Figure Selecting multiple dates Chapter 18 - 15-14: ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Figure 15-15: The VS .NET Tab Order Wizard

Chapter 20 - XML Web Ser vices I ndex Figure 15-16: Associating a ToolTip to a given widget List of Figur es

Figure 15-17: Working with Panel types

List of Tables

Figure 15-18: Working with UpDown types Figure 15-19: The ErrorProvider in action Figure 15-20: The AnchoringControls application Figure 15-21: The main Form Figure 15-22: The dialog box Form Figure 15-23: Obtaining information from the dialog box Figure 15-24: Building the derived Form Figure 15-25: The Components tab Figure 15-26: Creating a new Windows Control Library workspace

Figure 15-27:C#Creating an d th ethe .Ndesign ET Plattime f ormGUI , Se con d Ed it ion by Andr ew Tr oelsen Apr ess © 2003 (1200 pages)

Figure 15-28: The client-side GUI

ISBN:1590590554

compr ehensiv e texttostar w ith a value brief ov er view of the Figure 15-29:This Resetting a property thetsdefault C# language and then quickly m oves to key technical and chitectur al issues for .NET developer s. Figure 15-30:arThe custom category

Chapter 16: The System.IO Namespace

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition

Figure 16-1: The File- and Directory-centric types I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Figure 16-2: %windir% directory information

Chapter 1

- The Philosophy of .NET

Chapter 2 - 16-3: Building C# Applications Figure Bitmap file information Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Figure CreatingFundamentals subdirectories Chapter 3 - 16-4: C# Language Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Figure 16-5: Stream-derived types

Chapter 6 - 16-6: I nter faces and and Collections Figure Readers writers Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Figure The contents of your *.txt file Chapter 8 - 16-7: Advanced C# Type Const ruction Techniques Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure 16-8: Reading from a file

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - 16-9: Pr ocesses, AppDomains, Cont exts, and Threads Figure Manipulating the StringBuilder Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Figure Watching some Pa r t Four - Le16-10: ve r a ging the .NET Libr a*.txt r ie s files Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Figure 16-11: The car logger application

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - 16-12: A Better Paint ingaFrCar amew or k (box GDI + ) Figure The Add dialog Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure File Save dialog box Chapter 16 - 16-13: The Sy The stemstandard .I O Nam espace Chapter 17 - Data Access w ith ADO.NET

Chapter 17: Data Access with ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - 17-1: ASP.NET Web Applicat ions Figure ADO.NET data providers provide access to a given DBMS. Chapter 20 - XML Web Ser vices I ndex Figure 17-2: Exercising a DataColumn type List of Figur es

Figure 17-3: Auto-incrementation of a DataColumn

List of Tables

Figure 17-4: Examining row state Figure 17-5: The structure of an ADO.NET DataTable Figure 17-6: The DataTable under construction Figure 17-7: The visual representation of the DataTable Figure 17-8: Removing rows from the DataTable Figure 17-9: Specifying a filter Figure 17-10: Filtered data Figure 17-11: Specifying a range of data Figure 17-12: Editing rows in a DataGrid

Figure 17-13: The updated set of BMW autos

C# an d th e .N ET Plat f orm , Se con d Ed it ion

ISBN:1590590554 Andr ew multiple Tr oelsen views for a single DataTable Figure 17-14:byCreating

Apr ess © 2003 (1200 pages)

Figure 17-15:This Thecompr anatomy of ea text DataSet ehensiv star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

Figure 17-16:arThe Carsaldatabase chitectur issues for .NET developer s. Figure 17-17: Navigating data relations Ta ble o f Con t en t s

Figure 17-18: Navigating parent/child relations

C# and t he .NET Plat for m, Second Edition

I ntr oduction Figure 17-19: The Cars database as XML Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Figure The finalofGUI update Chapter 1 - 17-20: The Philosophy .NET Chapter 2

- Building C# Applications

Figure 17-21: The Cars XML schema file

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - 17-22: C# Language Fundamentals Figure Reading records with the OleDbDataReader Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C#

Figure Mapping database column names to unique display names Chapter 5 - 17-23: Exceptions and Obj ect Lifetim e Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Figure 17-24: Inserting new records using a data adapter

Chapter 8 - 17-25: Advanced C# Type Const records ruction Techniques Figure Updating existing using a data adapter Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Figure All good.NET things do come Chapter 9 - 17-26: Under standing Assem blies ... Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Figure 17-27: Viewing related DataTables

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le17-28: ve r a ging the .NET Libr a r ie s Figure Adding a new data connection

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Figure Configuring the new connection Chapter 13 - 17-29: Building a Bet ter Win dow ( Intdata roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Figure 17-30: Interacting with the Cars database via VS .NET

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Chapter 16 - 17-31: The Sy Design stem .I Otime Namconnection espace Figure configuration Chapter 17 - Data Access w ith ADO.NET

the connection Pa r t FiFigure ve - W 17-32: e b ApplSpecifying ica ti ons and X ML W e b Se r vifor cesthe

new SqlDataAdapter

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Figure 17-33: Specifying data store updates

Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 - 17-34: XML Web Ser vices Figure Creating the initial SELECT logic I ndex List ofFigure Figur es17-35: Altering column display names at design time List of Tables

Figure 17-36: Creating a typed DataSet at design time Figure 17-37: Typed DataSets have a related "code behind" file Figure 17-38: The DataSet-derived type maintains a set of nested classes.

Chapter 18: ASP.NET Web Pages and Web Controls Figure 18-1: The HTTP request and response cycle Figure 18-2: The IIS applet Figure 18-3: The Cars virtual directory Figure 18-4: The HTML Controls Toolbox Figure 18-5: Editing an HTML document via VS .NET

Figure 18-6: C# Thean initial thef default.htm page d th crack e .N ETatPlat orm , Se con d Ed it ion by Andr ew Tr oelsen

Figure 18-7: Apr Capturing HTML widget events a la VS .NET ess © 2003 (1200 pages)

ISBN:1590590554

ehensivgenerated e text star ts w ith a brief ov er view of the Figure 18-8: This The compr dynamically HTML C# language and then quickly m oves to key technical and

chitectur al issues for .NET developer s. Figure 18-9: ar Your first ASP.NET Web application

Figure 18-10: The location of the dynamically created assembly Ta ble o f Con t en t s

Figure 18-11: files become C# and t he .NET Plat*.aspx for m, Second Edition classes that extend System.Web.UI.Page. I ntr oduction

Figure 18-12: The ASP.NET compilation cycle

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 - 18-13: The Philosophy Figure Creating ofan.NET ASP.NET application project with VS .NET Chapter 2 - Building C# Applications Pa r t Tw Figure o - The 18-14: C# PrYour ogr am design m ing La time ngua template ge

Chapter 3

- C# Language Fundamentals

Figure- 18-15: Initial files of an ASP.NET application Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 4

Chapter 5 - 18-16: Exceptions Obj ect Web Lifetim e Figure The and ASP.NET Controls Toolbox Chapter 6

- I nter faces and Collections

Figure The derivation of an ASP.NET page Chapter 7 - 18-17: Callback I nter faces, Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Figure 18-18: The result of calling ClearError()

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 - 18-19: Under standing .NET blies ClearError() Figure The result of Assem not calling Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Figure The ASP.NET Web controls Chapter 11 - 18-20: Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Figure 18-21: Panel with contained controls

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - 18-22: Building a Bet ter Win contained dow ( Int roducin g Window s For ms) Figure Enumerating widgets Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Figure A ming dynamically generated Chapter 15 - 18-23: Pr ogr am with Windows FormHTML s Contrtable ols Chapter 16 - The Sy stem .I O Nam espace

Figure 18-24: A DataGrid with friendly column names

Chapter 17 - Data Access w ith ADO.NET

Pa r t FiFigure ve - W 18-25: e b ApplA ica ti ons anddefault X ML W paging e b Se r visupport ces DataGrid

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Figure AnWeb editable DataGrid Chapter 19 - 18-26: ASP.NET Applicat ions Chapter 20 - XML Web Ser vices I ndex

Figure 18-27: The items to be validated

List ofFigure Figur es18-28: Creating a regular expression via VS .NET List of Tables

Figure 18-29: Bad data . . . Figure 18-30: Custom server-side validation GUI prep Figure 18-31: Using a validation summary Figure 18-32: The System.Web.UI.HtmlControls hierarchy Figure 18-33: The GDI+ page UI Figure 18-34: Serving up dynamic images Figure 18-35: Logging custom trace messages

Chapter 19: ASP.NET Web Applications

Figure 19-1: The UI for the simple state page

C# an d th e .N ET Plat f orm , Se con d Ed it ion

ew Tr oelsen Figure 19-2: by TheAndr Global.asax designer

ISBN:1590590554

Apr ess © 2003 (1200 pages)

Figure 19-3: This The compr Application/Session state ehensiv e text star ts wdistinction ith a brief ov er view of the C# language and then quickly m oves to key technical and

Figure 19-4: ar The cachealapplication GUI developer s. chitectur issues for .NET Figure 19-5: The cache application GUI Ta ble o f Con t en t s

Figure 19-6: Cookie data as persisted under Microsoft IE

C# and t he .NET Plat for m, Second Edition

I ntr oduction Figure 19-7: The UI of the CookiesStateApp Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Figure The persistent cookie data Chapter 1 - 19-8: The Philosophy of .NET Chapter 2

- Building C# Applications

Figure 19-9: Viewing cookie data

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 - 19-10: C# Language Fundamentals Figure The Services applet Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Figure Configuration Chapter 5 - 19-11: Exceptions and Obj ectinheritance Lifetim e Chapter 6

- I nter faces and Collections

Chapter - Callback 20: XML I nter faces, Web Delegates, Services and Ev ents

Chapter 7 Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s Figure 20-1: XML Web services in action

Chapter 9

- Under standing .NET Assem blies Figure Viewing the functionality of the Web service Chapter 10 - 20-2: Pr ocesses, AppDomains, Cont exts, andHelloWorldWS Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Figure 20-3: Web method return values are expressed in terms of XML.

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - 20-4: Obj ectViewing Ser ialization and the .NET Figure the compiled .NETRemoting assemblyLay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Figure Creating a new VS or .NET XML Chapter 14 - 20-5: A Better Paint ing Fr amew k ( GDI + ) Web Service project Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Figure 20-6: Invoking the Add() Web method

Chapter 16 - The Sy stem .I O Nam espace Chapter Figure 17 - 20-7: Data Access Documenting w ith ADO.NET your Web methods Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Figure TheWeb dummy value XML Chapter 18 - 20-8: ASP.NET Pages and for Webyour Contr ols namespace is http—//tempuri.org. Chapter 19 - ASP.NET Web Applicat ions

Figure 20-9: The VS .NET Add Web Reference utility

Chapter 20 - XML Web Ser vices

I ndex Figure 20-10: A Windows Forms XML Web Service Client application List of Figur es List ofFigure Tables 20-11: Interacting with a UDDI catalog

Figure 20-12: Obtaining a list of posted weather-centric Web services

C# an d th e .N ET Plat f orm , Se con d Ed it ion

by Andr ew Tr oelsen List of Tables

ISBN:1590590554

Apr ess © 2003 (1200 pages) compr ehensiv e text star ts w ith a brief ov er view of the Chapter 1: This The Philosophy of m.NET C# language and then quickly oves to key technical and ar chitectur al issues for .NET developer s.

Table 1-1: A Sampling of .NET-Aware Programming Languages Class Characteristics Ta ble Table o f Con1-2: t en t CTS s C# and t he .NET Plat for m, Second Edition

Table 1-3: The Intrinsic CTS Data Types

I ntr oduction

Pa r t One - I nt r oduci ng C# a ndofthe .NET P la tf or m Table 1-4: A Sampling .NET Namespaces

Chapter 1

- The Philosophy of .NET Table ildasm.exe Tree View Icons Chapter 2 -1-5: Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Table -1-6: Select Links to the Platform-Agnostic Nature of .NET C# Language Fundamentals

Chapter 3 Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 2: Building C#Lifetim Applications - Exceptions and Obj ect e

Chapter 5 Chapter 6

- I nter faces and Collections

Table Output Options the C# Compiler Chapter 7 -2-1: Callback I nter faces, of Delegates, and Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Table 2-2: Options of the C# Command Line Compiler

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9 -2-3: Under standing of .NET Assem blies Table A Handful Useful cordbg.exe Flags Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Table Core ProjectLate Workspace Chapter 11 -2-4: Type Reflection, Binding, Types and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Table 2-5: The Structure of a VS .NET Console Application

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Chapter 13 -2-6: Building Bet terTags Win dow ( Int roducin g Window s For ms) Table Stocka XML Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Table XML Format Characters Chapter 15 -2-7: Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Table 2-8: C# Preprocessor Directives

Chapter 17 - Data Access w ith ADO.NET

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 3: C# Language Fundamentals

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Table Format Characters Chapter 20 -3-1: XML.NET Web String Ser vices I ndex

Table 3-2: Value Types and Reference Types Side by Side

List of Figur es

List ofTable Tables3-3: Core Members of System.Object

Table 3-4: System Types and C# Aliases Table 3-5: C# Relational and Equality Operators Table 3-6: C# Conditional Operators Table 3-7: The Full Set of C# Operators Table 3-8: C# Accessibility Keywords Table 3-9: C# Parameter Modifiers Table 3-10: Select Members of System.Array Table 3-11: Select Members of System.String

Table 3-12: String Escape Characters

C# an d th e .N ET Plat f orm , Se con d Ed it ion

by Andrstatic ew TrMembers oelsen Table 3-13: Select of System.Enum

ISBN:1590590554

Apr ess © 2003 (1200 pages) compr ehensiv eand text star ts w ith a brief ov er view of the Chapter 5: This Exceptions Object Lifetime C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Table 5-1: Core Members of the System.Exception Type Members of the System.GC Type Ta ble Table o f Con5-2: t en t Select s C# and t he .NET Plat for m, Second Edition

Chapter 6: Interfaces and Collections

I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter Table 1 -6-1: TheCompareTo() Philosophy of .NET Return Values Chapter 2

- Building C# Applications

Table 6-2:C#Interfaces ofing System.Collections Pa r t Tw o - The Pr ogr am m La ngua ge Chapter 3

C# Language Fundamentals Table -6-3: Classes of System.Collections

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter Table 5 -6-4: Exceptions Members andofObj theect Queue LifetimType e Chapter 6

- I nter faces and Collections

Table -6-5: Types of the System.Collections.Specialized Namespace Callback I nter faces, Delegates, and Ev ents

Chapter 7 Chapter 8

- Advanced C# Type Const ruction Techniques

Chapter 7: Callback Interfaces, Delegates, and Events

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Table Select Members of System.MultcastDelegate/System.Delegate Chapter 10 -7-1: Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Chapter 8: Advanced C# Type Construction Techniques

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 -8-1: Building a Bet ter WinC# dow ( Int roducin g Window s For ms) Table Pointer-Centric Operators Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Table A am Summary of Windows C# Keywords Chapter 15 -8-2: Pr ogr ming with Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace

Table 8-3: C#-Operator-to-CIL Special Name Roadmap

Chapter 17 - Data Access w ith ADO.NET

Pa r t FiTable ve - W8-4: e b Appl icaOverloadable ti ons and X MLOperators W e b Se r vi ces Valid

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Chapter 9: Understanding .NET Assemblies

Chapter 20 - XML Web Ser vices I ndex

Table 9-1: Key Elements of an Assembly Manifest

List of Figur es

List ofTable Tables9-2: Manifest CIL Tokens

Chapter 10: Processes, AppDomains, Contexts, and Threads Table 10-1: Select Members of the System.Diagnostics Namespace Table 10-2: Select Members of the Process Type Table 10-3: Select Members of the ProcessThread Type Table 10-4: Select Members of AppDomain Table 10-5: Events of the AppDomain Type Table 10-6: Select Types of the System.Threading Namespace Table 10-7: Key Static Members of the Thread Type

Table 10-8: Select Instance Level Members of the Thread Type C# an d th e .N ET Plat f orm , Se con d Ed it ion

by Andr ewofTrthe oelsen Table 10-9: Members Interlocked Type

ISBN:1590590554

Apr ess © 2003 (1200 pages) compr ehensiv e text star ts w ith a brief ov er view of the Chapter 11:This Reflection, and C#Type language and then quicklyLate m oves Binding, to key technical and Attribute-Based ar chitectur al issues for .NET developer s. Programming

Table 11-1: Select Members of System.Type

Ta ble o f Con t en t s

C# and t he .NET for m, Second Edition Table 11-2:Plat A Sampling of Members of the System.Reflection Namespace I ntr oduction

Table 11-3: A ng Tiny of Predefined Pa r t One - I nt r oduci C#Sampling a nd the .NET P la tf or m Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

System Attributes

Table 11-4: Select Assembly-level Attributes

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 12: Object Serialization and the .NET Remoting Layer - C# Language Fundamentals

Chapter 3 Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Table BinaryFormatter Chapter 5 -12-1: Exceptions and Obj ect Members Lifetim e Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Table 12-2: System.Runtime.Serialization Namespace Core Types

Chapter 8 -12-3: Advanced C# Type Const ruction Techniques Members Table StreamingContextStates Enumeration Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Table The .NET .NET Remoting Chapter 9 -12-4: Under standing AssemNamespaces blies Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Table 12-5: Key Members of System.MarshalByRefObject

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s for Table 12-6: Configuration Options

MBR Types

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Table Select Members of the Chapter 13 -12-7: Building a Bet ter Win dow ( IntChannelServices roducin g Window s Type For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Table 12-8: Members of the RemotingConfiguration Type

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 -12-9: The Sy stem .I O of Nam Table Members theespace ILease Interface Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 13: Building a Better Window (Introducing Windows Forms)

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Table 13-1: A Subset of Types Within the System.Windows.Forms Namespace

Chapter 20 - XML Web Ser vices

I ndex Table 13-2: Methods of the Application Type List of Figur es List ofTable Tables13-3: Core Properties of the Application Type

Table 13-4: Events of the Application Type Table 13-5: Core Properties of the Control Type Table 13-6: Select Members of the Control Type Table 13-7: Events of the Control Type Table 13-8: Properties of the MouseEventArgs Type Table 13-9: Properties of the KeyEventArgs Type Table 13-10: Additional Control Properties Table 13-11: Additional Control Methods Table 13-12: Additional Control Properties

Table 13-13:C# Members an d th eof.Nthe ET ContainerControl Plat f orm , Se con dType Ed it ion by Andr ew Tr oelsen

Table 13-14:Apr Properties of the Form Type ess © 2003 (1200 pages)

ISBN:1590590554

ehensiv e text starType ts w ith a brief ov er view of the Table 13-15:This Keycompr Methods of the Form C# language and then quickly m oves to key technical and

chitectur al issues for .NET developer s. Table 13-16:arSelect Events of the Form Type

Table 13-17: Form Life Time Events Ta ble o f Con t en t s

Table 13-18: of the Menu Type C# and t he .NET PlatMembers for m, Second Edition I ntr oduction

Table 13-19: The Nested MenuItemCollection Type

Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1 -13-20: The Philosophy of .NET Table More Details of the MenuItem Type Chapter 2 - Building C# Applications Pa r t Tw Table o - The 13-21: C# Pr Select ogr amStatusBar m ing La ngua Properties ge

Chapter 3

- C# Language Fundamentals

Table -13-22: Properties of the StatusBarPanel Type Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 4

Chapter 5 -13-23: Exceptions and Obj ect Lifetim e Table The Timer Type Chapter 6

- I nter faces and Collections Table Properties of the ToolBarand Type Chapter 7 -13-24: Callback I nter faces, Delegates, Ev ents Chapter 8

- Advanced C# Type Const ruction Techniques

Table 13-25: Properties of the ToolBarButton Type

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 14: A Better Painting Framework (GDI+)

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Table 14-1: The Core GDI+ Namespaces Pa r t Four - Le ve r a ging the .NET Libr a r ie s Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er

Table 14-2: Core Types of the System.Drawing Namespace

Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 -14-3: A Better Paint ing Fr amew k ( GDI + ) Table Enumerations in theorSystem.Drawing Namespace Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Table Key Members the Point(F) Types Chapter 16 -14-4: The Sy stem .I O Nam of espace Chapter 17 - Data Access w ith ADO.NET

Table 14-5: Key Members of the Rectangle(F) Types

Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 -14-6: ASP.NET Web Pagesof and ContrTypes ols Table Key Members theWeb Size(F) Chapter 19 - ASP.NET Web Applicat ions

Table of the Region Class Chapter 20 -14-7: XML Members Web Ser vices I ndex

Table 14-8: Members of the Graphics Class

List of Figur es

List ofTable Tables14-9: Stateful Properties of the Graphics Class

Table 14-10: The GDI+ Coordinate Systems Table 14-11: The GraphicsUnit Enumeration Table 14-12: Members of the Color Type Table 14-13: The FontStyle Enumeration Table 14-14: Members of the FontFamily Type Table 14-15: The Text Type Table 14-16: The Classes of System.Drawing.Drawing2D Table 14-17: The Enumerations of System.Drawing.Drawing2D

Table 14-18: Various SmoothingMode Values

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Andr ewMembers Tr oelsen of the Graphics Class Table 14-19:by Drawing

ISBN:1590590554

Apr ess © 2003 (1200 pages)

Table 14-20:This Pencompr Properties ehensiv e text star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

Table 14-21:arDash Styles chitectur al issues for .NET developer s. Table 14-22: LineCap Values Ta ble o f Con t en t s

Table 14-23: Fill Methods of the Graphics Type

C# and t he .NET Plat for m, Second Edition

I ntr oduction Table 14-24: Values of the HatchStyle Enumeration Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Table LinearGradientMode Enumeration Chapter 1 -14-25: The Philosophy of .NET Chapter 2

- Building C# Applications

Table 14-26: Members of the Image Type

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3 -14-27: C# Language Fundamentals Table The PictureBoxSizeMode Enumeration Chapter 4 - Obj ect -Or iented Pr ogr am ming w ith C#

Table Add-Centric Methods Chapter 5 -14-28: Exceptions and Obj ect Lifetimof e the GraphicsPath Class Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Table 14-29: Members of the System.Resources Namespace

Chapter 15: Programming with Windows Forms Controls

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Table NestedAppDomains, ControlCollection Members Chapter 10 -15-1: Pr ocesses, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Table 15-2: Members of the TextBoxBase Type

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 -15-3: Obj ect Ser ialization and the .NET Remoting Lay er Table TextBox Properties Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Table ButtonBase Properties Chapter 14 -15-4: A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Table 15-5: CheckBox Properties

Chapter 16 - The Sy stem .I O Nam espace Chapter Table 17 -15-6: Data MonthCalendar Access w ith ADO.NET Properties Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Table DateTime Members Chapter 18 -15-7: ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Table 15-8: ToolTip Members

Chapter 20 - XML Web Ser vices I ndex Table 15-9: TrackBar Properties List of Figur es

Table 15-10: UpDownBase Properties

List of Tables

Table 15-11: DomainUpDown Properties Table 15-12: NumericUpDown Properties Table 15-13: Control Properties Table 15-14: ErrorBlinkStyle Properties Table 15-15: FormBorderStyle Properties Table 15-16: AnchorStyles Values Table 15-17: DockStyle Values Table 15-18: Select Members of System.ComponentModel

Chapter 16:C#The System.IO Namespace an d th e .N ET Plat f orm , Se con d Ed it ion ISBN:1590590554

by Andr ew Tr oelsen

Table 16-1: Key Members of the System.IO Namespace Apr ess © 2003 (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the

Table 16-2: FileSystemInfo Properties C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Table 16-3: Key Members of the DirectoryInfo Type Table 16-4: Select FileAttributes Values

Ta ble o f Con t en t s

C# and t he .NET for m, Core Second Edition Table 16-5:Plat FileInfo Members I ntr oduction

Table 16-6: FileMode Enumeration Pa r t One - I nt r oduci ng C# a nd the .NET P laValues tf or m Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Table 16-7: FileAccess Enumeration Values

Pa r t Tw o - The C# FileShare Pr ogr am mEnumeration ing La ngua ge Values Table 16-8:

Chapter 3

- C# Language Fundamentals

Table Abstract Stream Members Chapter 4 -16-9: Obj ect -Or iented Pr ogr am ming w ith C# Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Table 16-10: MemoryStream Core Members

Chapter 7 -16-11: Callback I nter faces, Delegates, and Ev ents Table Core Members of TextWriter Chapter 8

- Advanced C# Type Const ruction Techniques

Table TextReader Core Members Pa r t Thre e - 16-12: Pr ogr am m i ng w i th .N ET Assem bl ie s Chapter 9

- Under standing .NET Assem blies

Table 16-13: BinaryWriter Core Members

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 -16-14: Type Reflection, Late Core Binding, and Attr ibute- Based Pr ogramm ing Table BinaryReader Members Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Table Menu Options of .NET the CarLogApp Project Chapter 12 -16-15: Obj ectFile Ser ialization and the Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Chapter 17: Data Access with ADO.NET

Chapter 14 - A Better Paint ing Fr amew or k ( GDI + )

Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 -17-1: The Sy stem .I O Nam espace Table ADO.NET Namespaces Chapter 17 - Data Access w ith ADO.NET

Key theWSystem.Data Pa r t FiTable ve - W17-2: e b Appl icaMembers ti ons and of X ML e b Se r vi ces

Namespace

Chapter 18 - ASP.NET Web Pages and Web Contr ols

Table 17-3: Properties of the DataColumn

Chapter 19 - ASP.NET Web Applicat ions

Chapter 20 -17-4: XML Values Web Serof vices Table the MappingType Enumeration I ndex

17-5: Key Members of the DataRow Type List ofTable Figur es List of Tables

Table 17-6: Values of the DataRowState Enumeration Table 17-7: Key Members of the DataTable Table 17-8: Members of the DataView Type Table 17-9: Properties of the Mighty DataSet Table 17-10: Methods of the Mighty DataSet Table 17-11: Properties of the DataRelation Type Table 17-12: Key Types of the System.Data.OleDb Namespace Table 17-13: Core OLE DB Providers Table 17-14: Members of the OleDbConnection Type

Table 17-15: Members of the OleDbCommand Type

C# an d th e .N ET Plat f orm , Se con d Ed it ion

Andr ew Tr oelsen Table 17-16:by Key Members of the OleDbParameter Type ISBN:1590590554 Apr ess © 2003 (1200 pages)

Table 17-17:This Core Members ofe the compr ehensiv textOleDbDataAdapter star ts w ith a brief ov er view of the C# language and then quickly m oves to key technical and

Table 17-18:arCore Types of the for System.Data.SqlClient Namespace chitectur al issues .NET developer s. Table 17-19: Types of the System.Data.SqlTypes Namespace Ta ble o f Con t en t s

Chapter 18: ASP.NET Web Pages and Web Controls

C# and t he .NET Plat for m, Second Edition I ntr oduction

Pa r t One - I nt r oduci ng C# a nd the .NET la tf or m Table 18-1: Common HTML GUI PTypes

Chapter 1

- The Philosophy of .NET

Table ASP.NET Namespaces Chapter 2 -18-2: Building C# Applications Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Table 18-3: Core Types of the System.Web Namespace

Chapter 3

- C# Language Fundamentals

Chapter 4 -18-4: Obj ect -Or iented Pr ogrAll) am of ming ith C# Attributes Table Some (But Not thew@Page Chapter 5 - Exceptions and Obj ect Lifetim e

Table Project Files Chapter 6 -18-5: I nterInitial faces and Collections Chapter 7

Callback I nter faces, Delegates, and Ev ents Table -18-6: Properties of the Page Type

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - 18-7: Pr ogr am m i ng w of i th the .N ET Assem bl ie s Type Table Members HttpRequest

Chapter 9

- Under standing .NET Assem blies

Table Properties of the HttpResponse Chapter 10 -18-8: Pr ocesses, AppDomains, Cont exts, andType Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing

Table 18-9: Methods of the HttpResponse Type

Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 -18-10: Obj ectThe Ser ialization andInit, theLoad, .NET Remoting Lay Events er Table Role of the and Unload Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms)

Table Select oforSystem.Web.UI.Control Chapter 14 -18-11: A Better PaintMembers ing Fr amew k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols

Table 18-12: Properties of the WebControl Base Class

Chapter 16 - The Sy stem .I O Nam espace Chapter Table 17 -18-13: Data Access Rich WebControl w ith ADO.NET Widgets Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Table TheWeb ASP.NET Validation Controls Chapter 18 -18-14: ASP.NET Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions

Table 18-15: Common Properties of the ASP.NET Validators

Chapter 20 - XML Web Ser vices I ndex

Chapter 19: ASP.NET Web Applications

List of Figur es List of Tables

Table 19-1: Core Types of the System.Web Namespace Table 19-2: Key Members Defined By the System.Web.HttpApplication Type Table 19-3: Members of the HttpApplicationState Type Table 19-4: Select Elements of a web.config File Table 19-5: Attributes of the Element

Chapter 20: XML Web Services Table 20-1: XML Web Service-Centric Namespaces Table 20-2: Members of the System.Web.Services Namespace Table 20-3: Key Members of the System.Web.Services.WebService Type

C# an d th e .Nof ETthe Plat f orm , Se con d Ed it ion Table 20-4: Key Members WebMethodAttribute Type by Andr ew Tr oelsen

ISBN:1590590554

Table 20-5: Select wsdl.exe Apr ess Flags © 2003 of (1200 pages) This compr ehensiv e text star ts w ith a brief ov er view of the Table 20-6: Web Service Wire Protocols C# language and then quickly m oves to key technical and ar chitectur al issues for .NET developer s.

Table 20-7: Supported POST and GET Data Types

Table 20-8: Core Members of the SoapHttpClientProtocol Type

Ta ble o f Con t en t s

C# and t he .NET Plat for m, Second Edition I ntr oduction Pa r t One - I nt r oduci ng C# a nd the .NET P la tf or m

Chapter 1

- The Philosophy of .NET

Chapter 2

- Building C# Applications

Pa r t Tw o - The C# Pr ogr am m ing La ngua ge

Chapter 3

- C# Language Fundamentals

Chapter 4

- Obj ect -Or iented Pr ogr am ming w ith C#

Chapter 5

- Exceptions and Obj ect Lifetim e

Chapter 6

- I nter faces and Collections

Chapter 7

- Callback I nter faces, Delegates, and Ev ents

Chapter 8

- Advanced C# Type Const ruction Techniques

Pa r t Thre e - Pr ogr am m i ng w i th .N ET Assem bl ie s

Chapter 9

- Under standing .NET Assem blies

Chapter 10 - Pr ocesses, AppDomains, Cont exts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attr ibute- Based Pr ogramm ing Pa r t Four - Le ve r a ging the .NET Libr a r ie s

Chapter 12 - Obj ect Ser ialization and the .NET Remoting Lay er Chapter 13 - Building a Bet ter Win dow ( Int roducin g Window s For ms) Chapter 14 - A Better Paint ing Fr amew or k ( GDI + ) Chapter 15 - Pr ogr am ming with Windows Form s Contr ols Chapter 16 - The Sy stem .I O Nam espace Chapter 17 - Data Access w ith ADO.NET Pa r t Fi ve - W e b Appl ica ti ons and X ML W e b Se r vi ces

Chapter 18 - ASP.NET Web Pages and Web Contr ols Chapter 19 - ASP.NET Web Applicat ions Chapter 20 - XML Web Ser vices I ndex List of Figur es List of Tables