C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Back Cover ISBN:1590590554 by Andrew Troelsen C# and the .NET Platform, Second Edition starts with a brief overview of the C# language and then quickly moves Apress © 2003 (1200 pages) to key technical and architectural issues for .NET developers. Not only is there extensive coverage of the .NET This comprehensive text starts with a brief overview of the Framework, but Andrew Troelsen also shows programmers what they need to know about such necessary, but language then and quickly to keythe technical andremoting protocol. Readers will also subtle, areas as the C# proper use ofand threads howmoves to leverage new .NET architectural issues for developers. see how to use C# for GUI applications with.NET a complete discussion of Windows Forms, custom controls, and GDI+. There are equally useful discussions on how to use C# and .NET for Web development, Web services, and data accessof using ADO.NET. From Windows-based to Web-based applications, it's all here. There are detailed discussions Table Contents of every aspect of .NET development and useful examples with no toy code. C# and the .NET Platform, Second Edition Introduction
About the Author
Part One - Introducing C# and the .NET Platform
Andrew a partner, trainer, ChapterTroelsen 1 - TheisPhilosophy of .NET 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 COM. His earlier five-star treatment of Chapter 2 COM - Building C# Applications traditional in the best-selling Developer's Workshop to COM and ATL 3.0 is mirrored in his latest book, COM Part Two The C# Programming and .NET Interoperability, and his Language award-winning treatment of C# in C# and the .NET Platform , as well as his fivestar investigation VB .NET Fundamentals in Visual Basic .NET and the .NET Platform: An Advanced Guide . He has a degree in Chapter 3 - C# of Language mathematical linguistics and South Asian studies from the University of Minnesota and is a frequent speaker at Chapter 4 - Object-Oriented Programming with C# numerous .NET-related conferences. Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition C# and the .NET Platform, Second Edition ISBN:1590590554 by Andrew Troelsen
ANDREW TROELSEN Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents
Copyright © 2003 by Andrew Troelsen C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
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. Part Two - The C# Programming Language ISBN: 1-59059-055-4 Chapter 1
Chapter 3
- C# Language Fundamentals
Printed4and bound in the United States ofwith America Chapter - Object-Oriented Programming C# 12345678910 Chapter 5
- Exceptions and Object Lifetime
Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence - Interfaces 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 Interfaces, Delegates, and Events owner, with no intention of infringement of the trademark. Chapter 6 Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Technical Reviewers: Gregory A.Assemblies Beamer, Gary
Cornell, Eric Gunnerson, Joe Nalewabau, Kent
Chapter 9 Nick - Understanding Assemblies Sharkey, Symmonds,.NET Pradeep Tapadiya Chapter 10 - Processes, AppDomains, Contexts, and Threads
Editorial Dan Appleman, Gary Cornell, Simon Hayes, Martin Streicher, Karen Watterson, John Chapter 11 Directors: - Type Reflection, Late Binding, and Attribute-Based Programming Zukowski Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
Assistant Publisher: Grace Wong
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Framework Copy Editors: AnnePainting Friedman and Ami(GDI+) Knox Chapter 15 - Programming with Windows Forms Controls
Proofreader: LizSystem.IO Berry Chapter 16 - The Namespace Chapter 17 - Data Access with ADO.NET
Production Goddess: Susan Glinert Stevens
Part Five - Web Applications and XML Web Services
Chapter 18 Ron - ASP.NET Web Pages and Web Controls Indexer: Strauss Chapter 19 - ASP.NET Web Applications
Artist and Designer: Chapter 20 -Cover XML Web Services Kurt Krames Index
Manufacturing Manager: Tom Debolski
List of Figures
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# and the .NET Platform, Second Edition section. by Andrew Troelsen
ISBN:1590590554
Apress 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. text starts with a brief overview of the comprehensive C# language and then quickly moves to key technical and architectural issues for .NET developers.
Luv ya, Damn Kid
About the Author Table of Contents C# and the .NET Platform, 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 Part One - Introducing C# and the .NET Platform 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 Part Two - The C# Programming Language 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 - Object-Oriented Programming with C# conferences. Introduction
Chapter 5
- Exceptions and Object Lifetime He currently lives in Minneapolis, Minnesota, with his wife Amanda, and spends his free time investigating Chapter 6 - Interfaces and Collections
.NET and forInterfaces, the Wild toDelegates, win the Stanley Cup, the Vikings to win the Super Bowl (before he retires Chapter 7 waiting - Callback and Events would be and the to grab numerous NBA championship titles. Chapter 8 nice), - Advanced C#Timberwolves Type Construction Techniques Part Three - Programming with .NET Assemblies
Acknowledgments
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, and Threads Completing the secondAppDomains, edition of C#Contexts, and the .NET Platform would have been completely impossible Chapter Type Reflection, Late Binding, Attribute-Based Programming without11 the- assistance and talent offered and by numerous individuals. First of all, many thanks to my copy Part Four Anne - Leveraging theand .NETAmi Libraries editors, Friedman Knox.
Both of you, as always, did an outstanding job massaging my raw
Chapter 12 - into Object Serialization and the .NET Layer manuscript a polished product. (See youRemoting both on the nextbook?) Next, I must thank the numerous Chapter technical 13 reviewers - Building who a Better tookWindow the time(Introducing to read these Windows chapters Forms) for any coding faux pas: Gregory A. Beamer,
Gary Cornell, Eric Gunnerson, Joe Nalewabau, Chapter 14 - A Better Painting Framework (GDI+) Kent Sharkey, Nick Symmonds, and Pradeep Tapadiya. Special15 thanks to Beth Christmas, Ron Forms Strauss, Susan Glinert Stevens, and Liz Berry, whose combined Chapter - Programming with Windows Controls efforts formatted, indexed, Namespace and finalized this text to completion. Of course, any remaining errors (spelling, Chapter 16 - The System.IO coding,17 or -otherwise) that may have snuck into this book are my sole responsibility. Chapter Data Access with ADO.NET Part Five - Web Applications and XML Web Services
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 Applications 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 Services you today" many times. Chapter 18 - ASP.NET Web Pages and Web Controls
Index
Thanks to my friends and family who (once again) tolerated my lack of time and sometimes grumpy List of Figures 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# and the .NET Platform, Second Edition Introduction by Andrew Troelsen
ISBN:1590590554
Apress 2003 when (1200 pages) I remember a time years© ago I proposed a book to Apress regarding a forthcoming software SDK This comprehensive text starts with a brief overview of the know, NGWS eventually named Next Generation Windows Services (NGWS). As you may already C# language and then quickly moves to key technical and became what we now know as the .NET platform. My research of the C# programming language and the architectural issues for .NET developers.
.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 drastic changes over the course of its development. It pains me to recall how many chapters had to be Table of Contents completely destroyed and rewritten during that time. Thankfully, after many sleepless nights, the first C# and the .NET Platform, Second Edition edition of C# and the .NET Platform was published in con-junction with the release of .NET Beta 2, circa Introduction the summer of 2001. Part One - Introducing C# and the .NET Platform
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 Part Twofinalist - The C# Programming award (I lost ... crap!) asLanguage well as the
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 - Object-Oriented Programming C# brought about with the minor release of the .NET was in order—not only to account for the with changes Chapter platform, 5 but - Exceptions to expandand upon Object and Lifetime improve the existing content. As I write this frontmatter, version 1.1 of the
.NET platform is just about official, and I am happy to say that C# and the .NET Platform, Second Edition is Chapter 6 - Interfaces and Collections being released in tandem. Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction 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 - Understanding .NET Assemblies authors have to spit out prose that reads more like a GRE vocabulary study guide than a readable Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming build software solutions today, rather than spending too much time focusing on esoteric details that few Part Four - Leveraging the .NET Libraries individuals will ever actually care about. To this end, when I do dive under the hood and check out some Chapter 12 - Object Serialization andCLR the .NET Remoting Layer more low-level functionality of the (or blocks of CIL code), I promise it will prove enlightening (rather Chapter 13 Building a Better Window (Introducing Windows Forms) than simple eye candy). Part Three - Programming with .NET Assemblies
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
We 're a Team, You and I
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with Technology authors write for ADO.NET a demanding group of people (I should know, I'm one of them). You know Part - Web Applications and XML thatFive building software solutions usingWeb anyServices platform
is extremely detailed and is very specific to your
Chapter 18 - ASP.NET Web Pages and and Websubject Controlsmatter. Perhaps you work in the electronic publishing department, company, client base, Chapter 19develop - ASP.NET Web Applications industry, systems for the state or local government, work at NASA or a branch of the military. Chapter Speaking 20 for - XML myself, Web IServices have 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 Index code you write at your place of employment has little to do with the code I write at mine (unless we List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# of andthe the .NET Platform, Second Edition An Overview Second Edition by Andrew Troelsen
ISBN:1590590554
C# and the .NET Apress Platform, Second Edition is logically divided into five distinct sections, each of which © 2003 (1200 pages) contains some number of chapters together." you read the first edition of this text, This comprehensivethat textsomehow starts with"belong a brief overview ofIfthe you will notice some similarities in chapter names; however, be aware that C# language and then quickly moves to key technical and just about every page has been issues for .NET developers. updated with newarchitectural content. You will also notice that some topics in the first edition (such as .NET 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 Table ofdeeper Contents much examination of ASP.NET). C# and the .NET Platform, Second Edition
On the flip side, I did choose to remove some topics from the second edition to make room for new Introduction content. most notable omission the topic Part One -The Introducing C# and the .NETisPlatform
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, Part Two - 2002). The C# Programming Language Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
These things being said, here is a chapter-by-chapter breakdown of the text.
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET C# Platform, EditionPlatform Part One: Introducing andSecond the .NET by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Chapter 1: This Thecomprehensive Philosophy of .NET text starts with a brief overview of the C# language and then quickly moves to key technical and
This first chapter architectural functions asissues the backbone for the remainder of this text. We begin by examining the for .NET developers. 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 suchofasContents the common language runtime (CLR), Common Type System (CTS), Common Language Table Specification (CLS), and Second the base class libraries. You also take an initial look at the C# programming C# and the .NET Platform, Edition language, the role of the .NET assembly, and various development utilities that ship with the .NET SDK. Introduction Part One - Introducing C# and the .NET Platform
Chapter - The 2:Philosophy Building of .NET C# Applications
Chapter 1 Chapter 2
- Building C# Applications
TheTwo goal- The of this is to introduce you Part C#chapter Programming Language
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 - Object-Oriented Programming with C# how to make use of the Visual Studio .NET IDE, navigate the official .NET help system (MSDN), and Chapter 5 - Exceptions and Object Lifetime understand the role of XML-based source code comments. Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and .NET Platform, Second Edition Part Two: The C#theProgramming Language by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Chapter 3: This C#comprehensive LanguagetextFundamentals starts with a brief overview of the C# language and then quickly moves to key technical and
This chapter examines the core constructs of the C# programming language. Here you come to architectural issues for .NET developers. 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, System.Object. Table of ContentsAlso, Chapter 3 illustrates how the .NET platform places a spin on various commonplace programming such asEdition enumerations, arrays, and string processing. C# and the .NETconstructs Platform, Second Introduction
Chapter 4: Object-Oriented Programming with C#
Part One - Introducing C# and the .NET Platform
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, Part Two - The C# Programminginheritance, Language
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 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 5: Exceptions and Object Lifetime - Interfaces and Collections
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
Here you learn how to handle runtime anomalies using the official error handling mechanism of the .NET Chapter 8 - Advanced C# Type Construction Techniques platform: structured exception handling. As you will see, exceptions are class types that contain Part Three - Programming with .NET Assemblies information regarding the error at hand and can be manipulated using the "try", "catch", "throw", and Chapter 9 - Understanding .NET Assemblies "finally" keywords of C#. The latter half of this chapter examines how the CLR manages the memory Chapter 10 - Processes, AppDomains, Contexts, and Threads consumed by allocated objects using an associated garbage collector. This discussion also examines the Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming role of the IDisposable interface, which is a perfect lead-in to the next chapter. Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 6: Interfaces and Collections
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (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 System.IO Namespace discover these behaviors at runtime, and how to selectively hide select behaviors using explicit interface Chapter 17 - Data To Access with ADO.NET implementation. showcase the usefulness of interface types, the remainder of this chapter examines Part Five Web Applications and XML Web Services the System.Collections namespace. As you will see, this region of the base class libraries contains Chapter 18 ASP.NET Web Pages and Web numerous types that may be used out of Controls the box, or serve as a foundation for the development of strongly Chapter 19 - ASP.NET Web Applications typed collections. Chapter 15 - Programming with Windows Forms Controls
Chapter 20 - XML Web Services Index
Chapter 7: Callback Interfaces, Delegates, and Events
List of Figures
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.
and the .NET Platform, Part Three:C# Programming withSecond .NETEdition Assemblies by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Chapter 9: This Understanding .NET Assemblies comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and
From a very higharchitectural level, an assembly can be considered the term used to describe a managed *.dll or *.exe issues for .NET developers. 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 examines how private and shared assemblies may be configured using XML-based *.config files and Table of Contents publisher policy *.dlls. Along the Edition way, you investigate the internal structure of the Global Assembly Cache C# and the .NET Platform, Second (GAC) and learn how to force Visual Studio .NET to display your custom assemblies within the Add Introduction Reference dialog box (trust me, this is one of the most common questions I am asked). Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 10: Processes, - Building C# Applications AppDomains, Contexts, and Threads
Chapter 2
Part Two - The C# Programming Language
Now that have a solidFundamentals understanding of assemblies, this chapter dives much deeper into the Chapter 3 you - C# Language
composition of a loaded .NET executable. The goal of Chapter 10 is to define several terms and illustrate - Object-Oriented Programming with C# the relationship between processes, application domains, contextual boundaries, and threads. Once these Chapter 5 - Exceptions and Object Lifetime terms have been qualified, the remainder of this chapter is devoted to the topic of building multithread Chapter 6 - Interfaces and Collections applicationsusing the types of the System.Threading namespace. Be aware that the information Chapter 7 - Callback Interfaces, Delegates, and Events presented here provides a solid foundation for understanding the .NET Remoting layer (examined in Chapter 8 - Advanced C# Type Construction Techniques Chapter 12). Chapter 4
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 11: Type Reflection, Late Binding, and Attribute-Based Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Programming Chapter 10 - Processes, AppDomains, Contexts, and Threads Part Four - Leveraging the .NET Libraries
Chapter our examination of .NET assemblies Chapter 1211 - concludes Object Serialization and the .NET Remoting Layer 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 Better Window namespace. (Introducing Windows Forms) can read metadata on the(GDI+) fly (think object browsers). Next, you learn how to dynamically Chapter 14 an - Aassembly's Better Painting Framework
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 System.IO Namespace chapter concludes with the construction of an extendable Windows Forms application. Chapter 15 - Programming with Windows Forms Controls Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Part Four: Leveraging the .NET Libraries by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Chapter 12:This Object Serialization and the .NET Remoting Layer comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and
Contrary to popular belief, XML Web services are not the only way to build distributed applications under architectural issues for .NET developers. 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 machine boundaries using marshal-by-value (MBV) and marshal-by-reference (MBR) semantics. Also, the Table of Contents runtime behavior of a distributed .NET application can be altered without the need to recompile the client C# and the .NET Platform, Second Edition and server code bases using XML configuration files. Introduction Part One - Introducing C# and the .NET Platform
Chapter - The 13: Philosophy Building of .NET a Better Window (Introducing Windows Forms)
Chapter 1 Chapter 2
- Building C# Applications
Despite term .NET, the base class libraries Part Two -the The C# Programming Language
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 - Object-Oriented Programming with C# menu systems, toolbars, and status bars. As you would hope, various aspects of the Visual Studio .NET Chapter 5 - Exceptions and Object Lifetime IDE are examined over the flow of this material. Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 14: A C# Better Painting Framework (GDI+) Chapter 8 - Advanced Type Construction Techniques Part Three - Programming with .NET Assemblies
This chapter examines how to dynamically render graphical data in the Windows Forms environment. In - Understanding .NET Assemblies addition to learning how to manipulate fonts, colors, geometric images, and image files, you also examine Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming which, as you may suspect by this point in the text, is based on XML data representation. By way of a Part Four - Leveraging the .NET Libraries friendly heads up, don't pass over this chapter if you are primarily concerned with ASP.NET. As you will Chapter 12 - Object Serialization and the .NET Remoting Layer see later in Chapter 18, GDI+ can be used to dynamically generate graphical data on the Web server. Chapter 9
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15: Programming with Windows Forms Controls
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
This final Windows-centric chapter examines numerous GUI widgets that ship with the .NET Framework.
Chapter 17do - Data Access with Not only you learn how to ADO.NET program against the core Windows Forms controls, but you also learn about Part - Web Applications Web Services the Five related topics of dialog and box XML development and
Form inheritance, and how to build customWindows
Chapter - ASP.NET Pages and Web Controls Forms 18 controls. If youWeb have a background in ActiveX control development, you will be pleased to find that Chapter 19 - ASP.NET Web Applications the process of building a custom GUI widget has been greatly simplified (especially with regard to design Chapter 20 - XML Web Services time support). Index List of Figures
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# and the .NET Platform, Second Edition Visual Studio .NET. by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform,and Second Edition Part Five: Web Applications XML Web Services by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Chapter 18:This ASP.NET Web Pages and Web Controls comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and
This chapter begins your study of Web technologies supported under the .NET platform. ASP.NET is a architectural issues for .NET developers. 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 languages (such as C#, VB.NET, managed C++ and the like). This chapter introduces you to key Table of Contents ASP.NET topics such asSecond workingEdition with (or without) code behind files, the role of ASP.NET Web controls C# and the .NET Platform, (including the mighty DataGrid), validation controls, and interacting with the base class libraries from Introduction *.aspx files. Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 19: ASP.NET Web Applications - Building C# Applications
Chapter 2
Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# application-level and session-level variables. However, ASP.NET also introduces a new state Chapter 5 - Exceptions and Object Lifetime management technique: the application cache. Once you examine the numerous ways to handle state Chapter 6 - Interfaces and Collections with ASP.NET, you then learn the role of the System.HttpApplication base class (lurking within the Chapter 7 - Callback Interfaces, Delegates, and Events Global.asax file) and how to dynamically alter the runtime behavior of your Web application using the Chapter 8 - Advanced C# Type Construction Techniques web.config file. Chapter 4
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 20: XML Web Services
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer 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 Better Window Windows Forms) excellent for building platform-(Introducing and language-neutral distributed systems. You also check out Chapter 14 -surrounding A Better Painting Framework (GDI+)SOAP, and UDDI) which enable a Web service and external numerous tech-nologies (WSDL, Chapter - Programming with Windows Forms Controls client to15communicate in harmony. Part Four - Leveraging the .NET Libraries
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andBook's the .NET Platform, Edition Obtaining This SourceSecond Code by Andrew Troelsen
ISBN:1590590554
All of the code examples within this book (minus small code snippets here and there) are Apress © contained 2003 (1200 pages) available for free This and comprehensive immediate download from theaApress Web site. Simply navigate to text starts with brief overview 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 moves to key technical and architectural issues you for .NET the .NET Platform, Second Edition, may developers. download 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: Table of Contents
SOURCE is your cue that Edition the example under discussion may be loaded into Visual Studio .NET for C# and the .NET Platform, Second CODE Introduction
further examination and modification. To do so, simply open the *.sln file found in the
correct Part One - Introducing C# subdirectory. and the .NET Platform 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 Part Two - The C# Programming Language 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 - Object-Oriented Programming with C# using the Project | Add Existing Item menu selection. Chapter 2
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Second Edition Obtaining Updates for Platform, This Book by Andrew Troelsen
ISBN:1590590554
As you read overApress this text, you(1200 maypages) find an occasional grammatical or code error (although I sure hope © 2003 not). If this is the This case,comprehensive my apologies.text Being human, am sure that aofglitch starts with aI brief overview 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 moves to key technical and issues for book) .NET developers. once again on thearchitectural "homepage" for this as well as information on how to notify me of any errors you might find. Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition ContactingC# Me by Andrew Troelsen
ISBN:1590590554
If you have any questions regarding this book's source code, are in need of clarification for a given Apress © 2003 (1200 pages) example, or simply wish to offer your thoughts .NET platform, feel free to drop me a line at This comprehensive text starts regarding with a briefthe overview 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 moves to key technical and architectural issues for .NET developers. "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 Table busyoffrom Contents time to 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'm just busy (or if I'm lucky, on vacation somewhere). C# andtothe Platform, Second Edition Introduction
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.
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2 - Building C# Applications Take care, Part Two - The C# Programming Language
Andrew3 Troelsen Chapter - C# Language Fundamentals Minneapolis, MN Chapter 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Part One:C# Introducing C# and the .NET Platform ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages)
Chapter List This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Chapter 1: The Philosophy of .NET Table of Contents
Chapter 2: Building C# Applications
C# and the .NET Platform, Second Edition Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
the .NET Platform, Second Edition Chapter C# 1:and The Philosophy of .NET ISBN:1590590554 by Andrew Troelsen
Overview
Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and Every few years or architectural so, THE modern issues for day.NET programmer developers. 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 Table of Contents bullets of software development, eventually become overshadowed by something better or at very least C# and the .NET Second Edition something new.Platform, Regardless of the frustration you can feel when upgrading your internal knowledge base, Introduction it is unavoidable. Microsoft's .NET platform represents the latest wave of (positive) changes coming from Part those One kind - Introducing folks in Redmond. C# and the .NET Platform 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 Part Two - The C# Programming Language 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 - Object-Oriented Programming with C# .NET Framework, such as the common language runtime (CLR), the Common Type System (CTS), and Chapter 5 - Exceptions and Object Lifetime the Common Language Specification (CLS). As you would hope, many of these topics are explored in Chapter 6 - Interfaces and Collections further detail throughout the remainder of this text. Chapter 2
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter This chapter 8 - Advanced also provides C# Type youConstruction with an overview Techniques of the functionality supplied by the .NET base class Part libraries, Three sometimes - Programming abbreviated with .NETas Assemblies the "BCL"
or alternatively as the "FCL" (being the Framework Class
Library). you examine number of helpful utilities (such as ildasm.exe and wincv.exe) that may be Chapter 9 Finally, - Understanding .NETa Assemblies used to10 investigate the AppDomains, structure of these libraries your leisure. Chapter - Processes, Contexts, and at Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform,State Second of Edition Understanding Previous Affairs by Andrew Troelsen
ISBN:1590590554
Before examiningApress the 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. To get mindset, This comprehensive text starts withina the briefproper overview of the let's begin this chapter with a brief and painlessC# history lesson to remember our roots and understand language and then quickly moves to key technical and the limitations of the previous architectural issues forhave .NET adevelopers. state of affairs (after all, admitting you problem 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. Table of Contents C# and the .NET Platform, Second Edition
Life As a C/Win32 API Programmer
Introduction
Part One - Introducing C# and the .NET Platform
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 Part Two - The Language approach, fewC# of Programming us would disagree that
Chapter 3
building applications using the raw API is a complex undertaking.
- C# Language Fundamentals
The first problem isProgramming that C is a very terse Chapter 4 obvious - Object-Oriented with C# language. C developers are forced to contend with manual5 memory management, ugly pointer arithmetic, and ugly syntactical constructs. Furthermore, given Chapter - Exceptions and Object Lifetime that C is it lacks the benefits provided by the object-oriented approach (can anyone Chapter 6 a -structured Interfaceslanguage, and Collections sayspaghetti code?) Interfaces, When you Delegates, combine the of global functions and data types defined by the Chapter 7 - Callback andthousands Events raw Win32- API to an already formidable language, it is little wonder that there are so many buggy Advanced C# Type Construction Techniques applications floating around today. Part Three - Programming with .NET Assemblies Chapter 8 Chapter 9
- Understanding .NET Assemblies
Life As a C++/MFC Programmer
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
OneFour vast- improvement over raw C/API Part Leveraging the .NET Libraries
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 - Object Serialization and the .NET Remoting Layer programmers benefit from the famed "pillars of OOP" (encapsulation, inheritance, and polymorphism), Chapter 13 - Building a Better Window (Introducing Windows Forms) they are still at the mercy of the painful aspects of the C language (e.g., manual memory management, Chapter 14 - A Better Painting Framework (GDI+) ugly pointer arithmetic, and ugly syntactical constructs). Chapter 15 - Programming with Windows Forms Controls
Chapter The System.IO Namespace Despite16its-complexity, many C++ frameworks exist today. For example, the Microsoft Foundation Classes Chapter - Datathe Access with ADO.NET (MFC) 17 provides developer with a set of existing C++ classes that facilitate the construction of Windows Part Five - WebThe Applications XML Web Services applications. main roleand of MFC is to wrap a "sane
subset" of the raw Win32 API behind a number of
Chapter classes, 18magic - ASP.NET macros, Weband Pages numerous and Webcode Controls Wizards (i.e., AppWizard, ClassWizard, and so forth).
Regardless of the helpful assistance offered by the MFC framework (as well as many other C-based Chapter 19 - ASP.NET Web Applications windowing fact of the matter is C++ programming remains a difficult and error-prone Chapter 20 -toolkits), XML Webthe Services experience, given its historical roots in C. Index List of Figures
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# and the .NET Platform, Second Edition roots in C++. As many of you are aware, Java's strengths are far greater than its support for platform ISBN:1590590554 by Andrew Troelsen cleans up the unsavory syntactical independence. Java (as a language) aspects of C++. Java (as a Apress © 2003 (1200 pages) platform) provides programmers with a large number of predefined "packages" that contain various class This comprehensive starts with a brief overview theto build "100% Pure Java" and interface definitions. Using thesetext types, Java programmers are of able C# language and then quickly moves to key technical and applications complete with database connectivity, messaging support, Web-enabled front ends, and a richarchitectural issues for .NET developers. 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 the .NET Platform, Second Edition language independence, as this goes against the grain of Java's primary goal (a single programming Introduction language for every need). In reality however, there are millions of lines of existing code out there in the Part One - Introducing C# and the .NET Platform world that would ideally like to commingle with newer Java code. Sadly, Java makes this task problematic.
Table of Contents
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 intensive Part Two - The C#are Programming Language
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 - Object-Oriented Programming with C# ability to access non-Java APIs, there is little support for true cross-language integration. Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Interfaces, Delegates, and Events Life As- aCallback COM Programmer
Chapter 7 Chapter 8
- Advanced C# Type Construction Techniques
TheThree truth -ofProgramming the matter is,with if you areAssemblies not currently Part .NET
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 - Understanding .NET Assemblies COM is an architecture that says in effect, "If you build your classes in accordance with the rules of COM, Chapter 10 - Processes, AppDomains, Contexts, and Threads you end up with a block of reusable binary code." Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
The beauty of a binary COM server is that it can be accessed in a language-independent manner. Thus,
Chapter 12 - Object Serialization and classes the .NETthat Remoting C++ programmers can build COM can beLayer used by VB. Delphi programmers can use COM Chapter 13 Building a Better Window (Introducing Windows Forms) classes built using C, and so forth. However, as you may be aware, COM's language independence is
Chapter 14 -limited. A BetterFor Painting Framework somewhat example, there is(GDI+) no way to derive a new COM type using an existing COM type (no Chapter Programming with Windows Forms support15 for- classical inheritance). Rather, you Controls must make use of the more cumbersome "has-a" Chapter 16 - The System.IO relationship to reuse COM Namespace types. Chapter 17 - Data Access with ADO.NET
Another of COM is its location-transparent Part Five -benefit Web Applications and XML Web Services
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 Controls with raw sockets, RPC calls, and other lowlevel details. For example, ponder the following Visual Basic 6.0 Chapter 19 - ASP.NET Web Applications COM client code: Chapter 20 - XML Web Services Index
' of This block of VB 6.0 code can activate a COM class written in List Figures ' 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# and the .NET Platform, Second Edition Life As a Windows DNA Programmer by Andrew Troelsen
ISBN:1590590554
© 2003 (1200 the pages) Finally, there is aApress little thing called Internet. Over the last several years, Microsoft has been adding more Internet-aware into its text family of operating systems. seems This features comprehensive starts with a brief overviewIt of the that the popularity of Web C#expanding. language and thenbuilding quickly moves to keyWeb technical and applications is ever Sadly, a complete application using classic Windows DNA architectural issues .NET (Distributed iNternet Architecture) is for also verydevelopers. complex.
Some of this complexity is due to the simple fact that Windows DNA requires the use of numerous Table of Contents technologies and languages (ASP, HTML, XML, JavaScript, VBScript, COM(+), as well as a data access C# and theas .NET Platform, Second Edition API such ADO). One problem is that many of these items are completely unrelated from a syntactic Introduction point of view. For example, JavaScript has a syntax much like C, while VBScript is a subset of Visual Basic Part One The - Introducing C# and the .NET Platform proper. COM servers that are created to run
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 typically looks nothing likeLanguage the other Part Two - The C# Programming
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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The .NET Solution by Andrew Troelsen
ISBN:1590590554
So much for the brief history The bottom line is that life as a Windows programmer has been Apress © 2003lesson. (1200 pages) tough. The .NET This Framework is a rather and abrute-force approach comprehensive textradical starts with brief overview 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 moves to key technical (sorry, and for .NET for the message).architectural As you will issues see during the developers. remainder of this book, the .NET Framework is a completely 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 Table Contents coreof features provided courtesy of .NET: C# and the .NET Platform, Second Edition
Full interoperability with existing Win32 code. This is (of course) a good thing. Existing COM binaries Introduction can-commingle interop) withPlatform newer .NET Part One Introducing(i.e., C# and the .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 Part Two - The C# Programming Language
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
- Object-Oriented Programming with C#
Chapter 5 - Exceptions Object Lifetime A common runtime and engine shared by all .NET-aware languages. One aspect of this engine is a wellChapter defined 6 - Interfaces set of types and that Collections each .NET-aware language "understands." Chapter 7
- Callback Interfaces, Delegates, and Events
A base class library that provides shelter from the complexities of raw API calls, and offers a Chapter 8 - Advanced C# Type Construction Techniques consistent object model used by all .NET-aware languages. Part Three - Programming with .NET Assemblies Chapter - Understanding .NETIClassFactory, Assemblies No9more COM plumbing! IUnknown, IDispatch, IDL code, and the evil VARIANTChapter 10 Processes, AppDomains, Contexts, andand Threads compliant data types (BSTR, SAFEARRAY, so forth) have no place in a native .NET binary. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
A truly simplified deployment model. Part Four - Leveraging the .NET Libraries
Under .NET, there is no need to register a binary unit into the
system registry. Furthermore, runtime allows Chapter 12 - Object Serialization andthe the .NET .NET Remoting Layer multiple versions of the same *.dll to exist in harmony on a single machine (using an approach termed "side-by-side execution"). Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# Blocks and the .NET Second Edition The Building ofPlatform, the .NET Platform (CLR, CTS, and CLS) by Andrew Troelsen
ISBN:1590590554
Now that you have been©given a peek into some of the benefits provided by .NET, let's preview three key Apress 2003 (1200 pages) (and interrelated)This entities that make it all possible: CLR, CTS, and CLS. From a programmer's point of comprehensive text starts withthe a brief overview of the view, .NET can be simply understood as a new runtime environment and C# language and then quickly moves to key technical and a common base class library. issues forto.NET developers. The runtime layerarchitectural is properly referred as the common language runtime, or CLR. The primary role of 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 Table of Contents safety. C# and the .NET Platform, Second Edition
Another building block of the .NET platform is the Common Type System, or CTS. The CTS fully Introduction describes all possibleC# data types and programming Part One - Introducing and the .NET Platform
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 Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# and programming constructs that all .NET programming languages can agree on. Thus, if you build .NET Chapter 5 -only Exceptions Object Lifetime types that expose and CLS-compliant features, you can rest assured that all .NET-aware languages could Chapter 6 Interfaces and Collections make use of your types. Conversely, if you make use of a data type or programming construct that is Chapter Callback Interfaces, outside7of -the CLS, you cannot Delegates, guarantee and thatEvents every .NET programming language can interact with your Chapter 8 - Advanced binary code library. C# Type Construction Techniques Chapter 3
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and.NET the .NET Platform, Second Edition The Role ofC#the Base Class Libraries by Andrew Troelsen
ISBN:1590590554
In addition to the Apress CLR and CTS/CLS specifications, the .NET platform provides a base class library that is © 2003 (1200 pages) available to all .NET programming languages. does this base class library encapsulate various This comprehensive text starts Not with only a brief overview of the primitives such asC# threads, file IO, graphical rendering and interaction with language and then quickly moves to key technical and various hardware devices, but it architectural issues of forservices .NET developers. also provides support for a number required by most real-world applications. For example, the base class libraries define types that facilitate database manipulation, XML integration, Table programmatic of Contents security, and the construction of Web-enabled (as well as traditional desktop and console-
based) front ends. From Second a conceptual C# and the .NET Platform, Editionpoint of view, you can visualize the relationship between the .NET runtime layer and the corresponding base class library as shown in Figure 1-1. Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Figure 1-1: The CLR, CTS, CLS base class library relationship
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, What C# Brings to the Table Second Edition by Andrew Troelsen
ISBN:1590590554
Given that .NET is such ©a 2003 radical from the current thoughts of the day, Microsoft has developed Apress (1200departure pages) a new programming language (C#) specifically for this newoverview platform. This comprehensive text starts with a brief of C# theis a programming language that looksvery similar C# (butlanguage not identical) to the syntax of Java. For example, and then quickly moves to key technical andlike Java, a C# class definition is issues forfile .NET developers. contained within aarchitectural single-source code (*.cs) rather 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 Table waysofa Contents cleaned-up version of C++, C# can be viewed as a cleaned-up version of Java—after all, they are C# thesame .NET Platform, Second Edition alland in the family of languages. Introduction
TheOne truth- Introducing of the matter thatthe many ofPlatform C#'s syntactic Part C#isand .NET
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 declaration of methods that take a varying number of arguments (via parameter Chapter 2 -as Building C# Applications arrays). C# allows you to overload Part Two -Like TheC++, C# Programming Language
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
Object-Oriented Programming with 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 Object Lifetimeas Visual Basic 6.0, and provides just about as much power and cleaner) Java, justand about as simple Chapter 6 Interfaces and Collections flexibility as C++ (without the associated ugly bits). In a nutshell, the C# languages offers the following Chapter 7 (many - Callback Interfaces, Delegates, and.NET-aware Events features of which are shared by other programming languages): Chapter 8 - Advanced C# Type Construction Techniques
No pointers required!with C# .NET programs typically Part Three - Programming Assemblies
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 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
Automatic memory management. Given this, C# does not support a "delete" keyword.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging .NET Libraries Formal syntactic the constructs for enumerations,
structures, and class properties.
Chapter 12 - Object Serialization and the .NET Remoting Layer
The ability to overload forWindows a customForms) type, without the complexity (i.e., making sure Chapter 13C++-like - Building a Better Window operators (Introducing to "return *this toPainting allow chaining" is not your problem). Chapter 14 - A Better Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
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 with ADO.NET can17be- passed between boundaries (by reference or by value). Chapter 16 - The System.IO Namespace
Part Five - Web Applications and XML Web Services
Chapter Full 18support - ASP.NET for aspect-based Web Pages andprogramming Web Controls 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 Applications the20 behavior of a Services given entity. Chapter - XML Web Index
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 Figures
C# and the .NET Platform, Second Edition Additional .NET-Aware Programming Languages by Andrew Troelsen
ISBN:1590590554
On a related language-centric note,pages) understand that C# is not the only language targeting the .NET Apress © 2003 (1200 platform. When the .NET platform was revealed theoverview general of public This comprehensive textfirst starts with a to brief the during the 2000 Professional Developers Conference (PDC), several vendors announced they were C# language and then quickly moves to key technical andbusy building .NET-aware versions issues developers. of their respectivearchitectural compilers. At the for time.NET of this writing, 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 Table of Contents lookout for .NET-aware compilers targeting Smalltalk (S#), COBOL, Pascal, Python, and Perl (as well as C# and others). the .NET Platform, Second Edition many Introduction
Although this book focuses Part One - Introducing C# and(almost) the .NETexclusively Platform
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 Part Two - The C# Programming Language
Table 1-1: Sampling .NET-Aware Programming Languages Chapter 3 - AC# LanguageofFundamentals Chapter 4 - Object-Oriented Programming with C# .NET-Centric Web Link Chapter 5
http://www.oberon.ethz.ch Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques http://www.dyadic.com Part Three - Programming with .NET Assemblies
Chapter 9
Meaning in Life
- Exceptions and Object Lifetime
Homepage for Active Oberon .NET Homepage for Dyalog APL .NET
- Understanding .NET Assemblies
http://www.adtools.com
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries http://www.eiffel.com
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
http://research.microsoft.com/projects/ilx/fsharp.htm
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
http://lahey.com Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
http://www.cs.inf.ethz.ch
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
http://www.activestate.com Chapter 20 - XML Web Services Index List of Figures Listhttp://smallscript.org of Tables
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 and the .NET Platform, Second Edition as VB .NET). StillC# others may want to leverage their mainframe skills while moving to the .NET platform ISBN:1590590554 by Andrew Troelsen (via COBOL .NET). Apress © 2003 (1200 pages)
Now, be honest: If Microsoft were to text buildstarts a single .NET language This comprehensive with"official" a brief overview of the that was derived from the C# languagecan andyou then quickly to key technical and BASIC family of languages, really saymoves all programmers would be happy with this choice? Or, if the architectural issues forbased .NET developers. 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 Table of Contents among teammates, departments, and external organizations (regardless of which .NET language others C# and the .NET Platform, Second Edition choose to use). Introduction
Part One -excellent Introducing C# and of theintegrating .NET Platform Another byproduct 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. Others offer superior support Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# everybody wins. Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Of course, in reality the chances are quite good that you will spend much of your time building software Callback Interfaces, Delegates, and Events using your-.NET language of choice (which is great! ) However, as you may be expecting, once you learn Chapter 8 -ofAdvanced Type Construction Techniques the syntax one .NETC#language, it is very easy to master another. This is also quite beneficial, especially Part Three - Programming with .NET Assemblies to the consultants of the world. If your language of choice happens to be C#, but you are placed at a client Chapter - Understanding Assemblies site that9 has committed to .NET VB .NET, you should be able to parse the existing code body almost instantly Chapter 10 while - Processes, AppDomains, Contexts, Threads (honest!) still continuing to leverage the and .NET Framework. Enough said. Chapter 7
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# of and.NET the .NET Platform, Second An Overview Binaries (aka Edition Assemblies) by Andrew Troelsen
ISBN:1590590554
Regardless of which .NET language you choose to program with, understand that despite the fact that Apress © 2003 (1200 pages) .NET binaries take the same file extension as classic binaries of (*.dll This comprehensive text starts with a COM brief overview 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 moves to key technical and architectural developers. with the classic COM runtime issues (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 Table of Contents "intermediate language" (IL). Conceptually, Figure 1-2 shows the big picture of the story thus far. C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
Advanced C# Type Construction Techniques Figure- 1-2: All .NET-aware compilers emit IL instructions and metadata.
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies Note is one AppDomains, point to be made regarding the acronym "IL." During the development of .NET, the Chapter 10 There - Processes, Contexts, and Threads
for "IL" was Microsoft language (MSIL). However with the final release Chapter 11 official - Type term Reflection, Late Binding, andintermediate Attribute-Based Programming of .NET, thethe (new) term Part Four - Leveraging .NETofficial Libraries
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 - Object Serialization and the .NET edition Remoting Layer describing the same exact entity. In keeping with the current terminology, I will use the term CIL Chapter 13 - Building a Better Window (Introducing Windows Forms) throughout this text from here on out. Chapter 14 - A Better Painting Framework (GDI+)
Chapter - Programming When a15*.dll or *.exe has with beenWindows created Forms using aControls .NET-aware compiler, the resulting module is bundled into Chapter 16 The System.IO Namespace an "assembly." You examine numerous details of .NET assemblies in Chapter 9. However to facilitate the Chapter 17 -of Data with ADO.NET discussion the Access .NET runtime environment, you do need to examine some basic properties of this new Part - Web Applications and XML Web Services file Five format.
Chapter 18 - ASP.NET Web Pages and Web Controls
As mentioned, an assembly contains CIL code, which is conceptually similar to Java byte code in that it is Chapter 19 - ASP.NET Web Applications not compiled to platform-specific instructions until absolutely necessary. Typically "absolutely necessary" Chapter 20 - XML Web Services
is the point at which a block of CIL instructions (such as a method implementation) are referenced for use by the .NET runtime engine.
Index
List of Figures
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# and the .NET Platform, Second Edition to examine an assembly's underlying CIL, type metadata and manifest information later in this chapter. by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Single File This andcomprehensive Multifile text Assemblies starts with a brief overview of the C# language and then quickly moves to key technical and
In a great numberarchitectural of cases, there is for a simple one-to-one correspondence between a .NET assembly and issues .NET developers. 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 application, the *.exe can simply be referred to as the assembly itself. As seen in Chapter 9 however, this Table of Contents is not completely accurate. Technically C# and the .NET Platform, 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 Introduction and associated manifest in an autonomous, single, well-defined package. Part One - Introducing C# and the .NET Platform 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) Part Two - The C# Programming Language 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 - Object-Oriented with C# primary4module documentsProgramming the set of required secondary modules within the assembly manifest. Chapter 2
Chapter 5
- Exceptions and Object Lifetime So, why6 would you choose to create a multifile assembly? When you partition an assembly into discrete Chapter - Interfaces and Collections
modules, end upInterfaces, with a more flexible deployment Chapter 7 you - Callback Delegates, and Events 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 TypetoConstruction Techniques the Three required modules. Therefore, are free Part - Programming with .NETyou Assemblies
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 - Understanding .NET Assemblies alone module. Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object and the Layer modules that are intended to be deployed and assembly really aSerialization logical grouping of.NET one Remoting or more related Chapter 13 Building a Better Window (Introducing Windows Forms) versioned as a single unit. Part Four - Leveraging the .NET Libraries
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
andCommon the .NET Platform, Second Edition The Role ofC#the Intermediate Language by Andrew Troelsen
ISBN:1590590554
Now that you have a better feel for pages) .NET assemblies, let's examine the role of the common intermediate Apress © 2003 (1200 language (CIL) inThis a bitcomprehensive more detail. CIL a language that sits aboveofany textisstarts with a brief overview theparticular platform-specific instruction set. Regardless of which .NET-aware language you choose C# language and then quickly moves to key technical and(C#, Visual Basic .NET, Eiffel architectural issues compiler for .NET developers. .NET, and so forth), the associated emits CIL 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 Table ofmethod: Contents Add() C# and the .NET Platform, Second Edition Introduction
// We will examine namespaces later in the chapter... using System;
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2 - Building C# Applications namespace Calculator Part { Two - The C# Programming Language
Chapter // 3 -This C# Language class Fundamentals contains the app's entry point. Chapter public 4 - Object-Oriented Programming with C# class CalcApp Chapter { 5 Chapter 6
- Exceptions and Object Lifetime
Chapter 7
{ - Callback Interfaces, Delegates, and Events
Chapter 8
Calc = new Calc(); - Advanced C# c Type Construction Techniques
- Interfaces public static and Collections void Main()
int ans c.Add(10, Part Three - Programming with=.NET Assemblies84); Chapter 9
Console.WriteLine("10 + 84 is {0}.", ans); - Understanding .NET Assemblies
Console.ReadLine(); // Threads Wait for user key-press. Chapter 10 - Processes, AppDomains, Contexts, and } Reflection, Late Binding, and Attribute-Based Programming Chapter 11 - Type Part Four} - Leveraging the .NET Libraries
// The C# calculator. public class Calc 13 - Building a Better Window (Introducing Windows Forms) { 14 - A Better Painting Framework (GDI+) // A single method. 15 - Programming with Windows Forms Controls public int Add(int x, int y) 16 - The System.IO Namespace { return x + y; } 17 - Data Access with ADO.NET }
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter Chapter Chapter Chapter Chapter
Part } Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Once the compiler (csc.exe) compiles this source code file, you end up with a single file *.exe Chapter 20 C# - XML Web Services assembly that contains a manifest, CIL instructions, and metadata describing each aspect of the Calc and Index CalcApp classes. For example, if you peek inside this binary using ildasm.exe (examined a little later in this List of Figures 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# and the .NET Platform, Second Edition
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 Andrew Troelsen concentrate on is that the C# compiler emits CIL, not platform specific instructions. Apress © 2003 (1200 pages)
Thisiscomprehensive text startscompilers. with a brief of assume the Now, recall that this true of all .NET-aware Tooverview illustrate, you created the Calc language then quickly moves application using C# Visual Basic and .NET, rather than C#: to key technical and architectural issues for .NET developers.
' The VB .NET calculator... Class Calc Table of Contents Public Add(ByVal x As Integer, ByVal y As Integer) As Integer C# and the .NET Function Platform, Second Edition ' Yes! VB .NET (finally) supports a 'Return' keyword. Introduction Return x + y Part One - Introducing C# and the .NET Platform End Function Chapter 1 - The Philosophy of .NET End Class Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
' A VB .NET 'Module' is a class that only contains - C# Language Fundamentals ' static members. Chapter 4 - Object-Oriented Programming with C# Module CalcApp Chapter 5 - Exceptions and Object Lifetime Sub Main() Chapter 6 -Dim Interfaces and Integer Collections ans As Chapter 7 -Dim Callback Interfaces, Delegates, and Events c As New Calc Chapter 8 -ans Advanced C# Type Construction Techniques = c.Add(10, 84) Part Three - Programming with .NET Assemblies Console.WriteLine("10 + 84 is {0}.", ans) Chapter 9 -Console.ReadLine() Understanding .NET Assemblies ChapterEnd 10 -Sub Processes, AppDomains, Contexts, and Threads Chapter End Module 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter 3
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
If you examine the CIL for theWindow Add() method, you Windows find the same sort of instructions (slightly tweaked by the Chapter 13 - Building a Better (Introducing Forms) VB .NET compiler):
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
.method instance int32 Add(int32 x, int32 y) cil managed Chapter 16 -public The System.IO Namespace { Chapter 17 - Data Access with ADO.NET 9 XML (0x9) Part// FiveCode - Websize Applications and Web Services .maxstack 2 .locals init ([0] int32 Add) Chapter 19 - ASP.NET Web Applications IL_0000: nop Chapter 20 - XML Web Services IL_0001: ldarg.1 Index IL_0002: ldarg.2 List of Figures 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 Controls
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# and the .NET Platform, Second Edition defined binary arena. by Andrew Troelsen
ISBN:1590590554
Apress 2003 pages)agnostic, the .NET runtime is poised to become a platformFurthermore, given that ©CIL is (1200 platform independent architecture, providing the Javaoverview developers have grown accustomed to (i.e., This comprehensive textsame startsbenefits with a brief of the language and then quickly to key technicalsystems). and the potential of a C# single code base running on moves numerous operating In fact, there is an architectural issues for .NET developers. international standard for a large 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 Table of Contents a language-independent fashion. Thus, .NET has the potential to allow you to develop an application in C# and the .NET Platform, Second Edition any language and have it run on any platform. Introduction
Part One - Introducing andmore the .NET Platform Note I'll commentC# a bit on the platform-independent
nature of .NET at the conclusion of this
Chapter 1 chapter. - The Philosophy of .NET Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition The Role ofC#.NET Type Metadata by Andrew Troelsen
ISBN:1590590554
COM programmers are ©without a doubt Apress 2003 (1200 pages) familiar with the Interface Definition Language (IDL). IDL is a "metalanguage" that is used to describe types within aofgiven This comprehensive text the starts withcontained a brief overview the COM server. IDL is compiled into a binary format (termed a type library) using the midl.exe compiler, C# language and then quickly moves to key technical andwhich can then be used by a COMarchitectural issues for .NET developers. aware language to manipulate the contained types. In addition to describing the types within a COM binary, IDL has minimal support to describe characteristics Table about ofthe Contents COM binary itself, such as its current version (e.g., 1.0, 2.0, or 2.4) and intended locale (e.g.,
English, Urdu, Russian). The problem with COM metadata is that it may or may not be present C# and theGerman, .NET Platform, Second Edition and it is often the role of the programmer to ensure the underlying IDL accurately reflects the internal Introduction types. Part One - Introducing C# and the .NET Platform 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 Part Two - The C# Programming Language 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 - Object-Oriented Programming with C# type (properties, methods, events, and so on). Chapter 2
Chapter 5
- Exceptions and Object Lifetime
Chapter Furthermore, 6 - Interfaces the .NETand manifest Collections (which as you recall is metadata describing the assembly itself) is far
more complete than Interfaces, IDL, in thatDelegates, it also describes each externally referenced assembly that is required by Chapter 7 - Callback and Events the executing assembly operate correctly.Techniques Because .NET metadata is so wickedly meticulous, Chapter 8 - Advanced C#toType Construction assemblies are completely selfdescribing entities. Part Three - Programming with .NET Assemblies
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 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
A Quick Metadata Example
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
To illustrate the format of .NETand metadata, take a Layer look at the metadata that has been generated for Chapter 12 - Object Serialization the .NETlet's Remoting the Add() ofathe C# Calculator class you Windows examinedForms) previously (the metadata generated for the VB Chapter 13 method - Building Better Window (Introducing .NET Add() similar). Using the(GDI+) ildasm.exe utility (examined at the end of this chapter) you can Chapter 14 - method A Better is Painting Framework view your metadata by hitting the Ctrl+M keystroke. Within the resulting "MetaInfo" window, you Chapter 15 assembly's - Programming with Windows Forms Controls will find a description of the Add() method looking something like the following::
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Method #2 Applications and XML Web Services Part Five - Web ------------------------------------------------------Chapter 18 - ASP.NET Web Pages and Web Controls MethodName: Add Web (06000002) Chapter 19 - ASP.NET Applications Flags : [Public] [HideBySig] [ReuseSlot] (00000086) RVA : 0x00002064 Index ImplFlags : [IL] [Managed] (00000000) List of Figures 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 Services
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
andAssembly the .NET Platform, Second Edition The Role ofC#the Manifest by Andrew Troelsen
ISBN:1590590554
Last but not least,Apress recall©that validpages) .NET assembly will also contain metadata that describes the code 2003a(1200 library itself (technically termed a manifest). Like type metadata, it isofalways the job of the compiler to This comprehensive text starts with a brief overview the generate the assembly's manifest. For example, here are some relevant details of the CSharpCalculator C# language and then quickly moves to key technical and architectural issues for .NET developers. assembly: .assembly extern mscorlib { C# and the .NET Platform, Second Edition .publickeytoken = (B7 7A 5C 56 19 34 E0 89) Introduction .ver 1:0:3300:0 Part One - Introducing C# and the .NET Platform } Chapter 1 - The Philosophy of .NET .assembly CSharpCalculator Chapter 2 Building C# Applications { Part.hash Two - The C# Programming Language algorithm 0x00008004 Chapter 3 1:0:932:40235 - C# Language Fundamentals .ver Chapter 4 - Object-Oriented Programming with C# } Chapter 5 - Exceptions and Object Lifetime .module CSharpCalculator.exe Chapter .imagebase 6 - Interfaces 0x00400000 and Collections .subsystem 0x00000003 Chapter 7 - Callback Interfaces, Delegates, and Events .file alignment Chapter 8 - Advanced C# 512 Type Construction Techniques 0x00000001 Part.corflags Three - Programming with .NET Assemblies
Table of Contents
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, 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 Part Four - Leveraging the .NET Libraries binary itself (via the .assembly, .ver, .module (etc.) directives). Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and .NET Platform, Second Edition Compiling CIL tothePlatform-Specific Instructions by Andrew Troelsen
ISBN:1590590554
Due to the fact that assemblies contain Apress © 2003 (1200 pages)CIL instructions and metadata, rather than platform-specific instructions, the underlying CIL must be compiled before use. The entity that compiles the CIL This comprehensive text starts withon a the brieffly overview of the into meaningful CPU instructions is termed a just-in-time (JIT) compiler that sometimes goes by the C# language and then quickly moves to key technical and architectural issuesruntime for .NETenvironment developers. leverages a JIT compiler for each CPU targeting friendly name of "Jitter." The .NET the CLR, each of which is optimized for the platform it is targeting. Table For example, of Contents if you are building a .NET application that is to be deployed on a handheld device, the
corresponding is well-equipped to run within a low-memory environment. On the other hand, if you C# and the .NET Jitter Platform, Second Edition are deploying your assembly to a back end server (where memory is seldom an issue), the related Jitter Introduction will One be optimized to function a high-memory Part - Introducing C# and in the .NET Platform environment.
In this way, developers can write a single body
of code1that 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 - Object-Oriented Programming with C# instructions on the first invocation and retained in memory for later use. Therefore, the next time Bar() is Chapter - Exceptions Object Lifetime called, 5there is no needand to recompile the CIL. As you will see in Chapter 9, the .NET SDK also provides a Chapter 6 Interfaces and Collections tool called ngen.exe that will compile CIL code to a native image at the time of installation. Part Two - The C# Programming Language
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, Type Second System Edition Understanding Common by Andrew Troelsen
ISBN:1590590554
As already mentioned, assembly Apressa©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 used toofcollectively refer to an entity from the This comprehensive is text startsa with a brief overview the set {class, structure, interface, enumeration, delegate}. When you build solutions using a .NET-aware C# language and then quickly moves to key technical and architectural issues forlikely .NETinteract developers. language (such as C#), you will most with each of these types. For example, your assembly 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. Table of Contents
Recall that.NET the Common Type System C# and the Platform, 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 Introduction CTS defines a number syntactic constructs Part One - Introducing C#ofand the .NET Platform (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 languages, you need to conform your exposed types to the rules of the CLS (defined Chapter 2 .NET-aware - Building C# Applications shortly). being, let's preview Part Two -For Thethe C# time Programming Language Chapter 3
the formal definitions of all possible CTS types.
- C# Language Fundamentals
- Object-Oriented CTS Class Types Programming with C#
Chapter 4 Chapter 5
- Exceptions and Object Lifetime Every .NET-aware language supports, at the very least, the notion of a "class type," which is the Chapter 6 - Interfaces and Collections
cornerstone of object-oriented class may be composed of any number of members (such Chapter 7 - Callback Interfaces, programming. Delegates, and A Events
as constructors, operators, properties, methods, and events) and data points (fields). As you would expect, - Advanced C# Type Construction Techniques the CTS allows a given class to support virtual and abstract members that define a polymorphic interface Part Three - Programming with .NET Assemblies for derived classes. On the limiting side of the equation, CTS classes may only derive from a single base Chapter 9 - Understanding .NET Assemblies class (multiple inheritance is not allowed for class types). Chapter 4 provides all the gory details of building Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming types. Chapter 8
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Table 1-2: CTS Class Characteristics
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Class Meaning in Life Chapter 14 - A Better Painting Framework (GDI+) Characteristic Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Is the class "sealed" or not?
Sealed classes are types that cannot function as a base class to other types.
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Does 18 the-class implement is a collection of abstract members that provide a Chapter ASP.NET Web Pages An andinterface Web Controls any interfaces? contract between the object and object user. The CTS allows a Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
class to implement any number of interfaces.
Index Is the class abstract or Listconcrete? of Figures
Abstract classes cannot be directly created, but are intended to define common behaviors for derived types. Concrete classes can be created directly.
List of Tables
What is the "visibility" of this class?
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# and the .NET Platform, Second Edition a bit more pizzazz (at the risk of offending the C++ purists): by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
// Create a C# structure. This comprehensive text starts with a brief overview of the struct Baby C# language and then quickly moves to key technical and { architectural issues for .NET developers. // Structures can contain fields. public string name; Table of Contents
// .NET Structures can contain constructors (with arguments). C# and the Platform, Second Edition public Baby(string name) Introduction this.nameC#=and name; } Platform Part One{- Introducing the .NET Chapter 1
- The Philosophy of .NET may take methods. Chapter // 2 -Structures Building C# Applications
Cry() Language Part Twopublic - The C# void Programming { Console.WriteLine("Waaaaaaaaaaaah!!!"); } - C# Language Fundamentals
Chapter 3 Chapter 4
- Object-Oriented Programming with C#
public bool IsSleeping() { return false; } - Exceptions and Object Lifetime public bool IsChanged() { return false; }
Chapter 5 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
}
Part Three - Programming with .NET Assemblies Here is our structure in action (assume this logic
Chapter 9
is contained in some Main() method):
- Understanding .NET Assemblies
Chapter 10 - Processes, Contexts, and Threads // Welcome to theAppDomains, world Max Barnaby!! Chapter 11 - Type Reflection, Binding, and Attribute-Based Programming Baby barnaBaby = new Late Baby("Max"); Part Four - Leveraging the .NET Libraries Console.WriteLine("Changed?:
{0} ", barnaBaby.IsChanged());
Chapter 12 - Object Serialization and the .NET Remoting Layer Console.WriteLine("Sleeping?: {0} ", barnaBaby.IsSleeping()); Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter // Show 14 -your A Better true Painting colors Framework Max... (GDI+)
for(int = 0; i < with 10000; i++) Chapter 15 -iProgramming Windows Forms Controls Chapter barnaBaby.Cry(); 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
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 Applications be aware that the CTS permits structures to implement any number of interfaces; however, structures may Chapter 20 - XML Web Services not function as the base type to other classes or structures and are therefore explicitly "sealed." Chapter 18 - ASP.NET Web Pages and Web Controls
Index
List of Figures
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# and the .NET Platform, Second Edition specific name. For example, assume you are creating a video game application that allows the user to ISBN:1590590554 by player Andrewtypes Troelsen select one of three (Wizard, Fighter, or Thief). Rather than keeping track of raw numerical Apress © 2003 (1200 pages) values to represent each possibility, you could build a custom enumeration: This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and // A C# enumeration. architectural issues for .NET developers.
public enum PlayerType { Wizard = 100, Fighter = 200, Thief = 300 } ; Table of Contents C# and the .NET Platform, 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 Part One - Introducing C# and the .NET Platform 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. Introduction
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
CTS Delegate Types - Object-Oriented Programming with C#
Chapter 4 Chapter 5
- Exceptions and Object Lifetime
Delegates are the .NET equivalent of a type safe C style function pointer. The key difference is that a .NET - Interfaces and Collections delegate is a class that derives from System.MulticastDelegate, rather than a simple pointer to a raw Chapter 7 - Callback Interfaces, Delegates, and Events 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 Construction Techniques another entity. Furthermore, delegates provide intrinsic support for multicasting (i.e., forwarding a request Part Three - Programming with .NET Assemblies to multiple recipients) and asynchronous method invocations. As you will see in Chapter 7, delegates Chapter Understanding .NET.NET Assemblies provide9the- foundation for the event protocol. Chapter 6
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
CTS Type Members
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Now that you have previewed each of the .NET types formalized by the CTS, realize that each may take
Chapter 13 - Building a Better Windowspeaking, (Introducing Windows Forms) any number of members. Formally a type member is constrained by the set {constructor, static Chapter 14 - Anested Better type, Painting Framework (GDI+) constructor, operator, method, property, field, constant, event}. Chapter 15 - Programming with Windows Forms Controls
The CTS the various "adornments" that may be associated with a given member. For example, Chapter 16 defines - The System.IO Namespace each member has a given "visibility" Chapter 17 - Data Access with ADO.NETtrait (e.g., public, private, protected, and so forth). A member may be declared as "abstract" to enforce a polymorphic Part Five - Web Applications and XML Web Servicesbehavior
on derived types as well as "virtual" to define a
canned18 (but overridable) As well, most members may be configured as "static" (bound at Chapter - ASP.NET Web implementation. Pages and Web Controls the class or "instance" level (bound at the object level) entities. The construction of type members is Chapter 19 level) - ASP.NET Web Applications examined over the course of the next several chapters.
Chapter 20 - XML Web Services Index
Intrinsic CTS Data Types
List of Figures 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# Edition C# and the .NET Platform, Second .NET Keyword by Andrew Troelsen Apress © 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 comprehensive text starts with a brief overview of the and then quickly moves to key technical and char System.SByte C# language Not supported sbyte signed architectural issues for .NET developers.
Table of Contents
C#System.Int64 and the .NET Platform,Long Second Edition Introduction
System.UInt16
Not supported
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy .NET System.UInt32 Not of supported Chapter 2
- Building C# Applications
System.UInt64
Not supported
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals System.Single Single Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
System.Double
Double
Chapter 6 - Interfaces and Collections System.Object Object Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
System.Char
Char
Part Three - Programming with .NET Assemblies System.String String
Chapter 9
- Understanding .NET Assemblies
System.Decimal
Decimal
char
__wchar_t
string
String*
decimal
Decimal
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter System.Boolean 11 - Type Reflection, Boolean Late Binding, and Attribute-Based bool Programming bool Part Four - Leveraging the .NET Libraries
Chapter As you 12 can- see, Object not Serialization all languages and are the able .NET to Remoting represent Layer the same intrinsic data types of the CTS using
specific13 keywords. you might imagine, it wouldWindows be very helpful Chapter - BuildingAs a Better Window (Introducing Forms) to create a well-known subset of the CTS that defines common, shared set of programming constructs (and data types) for all .NET-aware Chapter 14 - Aa Better Painting Framework (GDI+) languages. the CLS. Chapter 15 - Enter Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, Language Second Edition Specification Understanding Common by Andrew Troelsen
ISBN:1590590554
As you are aware, different languages express the same programming constructs in unique, languageApress © 2003 (1200 pages) specific terms. For example, in C#, string concatenation is overview denoted using This comprehensive text starts with a brief 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 moves to key technical andlanguages express the same architectural issuesafor .NET developers. programmatic idiom (for example, function with no return value) the chances are very good that the syntax will appear quite different on the surface: Table of Contents
' VB .NET function returning void (aka VB .NET subroutines). Public Sub Foo() Introduction ' stuff... Part One - Introducing C# and the .NET Platform End Sub C# and the .NET Platform, Second Edition
Chapter 1
- The Philosophy of .NET
Chapter - Building C# Applicationsvoid. // C#2 function returning Part Two - The C# Foo() Programming Language public void
Chapter 3 {
- C# Language Fundamentals
Chapter // 4 -stuff... Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime } Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
As you 8have already seen, these minor syntactic variations are inconsequential in the eyes of the .NET Chapter - Advanced C# Type Construction Techniques runtime, given that the respective compilers (csc.exe or vbc.exe in this case) are configured to emit the Part Three - Programming with .NET Assemblies same CIL instruction set. However, languages can also differ with regard to their overall level of Chapter 9 - Understanding .NET Assemblies functionality. For example, some languages (C#) allow you to overload operators for a given type while Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming correctly in other languages. What we need is to have a baseline to which all .NET aware languages are Part Four - Leveraging the .NET Libraries expected to conform. Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 is- a Building a Better Window (Introducing Windows Forms) The CLS set of guidelines that describe in vivid detail, the minimal and complete set of features a Chapter 14 - A Better Painting must Framework (GDI+) given .NET-aware compiler support to produce code that can be hosted by the CLR, while at the Chapter same time 15 - be Programming accessed inwith a uniform Windows manner Forms by Controls all languages that target the .NET platform. In many ways
the CLS be System.IO viewed as Namespace a physical subset of the full functionality defined by the CTS. Chapter 16can - The Chapter 17 - Data Access with 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 Controls and describes how this rule affects those who build the compilers as well as those who (in some way) Chapter 19 - ASP.NET Web Applications interact with them. For example, the crème de la crème of the CLS is the mighty Rule 1: Part Five - Web Applications and XML Web Services
Chapter 20 - XML Web Services Index
1: CLS rules apply only to those parts of a type that are exposed outside the defining assembly. List ofRULE Figures 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# and the .NET Platform, Second Edition // Not CLS compliant! by Andrew Troelsen x, ulong y) public ulong Add(ulong © 2003 (1200 pages) { return Apress x + y;}
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
}
However, if you were to update your CLS-compliant method as follows: Table of Contents
public class Calc { Introduction // Still CLS compliant! Part One - Introducing C# and the .NET Platform 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 Part Two - The C# Programming Language // CLS compliant. Chapter 3 -ulong C# Language Fundamentals theAnswer = (ulong)(x + y); Chapter 4 -Console.Write("Answer Object-Oriented Programming with C# as ulong: {0}\n", Chapter 5 - Exceptions and Object Lifetime theAnswer); Chapter 6 -return Interfacesxand + Collections y; Chapter}7 - Callback Interfaces, Delegates, and Events ... 8 - Advanced C# Type Construction Techniques Chapter } Three - Programming with .NET Assemblies Part C# and the .NET Platform, Second Edition
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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.
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 -inBuilding a to Better (Introducing Windows Forms) Of course, addition RuleWindow 1, the CLS defines numerous other rules. For example, the CLS describes Chapter 14 - Alanguage Better Painting Frameworktext (GDI+) how a given must represent strings, how enumerations should be represented internally (the Chapter 15 -used Programming withhow Windows base type for storage), to useForms static Controls types, and so forth. Again, remember that in most cases Chapter these rules 16 - do Thenot System.IO have to be Namespace committed to memory (unless you need to build a LISP .NET compiler!). Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Ensuring CLS Compliance
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter ASP.NET Webcourse Applications As you 19 will- see over the of this book, C# does define a number of constructs that are not CLS Chapter compliant. 20 -The XMLgood Web Services news, 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 Index namespace List of Figures 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# andthe the .NET Platform, Language Second Edition Runtime Understanding Common by Andrew Troelsen
ISBN:1590590554
In addition to the Apress CTS and CLS specifications, the final TLA (three-letter-acronym) to contend with at the © 2003 (1200 pages) moment is the CLR. Programmatically speaking, thea term runtime can be understood as a collection of This comprehensive text starts with brief overview of the external services C# thatlanguage are required to execute a given compiled unit of code. For example, when and then quickly moves to key technical and issues forFoundation .NET developers. developers makearchitectural use of the Microsoft 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 Table of Contents are also tied to a runtime module or two (e.g., msvbvm60.dll). Java developers are tied to the Java Virtual C# and the(e.g., .NET JVM) Platform, Edition Machine andSecond so forth. Introduction
TheOne .NET platform offers yet the another runtime system. Part - Introducing C# and .NET Platform
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 welldefined2runtime layerC# that is shared by all languages and platforms that are .NET aware. As mentioned Chapter - Building Applications earlier the .NETLanguage runtime is Part Twoin- this The chapter, C# Programming 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 - Object-Oriented Programming with C# Object Runtime Execution Engine). When an assembly is referenced for use, mscoree.dll is loaded Chapter 5 - Exceptions automatically, which in and turnObject loads Lifetime the required assembly into memory. The runtime engine is responsible Chapter 6 Interfaces 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 Interfaces, Delegates, Events structure, etc.) within the binary by reading the and finding requested type (e.g., class,and interface, Chapter 8 -metadata. Advanced The C# Type Construction contained execution engine Techniques lays out the type in memory, compiles the associated CIL into Part Three - Programming with .NET Assemblies platform-specific instructions, performs any (optional) security checks and then executes the code in Chapter 9 - Understanding .NET Assemblies question. Chapter 4
Chapter 10 - Processes, AppDomains, Contexts, and Threads
In addition loading your custom assemblies and creating your custom types, the CLR will also interact Chapter 11 -toType Reflection, Late Binding, and Attribute-Based Programming withFour the types contained the .NET Part - Leveraging the within .NET Libraries
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 - Object Serialization and the .NET Remoting Layer contains a large number of core types that encapsulate a wide variety of common programming tasks as Chapter 13 - Building a Better Window (Introducing Windows Forms) well as the core data types used by all .NET languages. When you build .NET solutions, you always make Chapter 14 - A Better Painting Framework (GDI+) use of this particular assembly, and perhaps numerous other .NET binaries (both system supplied and Chapter 15 - Programming with Windows Forms Controls custom). Chapter 16 - The System.IO Namespace
Chapter Data Access ADO.NET Figure 17 1-3-illustrates thewith workflow that takes place between your source code (which is making use of Part Five - Web Applications XML Web Services and base class library types), a and given .NET compiler,
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
the .NET execution engine.
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Figure mscoree.dll in action Chapter 16 - 1-3: The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the Namespaces .NET Platform, Second Edition A Tour of the .NET by Andrew Troelsen
ISBN:1590590554
Each of us understands importance Apress ©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 comprehensiveset textofstarts withcode a brief overview in of their the applications. For example, MFC defines a numberC# of language C++ classes that provide canned implementations and then quickly moves to key technical andof dialog boxes, menus, and issues .NET developers. of the world, as they can spend less time toolbars. This is aarchitectural good thing for 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. Table of Contents
Unlike MFC, Java, or Visual Basic 6.0, the C# language does not come with a predefined set of languageC# and the .NET Platform, Second Edition specific classes. Ergo, there is no C# class library. Rather, C# developers leverage existing types supplied Introduction by the Framework. To keep all the types Part One.NET - Introducing C# and the .NET Platform
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 - Object-Oriented Programming with C# application, written in C#, VB .NET, and C++ with managed extensions (MC++): Part Two - The C# Programming Language
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
// Hello world in C# - Callback Interfaces, Delegates, and Events using System; Chapter 8 - Advanced C# Type Construction Techniques public class MyApp Part Three - Programming with .NET Assemblies { Chapter public 9 - Understanding .NET Assemblies static void Main() Chapter { 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, andfrom Attribute-Based Console.WriteLine("Hi C#"); Programming Part Four} - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer } Chapter 7
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter ' Hello 14 -world A Betterin Painting VB .NET Framework (GDI+)
Imports Chapter 15 -System Programming with Windows Forms Controls Public MyApp Namespace Chapter 16 Module - The System.IO Main() Chapter Sub 17 - Data Access with ADO.NET from Part Five - WebConsole.WriteLine("Hi Applications and XML Web Services
VB .NET")
Sub Chapter End 18 - ASP.NET Web Pages and Web Controls End Module Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
// Hello world in Managed C++ (MC++) #using List of Figures using namespace System; List of Tables void main() { Console::WriteLine(S"Hi from MC++"); } Index
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# and the .NET Platform, Second Edition to group semantically related types (classes, enumerations, interfaces, delegates, and structures) under a ISBN:1590590554 by Andrew Troelsen single umbrella. For example, the System.Drawing namespace contains a number of types to assist you in Apress © 2003 (1200 pages) rendering images onto a given graphics device. Other namespaces exist for data access, Web This comprehensive text starts with a(among brief overview of the From a very high level, Table development, threading, and programmatic security many others). C# language and then quickly moves to key technical and 1-4 offers a rundown of some (but certainly not all) of the .NET namespaces. architectural issues for .NET developers. Table 1-4: A Sampling of .NET Namespaces Table of Contents
.NET Namespace
Meaning in Life
C# and the .NET Platform, Second Edition
System Introduction
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.
with primitive Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
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 - Object-Oriented Programming C#you to build customized collections. thatwith allow
Chapter 5
- Exceptions and Object Lifetime System.Data Chapter 6 - Interfaces 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 Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques System.Data.OleDb Part Three - Programming with .NET Assemblies
System.Data.SqlClient
Chapter 9
- Understanding .NET Assemblies System.Diagnostics Here, you numerous types that can be used by any Chapter 10 - Processes, AppDomains, Contexts, andfind Threads
.NET-aware language Programming to programmatically debug and trace Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Part Four - Leveraging the .NET Librariesyour
source code.
Chapter 12 - Object Serialization and the .NET Remoting Layer
System.Drawing
Here, you find numerous types wrapping GDI+ primitives
Chapter 13 - Building a Better Window (Introducing Windows Forms) such as bitmaps, fonts, icons, printing support, and advanced System.Drawing.Drawing2D Chapter 14 - A Better Painting Framework (GDI+) rendering support. graphical
System.Drawing.Printing Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace This namespace includes file IO, buffering, and so forth. System.IO Chapter 17 - Data Access with ADO.NET
System.Net This namespace (as Part Five - Web Applications and XML Web Services
well as other related namespaces)
contains types related to network programming Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications (requests/responses, sockets, end points, etc.). Chapter 20 - XML Web Services System.Reflection Index
System.Reflection.Emit
Defines types that support runtime type discovery and dynamic creation and invocation of custom types.
List of Figures
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
A number of namespaces are specifically geared toward the C# and the .NET Platform, Second Edition applications, including ASP.NET ISBN:1590590554 by Andrew Troelsen development of .NET Web and XML Web services. Apress © 2003 (1200 pages)
This comprehensive text startsthe with a briefthe overview of the does contain System.Windows.Forms Despite name, .NET platform C# language and then quickly moves to key technical and namespaces that facilitate the construction of more architectural issues for .NET developers. 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 the .NET Platform, Second EditionXML data.
Table of Contents Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET Accessing a Namespace Programmatically - Building C# Applications
Chapter 2
Part - The C# Programming Languageis It is Two worth reiterating that a namespace
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, Object-Oriented with System.Console C# From your you Programming can assume that represents a class named Console that is Chapter 5 -within Exceptions and Object Lifetime contained a namespace called System. However, in the eyes of the .NET runtime, this is not so. The Chapter - Interfaces andaCollections runtime6 engine only sees single entity named System.Console. Chapter 7
- Callback Interfaces, Delegates, and Events
As you 8build your custom types, you have the option of organizing your items into a custom namespace. Chapter - Advanced C# Type Construction Techniques Again, a namespace is a logical naming scheme used by .NET languages to group related types under a Part Three - Programming with .NET Assemblies unique umbrella. When you group your types into a namespace, you provide a simple way to circumvent Chapter 9 - Understanding .NET Assemblies possible name clashes between assemblies. For example, if you were building a new Windows Forms Chapter 10 - Processes, AppDomains, Contexts, and Threads application that references two external assemblies, and each assembly contained a type named GoCart, Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming you would be able to specify which GoCart class you are interested in by appending the type name to its Part Four - Leveraging the .NET Libraries containing namespace (i.e., "Intertech.CustomVehicles.GoCart" not "SlowVehicles.GoCart"). Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 -"using" Building a Bettersimplifies Window (Introducing Forms) In C#, the keyword the process Windows of declaring types defined in a particular namespace. Chapter - Ait Better Framework (GDI+) in building a traditional desktop application. The main Here is14 how works.Painting Let's say you are interested Chapter window15 renders - Programming a bar chart with based Windows on some Forms information Controls obtained from a back-end database and displays
your company using aNamespace Bitmap type. While learning the types each namespace contains takes study Chapter 16 - Thelogo System.IO and experimentation, here are some obvious candidates to reference in your program: Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 -are ASP.NET and Web Controls // Here allWeb thePages namespaces used to build this application. Chapter using19System; - ASP.NET Web Applications // General base class library types.
using20System.Drawing; Chapter - XML Web Services using System.Windows.Forms; Index using System.Data; List of Figures 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# and the .NET Platform, Second Edition
}
by Andrew Troelsen Apress © 2003 (1200 pages)
}
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and Because your application is referencing System.Drawing, the compiler is able to resolve the Bitmap class architectural issues for .NET developers. as a member of this namespace. If you did not directly 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:
Table of Contents
C# and the .NET Platform, Second Edition
// Not listing System.Drawing namespace! using System; Part One - Introducing C# and the .NET Platform class MyClass Chapter 1 - The Philosophy of .NET { Chapter 2 - Building C# Applications public void DoIt() Part Two - The C# Programming Language { Chapter 3 - C# Language Fundamentals // Using fully qualified name. Chapter 4 - Object-Oriented Programming withbm C#= new System.Drawing.Bitmap(20, 20); System.Drawing.Bitmap Chapter 5 - Exceptions and Object Lifetime ... Chapter } 6 - Interfaces and Collections Chapter 7 - Callback Interfaces, Delegates, and Events } Introduction
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies While defining a type using the fully Contexts, qualified name provides greater readability, I think you'd agree that the Chapter 10 - Processes, AppDomains, and Threads
C# using reduces keystrokes. thisAttribute-Based text, I will avoidProgramming the use of fully qualified names (unless there Chapter 11 keyword - Type Reflection, Late Binding,Inand is a Four definite ambiguitythe to be resolved) Part - Leveraging .NET Librariesand
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 - Object Serialization and the .NET Remoting Layer qualified name, and each approach results in the exact same underlying CIL. Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Referencing External Assemblies
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
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 Part Five - Web Applications and XML Web Services core .NET namespaces live within mscorlib.dll. System.Drawing however, is contained in a separate binary Chapter 18 - ASP.NET Web Pages and Web Controls named System.Drawing.dll. By default, the system-supplied assemblies are located under : \ Chapter 19 - ASP.NET Web Applications %windir%\ Microsoft.NET\ Framework\ , as seen in Figure 1-4. Chapter 17 - Data Access with ADO.NET
Chapter 20 - XML Web Services Index List of Figures 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.
and the .NET Platform,Nomenclature Second Edition Increasing C# Your Namespace by Andrew Troelsen
ISBN:1590590554
If you are beginning to feel a tad overwhelmed at the thought of gaining mastery over every nuance of the Apress © 2003 (1200 pages) .NET universe, just remember that what makes a namespace unique that the types it defines are all This comprehensive text starts with a brief overview of is the somehow semantically related. Therefore, if you have no need for a user C# language and then quickly moves to key technical and interface beyond a simple architectural issues all forabout .NET developers. console application, you can forget 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. Table of Contents
Over that follow, you are exposed to numerous aspects of the .NET platform and related C# andthe thechapters .NET Platform, Second Edition namespaces. As it would be impractical to detail every type contained in every namespace in a single Introduction book (honestly, there C# areand many of types Part One - Introducing thethousands .NET Platform
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 Part Two - The C# Programming Language
.NET SDK online documentation (MSDN)
Chapter 3
- C# Language Fundamentals
Chapter 4 ildasm.exe - Object-Oriented The utility Programming with C# Chapter 5 - Exceptions and Object Lifetime
The Viewer and WebCollections application Chapter 6 Class - Interfaces Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
The wincv.exe desktop application
Part Three - Programming withintegrated .NET Assemblies The Visual Studio .NET Object
Chapter 9
Browser
- Understanding .NET Assemblies
I think it's to assume you know Contexts, what to doand with the supplied online Help (remember, F1 is your friend), Chapter 10 safe - Processes, AppDomains, Threads however 2 points outLate some strategies used when navigating MSDN. In addition, it is important that Chapter 11Chapter - Type Reflection, Binding, and Attribute-Based Programming youFour understand how to the ildasm.exe, Part - Leveraging thework .NETwith Libraries
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 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Using ildasm.exe
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
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 with ADO.NET Dissasembler utility (ildasm.exe) allows you to load up any .NET assembly and investigate its contents Part Five - Web Applications and XML Web Services (including the associated manifest, CIL instruction set and type metadata) using a friendly GUI. The Chapter 18 - ASP.NET Web Pages and Web Controls ildasm.exe is most likely found in :\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin. Chapter 19 - ASP.NET Web Applications Once you launch this tool, proceed to the "File | Open" menu command and navigate to the assembly you Chapter 20 - XML Web Services wish to explore. For the time being, open up mscorlib.dll (Figure 1-5). Note the path of the opened Index assembly is documented in the caption of the ildasm.exe utility. Chapter 16 - The System.IO Namespace
List of Figures List of Tables
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Figure YourPainting new best friend, ildasm.exe Chapter 14 - 1-5: A Better Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter The System.IO Namespace As you 16 can- see, the structure of an assembly is presented in a familiar tree view format. While exploring a Chapter 17 Data Access with ADO.NETfor a given type (methods, properties, nested classes, and so forth) given type, notice that the members Part - Webby Applications and XML Web are Five identified a specific icon. Table 1-5Services lists some
of the more common iconic symbols and text dump
Chapter 18 - ASP.NET Web Pages and Web Controls abbreviations. Chapter 19 - ASP.NET Web Applications Chapter Table 1-5: 20 - ildasm.exe XML Web Services Tree View Icons Index
ildasm.exe TreeView Icon
List of Figures List of Tables
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. 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] Represents C# and the .NET Platform, Second Edition a static method of a given type (note the "s" marker). ISBN:1590590554
by Andrew Troelsen Apress © 2003 (1200 pages) [FLD]
Represents a field (e.g., public data) defined by
This comprehensive text starts with a a given brief overview of the type. C# language and then quickly moves to key technical and architectural issues for .NET developers. [STF] Represents a static field defined by a given type
(again note the "s" marker). Table of Contents
[PTY]
Signifies a property supported by the type.
C# and the .NET Platform, Second Edition Introduction Beyond allowing you to explore the types (and members of a specific type) contained in a given assembly, Part One - Introducing C#you and .NET ildasm.exe also allows tothe view thePlatform underlying
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. Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Figure 1-6: Viewing the underlying CIL
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Dumping Namespace Information
to File
Part Five - Web Applications and XML Web Services
The next of interest regard to ildasm.exe Chapter 18point - ASP.NET Web with Pages and Web Controls is the very useful ability to dump the relational hierarchy of an assembly into aWeb textApplications file. In this way, you can make hard copies of your favorite assemblies to read at Chapter 19 - ASP.NET your neighborhood coffeehouse (or brew pub). To do so, select "File | Dump TreeView" and provide a Chapter 20 - XML Web Services name for the resulting *.txt file. As you look over the dump, notice that the identifying icons have been Index replacedwith their corresponding textual abbreviations (see the previous table). For example, ponder Figure 1-7.
List of Figures List of Tables
Figure 1-7: Dumping namespace information to file
C# and the .NET Platform, Second Edition
Dumping CILbyInstructions to File Andrew Troelsen
ISBN:1590590554
Apress © 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 comprehensive text starts with a brief overview 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 moves to key technical and the *.IL file. Assuming you have dumped the developers. contents of mscorlib.dll to file you can view its contents using architectural 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(). Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Figure Dumping CIL file Chapter 9 - 1-8: Understanding .NETtoAssemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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. - Object Serialization and.NET-aware the .NET Remoting Layer "Ctrl+M" As you recall, compilers emit CIL and metadata that is used by the CLR Chapter 13 Building a Better Window (Introducing Windows Forms) to interact with a given type. Once you load an assembly into ildasm.exe, press Ctrl+M to view the Chapter 14 -type A Better Painting (GDI+) generated metadata. ToFramework offer a preview of things to come, Figure 1-9 shows the metadata for the Chapter 15 - Programming with Controls TestApp.exe assembly you willWindows create inForms Chapter 2. Part Four - Leveraging the .NET Libraries
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Figure 1-10: Double click here to view the assembly manifest. Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language 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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
The Class Viewer Web Application - Interfaces and Collections
Chapter 6 Chapter 7
Interfaces, Delegates, and Events In addition-toCallback ildasm.exe, the Class Viewer Web application (shipped with the .NET SDK sample Chapter 8 - Advanced C# Type Techniques applications) is yet another wayConstruction to explore the .NET namespaces. Once you have configured the samples Part Three with - Programming with(via .NET Assemblies provided the .NET SDK the Start | All Programs | Microsoft .NET Framework SDK v1.1 | Samples Chapter 9 - Understanding .NET item), Assemblies and QuickStart Tutorials menu launch your browser of choice and navigate to Chapter 10 - Processes, AppDomains, Contexts, and Threads http://localhost/quickstart/aspplus/samples/classbrowser/vb/classbrowser.aspx Chapter 11that - Type Reflection, LateofBinding, andapplication Attribute-Based Programming (do note the exact location this Web may change in future releases of the .NET SDK). Part - Leveraging the .NETthe Libraries ThisFour enables you to examine relationship of various types in a more Web-savvy manner (Figure 1-11). Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition 1-12 shows the member set for the System.Windows.Forms.ToolTip class. by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections Figure Working with wincv.exe Chapter 7 - 1-12: Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction 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 - Understanding .NET Assemblies comment on one final "minor" (read: "not-so-minor") detail. Part Three - Programming with .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Deploying the .NET Runtime by Andrew Troelsen
ISBN:1590590554
As you have mostApress likely ©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 an individual whoofbuilds This comprehensive text starts with a brief overview 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 moves to key technical and architectural issues However, for .NET developers. .NET SDK (or Visual Studio .NET). assume 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. Table of Contents
Rather than opting for overkill and installing the full .NET SDK on each and every machine that may run C# and the .NET Platform, Second Edition your application, Microsoft has created a specific redistribution package named Dotnetfx.exe that can be Introduction freely shipped and installed withPlatform your custom Part One - Introducing C# andalong the .NET
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 Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# OS will have native .NET support): Chapter 3 Chapter 5
- Exceptions and Object Lifetime
Chapter Microsoft 6 - Interfaces Windowsand 98Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Microsoft Windows NT 4.0 (SP 6a or greater) Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Microsoft Windows Millennium Edition (aka Windows Me)
Chapter 9
- Understanding .NET Assemblies
Chapter Microsoft 10 - Processes, WindowsAppDomains, 2000 (SP2 or Contexts, greater)and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Microsoft Windows Home / Professional Part Four - Leveraging theXP .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Once installed, the target machine will now host the necessary base class libraries, mscoree.dll, and
Chapter 13 -.NET Building a Better Window (Introducing Forms) additional infrastructure (such as the GlobalWindows Assembly Cache). Do understand however, that if you Chapter 14 - Aa Better Painting Framework (GDI+) are building Web application using .NET technologies, the end user's machine does not need to be Chapter 15 - with Programming with Windows kit Forms Controls configured the .NET redistribution (as the browser will simply display generic HTML). Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Running .NET on Non-Microsoft Operating Systems
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Webplaces Pages and Web Controls As mentioned at various in this chapter, the .NET platform is already being ported to other Chapter 19 systems. - ASP.NETThe Webkey Applications operating that makes this possible is yet another .NET specification termed the Chapter 20 Language - XML Web Infrastructure Services Common (CLI, which previously went under the code name "rotor"). Simply put, Index the CLI is the ECMA standard that describes the core libraries of the .NET universe. Microsoft has List released of Figures an 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 and Link the .NET Platform, SecondMeaning Edition in Life by Andrew Troelsen Apress © 2003 (1200 pages)
http://msdn.microsoft.com/net/ecma
ISBN:1590590554
Details the standardization of C# and the .NET platform
This comprehensive text starts with a brief overview of the
C# language and then quickly movesHomepage to key technical andMono project, which is a http://www.go-mono.com for the architectural issues for .NET developers. porting of C# and .NET to various flavors of Linux Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
The point of this chapter laypages) out the conceptual framework necessary for the remainder of this Apress ©was 2003 to (1200 book. We began This by examining a number of limitations andoverview complexities found within the technologies prior comprehensive text starts with a brief of the to .NET, and followed up with an overview of how .NET and C# attempt C# language and then quickly moves to key technical andto simplify the current state of architectural issues for .NET developers. affairs. .NET basically boils down to a runtime execution engine (mscoree.dll) and base class library (mscorlib.dll Table and of associates). Contents The common language runtime (CLR) is able to host any .NET binary (aka "assembly")
that abides by the rules of managed code. As you have seen, assemblies contain CIL instructions (in C# and the .NET Platform, Second Edition addition to type metadata and the assembly manifest) that are compiled to platform-specific instructions Introduction using a just-in-time (JIT) compiler. In addition, Part One - Introducing C# and the .NET Platform 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 machine Part Two -of The C# Programming Languageto 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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
the .NET Platform, Second Edition Chapter C# 2:and Building C# Applications ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) C# is one of many possible languages which may be hosted by Visual Studio .NET (VS .NET). Unlike This comprehensive text starts Development with a brief overview of the previous editions of Microsoft IDEs (Integrated Environments), the professional and C# language and then quickly moves to key technical and enterprise versions of VS .NET may be used to build C#, J#, VB .NET and MC++ project types (including architectural issues for .NET developers. 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 they of willContents 'snap-in' to the existing VS .NET IDE out of the box. Table C# and the .NET Platform, Second Edition
This chapter offers a grand tour of the key features of the VS .NET IDE within the context of C#. Along the
Introduction way, you will examine some common configuration options, preview various design time tools, examine the Part One - Introducing C# and the .NET Platform
use of XML-based code documentation, and examine 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. Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals The Role of the Command Line Compiler (csc.exe) - Object-Oriented Programming with C#
Chapter 4
Chapter 5 -a Exceptions Object Lifetime There are number ofand techniques you may use to compile C# source code. In addition to VS .NET proper Chapter 6 Interfaces and Collections (as well as various third party .NET IDEs), you are also able to compile your .NET assemblies using the Chapter 7 - Callback Interfaces, Delegates, stand-alone compiler, csc.exe (as I'm sureand youEvents can gather, "csc" is short for C Sharp Compiler). This tool is included in the freely downloadable Microsoft .NET SDK (http://msdn.microsoft.com/net). Chapter 8 - Advanced C# Type Construction Techniques Part Now, Three while - Programming it is true that you withmay .NETnever Assemblies decide
to build an entire application using the raw C# compiler, it is
important understand the basics of how to compile your *.cs files by hand. I can think of two reasons you Chapter 9 to - Understanding .NET Assemblies should 10 get-aProcesses, grip on theAppDomains, process: Contexts, and Threads Chapter Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer throughout this text. Part Four - Leveraging the .NET Libraries
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - Areason Better Painting Framework (GDI+) Another is this very important fact: Design time editors, code Wizards, and configuration Chapter 15 - Programming dialogs do little more with thanWindows save youForms typingControls time. The more you understand what happens "under the Chapter hood" 16 -the Thestronger System.IO yourNamespace programming 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 with ADO.NET it's edifying to see whatand takes place the Part Five - Web Applications XML Webbehind Services
scenes.
Chapter 18 - ASP.NET Web Pages and Web Controls
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 Services throughout this book, a number of important utilities are only accessible from the command prompt. Chapter 19 - ASP.NET Web Applications Index
List of Figures
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# and linethe to the .NET end Platform, of the current Second value Edition (note each value in the Path variable is separated by a semicolon, as shown in Figure 2-1): ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the :\%windir%\Microsoft.NET\Framework\v1.1.4322 C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
2-1: Establishing the pathwith to csc.exe Chapter 4 Figure - Object-Oriented Programming C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6 -the Interfaces andname Collections Of course, exact path may need to be adjusted based on your current version and location of Chapter 7 Callback Interfaces, and Events 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 Construction windows Techniques open in the background (to commit the settings), then Part open Three a new - Programming command window with .NET andAssemblies enter:
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads csc -? Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
If you set upSerialization correctly, you should seeRemoting a displayLayer of each option supported by the raw C# compiler. Chapter 12 things - Object and the .NET Chapter 13 - Building a Better Window (Introducing Windows Forms)
Configuring Additional .NET Command Line Tools
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Now, before we System.IO begin to investigate manipulating csc.exe, add the following additional Path variable to the Chapter 16 - The Namespace System17 Variables list boxwith (again, performing a sanity check to ensure path settings): Chapter - Data Access ADO.NET Part Five - Web Applications and XML Web Services
:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Bin Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
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 Figures 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: Index
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# and the .NET Platform, Second Edition Building a C# Application Using csc.exe by Andrew Troelsen
ISBN:1590590554
Now that your development machine recognizes csc.exe, the next goal of this chapter is to build a simple Apress © 2003 (1200 pages) single file assembly named TestApp.exe using with the raw C#overview compiler.ofFirst, This comprehensive text starts a brief the you need some source code. Open a text editorC# (notepad.exe is fine), and enter the following: language and then quickly moves to key technical and architectural issues for .NET developers.
// The first C# app of the book... using System; Table of Contents class TestApp C# and the .NET Platform, Second Edition { Introduction public static void Main() Part One - Introducing C# and the .NET Platform { Chapter 1 - The Philosophy of .NET Console.WriteLine("Testing! 1, 2, 3"); Chapter}2 - Building C# Applications Part } Two - The C# Programming Language Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# Once you finished, save the Lifetime file (in a convenient location) as TestApp.cs. Now, let's get to know the Chapter 5 -have Exceptions and Object
core options of the C#and compiler. The first point of interest is to understand how to specify the name and Chapter 6 - Interfaces Collections type of 7output file youInterfaces, are interested in obtaining (e.g., a console application named MyShell.exe, a code Chapter - Callback Delegates, and Events library named HelperTypes.dll, a Windows Forms application named MyRadWnd.exe, and so forth). Each Chapter 8 - Advanced C# Type Construction Techniques possibility represented with by a .NET specific flag passed Part Three -isProgramming Assemblies Chapter 9
into csc.exe as a command line parameter (Table 2-1).
- Understanding .NET Assemblies
Table 2-1: Output Options of the C# Compiler
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter - Type Reflection, Late Binding, and Attribute-Based Programming File11Output Meaning in Life Part Four - Leveraging the .NET Libraries Option
Chapter 12 - Object Serialization and the .NET Remoting Layer
/out 13 - Building a Used specify(Introducing the name ofWindows the output file (e.g., MyAssembly.dll, Chapter Better to Window Forms)
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 - Programming with Windows Forms Controls program's specified entry point (the static Main() method). Chapter 14 - A Better Painting Framework (GDI+) Chapter 16 - The System.IO Namespace
Chapter /target:exe 17 - Data Access This with option ADO.NET builds an *.exe console application. This is the default file output Part Five - Web Applications type, and andXML thusWeb mayServices be omitted
when building this application type.
Chapter 18 - ASP.NET Web Pages and Web Controls
/target:library
This option builds a single file *.dll assembly.
Chapter 19 - ASP.NET Web Applications
/target:module This option builds a "module." Modules are elements of multifile assemblies Chapter 20 - XML Web Services Index
(as seen later in Chapter 9).
List of Figures
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
csc TestApp.cs
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and To try things for yourself, open a command window and change to the directory containing your architectural issues for .NET developers.
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). Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Figure 2-2: The TestApp in action
Chapter 6 thing - Interfaces and strike Collections The first that should you is the fact that you have just created a console application using C#! Chapter 7 Callback Interfaces, Delegates, and Events The reason I point this out is due to a common misconception (especially among management) that .NET Chapter 8 - Advanced C#development Type Construction Techniques is only useful during the of Internet applications. Nothing could be further from the truth. As Part - Programming withof.NET youThree will see over the course this Assemblies text, .NET provides
support for developing any type of application you
Chapter 9 - Understanding Assemblies might envision (Web-based.NET or otherwise). Chapter 10 - Processes, AppDomains, Contexts, and Threads
While console applications less sexy a Windows-based or HTML-based front end, they can Chapter 11 - Type Reflection, are Latefar Binding, and than Attribute-Based Programming prove useful when you need build a program Part Four - Leveraging the .NETto Libraries
that requires a minimal graphical user interface.
Chapter 12 - Object Serialization and the .NET Remoting Layer
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 Painting Framework (GDI+) of building GUIs using Windows Forms or ASP.NET technologies. Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Referencing External Assemblies
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
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, caseControls you are wondering how the C# compiler understood your Chapter 19 -toASP.NET Web Applications reference the System.Console type, realize that mscorlib.dll is automatically referenced during the
Chapter 20 - XML Web(if Services compilation process for some strange reason you wish to disable this behavior, you may specify the Index /nostdlib flag). List of Figures
To of illustrate 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# and the .NET Platform, Second Edition Chapter 1). Recall that when you explicitly list the namespaces used within a given *.cs file, you avoid the ISBN:1590590554 by Andrew Troelsen need to make use of fully qualified names (which can lead to hand cramps). Apress © 2003 (1200 pages)
This text you starts withalso a brief overview of the In addition to using thecomprehensive "using" keyword, must inform csc.exe which assembly contains the C# language moves to of key technical and referenced namespace. Givenand thatthen we quickly have made use the System.Windows.FormsMessageBox class, architectural issues for .NET developers. you must specify the System.Windows.Forms.dll assembly using the /reference flag (which can be abbreviated to /r): Table of Contents
csc testapp.cs C# and/r:System.Windows.Forms.dll the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
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
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Figure- 2-3: Your first Windows Forms application Understanding .NET Assemblies
Chapter 9
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Compiling Multiple Source Files
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
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 Painting Framework (GDI+) in a single *.cs file, most projects are composed of multiple *.cs files to keep your code base a bit more Chapter Programming with you Windows Controls flexible.15To- illustrate, assume have Forms authored an additional class contained in a new file named Chapter 16 The System.IO Namespace HelloMsg.cs. Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
// The HelloMessage Class using System; Chapter - ASP.NET Web Applications using19System.Windows.Forms; Chapter 20 - XML Web Services class HelloMessage Index { List of Figures public void Speak() List of Tables { MessageBox.Show("Hello..."); } } Chapter 18 - ASP.NET Web Pages and Web Controls
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# and the .NET Platform, Second Edition by Andrew the Troelsen // Exercise HelloMessage class! ISBN:1590590554 Apress © 2003 (1200 pages) HelloMessage(); HelloMessage h = new This comprehensive text starts with a brief overview of the h.Speak(); C# language and then quickly moves to key technical and architectural issues for .NET developers.
} } Table of Contents
You can compile this multifile application by listing each *.cs file explicitly:
C# and the .NET Platform, Second Edition Introduction
csc /r:System.Windows.Forms.dll testapp.cs hellomsg.cs
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language As an alternative, the C# compiler 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 Object-Oriented with C# of the output file (/out) as well, to directly control the option, 4you- will typically wantProgramming to specify the name Chapter 5 the - Exceptions and Object Lifetime name of resulting assembly: Chapter 6 - Interfaces and Collections Chapter 7 - Callback Interfaces, Delegates, and Events csc /r:System.Windows.Forms.dll /out:TestApp.exe *.cs Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
When you the program.NET again, the output is identical. The only difference between the two applications Chapter 9 -run Understanding Assemblies is the fact the current logic has been split and among multiple files. Chapter 10 -that Processes, AppDomains, Contexts, Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Referencing Multiple External Assemblies
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Now, what you need to reference external assemblies? Simply list each assembly using a Chapter 13 -ifBuilding a Better Windownumerous (Introducing Windows Forms) semicolon-delimited list (annoyingly, the(GDI+) VB .NET compiler [vbc.exe] uses a comma delimited list, so be Chapter 14 - A Better Painting Framework mindful15 when using multiple compilers). You don't need to specify multiple external assemblies for Chapter - Programming with.NET Windows Forms Controls the current but some sample usage follows: Chapter 16 - example, The System.IO Namespace Chapter 17 - Data Access with ADO.NET
cscFive /r:System.Windows.Forms.dll;System.Drawing.dll Part - Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
/out:TestApp.exe *.cs
C# and the .NET Response Platform, Second Edition Working with Csc.exe Files by Andrew Troelsen
ISBN:1590590554
As you might guess, if you were to pages) build a complex C# application at the command prompt, your life would Apress © 2003 (1200 be full of pain as This you type in the flags thatstarts specify numerous referenced comprehensive text with a brief overview 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 moves to key technical and architectural issues for .NET developers.
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 Table out lines of Contents and lines of flags manually at the command prompt. To illustrate, assume that you have created a response file Platform, named TestApp.rsp that contains the following arguments (as you can see, comments are C# and the .NET Second Edition denoted with the "#" character): Introduction Part One - Introducing C# and the .NET Platform
Chapter 1 is - The Philosophy of .NET # This the response file Chapter # for2 the - Building TestApp.exe C# Applications app Part # of TwoChapter - The C# Programming 2. Language
# External references. Chapter 3 - C# assembly Language Fundamentals /r:System.Windows.Forms.dll Chapter 4 - Object-Oriented Programming with C# # output and files compile Chapter 5 - Exceptions andto Object Lifetime (using wildcard syntax). /target:exe /out:TestApp.exe *.cs Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction 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):
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
[email protected]
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 -output Building Better Window (Introducing Windows Forms) Again, the of athe compiler is identical. Chapter 14 - A Better Painting Framework (GDI+)
If the need arise, you also able to specify multiple *.rsp files as input (for example: csc Chapter 15 - should Programming withare Windows Forms Controls @FirstFile.rsp @ThirdFile.rsp). If you take this approach, do be aware that the compiler Chapter 16 -
[email protected] System.IO Namespace processes command options as they are encountered! Therefore, command line arguments in a later Chapter 17 -the Data Access with ADO.NET *.rsp file-can options a previous response Part Five Weboverride Applications andinXML Web Services
file.
Chapter 18 - ASP.NET Web Pages and Web Controls
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 youApplications were to enter: Chapter 20 - XML Web Services Index
csc/out:Foo.exe @TestApp.rsp
List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter Figure 6 - 2-4: Interfaces Behold, and the Collections default response file Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction 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 - Understanding .NET Assemblies files whatsoever, custom or csc.rsp). Given the presence of the default response file, it should be clear Chapter - Processes, AppDomains, Contexts, and Threadsa reference to the that the10 current TestApp.exe application (which contains Chapter 11 Type Reflection, Late Binding, and Attribute-Based Programming System.Windows.Forms.MessageBox class) could be successfully compiled using the following command Part Four Leveraging the .NET Libraries line (note that I did not specify /r:System.Windows.Forms.dll as this reference will be added via csc.rsp): Part Three - Programming with .NET Assemblies
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
csc /out:TestApp.exe *.cs
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter Finally,16 in the - The event System.IO that youNamespace wish to disable the automatic reading of csc.rsp, you can specify the /noconfig
flag: 17 - Data Access with ADO.NET Chapter Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls csc @TestApp.rsp /noconfig Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition GeneratingC# Bug Reports by Andrew Troelsen
ISBN:1590590554
The raw C# compiler provides a helpful Apress © 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) with various This comprehensive starts with brief overview of the statistics regarding your current build; including any errors encountered during the compilation process. C# language and then quickly moves to key technical andIts use is self-explanatory: architectural issues for .NET developers.
csc/bugreport:bugs.txt *.cs Table of Contents C# and the Platform, Second Edition When you.NET specify /bugreport, you will be prompted to enter corrective information for the possible error(s) Introduction at hand, which will be saved (along with other details) into the file you specify. To illustrate, let's inject a Part Introducing and the .NET Platform bugOne into-the TestApp C# class:
Chapter 1
- The Philosophy of .NET
Chapter 2 static - Buildingvoid C# Applications public Main() Part { Two - The C# Programming Language
Chapter 3 ...
- C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C# HelloMessage h = new HelloMessage(); Chapter - Exceptions andsemicolon Object Lifetime //5 Note lack of below! Chapter 6 - Interfaces h.Speak() //and Chapter/// 9 -'): {0}", char.IsPunctuation('>'));
Console.WriteLine("-> char.IsPunctuation(','): {0}", C# and the .NET Platform, Second Edition char.IsPunctuation(',')); by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
As you can see, each of these static text members of System.Char has of twothe calling conventions: a single character This comprehensive starts with a brief overview language and that thenspecified quickly moves to key of technical and or a string with a C# numerical index the position the character to test. architectural issues for .NET developers.
Parsing Values from String Data Table of Contents
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 Introduction convert a bit of user input data (such as a listbox selection) into a numerical value. Ponder the following Part One - Introducing C# and the .NET Platform parsing logic: C# and the .NET Platform, Second Edition
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
bool bool.Parse("True"); Part TwomyBool - The C# = Programming Language Console.WriteLine("-> Value of myBool: {0}", myBool); - C# Language Fundamentals double myDbl = double.Parse("99.884"); Chapter 4 - Object-Oriented Programming with C# Console.WriteLine("-> Value of myDbl: {0}", myDbl); Chapter 5 - Exceptions and Object Lifetime int myInt = int.Parse("8"); Chapter 6 - Interfaces and Collections Console.WriteLine("-> Value of myInt: {0}", myInt); Chapter 7 - Callback Interfaces, Delegates, and Events char myChar = char.Parse("w"); Chapter 8 - Advanced C# Type Value Construction Techniques{0}\n", myChar); Console.WriteLine("-> of myChar: Chapter 3
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
SOURCE The DataTypes project located underProgramming the Chapter 3 subdirectory. Chapter 11 - Type Reflection, Late Binding, and is Attribute-Based CODE Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Secondand Edition ConvertingC# Between Value Types Reference Types: Boxing and ISBN:1590590554 by Andrew Troelsen Unboxing Apress © 2003 (1200 pages) This comprehensive text startsof with a brief overview ofand thereference-based), you may Given that .NET defines two broad categories types (value-based C# language and then quickly moves to key technical and occasionally need to represent a variable of one category as a variable of the other category. C# provides a architectural issues for .NET developers. 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: Table of Contents
//and Make a simple C# the .NET Platform,value Second data Edition point. short s = 25; Introduction Part One - Introducing C# and the .NET Platform
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
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
// Box the value into an object reference. - Object-Oriented Programming with C# object objShort = s;
Chapter 4 Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter Callback Interfaces, and Events Boxing 7can- be formally defined Delegates, as the process of explicitly converting a value type into a corresponding Chapter 8 -type. Advanced Techniques reference WhenC# youType box Construction a value, essentially all you are doing is allocating a new object on the heap and Part Threethe - Programming .NETcase Assemblies copying internal valuewith (in this 25) into
that instance. What is returned to you is a true-blue reference to
Chapter 9 allocated - Understanding Assemblies the newly object..NET Using this technique, .NET developers have no need to make use of a set of Chapter 10classes - Processes, and Threads wrapper used AppDomains, to temporarilyContexts, treat intrinsic data as heap-allocated objects (as is the case in Java). Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
TheFour opposite operation alsoLibraries permitted through Part - Leveraging theis.NET
unboxing. Unboxing is the term given to the process of converting the value held in the object reference back into a corresponding value type on the stack. The Chapter 12 - Object Serialization and the .NET Remoting Layer unboxing operation begins by verifying that the receiving data type is equivalent to the boxed type, and if so, Chapter 13 - Building a Better Window (Introducing Windows Forms) copying the value out of the box into a local stack based variable. For example, the following unboxing operation Chapter 14 - A Better Painting Framework (GDI+) works successfully, given that the underlying type of the objShort is indeed a "short": Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
// Now, unbox the reference back into a corresponding short. short anotherShort = (short)objShort; Part Five - Web Applications and XML Web Services Chapter 17 - Data Access with ADO.NET
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20is -critical XML Web Again, it thatServices you unbox into an appropriate data type. Thus, the following unboxing logic generates an Index InvalidCastException exception (you examine casting and exception handling in detail in the next chapter, so List of tight Figures hold for now): 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 and the .NET Platform, Examples Second Edition by Andrew Troelsen
ISBN:1590590554
So, you may be thinking, would you really need to manually box (or unbox) a data type? The previous Apress © 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 comprehensive text starts with a brief overview of the point. The truth ofC# thelanguage matter isand that you will seldom to technical manuallyand box data types, if ever. Much of the time, then quickly movesneed to key the C# compiler automatically architectural issues boxesfor variables .NET developers. when appropriate. For example, if you pass a value type into a method requiring an object parameter, boxing occurs behind the curtains. However, if you wish to invoke members of the underlying value type, you will be required to perform Table of Contents an explicit unboxing operation. illustrate, ponder the following: C# and the .NET Platform, SecondTo Edition Introduction Part class One -Boxer Introducing C# and the .NET Platform
{ Chapter 1
- The Philosophy of .NET to illustrate automatic boxing. Chapter// 2 Helper - Buildingf(x) C# Applications
public static void Language UseThisObject(object Part Two - The C# Programming
o) { Chapter 3 - C# Language Fundamentals Chapter 4 -Console.WriteLine(o.GetType()); Object-Oriented Programming with C# Chapter 5 -Console.WriteLine(o.ToString()); Exceptions and Object Lifetime Console.WriteLine("Value of o is: {0}", o); Chapter 6 - Interfaces and Collections // Need to explicitly unbox to get at members of Chapter 7 - Callback Interfaces, Delegates, and Events // System.Int32. (GetTypeCode() returns a value Chapter 8 - Advanced C# Type Construction Techniques // representing the underlying "type of intrinsic type". Part Three - Programming with .NET Assemblies Console.WriteLine(((int)o).GetTypeCode()); Chapter 9 - Understanding .NET Assemblies } Chapter 10 - Processes, AppDomains, Contexts, and Threads static void Main(string[] args) Chapter{11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging .NET Libraries int x = the 99; Chapter 12 -UseThisObject(x); Object Serialization and the// .NET Remoting Layer Automatic boxing. Chapter}13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
In addition to the automaticand boxing when Part Five - Web Applications XMLperformed Web Services
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 Controls namespace (further examined in Chapter 6) defines a type named ArrayList. Like most collection types, Chapter 19 - ASP.NET Web Applications ArrayList provides members that allow you to insert, index, and remove items. If you were to check the formal Chapter 20 - XML Web Services class definition using wincv.exe, you would find prototypes such as: Index
List of Figures
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# and the .NET Platform, Second Edition myInts.Add(88); by Andrew Troelsen myInts.Add(3); Apress © 2003 (1200 pages) myInts.Add(9764);
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers. However, given your understanding of value types and 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 Table of Contents being stored into the ArrayList type. As well, just like the Foo() helper method, if you wish to interact with the C# and the .NET Platform, Second Edition members of the boxed type, you are required to unbox accordingly. Thus, assume the following static helper Introduction method: Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
public static void BoxAndUnboxInts() - Building C# Applications { Part Two - The C# Programming Language // Box ints into ArrayList. Chapter 3 - C# Language Fundamentals ArrayList myInts = new ArrayList(); ChaptermyInts.Add(88); 4 - Object-Oriented Programming with C# ChaptermyInts.Add(3); 5 - Exceptions and Object Lifetime ChaptermyInts.Add(9764); 6 - Interfaces and Collections Chapter// 7 Unbox - Callback Interfaces, Delegates, and Events first item. Chapterint 8 -firstItem Advanced C# = Type Construction Techniques (int)myInts[0]; Part Three - Programming with .NET Assemblies Console.WriteLine("First item is {0}", firstItem); Chapter } 9 - Understanding .NET Assemblies Chapter 2
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
(Un)Boxing Under the Hood
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter If you examine 14 - A Better the underlying Painting Framework CIL using (GDI+) ildasm.exe for the BoxAndUnboxInts() method, you can clearly see
exactly15 when the System.Int32 types are copied from the heap to the stack (and vice versa): Chapter - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 -public Data Access with ADO.NET .method hidebysig static void BoxAndUnboxInts() cil managed Part { Five - Web Applications and XML Web Services
Chapter // Code 18 - ASP.NET size Web Pages 81and (0x51) Web Controls
.maxstack 3 Web Applications Chapter 19 - ASP.NET .locals init class [mscorlib]System.Collections.ArrayList myInts, Chapter 20 - XML Web([0] Services [1] int32 firstItem) IL_0000: newobj List of Figures 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 Index
IL_0027: box [mscorlib]System.Int32 C# and the .NET Platform, Second Edition IL_002c: callvirt ISBN:1590590554 Andrew [mscorlib]System.Collections.ArrayList::Add(object) Troelsen instanceby int32 Apress © 2003 (1200 pages) IL_0031: pop This comprehensive text starts with a brief overview of the IL_0032: ldloc.0 C# language and then quickly moves to key technical and IL_0033: ldc.i4.0 architectural issues for .NET developers. IL_0034: callvirt instance object [mscorlib]System.Collections.ArrayList::get_Item(int32) IL_0039: unbox [mscorlib]System.Int32 Table of Contents IL_003e: ldind.i4 C# and the .NET Platform, Second Edition IL_003f: stloc.1 Introduction IL_0040: ldstr "First item is {0}" Part One - Introducing C# and the .NET Platform 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) Part Two - The C# Programming Language IL_0050: ret Chapter 3 - C# Language Fundamentals } Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime Here, we indirectly triggered a fourth CIL box operation at the point of printing out the value of the first item Chapter 6 have - Interfaces and Collections
help in 7the-ArrayList. The reason? System.Console.WriteLine() does not supply an overloaded variation that Chapter Callback Interfaces, Delegates, and Events operates raw System.Int32 types! Chapter 8 on - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
To be sure, boxing and unboxing types takes some processing time, and if used without restraint, could hurt the - Understanding .NET Assemblies performance of your application. However, given this .NET technique, you are able to symmetrically operate on Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming of the underlying type of a given variable (which would also result in extraneous code, as we see in C and C++). Part Four - Leveraging the .NET Libraries In this light, I'd place my vote that (un)boxing is a positive trait of a mature runtime. Chapter 9
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter On a final 13 -boxing-related Building a Better note, Window understand (Introducing that if Windows you wereForms) to pass custom structures or enumerations into a
method14taking generic System.Object you would also be required to unbox the parameter to Chapter - A Better Painting Frameworkparameters, (GDI+) interact15 with the specific members of the structure (or enum). This topic will be revisited later in this chapter Chapter - Programming with Windows Forms Controls when you examineNamespace the C# structure. Chapter 16 -formally The System.IO Chapter 17 - Data Access with ADO.NET
SOURCE CODE
The Boxing project is included under the Chapter 3 subdirectory.
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and theConstants .NET Platform, Second Edition Defining Program by Andrew Troelsen
ISBN:1590590554
Now that you canApress create©(and transform) 2003 (1200 pages) value-based and reference-based variables, you need to examine the logical opposite: Constants. C# offers thestarts "const" keyword, to defineofvariables with a fixed, unalterable value. This comprehensive text with a brief overview the Unlike C++, the C# "const" keyword cannot be used to qualify parameters or return values. Furthermore, it is C# language and then quickly moves to key technical and architectural issues for of .NET developers. important to understand that the value a constant point of data is computed at compile time, and therefore a 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 classTable Contents levelof constant definitions. For example: C# and the .NET Platform, Second Edition Introduction
// Some const data. using System; Chapter - The Philosophy of .NET class1 MyConstants Chapter 2 - Building C# Applications { Part Two// - The C# Programming Language When accessed by another type, these constants Chapter // 3 -must C# Language Fundamentals be referenced via the fully qualified name. Chapter public 4 - Object-Oriented Programming with = C#5; const int myIntConst Chapter public 5 - Exceptions Object Lifetime constand string myStringConst = "I'm a const"; Chapter public 6 - Interfaces static and void Collections Main() Chapter { 7 - Callback Interfaces, Delegates, and Events // Scoped constant. Chapter 8 - Advanced C# Type Construction Techniques const string localConst Part Three - Programming with .NET Assemblies = "I am a rock, I am an island"; // Use const data. Chapter 9 - Understanding .NET Assemblies Console.WriteLine("myIntConst = {0}\nmyStringConst = {1}", Chapter 10 - Processes, AppDomains, Contexts, and Threads myIntConst, myStringConst); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Console.WriteLine("Local constant: {0}", localConst); Part Four - Leveraging the .NET Libraries } Chapter 12 - Object Serialization and the .NET Remoting Layer } Part One - Introducing C# and the .NET Platform
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming Controls If you create a utility classwith thatWindows containsForms nothing but constant data, you may wish to define a private constructor. Chapter 16 The System.IO Namespace In this way, you ensure the object user cannot make an instance of your class (which would be desirable given Chapter - Data with ADO.NET that the17 class hasAccess no real implementation): Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls // Private constructors prevent the creation of a given type. Chapter - ASP.NET Web Applications class19MyConstants Chapter 20 - XML Web Services { Index
public const int myIntConst = 5;
List of Figures 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# and the .NET Platform, Second Edition These techniques can be quite helpful given that C# does not allow you to define global level constants. by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Referencing Across Types ThisConstant comprehensiveData text starts with a brief overview of the C# language and then quickly moves to key technical and
Given that we have architectural moved ourissues constant for .NET points developers. of data 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#, Table of points Contents global of data are not allowed. Thus, any time you wish to access a constant defined outside of the C# and the .NET you Platform, Edition defining class, must Second make use of the fully-qualified name. On the other hand, if a given class wishes to Introduction access a constant it directly defined, you are able to directly refer to the item at hand: Part One - Introducing C# and the .NET Platform
Chapter 1 static - The Philosophy of .NET public void Main() Chapter 2 Building C# Applications { Part Twoconst - The C# Programming Language= string localConst
"I am a rock, I am an island";
Chapter // 3 -Use C# Language Fundamentals const data. Chapter Console.WriteLine("myIntConst 4 - Object-Oriented Programming with C#= {0}\nmyStringConst = {1}\nLocalConst = {2}",
MyConstants.myStringConst, localConst); Chapter MyConstants.myIntConst, 5 - Exceptions and Object Lifetime } Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
SOURCE The Constants project is located under the Chapter 3 subdirectory. - Understanding .NET Assemblies CODE
Chapter 9
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition C# IterationC#Constructs by Andrew Troelsen
ISBN:1590590554
Consider the nextApress few pages mid-chapter reprieve from the complexities of value/reference types, © 2003a(1200 pages) overriding members of System.Object, and boxing the heap This comprehensive text starts withtypes a briefon overview 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 moves to key technical and architectural issues for .NET developers. repeat blocks of code until a terminating condition has 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: Table of Contents
forthe loop C# and .NET Platform, Second Edition Introduction
foreach/in loop
Part One - Introducing C# and the .NET Platform
Chapter 1 loop - The Philosophy of .NET while Chapter 2
- Building C# Applications
Part Two do/while - The loop C# Programming Language
Chapter 3
- C# Language Fundamentals
C, C++, and Java programmers will no doubt be familiar with the "for," "while," and "do/while" loops, but - Object-Oriented Programming with C# may be unfamiliar with the "foreach" statement. Visual Basic programmers on the other hand, are in the Chapter 5 - Exceptions and Object Lifetime fortunate position to be well aware of all four C# iteration statements, as VB already supports "For Each" Chapter 6 - Interfaces and Collections syntax. Let's quickly examine each looping construct in turn. Chapter 4
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
The for Loop
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
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 Attribute-Based Programming the terminating condition. Without belaboring the point, here is a sample of the syntax: Chapter 10 - Processes, AppDomains, Contexts, and Threads Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
// A basic for loop. public static int Main(string[] args) Chapter 14 - A Better Painting Framework (GDI+) { Chapter 15 - Programming with Windows Forms Controls // Note! 'i' is only visible within the scope of the for loop. Chapter 16 - The System.IO Namespace for(int i = 0; i < 10; i++) Chapter { 17 - Data Access with ADO.NET Part Five - WebConsole.WriteLine("Number Applications and XML Web Services is: {0} ", i); Chapter } 18 - ASP.NET Web Pages and Web Controls Chapter // 19 -'i' ASP.NET is Web not Applications visible here. Chapter return 20 - XML Web 0; Services Index } Chapter 13 - Building a Better Window (Introducing Windows Forms)
List of Figures 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# and the .NET Platform, Second Edition "Do you Remember Classic COM?", ISBN:1590590554 by Andrew Troelsen "C# and the .NET Platform", Apress © 2003 (1200 pages) "COM for the Angry Engineer" } ; comprehensive int COM This = 0, NET = 0; text starts with a brief overview of the C# language quickly moves to key technical // Assume we are and notthen looking for books on COMand interop. architectural issues for .NET developers. foreach (string s in arrBookTitles) { if (-1 != s.IndexOf("COM")) Table of Contents COM++; C# and the .NET Platform, Second Edition else if(-1 != s.IndexOf(".NET")) Introduction NET++; Part One - Introducing C# and the .NET Platform } Chapter 1 - The Philosophy of .NET Console.WriteLine("Found {0} COM references and {1} .NET references.", Chapter 2 - Building C# Applications COM, NET); Part Two - The C# Programming Language return 0; Chapter 3 - C# Language Fundamentals } Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime In addition iterating over simple arrays, foreach is also able to iterate over system-supplied or userChapter 6 -toInterfaces and Collections
defined7collections. hold off on the details Chapter 6, as this aspect of the "foreach" keyword entails Chapter - Callback I'll Interfaces, Delegates, anduntil Events an understanding of interface-based programming and the system-supplied IEnumerator and IEnumerable Chapter 8 - Advanced C# Type Construction Techniques interfaces. Part Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
The while and do/while Looping Constructs
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
YouFour have- Leveraging already seen the for statement Part thethat .NET Libraries
is typically used when you have some foreknowledge of the
number12of-iterations you wish toand perform (e.g., loop until j > 20). The while statement on the other hand is Chapter Object Serialization the .NET Remoting Layer useful for times when you are uncertain how long it might Chapter 13 those - Building a Better Window (Introducing Windows Forms)take for a terminating condition to be met. Chapter 14 - A Better Painting Framework (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 Namespace from a 16 given file.System.IO Notice that you are obtaining an instance of the StreamReader type as a return value from Chapter 17 Data Access with ADO.NET the static File.OpenText() method. Once you have opened the boot.ini file, you are able to iterate over each Part Five Web Applications and XML Web Services line in the file using StreamReader.ReadLine(): Chapter 15 - Programming with Windows Forms Controls
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
try
// Just in case we can't find the correct file...
Chapter 20 - XML Web Services { Index // Open the file named 'boot.ini'. List of Figures 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# and the .NET Platform, Second Edition you need to perform some action for an undetermined number of times. The difference is that do/while ISBN:1590590554 by Andrew Troelsen loops are guaranteed to execute the corresponding block of code at least once (in contrast, it is possible Apress © 2003 (1200 pages) that a simple while loop may never execute if the terminating condition is false from the onset). This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and // The do/while statement architectural issues for .NET developers.
string ans; do { of Contents Table Console.Write("Are you done? [yes] [no] : "); C# and the .NET Platform, Second Edition ans = Console.ReadLine(); Introduction }while(ans != "yes"); Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
SOURCE The Iterations project is located under the Chapter 3 subdirectory. - C# Language Fundamentals CODE
Chapter 3 Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition C# ControlC# Flow Constructs by Andrew Troelsen
ISBN:1590590554
Now that you canApress iterate©over a block of code, the next related concept is how to control the flow of program 2003 (1200 pages) execution. C# defines two simple constructs to with alter athe flow of yourofprogram, based on various contingencies. First This comprehensive text starts brief overview the you have our good friend, the "if/else" statement. Unlike C and C++ however, the if/else statement only operates on C# language and then quickly moves to key technical and architectural issues for .NET developers. Boolean expressions (not ad-hoc values such as -1, 0 and so on). Given this, if/else statements typically involve the use of the following C# operators (Table 3-5). Table of 3-5: Contents Table C# Relational and Equality Operators C# and the .NET Platform, Second Edition
C# Equality/Relational Introduction Operator Part One - Introducing C# and the
Example .NET PlatformUsage
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
==
if(age = = 30)
Meaning in Life Returns true only if each expression is the same.
Part Two - The C# Programming Language
!= Chapter 3
- C# Language Fundamentals
if("Foo" != Chapter 4 - Object-Oriented Programming with myStr) C#
Returns true only if each expression is different.
Chapter 5 <
- Exceptions and Object Lifetime
Returns true if expression A
Chapter 6
- Interfaces and Collections
> Chapter 7
- Callback Interfaces, Delegates, andif(bonus Events > 2000)
is less than, greater than, less
Chapter = 2000)
Chapter 10 - Processes, AppDomains, Contexts, and Threads
than or equal to expression B.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
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 Better Window (Introducing Windows Forms) tempted to write: Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
// 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 with ADO.NET if(thoughtOfTheDay.Length) // Error! Part Five - Web Applications and XML Web Services { Chapter 18 - ASP.NET Web Pages and Web Controls // Stuff... Chapter 19 - ASP.NET Web Applications } Chapter 16 - The System.IO Namespace
Chapter 20 - XML Web Services Index List of Figures
If you wish to make use of the String.Length property to determine if you have an empty string, you need to modify 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 far removed from Visual Basic). To build such a beast, C# offers an expected set of conditional operators (Table 3-6). Table 3-6: C# Conditional Operators
C# Conditional Operator Example C# and the .NET Platform, Second Edition ISBN:1590590554 by Andrew Troelsen if((age = = 30) && (name = = "Fred")) Apress © 2003 (1200 pages)
&& ||
This comprehensive text if((age starts=with = 30) a brief || (name overview = = "Fred")) of the C# language and then quickly moves to key technical and architectural issues for if(!myBool) .NET developers.
!
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 Table of Contents statements allow you to handle program flow based on a predefined set of choices. For example, the following C# and the .NET Platform, Second application prompts the user for Edition one of three possible values. Based on the user input, act accordingly: Introduction Part and thestatement. .NET Platform // One The- Introducing good ol' C# switch
Chapter - The Philosophy of .NET class1 Selections Chapter 2 {
- Building C# Applications
Part Twopublic - The C# static Programming int Language Main(string[]
args)
Chapter { 3 Chapter 4
- C# Language Fundamentals
Chapter 5
Console.WriteLine("1 - Exceptions and Object Lifetime = C#\n2 = Managed C++ (MC++)\n3 = VB.NET\n");
Chapter 6
Console.Write("Please select your implementation language:"); - Interfaces and Collections
Chapter 7
string s = Console.ReadLine(); - Callback Interfaces, Delegates, and Events
Chapter 8
int n C# = int.Parse(s); - Advanced Type Construction Techniques
- Object-Oriented Console.WriteLine("Welcome Programming with C# to the world of .NET");
Part Three - Programming with .NET Assemblies
Chapter 9
switch(n) .NET Assemblies - Understanding {
Chapter 10 - Processes, AppDomains, Contexts, and Threads
// C# demands that each case (including 'default') which // contains executable statements, must have Part Four - Leveraging the .NET Libraries // a terminating 'break' or 'goto' to avoid fall through. Chapter 12 - Object Serialization and the .NET Remoting Layer case 1: Chapter 13 - Building a Better Window (Introducing Windows Forms) Console.WriteLine("Good choice! C# is all about managed code."); Chapter 14 - A Better Painting Framework (GDI+) break; Chapter 15 - Programming casewith 2:Windows Forms Controls Chapter 16 - The System.IO Console.WriteLine("Let Namespace me guess, maintaining a legacy system?"); Chapter 17 - Data Access with ADO.NET break; Part Five - Web Applications case and 3: XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls Console.WriteLine("VB .NET: It is not just for kids anymore..."); Chapter 19 - ASP.NET Web Applications break; Chapter 20 - XML Webdefault: Services Console.WriteLine("Well...good luck with that!"); Index break; List of Figures List of Tables } return 0; } } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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# and theof .NET Platform, Second Edition The Complete Set C# Operators by Andrew Troelsen
ISBN:1590590554
C# defines a number of ©operators addition to those you have previously examined. By and large, these Apress 2003 (1200 in pages) operators behaveThis likecomprehensive their C(++) andtext Java counterparts. 3-7 of lists starts with a briefTable overview thethe set of C# operators in order of precedence. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 3-7: The Full Set of C# Operators Operator Category Table of Contents C# and the .NET Platform, Second Edition
Unary
Introduction
Operators + - ! ~ ++x x++ --x x--
Part Multiplicative One - Introducing C# and the .NET Platform */%
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Additive
Part Shift Two - The C# Programming Language
+>
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Relational
< > = is as
Equality Chapter 5 - Exceptions and Object Lifetime= = ! = Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Logical AND
&
Logical ^ Techniques Chapter 8 XOR - Advanced C# Type Construction Part Three - Programming with .NET Assemblies
Logical OR
Chapter 9
|
- Understanding .NET Assemblies
Conditional AND && and Threads Chapter 10 - Processes, AppDomains, Contexts, Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Conditional OR
Part Four - Leveraging the .NET Libraries
||
Conditional ?: Remoting Layer Chapter 12 - Object Serialization and the .NET Chapter 13 - Building a Better Window (Introducing Windows Forms)
Indirection / Address
* -> &
Chapter 14 - A Better Painting Framework (GDI+)
Assignment = *= /= %= += -= = &= ^= |= Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
The only that you not be familiar with are the is and as operators. The is operator is used to Chapter 17operators - Data Access with may ADO.NET verify at -runtime if an objectand is compatible with a given Part Five Web Applications XML Web Services
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 Controls allows you to downcast between types (seen briefly in this chapter and formally in Chapter 4) or Chapter 19 - ASP.NET Web Applications implemented interface. Chapter 20 - XML Web Services
Index Also note that the C# language does support the use of classic C(++) pointer manipulations, via the *, -> List andof&Figures 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# and the .NET Platform, Second Edition Defining Custom Class Methods by Andrew Troelsen
ISBN:1590590554
Now that we haveApress concluded reprieve, let's move on to more interesting topics and © 2003 our (1200mid-chapter pages) examine the details of defining custom methods for aa brief C# class. Firstofunderstand that, like points of data, This comprehensive text starts with overview the every method youC# implement must be a member of a class or struct (global methods are not allowed in language and then quickly moves to key technical and architectural issues for .NET developers. C#). As you know, a method exists to allow the type to perform a unit of work. Like Main(), your custom Table methods of Contents may or may not take parameters, may or may not return values (of any intrinsic or user defined
types). Also custom methods may be declared nonstatic (instance-level) or static (class-level) entities. C# and the .NET Platform, Second Edition Introduction
Method Access Modifiers
Part One - Introducing C# and the .NET Platform
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 Part modifiers Two - The (youC# examine Programming the useLanguage of protected
and internal methods in the next chapter during the
discussion class hierarchies): Chapter 3 -of C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Table 3-8: Accessibility Keywords Chapter 5 - C# Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections C# Access Meaning in Life
Chapter 7 - Callback Interfaces, Delegates, and Events Modifier Chapter 8
- Advanced C# Type Construction Techniques
public Marks method as accessible Part Three - Programming with a .NET Assemblies Chapter 9
private
from an object instance, or any subclass.
- Understanding .NET Assemblies
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 Attribute-Based Programming visibility Chapter 10 - Processes, AppDomains, Contexts, and Threads Part Four - Leveraging the .NET Libraries
protected Marks a and method as usable by the defining class, as well as any child class, Chapter 12 - Object Serialization the .NET Remoting Layer but is Window private as far as the Windows outside world is concerned. Chapter 13 - Building a Better (Introducing Forms) Chapter 14 - A Better Painting Framework internal Defines a method(GDI+) that is publicly accessible by all types in an assembly (but Chapter 15 - Programming Controls notwith fromWindows outsideForms the assembly). Chapter 16 - The System.IO Namespace
protected internal
Defines a method whose access is limited to the current assembly or types derived from the defining class in the current assembly. - Web Applications and XML Web Services
Chapter 17 - Data Access with ADO.NET Part Five
Chapter 18 - ASP.NET Web Pages and Web Controls
Here are the implications of each accessibility keyword:
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
// Visibility options. Index 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 Figures
As you may already know, methods that are declared public are directly accessible from an object C# and the .NET Platform, Second Edition instance via the dot operator. Private methods cannot be accessed by an object reference, but instead are ISBN:1590590554 by the Andrew Troelsen called internally by object to help the instance get its work done (that is, private helper functions). To Apress © 2003 (1200 pages) illustrate, the Teenager class shown next defines two public methods, Complain() and BeAgreeable(), This comprehensive starts with a brief overview of the make use of a private helper each of which returns a string to the text object user. Internally, both methods C# language and then quickly moves to key technical and method named GetRandomNumber(), which manipulates a private member variable of type architectural issues for .NET developers. System.Random: // Two public methods, each using an internal helper function. Table of Contents using System; C# and the .NET Platform, Second Edition class Teenager Introduction { One - Introducing C# and the .NET Platform Part System.Random Chapter // 1 -The The Philosophy of .NET type generates random numbers. Random r = new Random(); Chapter private 2 - Building C# Applications Complain() Part Twopublic - The C# string Programming Language { - C# Language Fundamentals string[] messages = new string[5]{ "Do I have to?", Chapter 4 - Object-Oriented Programming with C# "He started it!", "I'm too tired...", Chapter 5 - Exceptions and Object Lifetime "I hate school!", "You are sooo wrong." } ; Chapter 6 - Interfaces and Collections return messages[GetRandomNumber(5)]; Chapter 7 - Callback Interfaces, Delegates, and Events } Chapter public 8 - Advanced C# Type Construction Techniques string BeAgreeable() Part Three { - Programming with .NET Assemblies Chapter 9 - Understanding .NET Assemblies string[] messages = new string[3]{ "Sure! No problem!", Chapter 10 - Processes, AppDomains, Contexts, Threads "Uh uh.", "I guessand so." } ; Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming return messages[GetRandomNumber(3)]; Part Four} - Leveraging the .NET Libraries Chapter private 12 - Objectint Serialization and the .NET Remoting Layer GetRandomNumber(short upperLimit) Chapter { 13 - Building a Better Window (Introducing Windows Forms) Random.Next() returns Chapter 14 - A // Better Painting Framework (GDI+) a random integer // between 0 and upperLimit. Chapter 15 - Programming with Windows Forms Controls return r.Next(upperLimit); Chapter 16 - The System.IO Namespace } Chapter 17 - Data Access with ADO.NET static void Main(string[] args) Part Fivepublic - Web Applications and XML Web Services { Chapter 18 - ASP.NET Web Pages and Web Controls // Let mike do his thing. Chapter 19 - ASP.NET Web Applications Console.WriteLine("Grumpy Mike says:"); Chapter 20 - XML Web Services Teenager mike = new Teenager(); Index for(int i = 0; i < 10; i++) List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3 - 3-14: C# Language Figure RandomFundamentals teenager chatter Chapter 4 - Object-Oriented Programming with C#
Note System.Random type is used to generate and manipulate random numbers. Chapter 5 The - Exceptions and Object Lifetime returns a number between 0 and the specified upper limit. As you would Chapter 6 Random.Next() - Interfaces and method Collections Chapter 7 Chapter 8
guess, the Random type provides additional members, all of which are documented within - Callback Interfaces, Delegates, and Events MSDN. - Advanced C# Type Construction Techniques
Part Three - Programming .NET Assemblies SOURCE The with Teenager application
is located under the Chapter 3 subdirectory.
Chapter 9 - Understanding .NET Assemblies CODE Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andStatic the .NETMethods Platform, Second Edition Understanding by Andrew Troelsen
ISBN:1590590554
As you have seen, methods can bepages) declared "static." But, what exactly does it mean to be a static method? Apress © 2003 (1200 When a method is marked with the "static" keyword, mayoverview be called from the class level, and does This comprehensive text starts with a itbrief ofdirectly 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 moves to key technical and architectural issues for .NET developers. function without needing to allocate a new instance of 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 (...). Table You of should Contents also consider our good friend System.Console. As you have seen, you do not invoke the
WriteLine() method fromSecond an object instance: C# and the .NET Platform, Edition Introduction Part C# and theinstance .NET Platform // One No!- Introducing WriteLine() not level...
Chapter 1 -cThe of .NET Console = Philosophy new Console(); Chapter c.WriteLine("I 2 - Building C# can't Applications be printed..."); Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals but instead prefix theProgramming type name towith the C# static WriteLine() member. Chapter 4 - simply Object-Oriented Chapter 5
- Exceptions and Object Lifetime
// Yes! is static... Chapter 6 -WriteLine() Interfaces and Collections Console.WriteLine("Thanks..."); Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Simply put, static members are methods that are deemed (by the class designer) to be so commonplace that - Understanding .NET Assemblies there is no need to create an instance of the type. When you are designing your custom class types, you are Chapter 10 - Processes, AppDomains, Contexts, 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, andand Attribute-Based Programming assume11I have reconfigured the Complain() BeAgreeable() methods of the Teenager class as follows: Chapter 9
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
// Teenagers complain so often, there is no need to create an initial object... publicstatic string Complain() Chapter 14 - A Better Painting Framework (GDI+) { Chapter string[] 15 - Programming with Windows Controls "Do I have to?", messages = new Forms string[5]{ Chapter 16 - The System.IO Namespace "He started it!", "I'm too tired...", Chapter 17 - Data ADO.NET "You are sooo wrong." } ; "I Access hate with school!", Part Fivereturn - Web Applications and XML Web Services messages[GetRandomNumber(5)]; Chapter 18 ASP.NET Web Pages and Web Controls } Chapter 19 - ASP.NET Web Applications public static string BeAgreeable() Chapter { 20 - XML Web Services Index string[] messages = new string[3]{ "Sure! No problem!", "Uh uh.", "I guess so." }; List of Figures return messages[GetRandomNumber(3)]; List of Tables } Chapter 13 - Building a Better Window (Introducing Windows Forms)
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# and the .NET Platform, Second Edition name of the defining class: by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
// Call the static Complain method of the Teenager class. This comprehensive text starts with a brief overview of the public staticC#void Main(string[] args) language and then quickly moves to key technical and { architectural issues for .NET developers. for(int i = 0; i < 40; i++) Console.WriteLine("-> {0}", Teenager.Complain()); } Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
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
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
// Must -make an instance of Teenager class to call instance methods. Object-Oriented Programming with C# Teenager joe = new Teenager(); Chapter 5 - Exceptions and Object Lifetime joe.Complain(); Chapter 4 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming .NET Assemblies SOURCE The with StaticTeenager application
is located under the Chapter 3 subdirectory.
Chapter 9 - Understanding .NET Assemblies CODE Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Defining Static Data
Part Four - Leveraging the .NET Libraries
Chapter 12 -toObject the .NET Layer In addition static Serialization methods, a and C# class mayRemoting also define static data (such as the previous Random member Chapter 13 Building a Better Window (Introducing Windows Forms)a set of nonstatic state data. This simply variable from the Teenager example). Typically, a class defines Chapter - each A Better Painting Framework (GDI+) means14 that object instance maintains a private copy of the underlying values. Thus, if you have a class Chapter defined15 as-follows: Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter - Data Access with ADO.NET // We17all love Foo. Part Five -Foo Web Applications and XML Web Services class
Chapter 18 - ASP.NET Web Pages and Web Controls { Chapter public 19 - ASP.NET intWeb intFoo; Applications
} Chapter 20 - XML Web Services Index List of Figures
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# and the .NET Platform, Second Edition class Airplane ISBN:1590590554 by Andrew Troelsen { Apress © 2003 (1200 pages) // This static data member is shared by all Airplane objects. comprehensive text starts with a brief overview of the privateThis static int NumberInTheAir = 0; C# language and then quickly moves to key technical and public Airplane() architectural issues for .NET developers. { NumberInTheAir++; } Table of Contents // Get value from an object instance. C# and the .NET Platform, Second Edition public int GetNumberFromObject() { return NumberInTheAir; } Introduction // Get value from class level. Part One - Introducing C# and the .NET Platform public static int GetNumber() { returnNumberInTheAir; } Chapter 1 - The Philosophy of .NET } Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter C# Airplane Languageclass Fundamentals Notice 3that- the defines two methods. The static GetNumber() returns the current number of Chapter 4 objects - Object-Oriented Programming C#application. GetNumberFromObject() also returns the value airplane that have been allocatedwith by the Chapter of the static 5 - Exceptions NumberInTheAir and Object integer, Lifetime however 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 Interfaces andmethod Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8 -some Advanced C# Type Construction Techniques // Make airplanes are examine the static members. Part ThreeStaticApp - Programming with .NET Assemblies class
Chapter { 9
- Understanding .NET Assemblies static int Main(string[] args) Chapter public 10 - Processes, AppDomains, Contexts, and Threads Chapter { 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Make planes. Part Four - Leveraging the some .NET Libraries Console.WriteLine("Created two Airplane types"); Chapter 12 - Object Serialization and the .NET Remoting Layer Airplane a1Window = new(Introducing Airplane(); Chapter 13 - Building a Better Windows Forms) a2Framework = new Airplane(); Chapter 14 - A Airplane Better Painting (GDI+) // How many are in flight? Console.WriteLine("Number of planes: {0} ", Chapter 16 - The System.IO Namespace a1.GetNumberFromObject()); Chapter 17 - Data Access with ADO.NET Console.WriteLine("Number of planes: {0} ", Part Five - Web Applications and XML Web Services Airplane.GetNumber()); Chapter 18 - ASP.NET Web Pages and Web Controls // More planes! Chapter 19 - ASP.NET Web Applications Console.WriteLine("\nCreated two more Airplane types"); Chapter 20 - XML Web Services Airplane a3 = new Airplane(); Index Airplane a4 = new Airplane(); List of Figures // 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 - Programming with Windows Forms Controls
Figure 3-15 shows the output.
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table Figure of Contents 3-15: Static data is shared among like objects. C# and the .NET Platform, Second Edition Introduction
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. Part One - Introducing C# and the .NET Platform
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language SOURCE The StaticData project
is located under the Chapter 3 subdirectory.
Chapter 3 - C# Language Fundamentals CODE Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Method Parameter Modifiers by Andrew Troelsen
ISBN:1590590554
Methods tend to take parameters. you have a COM background, you are certainly familiar with the use of Apress © 2003 (1200 If pages) the [in], [out], andThis [in, comprehensive out] IDL attributes. COM objects use these text Classic starts with a brief overview 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 moves to key technical and issues for .NET developers. used in the .NET architectural universe, there is analogous behavior with the set of C# parameter modifiers shown in Table 3-9. Table of 3-9: Contents Table C# Parameter Modifiers C# and the .NET Platform, Second Edition
Parameter Introduction
Meaning in Life Modifier Part One - Introducing C# and the .NET Platform Chapter 1
of .NET (none) - The Philosophy If a parameter is not marked with a parameter modifier, it is assumed to be - Building C# Applications an input parameter passed by value. This is analogous to the IDL [in] Part Two - The C# Programming attribute.Language Chapter 2 Chapter 3
- C# Language Fundamentals
out 4 Chapter
This isProgramming analogous towith an IDL - Object-Oriented C# [out] parameter. Output parameters are assigned
Chapter 5
theObject calledLifetime member. - Exceptionsby and
Chapter ref 6 Chapter 7
- Interfaces Analogous and Collections to the IDL [in, out] attribute. The value is assigned by the caller, - Callback Interfaces, Delegates, andwithin Eventsthe scope of the method call. but may be reassigned
Chapter 8
- Advanced C# Type Construction 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 - Understanding .NET Assemblies params modifier, and must be the final parameter of the method. Part Three - Programming with .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
The Default Parameter Passing Behavior
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
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 - Programming with Windows Forms Controls changes slightly when passing reference types by value, as you will see in just a bit). You have already Chapter 16 - The System.IO Namespace been making use of by-value parameter passing, however, here is a simple example (with implications): Chapter 14 - A Better Painting Framework (GDI+)
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
// Default param passing is by value. public static int Add(int x, int y) Chapter 19 - ASP.NET Web Applications { Chapter 20 - XML Web Services int ans = x + y; Index // Caller will not see these changes. List of Figures x = 99999; List of Tables y = 88888; return ans; } Chapter 18 - ASP.NET Web Pages and Web Controls
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 the values of Platform, x and y remain identical before and after the call to Add(). C# and .NET Second Edition by Andrew Troelsen
ISBN:1590590554
Apress © 2003 (1200 pages) The C# "out" Keyword This comprehensive text starts with a brief overview of the language and then quicklyHere moves to key technicalversion and of the Add() method that Next, we have theC# use of output parameters. is an alternative architectural issues .NET returns the sum of two integers usingforthe C#developers. "out" keyword (note the physical return value of this method is now void): Table of Contents
// Output parameters are allocated by the callee. public static void Add(int x, int y, out int ans) Introduction { Part One - Introducing C# and the .NET Platform ans = x + y; Chapter 1 - The Philosophy of .NET } C# and the .NET Platform, Second Edition
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter - C# Language Fundamentals Calling3a method with output parameters also requires the use of the "out" keyword. Recall that when you Chapter 4 output - Object-Oriented Programming with C#assigned before use (if you do so, the value is forgotten are local, variables are not required to be Chapter after the 5 call). - Exceptions For example: and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter - Callback Interfaces, Delegates, Events // No7 need to assign before useand when a variable is used ala out. Chapter 8 - Advanced C# Type Construction Techniques int ans; Part .NET Assemblies // Three Note- Programming use of outwith keyword in calling
syntax.
Chapter Add(90, 9 -90, Understanding out ans); .NET Assemblies
Console.WriteLine("90 + 90Contexts, = {0} and ", Threads ans); Chapter 10 - Processes, AppDomains, Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
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 Better Window (Introducing Windows Forms) multiple return values from a single method invocation. For example, assume we have the following Chapter 14 - A Better Painting Framework (GDI+) member: Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
// Returning multiple output parameters. public static void FillTheseValues(out int a, out string b, out bool c) Part Five - Web Applications and XML Web Services { Chapter 18 - ASP.NET Web Pages and Web Controls a = 9; Chapter 19 - ASP.NET Web Applications b = "Enjoy your string..."; Chapter 20 - XML Web Services c = true; Index } Chapter 17 - Data Access with ADO.NET
List of Figures 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# and the .NET Platform, Second Edition wish to allow a method to operate on (and usually change the values of) various data points declared in Andrew the caller's scopeby(such as aTroelsen sort routine). Note the distinction ISBN:1590590554 between output and reference parameters: Apress © 2003 (1200 pages)
Output parameters do not need text to bestarts initialized they areof sent This comprehensive with abefore brief overview theto the callee. Reason? It is language moves to key technical and assumed theC# method fills and the then valuequickly on your behalf. architectural issues for .NET developers.
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 Table of Contents operating on a NULL pointer! C# and the .NET Platform, Second Edition
Let's check out the use of the "ref" keyword: Introduction Part One - Introducing C# and the .NET Platform
Chapter // Reference 1 - The Philosophy parameter. of .NET
public UpperCaseThisString(ref string s) Chapter 2 static - Buildingvoid C# Applications { Two - The C# Programming Language Part the Fundamentals uppercase version of the string. Chapter // 3 -Return C# Language s.ToUpper(); Chapter s 4 =- Object-Oriented Programming with C# } Chapter 5
- Exceptions and Object Lifetime public void Chapter 6 static - Interfaces and Main() Collections
{
Chapter 7
- Callback Interfaces, Delegates, and Events
... Chapter 8 - Advanced C# Type Construction Techniques // Use 'ref'. Part Three - Programming with .NET Assemblies string s = "Can you really have sonic hearing for $19.00?"; Chapter 9 - Understanding .NET Assemblies Console.WriteLine("Before: {0} ", s); Chapter 10 - Processes, AppDomains, Contexts, and Threads UpperCaseThisString(ref s); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Console.WriteLine("After: {0} ", s); Part Four - Leveraging the .NET Libraries } Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter Here, the 14 caller - A Better has Painting assignedFramework an initial value (GDI+) to a local string named "s." Once the call to
UpperCaseThisString() the caller will find "s" has been converted into uppercase, given the use of Chapter 15 - Programmingreturns, with Windows Forms Controls the "ref" Chapter 16keyword. - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
The C# "params" Keyword
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
The final is the "params" keyword, which is somewhat odd (but convenient) given that Chapter 19parameter - ASP.NET modifier Web Applications it allows20you to send varied number of arguments as a singleparameter. Yes, this can be confusing. To Chapter - XML Web aServices clear the air, assume I have written a simple method defined as follows: Index List of Figures
//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# and the .NET Platform, Edition DisplayArrayOfInts ("Enjoy these Second 3 ints", 1, 2, 3); by Andrew Troelsen DisplayArrayOfInts ("Take some more!", 55, 4,ISBN:1590590554 983, 10432, 98, 33); Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language quickly to keyitems technical Looking at the previous code, and you then can see thatmoves the bolded in a and given invocation correspond to the architectural issues for .NET developers. second parameter (the array of integers).
Of course, you do not have to make use of simple numeric value types when using the params keyword. Table of Contents Assume we have yet another variation of the Person class, now defined as follows: C# and the .NET Platform, Second Edition Introduction // Yet another person class. Part One - Introducing C# and the .NET Platform
class Person
Chapter 1 {
- The Philosophy of .NET
Chapter private 2 - Building C# Applications string fullName; Part Twoprivate - The C# Programming byte age; Language
Chapter public 3 - C# Language Fundamentals Person(string n, byte a) Chapter { 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions fullName and=Object n; Lifetime
Chapter 6
age = a; - Interfaces and Collections
Chapter } 7
- Callback Interfaces, Delegates, and Events
voidC#PrintInfo() Chapter public 8 - Advanced Type Construction Techniques { Console.WriteLine("{0} is {1} years old", fullName, age); } Part Three - Programming with .NET Assemblies } Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer an incoming Person type using the C# "is" keyword. If your current item is of type Person, call the Chapter 13 -method. BuildingIfayou Better Windows Forms) PrintInfo() do Window not have(Introducing a Person type, just dump the textual information of the type to the Chapter 14 - A Better Painting Framework (GDI+) console: Part Four - Leveraging the .NET Libraries
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
// This method takes any number of any type.
Chapter 17 static - Data Access ADO.NET public voidwith DisplayArrayOfObjects(params object[] list) Part { Five - Web Applications and XML Web Services
Chapter for 18 - ASP.NET Web and CurrSpeed = {0}", currSpeed); } } } Chapter 15 - Programming with Windows Forms Controls
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# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
// A Car has-a Radio. Apress © 2003 (1200 pages) public class Car This comprehensive text starts with a brief overview of the { C# language and then quickly moves to key technical and ... architectural issues for .NET developers. // The contained Radio. private Radio theMusicBox; } Table of Contents C# and the .NET Platform, Second Edition Introduction
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 Part Two - The C# Programming Language sees fit, one common place to do so is in the type's constructor set: Part One - Introducing C# and the .NET Platform
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
// Containing classes are responsible for creating any child objects. - Exceptions and Object Lifetime public class Car Chapter 6 - Interfaces and Collections { Chapter 7 - Callback Interfaces, Delegates, and Events ... Chapter 8 - Advanced C# Type Construction Techniques private Radio theMusicBox; Part Three - Programming with .NET Assemblies public Car() Chapter{9 - Understanding .NET Assemblies Chapter 10 -maxSpeed Processes, AppDomains, Contexts, and Threads = 100; Chapter 11 -theMusicBox Type Reflection, = Late Binding, and Attribute-Based Programming new Radio(); Part Four Leveraging the .NET Libraries } Chapterpublic 12 - Object Serialization name, and the int .NET Remoting Layer Car(string max, int curr) Chapter{13 - Building a Better Window (Introducing Windows Forms) Chapter 14 -currSpeed A Better Painting = curr; Framework (GDI+) = with max; Chapter 15 -maxSpeed Programming Windows Forms Controls = name; Chapter 16 -petName The System.IO Namespace new Radio(); Chapter 17 -theMusicBox Data Access with=ADO.NET } - Web Applications and XML Web Services Part Five } Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 5
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
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:
Index
List of Figures 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# and the .NET Platform,state) Second Edition public void CrankTunes(bool ISBN:1590590554 by Andrew Troelsen { Apress © 2003 (1200 pages) // Delegate request to inner object. This comprehensive text starts with a brief overview of the theMusicBox.TurnOn(state); C# language and then quickly moves to key technical and } architectural issues for .NET developers.
} Table of Contents
C# and the .NET Platform, Second Edition
In the following code, notice how the object user is able to interact with the hidden inner object indirectly, and
Introduction is totally unaware of the fact that the Car class is making use of a private Radio instance: Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
// Take this car for a test drive. - Building C# Applications public class CarApp Part Two - The C# Programming Language { Chapter 3 - C# Language Fundamentals public static int Main(string[] args) Chapter{4 - Object-Oriented Programming with C# Chapter 5 - Exceptions Object Lifetime makes the radio). // Make and a car (which Chapter 6 - Interfaces and Collections Car c1; Chapter 7 - Callback Interfaces, Delegates, and 100, Events 10); c1 = new Car("SlugBug", Chapter 8 - Advanced Typetunes Construction Techniques // Jam C# some (which makes use of the radio). Part Three - Programming with .NET Assemblies c1.CrankTunes(true); Chapter 9 - Understanding // Speed up .NET (and Assemblies watch engine die...) for(int AppDomains, i = 0; i Contexts, < 10; i++) Chapter 10 - Processes, and Threads c1.SpeedUp(20); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming // Shutthedown (which again makes use of the radio). Part Four - Leveraging .NET Libraries c1.CrankTunes(false); Chapter 12 - Object Serialization and the .NET Remoting Layer returna Better 0; Chapter 13 - Building Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls Chapter 2
Chapter 16 - The System.IO Namespace Chapter - Data Access with ADO.NET Figure 17 4-11 shows the output. Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 4-11: The contained Radio in action SOURCE CODE
The Containment project is included under the Chapter 4 subdirectory.
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# Definitions and the .NET Platform, Second Edition Nested Type by Andrew Troelsen
ISBN:1590590554
Before examiningApress the final pillar of pages) OOP (polymorphism), let's explore a programming technique termed © 2003 (1200 nested types. In C#, it is possible to a type (enum, interface, This comprehensive define text starts with a briefclass, overview 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 moves to key technical and formanipulated .NET developers. and in the eyes ofarchitectural the runtimeissues can be like any "normal" member (fields, properties, methods, events, etc.). The syntax used to nest a type is quite straightforward: Table of Contents
// C# allows classes to nest others. publicclass MyClass Introduction { Part One - Introducing C# and the .NET Platform // Members of outer class. Chapter ... 1 - The Philosophy of .NET Chapter public 2 - Building C# Applications class MyNestedClass Part Two{- The C# Programming Language Chapter 3 - C# Language Fundamentals // Members of inner class. Chapter 4 - Object-Oriented Programming with C# ... Chapter } 5 - Exceptions and Object Lifetime Chapter } 6 - Interfaces and Collections C# and the .NET Platform, Second Edition
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Although syntax is clean, why Part Three -the Programming with understanding .NET Assemblies
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 - Understanding .NET Assemblies world. This is slightly along the lines of the "has-a" relationship; however, in the case of nested types, you Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming services. In general, when you are attempting to model the fact that type B makes no sense outside of the Part Four - Leveraging the .NET Libraries context of type A, nested classes do the trick. Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 Be - Building a Better Window (Introducing Windows Forms) Note aware that when you read over the .NET literature (including online help samples) you may Chapter 14 find - A Better Painting Framework are (GDI+) that nested relationships denoted in text using the dollar sign token ($). Thus, if you Chapter 15 come - Programming across Car$Radio, with Windows youForms are able Controls to interpret this as "the Radio class is nested within the
class." As you will see during your examination of Windows Forms, the pattern of nesting Chapter 16 Car - The System.IO Namespace other is commonplace, so make a mental note of the $ token! Chapter 17 types - Datawithin Access withtypes ADO.NET Part Five - Web Applications and XML Web Services
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 Applications Radio. In other words, you are attempting to programmatically capture the idea that a Radio type makes Chapter 20 - XML Web Services no sense outside of the Car to which it belongs. Here is the update: Chapter 18 - ASP.NET Web Pages and Web Controls
Index
List of Figures
// 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# and the .NET Platform, Second Edition
}
by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Notice that the Car type is able to create instances any nested item. Also notice that this class This comprehensive text object starts with a brief of overview of the C#alanguage and then quickly moves keybe technical andprivate as well as public. Recall, has been declared private type. In C#, nested typestomay declared architectural forwithin .NET developers. however, that classes that areissues 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:
Table of Contents
C# and the .NET Platform, Second Edition
// Can't do it outside the scope of the Car class! Radio r = new Radio();
Introduction
Part One - Introducing C# and the .NET Platform
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: Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Car c1= new Car("SlugBug", 100, 10); - Object-Oriented Programming with C# // Jam some tunes. Chapter 5 - Exceptions and Object Lifetime c1.CrankTunes(true); Chapter 4 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
SOURCE The with Nested is included under Part Three - Programming .NETproject Assemblies
the Chapter 4 subdirectory.
CODE Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NETPolymorphic Platform, Second Edition The Third Pillar: C#'s Support by Andrew Troelsen
ISBN:1590590554
Switching back toApress the 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 comprehensive text starts with a named brief overview of the as follows: C# language and then quickly moves to key technical and architectural issues for .NET developers. // Employee defines a new method that gives a bonus to a given employee. public class Employee { Table of Contents ... C# and the .NET Platform, Second Edition public void GiveBonus(float amount) Introduction { Part One - Introducing C# and the .NET Platform currPay += amount; Chapter}1 - The Philosophy of .NET Chapter 2 - Building C# Applications } Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals Because method has been defined aswith public, Chapter 4 this - Object-Oriented Programming C# you can now give bonuses to sales-persons and managers
(see Figure for output): Chapter 5 - 4-12 Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter // Give 7 -each Callback child Interfaces, class Delegates, a bonus. and Events
Manager new Chapter 8 -chucky Advanced=C# TypeManager("Chucky", Construction Techniques92, 100000, "333-23-2322", 9000); chucky.GiveBonus(300); Part Three - Programming with .NET Assemblies chucky.DisplayStats(); Chapter 9 - Understanding .NET Assemblies SalesPerson fran AppDomains, = new SalesPerson("Fran", Chapter 10 - Processes, Contexts, and Threads 93, 3000, "932-32-3232", 31); fran.GiveBonus(200); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming fran.DisplayStats(); Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and thevoid .NET GiveBonus(float Platform, Second Edition public virtual amount) ISBN:1590590554 by Andrew Troelsen { currPay += amount; } ... }
Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
If a subclass wishes to redefine a virtual method, it is required to reimplement the method in question using the "override" keyword. For example:
Table of Contents
C# and the .NET Platform, Second Edition
public class SalesPerson : Employee { Part One - Introducing C# and the .NET Platform // 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 { Part Two - The C# Programming Language int salesBonus = 0; Chapter 3 - C# Language Fundamentals if(numberOfSales >= 0 && numberOfSales = 101 && numberOfSales :-) and Web Controls everyone Chapter public 19 - ASP.NET Web Applications static void FireThisPerson(Employee e) Chapter { 20 - XML Web Services
if(eis SalesPerson)
Index
List of Figures { 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 of the "as" keyword to obtain a reference to the more derived type (if the types are incompatible, the reference is set
to null):
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
SalesPerson p = e as SalesPerson; Apress © 2003 (1200 pages) if(p != null) This comprehensive text starts with a brief overview of the Console.WriteLine("# of sales: {0}", p.NumbSales); C# language and then quickly moves to key technical and architectural issues for .NET developers.
As you will see in Chapter 6, these same techniques (explicit cast, "is", and "as") can be used to obtain Table Note of Contents interface reference from an implementing type. C# and the an .NET Platform, Second Edition Introduction
Numerical Casts
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET In addition castingC# between objects, be aware that numerical conversions follow more or less the same rules. If Chapter 2 -toBuilding Applications
youTwo are -attempting to cast a "larger" numerical Part The C# Programming Language
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
- Object-Oriented Programming with C#
int x5 = -30000; Chapter Exceptions and Object Lifetime byte b (byte)x; Chapter 6 =- Interfaces and Collections
// Loss of information here...
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
However, when you are storing a "smaller" numerical type into a "larger" type (such as a byte to an integer), the - Understanding .NET Assemblies type is implicitly cast on your behalf, as there is no loss of data:
Chapter 9
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
byte b = 30; int x = b;
Part Four - Leveraging the .NET Libraries
// No loss of information...
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 -concludes A Better Painting Frameworkof(GDI+) Cool! This our examination how C# contends with the famed pillars of OOP. To close this chapter, Chapter 15 to - Programming with Windows Controls allow me point out a few select tools Forms of VS .NET that aid in the construction of custom types. Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and theDefinitions .NET Platform, Second GeneratingC# Class UsingEdition Visual Studio .NET by Andrew Troelsen
ISBN:1590590554
Over the course of this chapter, youpages) have seen how the C# programming language contends with the Apress © 2003 (1200 three pillars of OOP, by making use of the "Keyboard Wizard" (read:oftyping This comprehensive text starts with a brief overview 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 moves to key technical and architectural issues for .NET developers. does provide a number of integrated tools that allow you to build initial class definitions using various GUI input dialog boxes. Table To illustrate of Contents how 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 the you .NETchoose-I Platform,called Second Edition project. Your first task is to select the Class View tab of the Solution Explorer window. From here, simply Introduction right-click the solutionC# icon and Add | Class Part One - Introducing and theselect .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
(Figure 4-18).
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure Adding a new class(Introducing via VS .NETWindows Forms) Chapter 13 - 4-18: Building a Better Window Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls The resulting dialog box will allow you to set up the initial class definition. As you can see from Figure 4-19, Chapter 16 The System.IO Namespace the Class Options link of the wizard allows you to define whether the class is sealed or abstract, public or Chapter 17and - Data with ADO.NET internal, any Access optional XML code documentation (see Chapter 2). Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Chapter 3
- C# Language Fundamentals
Figure 4-20: Specifying theLanguage base class Part Two - The C# Programming Finally, the (rather poorly named) Inheritance link (Figure 4-21) allows you to choose the set of interfaces Object-Oriented Programming with C# (if any) the- type will implement (not inherit).
Chapter 4 Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Figure 4-21: Implementing (not inheriting) select interfaces
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Once you your new class using this integrated wizard, you will find your new type is now part Chapter 20 -have XMLdefined Web Services of your current project and is a member of the current default namespace. Index List of Figures
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Chapter 3
- C# Language Fundamentals
Figure 4-22: The Add Member Wizard Part Two - The C# Programming Language Chapter 4 -point Object-Oriented Programming with C# So, at this you should have a solid understanding of C#'s handling of the pillars of OOP (as well as Chapter 5 - Exceptions and some insights as to how VSObject .NET Lifetime can aid in the process of defining custom types). The next chapter will Chapter build upon 6 -this Interfaces foundation and Collections by examining how to handle runtime anomalies using structured exception
handling showing how the CLR manages an object's lifetime. Chapter 7 and - Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
If you already come to the universe of .NET from another object-oriented language, this chapter may have Apress © 2003 (1200 pages) been more of a quick compare and between youroverview current language of choice and C#. On the This comprehensive contrast text starts with a brief 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 moves to key technical and issuesRegardless for .NET developers. presented here aarchitectural bit confounding. of your 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. Table of Contents
This chapter began with a reviewEdition of the pillars of OOP: encapsulation, inheritance, and polymorphism. As C# and the .NET Platform, Second you have seen, C# provides full support for each aspect of object orientation. Encapsulation services can Introduction be accounted for using accessor/ mutator Part One - Introducing C#traditional and the .NET Platform
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 the "abstract", "virtual", Part Two The C# Programming Language
and "new" keywords (as you recall, "new" can be applied to
members well!). Chapter 3 -asC# Language Fundamentals Chapter 4
- Object-Oriented Programming with 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 andthe Object Lifetime "keyboard Again, mission of this text is not to examine every aspect of VS .NET; however, you Chapter 6 Interfaces and Collections will find numerous examples throughout the remainder of the book. Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
the .NET Platform, Second Edition Chapter C# 5:and Exceptions and Object Lifetime ISBN:1590590554 by Andrew Troelsen Apress ©you 2003 (1200 pages) In the previous chapter, dug into the details of how C# supports encapsulation services, reuse of code This comprehensive text startsrelated with a brief overview of theof this chapter is twofold. First, (inheritance), and polymorphic activity among classes. The point C# language and then quickly moves to key technical and you will come to understand how to handle runtime anomalies in your code base through the use of architectural issues for .NET developers. 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 Table of Contents 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 the .NET Platform, Second Edition Visual Studio .NET. Introduction
Part One - Introducing C# and the .NET Platform
The second half of the chapter will 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 Part Two - Thecome C# Programming (eventually) to pass. On Language this note, you
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 - Object-Oriented Programming with C# type, and illustrate a number of ways you are able to we wrap with an examination of the System.GC Chapter "get involved" 5 - Exceptions with the garbage and Object collection Lifetime process. Chapter 6
- Interfaces and Collections
Callback Interfaces, and Events Ode to- Errors, Bugs,Delegates, and Exceptions
Chapter 7 Chapter 8
- Advanced C# Type Construction Techniques
Part Despite Threewhat - Programming our (often inflated) with .NET egos Assemblies may tell
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 - Understanding Assemblies "problems." Sometimes the problemContexts, is caused byThreads "bad code" (such as overflowing the bounds of an Chapter 10 - Processes, AppDomains, and array). 11 Other times, a problem caused and by bogus user inputProgramming that has not been accounted for in the Chapter - Type Reflection, LateisBinding, Attribute-Based application's code base phone number Part Four - Leveraging the(e.g., .NET a Libraries
field assigned "Chucky"). Now, regardless of the cause of
said problem, the end result is that your.NET application does not work as expected. To help frame the Chapter 12 - Object Serialization and the Remoting Layer upcoming structured handling, allow me to provide definitions for three common Chapter 13 -discussion Building a of Better Windowexception (Introducing Windows Forms) anomaly-centric terms:
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 -This Programming Windows Forms Controls Bugs: is, simply with put, an error on the part of the programmer. For example, assume you are Chapter 16 The System.IO Namespace programming with unmanaged C++. If you make calls on a NULL pointer, overflow the bounds of an Chapter 17 -orData Access with ADO.NET array, fail to delete allocated memory (resulting in a memory leak), you have a bug. Part Five - Web Applications and XML Web Services
Errors: bugs, caused by the end user of the application, rather than by those Chapter 18 - Unlike ASP.NET Weberrors Pages are and typically Web Controls who saidWeb application. For example, an end user who enters a malformed string into a text box Chapter 19created - ASP.NET Applications that a Social Security number could very well generate an error if you fail to trap this faulty Chapter 20requires - XML Web Services Index input in your code base. List of Figures
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.
and the .NET Platform, Second Edition The Role ofC#.NET Exception Handling by Andrew Troelsen
ISBN:1590590554
Error handling among developers has grown into a confused mishmash of techniques over the ApressWindows © 2003 (1200 pages) years. Many programmers roll their own error logic within the context of a given application. For This comprehensive text startshandling with a brief overview of the example, a development team may define a set of numerical constants C# language and then quickly moves to key technical andthat represent known error architectural issuesas formethod .NET developers. conditions, and make use of them return values. For example, ponder the following C code: /* A very C-style error trapping mechanism. */ #defineE_FILENOTFOUND 1000
Table of Contents
C# and the .NET Platform, Second Edition Introduction
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. Part Two - The C# Programming Language return E_FILENOTFOUND; Chapter 3 - C# Language Fundamentals } Part One - Introducing C# and the .NET Platform
Chapter 4
- Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime void Main() Chapter { 6 - Interfaces and Collections
= SomeFunction(); Chapterint 7 -retVal Callback Interfaces, Delegates, and Events ==C#E_FILENOTFOUND) Chapterif(retVal 8 - Advanced Type Construction Techniques { printf("Can not .NET find file...");} Part Three - Programming with Assemblies } Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer the name, message, and other helpful information regarding this error condition into a single, well-defined Chapter 13 - Building a Better Window (Introducing Windows Forms) package (which is exactly what happens under structured exception handling). Part Four - Leveraging the .NET Libraries
Chapter 14 - A Better Painting Framework (GDI+)
Chapter In addition 15 -toProgramming this ad hoc technique, with Windows theForms Windows Controls API defines hundreds of error codes that come by way of
#defines, and Namespace far too many variations on the simple Boolean (bool, BOOL, VARIANT_BOOL, Chapter 16 HRESULTs, - The System.IO and so 17 on). many C++ developers (and indirectly, many VB 6.0 COM developers) have made Chapter - Also, Data Access with COM ADO.NET useFive of a -small set of standard interfaces (e.g., Part Web Applications andCOM XML Web Services
ISupportErrorInfo, IErrorInfo, ICreateErrorInfo) to
return meaningful error a COM client using a COM error object. Chapter 18 - ASP.NET Webinformation Pages and to Web Controls Chapter 19 - ASP.NET Web Applications
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 Index order to put an end to this madness, the .NET platform provides exactly one technique to send and trap List of Figures runtime errors: structured exception handling (SEH). Chapter 20 - XML Web Services
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# and the .NET Platform, Second Edition
bythrows Andrewthe Troelsen A method that exception to the caller
ISBN:1590590554
Apress © 2003 (1200 pages)
A block of code will invoke the method Thisthat comprehensive textexception-ready starts with a brief overview of the C# language and then quickly moves to key technical and
A block of code that will process (or.NET catch) the exception (should it occur) architectural issues for developers. As you will see, the C# programming language offers four keywords ("try", "catch", "throw", and "finally") that of allow you to throw and handle exceptions. The type that represents the problem at hand is a class Table Contents derived from System.Exception a descendent thereof). Given this fact, let's check out the role of this C# and the .NET Platform, Second (or Edition exception-centric base class. Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The System.Exception Base Class by Andrew Troelsen
ISBN:1590590554
All system-supplied and©custom exceptions ultimately derive from the System.Exception base class (which Apress 2003 (1200 pages) in turn derives from System.Object). As you canwith seea from following C# definition of this type, This comprehensive text starts brief the overview of the System.ExceptionC# also implements a standard interface named ISerializable; however, ignore this fact for language and then quickly moves to key technical and architectural for .NET developers. the time being (given that this issues interface has more to do with .NET Remoting than SEH). public class Exception : object, ISerializable C# and the .NET Platform, Second Edition { Introduction public Exception(); Part One - Introducing C# and the .NET Platform 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 Part Two - The C# Programming Language public Exception InnerException { get; } Chapter 3 - C# Language Fundamentals public string Message { virtual get; } Chapter 4 - Object-Oriented Programming with C# public string Source { virtual get; virtual set; } Chapter 5 - Exceptions Object Lifetime public string and StackTrace { virtual get; } Chapter public 6 - Interfaces MethodBase and Collections TargetSite { get; } public virtual bool Delegates, Equals(object obj); Chapter 7 - Callback Interfaces, and Events public virtual Exception GetBaseException(); Chapter 8 - Advanced C# Type Construction Techniques public virtual with int .NET GetHashCode(); Part Three - Programming Assemblies public virtual void Chapter 9 - Understanding .NET Assemblies info, StreamingContext context); Chapter 10 GetObjectData(SerializationInfo - Processes, AppDomains, Contexts, and Threads public Type GetType(); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming public virtual ToString(); Part Four - Leveraging the string .NET Libraries } Chapter 12 - Object Serialization and the .NET Remoting Layer
Table of Contents
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter A Better Painting (GDI+) by System.Exception are read-only in nature. This is due to As you 14 can- see, many of the Framework members defined Chapter 15 Programming with Windows Forms the simple fact that derived types will typically Controls supply default values for each property (for example, the Chapter - The System.IO Namespace default 16 message of the IndexOutOfRangeException type is "Index was outside the bounds of the array"). Chapter 17 Data Access with ADO.NET As you would expect, these default values can be altered and extended with custom information via Part Five - Web Applications and XML Web Services constructor parameters. Table 5-1 describes the core
members of System.Exception.
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - Core ASP.NET Web Applications Table 5-1: Members of the System.Exception Type Chapter 20 - XML Web Services
System.Exception Property
Index
Meaning in Life
List of Figures 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
ThisPlatform, read-only Second propertyEdition returns a MethodBase type, which describes C# and the .NET numerous details about the method that threw the exception ISBN:1590590554 by Andrew Troelsen (ToString() will identify the method by name). Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Throwing aC# Generic Exception by Andrew Troelsen
ISBN:1590590554
To illustrate the simplest System.Exception, let's revisit the Car class defined in Chapter 4, in Apress ©use 2003of (1200 pages) particular, the SpeedUp() method. Here is current implementation: This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and issues for .NET developers. // Currently,architectural SpeedUp() reports errors using console IO. public void SpeedUp(int delta) { Table of Contents // If the car is dead, just say so... C# and the .NET Platform, Second Edition if(carIsDead) Introduction Console.WriteLine("{0} is out of order....", petName); Part One - Introducing C# and the .NET Platform else // Not dead, speed up. Chapter { 1 - The Philosophy of .NET Chapter 2 - Building C# Applications currSpeed += delta; Part Two - The C# Programming if(currSpeed Language >= maxSpeed) Chapter 3 - C# { Language Fundamentals Chapter 4 - Object-Oriented Programming with C# Console.WriteLine("{0} has overheated...", petName); Chapter 5 - Exceptions and Object Lifetime carIsDead = true; Chapter 6 - Interfaces } and Collections else Interfaces, Delegates, and Events Chapter 7 - Callback CurrSpeed = {0}", currSpeed); Chapter 8 - AdvancedConsole.WriteLine("=> C# Type Construction Techniques } Part Three - Programming with .NET Assemblies } Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer System.Exception class, setting the value of the read-only Message property via the class constructor. Chapter 13 - Building a Better Window (Introducing Windows Forms) 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 Painting Framework (GDI+) the relevant update: Part Four - Leveraging the .NET Libraries
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
// This time, throw an exception if the user speeds up a trashed automobile. public void SpeedUp(int delta) Part Five - Web Applications and XML Web Services { Chapter if(carIsDead) 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET throwWeb newApplications Exception("This car is already dead..."); Chapter else 20 - XML Web Services Index { ... } List } of Figures Chapter 17 - Data Access with 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# and the .NET Platform, Second Edition Catching Exceptions by Andrew Troelsen
ISBN:1590590554
Because the SpeedUp() now throws an exception, you need to be ready to handle the exception Apress ©method 2003 (1200 pages) should it occur (you'll see what happens you fail an exception This comprehensive text if starts withtoa catch brief overview of thea bit later in this chapter). When you are calling a C# method that may throw an exception, you make use of a try/catch block. Once you have language and then quickly moves to key technical and architectural for .NET developers. caught the exception type, youissues are able to invoke of the members of the System.Exception type. What you 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 Table of Contents contents to the console window: C# and the .NET Platform, Second Edition Introduction
// 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. Part TwoCar - Thebuddha C# Programming Language = new Car("Buddha", 100, 20); Chapter // 3 -Speed C# Language Fundamentals up past the car's max speed to Chapter // 4 -trigger Object-Oriented Programming with C# the exception. Chapter try 5 - Exceptions and Object Lifetime Chapter { 6 - Interfaces and Collections for(int i = 0; i < 10; Chapter 7 - Callback Interfaces, Delegates, and i++) Events buddha.SpeedUp(10); Chapter 8 - Advanced C# Type Construction Techniques } - Programming with .NET Assemblies Part Three catch(Exception e)Assemblies Chapter 9 - Understanding .NET { Chapter 10 - Processes, AppDomains, Contexts, and Threads Console.WriteLine("\n*** Error! ***"); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Console.WriteLine("Method: {0}", e.TargetSite); Part Four - Leveraging the .NET Libraries Console.WriteLine("Message: {0}", e.Message); Chapter 12 - Object Serialization and the .NET Remoting Layer Console.WriteLine("Source: {0}", e.Source); Chapter 13 - Building a Better Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+) // The error has been handled, continue on with the flow of this app... Chapter 15 - Programming with Windows Forms Controls Console.WriteLine("\n***** Out of exception logic *****"); Chapter 16 - The System.IO Namespace return 0; Chapter 17 - Data Access with ADO.NET } Part One - Introducing C# and the .NET Platform
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter In essence, 19 - ASP.NET a try block Web is aApplications section of code that is on the lookout for any exception that may be
encountered during scope. If an exception is detected, the flow of program execution is sent to the Chapter 20 - XML Webits Services appropriate catch block. On the other hand, if the code within a try block does not trigger an exception, the Index catch block is skipped entirely, and all is right with the world. Figure 5-1 shows a test run of the handled List of Figures error. List of Tables
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Figure 5-1: Dealing with the error using structured exception handling
Chapter 3
- C# Language Fundamentals
Chapter Object-Oriented Programming with handled, C# As you 4can- see, once an exception has been the application is free to continue on from the point Chapter 5 Exceptions and Object Lifetime after the catch block. In some circumstances, a given exception may be critical enough to warrant the Chapter 6 - of Interfaces and Collections termination the application. However, in a good number of cases, the logic within the exception handler Chapter 7 Callback Interfaces, Delegates, and Events will ensure the application will be able to continue on its merry way (although it may be slightly less Chapter 8 -such Advanced Type Techniques functional, as theC# case ofConstruction not being able to connect to a remote data source). Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies The TargetSite Property
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter - Type Reflection, Late Binding, and Attribute-Based Programming As you 11 have just seen, the System.Exception.TargetSite property allows you to determine the name of the Part Four that - Leveraging .NET Libraries method threw thethe current exception.
Understand, however, that TargetSite does not simply return a
Chapter 12 - Object Serialization and the .NETSystem.Reflection.MethodBase Remoting Layer vanilla-flavored string, but a strongly typed class. This abstract type can be Chapter used to13 gather - Building numerous a Better details Window regarding (Introducing the offending Windowsmethod Forms) as well as the class that defines the
offending illustrate, assume(GDI+) the previous catch logic has been updated as follows: Chapter 14 method. - A BetterTo Painting Framework Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO catch(Exception e) Namespace Chapter { 17 - Data Access with ADO.NET Part FiveConsole.WriteLine("\n*** - Web Applications and XML Web Services Error!
***");
defining member: {0}", Chapter Console.WriteLine("Class 18 - ASP.NET Web Pages and Web Controls e.TargetSite.DeclaringType); Chapter 19 - ASP.NET Web Applications type: {0}", e.TargetSite.MemberType); Chapter Console.WriteLine("Member 20 - XML Web Services Console.WriteLine("Member name: {0}", e.TargetSite); Console.WriteLine("Message: {0}", e.Message); List of Figures Console.WriteLine("Source: {0}", e.Source); List of Tables } Index
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter Figure 4 - 5-2: Object-Oriented Obtaining detailed Programming error information with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
As you may be aware, the ability to discover information regarding the structure of a type is a form of RTTI - Callback Interfaces, Delegates, and Events (runtime type identification). The .NET base class library supplies an entire namespace devoted to the Chapter - Advanced C# Type Construction topic of8RTTI named System.Reflection (in Techniques fact, MethodBase is defined within System.Reflection). Chapter Part Three - Programming with .NET Assemblies 11 will examine the details of .NET reflection services. For the time being, simply understand that the Chapter 9 - Understanding .NET Assemblies System.Exception.TargetSite property allows you to discover a number of details about the method that Chapter 10 the - Processes, Contexts, and Threads triggered exceptionAppDomains, at hand. Chapter 7
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
The StackTrace Property
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 -toBuilding a Better Window In addition identifying the type and (Introducing member thatWindows threw a Forms) given exception via TargetSite, the Chapter 14 - A Better Painting Framework (GDI+)you to identify the series of calls that resulted in the System.Exception.StackTrace property allows Chapter 15 -To Programming with Windows Forms Controls exception. illustrate, assume you have once again updated your catch logic: Chapter 16 - The System.IO Namespace Chapter 17 - Data Access catch(Exception e)with ADO.NET Part { Five - Web Applications and XML Web Services
Chapter ... 18 - ASP.NET Web Pages and Web Controls Chapter Console.WriteLine("Stack: 19 - ASP.NET Web Applications {0}", e.StackTrace); Chapter 20 - XML Web Services } Index List of Figures
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 the StackTrace properties allowEdition programmers to gain an understanding of a given C# and .NET Platform, Second exception, this information is of little use to the end user. As you have already seen, the ISBN:1590590554 by Andrew Troelsen System.Exception.Message property can be used to obtain human-readable information that may be Apress © 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 comprehensive text starts with a brief overview of the or standard Win32 file that contains moremoves detailed information. C#help language and then quickly to key technical and architectural issues for .NET developers.
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 relevant update to the SpeedUp() method: Table of Contents C# and the .NET Platform, Second Edition
if(carIsDead) Introduction { One - Introducing C# and the .NET Platform Part 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 ex; Part Twothrow - The C# Programming Language } Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
Exceptions and Object Lifetime The catch -logic, of course, would print out this help link information as follows:
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
catch(Exception e) Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies ... Chapter 9 - Understanding .NET Assemblies Console.WriteLine("Help Link: {0}", e.HelpLink); Chapter 10 - Processes, AppDomains, Contexts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
SOURCE SimpleException projectWindows is included under the Chapter 5 subdirectory. Chapter 13 - Building aThe Better Window (Introducing Forms) CODE Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition CLR System-Level Exceptions (System.SystemException) by Andrew Troelsen
ISBN:1590590554
As mentioned, the .NET©base classpages) libraries already define a number of exception classes. For example, Apress 2003 (1200 the System namespace defines numerous general types of such This comprehensive text starts with exception a brief overview theas ArgumentOutOfRangeException, IndexOutOfRangeException, StackOverflowException, and so forth. C# language and then quickly moves to key technical and architectural issues for .NET developers. 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). Table of Contents
Exceptions thatPlatform, are thrown by methods C# and the .NET Second Edition in the base class libraries are (appropriately) called system exceptions. System exceptions generally (but sadly not always) derive directly from a base class named Introduction System.SystemException, which in turn derives Part One - Introducing C# and the .NET Platform
from System.Exception (which of course derives from
System.Object): Chapter 1 - The Philosophy of .NET Chapter 2
- Building C# Applications
Part public Two - The class C# Programming SystemException Language:
Exception, ISerializable Chapter 3 - C# Language Fundamentals { Chapter 4 - Object-Oriented Programming with C# SystemException(); Chapterpublic 5 - Exceptions and Object Lifetime public SystemException(string message); Chapter 6 - Interfaces and Collections public SystemException(string message, Exception innerException); Chapter 7 - Callback Interfaces, Delegates, and Events public string HelpLink { virtual get; virtual set; } Chapter 8 - Advanced C# Type Construction Techniques public Exception InnerException { get; } Part Three - Programming with .NET Assemblies public string Message { virtual get; } Chapter 9 - Understanding .NET Assemblies public string Source { virtual get; virtual set; } Chapter 10 - Processes, AppDomains, Contexts, and Threads public string StackTrace { virtual get; } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming public MethodBase TargetSite { get; } Part Four - Leveraging the .NET Libraries public virtual bool Equals(object obj); Chapter 12 - Object Serialization and the .NET Remoting Layer public virtual Exception GetBaseException(); Chapterpublic 13 - Building a Better Window (Introducing Windows Forms) virtual int GetHashCode(); Chapterpublic 14 - A Better Painting Framework (GDI+) virtual void Chapter 15 -GetObjectData(SerializationInfo Programming with Windows Forms Controls info, StreamingContext context); Chapterpublic 16 - TheType System.IO Namespace GetType(); Chapterpublic 17 - Data Access with ADO.NET virtual string ToString(); Part } Five - Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Given that System.SystemException type does not add any additional functionality beyond that of Chapter 20 -the XML Web Services
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 Figures 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. Index
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Figure 5-3: Identifying theLibraries exceptions
thrown from a given method
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
For those to Painting .NET from a Java mindset, Chapter 14 coming - A Better Framework (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 System.IO Namespace the operating system will trigger a "last chance exception." Chapter 15 - Programming with Windows Forms Controls Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Custom Application-Level Exceptions (System.ApplicationException) by Andrew Troelsen
ISBN:1590590554
Now that you understand the proposed Apress © 2003 (1200 pages)role of System.SystemException (to identify CLR exceptions), you may wonder if it isThis possible to build custom exceptions for use withinofyour comprehensive text starts with a brief overview the proprietary applications. The answer is a resounding "yes." In fact, the .NET base class library defines C# language and then quickly moves to key technical and another System.Exception derived architectural issues for .NET developers. type named (appropriately enough) System.ApplicationException: public class ApplicationException : Exception, ISerializable C# and the .NET Platform, Second Edition { Introduction public ApplicationException(); Part One - Introducing C# and the .NET Platform 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; } Part Two - The C# Programming Language public Exception InnerException { get; } Chapterpublic 3 - C# string Language Message Fundamentals { virtual get; } Chapterpublic 4 - Object-Oriented Programming with C#get; virtual set; } string Source { virtual Chapterpublic 5 - Exceptions Object Lifetime stringand StackTrace { virtual get; } Chapterpublic 6 - Interfaces MethodBase and Collections TargetSite { get; } virtual boolDelegates, Equals(object Chapterpublic 7 - Callback Interfaces, and Events obj); public virtual Exception GetBaseException(); Chapter 8 - Advanced C# Type Construction Techniques public virtualwith int.NET GetHashCode(); Part Three - Programming Assemblies public virtual void Chapter 9 - Understanding .NET Assemblies info, StreamingContext context); Chapter 10 -GetObjectData(SerializationInfo Processes, AppDomains, Contexts, and Threads public Type GetType(); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming public virtual string ToString(); Part Four - Leveraging the .NET Libraries } Chapter 12 - Object Serialization and the .NET Remoting Layer
Table of Contents
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Like SystemException, ApplicationException does not add any additional functionality beyond the inherited Chapter 15 Programming with Windows Forms Controls members of System.Exception. Again, the only real role of System.ApplicationException is to identify the Chapter 16 -source The System.IO Namespace underlying of the error. When you handle an exception deriving from System.ApplicationException, Chapter 17 Data Access with you can (ideally) assume theADO.NET exception was raised by the code base of the executing application, rather than Part Five.NET - Web Applications and XML Web Services by the base class libraries.
Chapter 18 - ASP.NET Web Pages and Web Controls
Figure 19 5-4-illustrates the relationship Chapter ASP.NET Web Applications between these key exception-centric base classes. Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Figure 5-4: Application and system exceptions
Part Strictly Three speaking, - Programming when you with create .NET Assemblies your own custom
.NET exception types, you are not required to derive
from System.ApplicationException. If you so choose, you are able to simply derive from the more generic Chapter 9 - Understanding .NET Assemblies System.Exception (andAppDomains, if you really wanted to,and nothing would stop you from deriving from Chapter 10 - Processes, Contexts, Threads System.SystemException . .Late . butBinding, don't doand so!Attribute-Based ). To understand the various possibilities, let's build a custom Chapter 11 - Type Reflection, Programming exception type. Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
Building Custom Exceptions, Take One
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Although could simplywith throw instances of System.Exception to signal a runtime error (as seen in the Chapter 15 you - Programming Windows Forms Controls previous it is sometimes advantageous to build a custom class that encapsulates the unique Chapter 16example), - The System.IO Namespace details 17 of your problem. For example, Chapter - Data Access with ADO.NET assume you wish to build a custom exception to represent the error of speeding up a Applications doomed automobile. Part Five - Web and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls
The first approach we will look at involves defining a new class derived directly from System.Exception (by
Chapter 19 - ASP.NET Web types Applications convention, all exception end with an "Exception" suffix). Like any class, you are free to include any Chapter 20 XML Web Services custom properties, methods, or fields that can be used from within the catch block of the calling logic. You Index are also free to override any virtual members defined by your parent class: List of Figures 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# and themsg .NET+= Platform, Second carName + " Edition has bought the farm..."; ISBN:1590590554 by Andrew Troelsen return msg; Apress © 2003 (1200 pages) } This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 the .NET Platform, Second Edition property in order to include the pet name of the car in the description. Throwing this error from within Introduction SpeedUp() is straightforward:
Table of Contents
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
// Throw the custom CarIsDeadException. - Building C# Applications public void SpeedUp(int delta) Part Two - The C# Programming Language { Chapter 3 - C# Language Fundamentals // If the car is dead, just say so... Chapter if(carIsDead) 4 - Object-Oriented Programming with C# Chapter { 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections // Throw 'car is dead' exception. Chapter 7 - Callback Interfaces, Delegates, and Events throw new CarIsDeadException(this.petName); Chapter } 8 - Advanced C# Type Construction Techniques Part Three - Programming withdead, .NET Assemblies else // Not speed up. Chapter { 9 ... - Understanding } .NET Assemblies } Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 2
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Catching the custom exception is just as easy:
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
try 14 - A Better Painting Framework (GDI+) Chapter {... } Chapter 15 - Programming with Windows Forms Controls catch(CarIsDeadException e) { Chapter 17 - Data Access with ADO.NET Console.WriteLine("Method: {0}", e.TargetSite); Part Five - Web Applications and XML Web Services Console.WriteLine("Message: {0}", e.Message); Chapter 18 - ASP.NET Web Pages and Web Controls } Chapter 16 - The System.IO Namespace
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index
List Figures So,ofnow that you understand the basic process of defining a custom exception, you may wonder if you are 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# and the .NET Platform, Second Edition : base(message){ } ISBN:1590590554 by Andrew Troelsen // Just in case the CarIsDeadException is generated by Apress © 2003 (1200 pages) // another exception, the previous exception can be passed in comprehensive text starts with a brief overview of the // as a This constructor parameter. C# language and then quickly moves message, to key technical and public CarIsDeadException(string Exception innerEx) architectural issues for .NET developers. : base(message, innerEx){ } } Table of Contents C# and the .NET Platform, Second Edition
Notice that this time you have not provided a private string to hold the pet name, and have not overridden the
Introduction Message property. Rather, you are simply passing all the relevant information to your base class. When you Part One - Introducing C# and the .NET Platform
wish to throw an exception of this type, you would send in all necessary information as a constructor
Chapter 1 -(the Theoutput Philosophy .NET argument wouldofbe identical): Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
public void SpeedUp(int delta) - C# Language Fundamentals { Chapter ... 4 - Object-Oriented Programming with C# Chapter if(carIsDead) 5 - Exceptions and Object Lifetime Chapter { 6 - Interfaces and Collections Chapter 7 - Callback Interfaces, Delegates, Events as ctor argument. // Pass pet name and and message Chapter 8 - Advanced Construction Techniques throw C# newType CarIsDeadException(this.petName + " has bought the farm!"); Part Three } - Programming with .NET Assemblies Chapter else 9 - Understanding // Not .NET dead, Assemblies speed up. } Chapter {... 10 - Processes, AppDomains, Contexts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter 3
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
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 Painting Framework (GDI+) classes follow this pattern. Many times, the role of a custom exception is not necessarily to provide additional Chapter 15 - Programming with Windows Forms Controls functionality beyond what is inherited from the base class, but to provide a strongly named type that clearly Chapter 16 - The System.IO Namespace identifies the nature of the error. Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Building Custom Exceptions, Take Three
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
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 Index class libraries), you are free to retrofit the type definition as follows: Chapter 20 - XML Web Services List of Figures 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# and theExceptions .NET Platform, Second Edition Handling Multiple by Andrew Troelsen
ISBN:1590590554
In its simplest form, a try©block haspages) a single corresponding catch block. In reality, you 23often run into a situation Apress 2003 (1200 where the code within a try block could For example, assume the car's This comprehensive texttrigger starts numerous with a briefpossible overviewexceptions. of the SpeedUp() method not only throws an exception when you attempt to speed up a doomed automobile, but throws C# language and then quickly moves to key technical and architectural issues .NET developers. a system-level exception if you sendfor in an invalid parameter (which for the sake of argument is any number less than zero): Table of Contents
// Test for bad parameter. public void SpeedUp(int delta) Introduction { Part One - Introducing C# and the .NET Platform // 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!"); Part Twoif(carIsDead) - The C# Programming Language Chapter { 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with application C# // Throw 'Car is dead' exception. Chapter 5 - Exceptions and Object Lifetime throw new CarIsDeadException(this.petName + " has bought the farm!"); Chapter } 6 - Interfaces and Collections Chapter ... 7 - Callback Interfaces, Delegates, and Events } Chapter 8 - Advanced C# Type Construction Techniques C# and the .NET Platform, Second Edition
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
The calling logic would look like this:
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
// Here, we are on the and lookout multiple Chapter 12 - Object Serialization the .NETfor Remoting Layer exceptions. try {
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
for(int i = 0; i < 10; i++) buddha.SpeedUp(10);
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
} catch(CarIsDeadException e) Part Five - Web Applications and XML Web Services { Chapter Console.WriteLine("Method: 18 - ASP.NET Web Pages and Web Controls {0}", e.TargetSite); Chapter Console.WriteLine("Message: 19 - ASP.NET Web Applications {0}", e.Message); Chapter 20 - XML Web Services } Index catch(ArgumentOutOfRangeException e) List { of Figures List of Tables Console.WriteLine("Method: {0}", e.TargetSite); Console.WriteLine("Message: {0}", e.Message); } Chapter 17 - Data Access with ADO.NET
When you are constructing multiple catch blocks for a single try block, you must be aware that when an exception 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# and the .NET e) Platform, Second Edition catch(CarIsDeadException ISBN:1590590554 by Andrew Troelsen {...} Apress © 2003 (1200 pages) catch(ArgumentOutOfRangeException e) This comprehensive text starts with a brief overview of the {...} C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 Table of Contents CarIsDeadException and ArgumentOutOfRangeException types. Therefore, the final two catch blocks are C# and the .NET Platform, Second Edition unreachable! Introduction
Part Introducing C# and .NET TheOne rule- of thumb to keep in the mind is toPlatform make sure
your catch blocks are structured such that the very first catch is
Chapter the most 1 specific - The Philosophy exceptionof(i.e., .NET the most derived type in a given exception inheritance chain) while the final catch
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 Part Two - The C# Programming Language
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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
// Better. Chapter 6 - Interfaces and Collections try {
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
for(int i = 0; i < 10; i++) buddha.SpeedUp(10);
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
} catch(CarIsDeadException e) Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming {...} Part Four - Leveraging the .NET Libraries catch(ArgumentOutOfRangeException e) Chapter {...}12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window Windows Forms) catch(Exception e) // This(Introducing will handle any other exception. Chapter {...}14 - A Better Painting Framework (GDI+) Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Again, notice howAccess this catch explicitly specifies the exception type it is willing to catch. Given that you Chapter 17 - Data with block ADO.NET construct your Applications final catch logic to handle System.Exception, Part Five - Web and XML Web Services
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 derive Chapter - ASP.NET andfrom WebSystem.Exception Controls from this class).Web Applications Chapter 19base - ASP.NET Chapter 20 - XML Web Services
Generic Catch Statements
Index
List of Figures
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# and the .NET Platform, Second Edition make use of the "throw" keyword within a catch block. This passes the exception up the chain of calling logic: try {
by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and // Speed architectural up car logic... issues for .NET developers.
} catch(CarIsDeadException e) { of Contents Table // .NET Do any partial of this error and pass the buck. C# and the Platform, Second processing Edition // Here, we are rethrowing the CarIsDeadException type. Introduction // HOWEVER, you are also free to throw a different exception if need be. Part One - Introducing C# and the .NET Platform throw e; Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition The Finally C# Block by Andrew Troelsen
ISBN:1590590554
Your try/catch logic may©also augmented with an optional finally block. The idea behind a finally block Apress 2003 be (1200 pages) is to ensure that aThis block of code will always execute, if an exception comprehensive text starts with a even brief overview of the (of any type) interferes with the normal flow of execution. For example, assume you wish to always C# language and then quickly moves to key technicalpower and down the car's radio before architectural issues for .NET developers. exiting Main(), regardless of any possible exception: // Provide a manner to clean up. public static int Main(string[] args) C# and the .NET Platform, Second Edition { Introduction ... Part One - Introducing C# and the .NET Platform // Try to rev the engine hard! Chapter try 1 - The Philosophy of .NET Chapter { 2 - Building C# Applications Part Two - The C# Language // Programming Speed up car logic ... Chapter } 3 - C# Language Fundamentals Chapter catch(CarIsDeadException 4 - Object-Oriented Programming with e) C# Chapter {...} 5 - Exceptions and Object Lifetime Chapter catch(ArgumentOutOfRangeException 6 - Interfaces and Collections e) Chapter {...} 7 - Callback Interfaces, Delegates, and Events Chapter finally 8 - Advanced C# Type Construction Techniques { - Programming with .NET Assemblies Part Three // This will always occur. Exception or not. Chapter 9 - Understanding .NET Assemblies buddha.CrankTunes(false); Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter } 11 - Type Reflection, Late Binding, and Attribute-Based Programming 0; the .NET Libraries Part Fourreturn - Leveraging } Chapter 12 - Object Serialization and the .NET Remoting Layer
Table of Contents
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 include - A Better Painting Framework (GDI+) If you did a finally block, the radio would not be turned off if an exception is caught (which may or Chapter 15 Programming with Windows Forms may not be problematic). In a more real-worldControls scenario, if you need to clean up any allocated memory, Chapter 16 - a The System.IO close down file, or detachNamespace from a data source (or whatever), you must add that code within a finally block Chapter 17 Data Access with to ensure proper cleanup. ToADO.NET this end, it is important to realize that the code contained within a finally Part Five - Web Applications XML Web Services block executes all the time,and even if the logic within
your try clause does not generate an exception. This is
Chapter 18 -helpful ASP.NET Pages and Web Controls especially if aWeb given exception requires the termination of the current application. Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The Last Chance Exception by Andrew Troelsen
ISBN:1590590554
Unlike ad hoc error handling Apress © 2003techniques, (1200 pages) .NET exceptions cannot be ignored. One obvious question that may be on your mind is what would if you an of exception thrown your direction. For This comprehensive happen text starts withdo a not briefhandle overview the example, assumeC# that the logic in Main() that increases the speed of the Car object has no error handling language and then quickly moves to key technical and architectural issues for .NET developers. logic. The result of ignoring the generated error would be highly obstructive to the end user of your application, as the following "last chance exception" dialog box is displayed (Figure 5-5). Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - 5-5: Building Better Window (Introducing Windows Forms) Figure Youahave just entered no-man's land. Chapter 14 - A Better Painting Framework (GDI+)
Now that see the inherent goodness of catching an exception programmatically, you may wonder what Chapter 15 you - Programming with Windows Forms Controls to do with exception once you have trapped it. Again, this is a design issue based on your current Chapter 16 -the The System.IO Namespace project.17 In -your Carwith example, you simply dumped your custom message and call stack to the Chapter Datatrivial Access ADO.NET console. more realistic scenario freeing Part Five - A Web Applications and XMLmay Webinclude Services
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 Controls anomalies. How you do so is largely up to you. Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML WebThe Services SOURCE CustomException project is included under the Chapter 5 subdirectory. IndexCODE List of Figures List of Tables
C#Identifying and the .NET Platform, Second Edition Dynamically Applicationand System-Level Exceptions by Andrew Troelsen
ISBN:1590590554
In the previous example, to handle each exception by its specific class name. As an Apress ©you 2003 saw (1200how pages) illustrative alternative, assume you wish generalize youroverview catch blocks in such a way that all applicationThis comprehensive textto starts with a brief of the level exceptions are handled apart from possible system-level exceptions: C# language and then quickly moves to key technical and architectural issues for .NET developers.
// This time, make things a bit more general. try Table of Contents { C# and the .NET Platform, Second Edition for(int i = 0; i < 10; i++) Introduction buddha.SpeedUp(10); Part One - Introducing C# and the .NET Platform } Chapter 1
- The Philosophy of .NET
Chapter 2 type - Building C# Applications // Any derived from System.ApplicationException Part - The C# Programming Language // Two handled here.
Chapter 3 - C# Language Fundamentals catch(ApplicationException e) Chapter 4 {
- Object-Oriented Programming with C#
Chapter Console.WriteLine("Caught 5 - Exceptions and Object Lifetime an app exception!"); Chapter Console.WriteLine("Method: 6 - Interfaces and Collections {0}", e.TargetSite); Chapter Console.WriteLine("Message: 7 - Callback Interfaces, Delegates, and {0}", Events e.Message);
} Chapter 8
- Advanced C# Type Construction Techniques
// Three Any -type derived from Part Programming with .NET System.SystemException Assemblies // handled here. Chapter 9 - Understanding .NET Assemblies catch(SystemException e) Contexts, and Threads Chapter 10 - Processes, AppDomains, { Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part FourConsole.WriteLine("Caught - Leveraging the .NET Libraries
a system-level exception"); Console.WriteLine("Method: {0}", e.TargetSite); Chapter 12 - Object Serialization and the .NET Remoting Layer Console.WriteLine("Message: {0}", e.Message); Chapter 13 - Building a Better Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls Chapter 16 the - The System.IO Namespace Although ability to discover at runtime the underlying source of an exception might sound intriguing, Chapter 17 Data Access with ADO.NET you really gain nothing by doing so. Sadly, if you spend time digging through the .NET base class libraries, Part - Web Applications XML Web Services youFive will find that some baseand class library methods
that should ideally throw a type derived from
Chapter 18 - ASP.NET Web Pages Controls System.SystemException are in and factWeb derived from System.ApplicationException or even the more generic Chapter System.Exception! 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
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 Figures 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. Index
and the .NET Platform, Second Edition DebuggingC# System Exceptions Using VS .NET by Andrew Troelsen
ISBN:1590590554
Visual Studio .NET provides number of helpful tools that you can use to debug the exceptions that may Apress © 2003a (1200 pages) be thrown by a given member during the development cycle. By default, This comprehensive text starts with a brief overview 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 moves to key technical and architectural issues for .NET developers.
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 Table printed of Contents to the console (via your catch block), which disappears so quickly you cannot see the error. Of course, you arePlatform, free to set any number C# and the .NET Second Edition of manual breakpoints by hand; however, there is a better way. Introduction
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). Part One - Introducing C# and the .NET Platform
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Figure 5-6: Preparing to enable VS .NET exception handling
Index
List of Figures List Tables As of you 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Figure 5-7: The CLRwith exception set Part Three - Programming .NET Assemblies Chapter 9
- Understanding .NET Assemblies
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 Attribute-Based Programming check the "Break into the debugger" option (Figure 5-8). Chapter 10 - Processes, AppDomains, Contexts, and Threads Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition CLR Exceptions node and click the Add button. At this point, type in the fully qualified name of your custom ISBN:1590590554 by Andrew exception type (Figure 5-9). Troelsen Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Edition application exceptions via VS .NET Figure 5-9:Platform, EnablingSecond your custom Introduction Part One - Introducing C# and the .NET Platform
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
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five Figure - Web 5-10: Applications Handling and yourXML custom Web application Services
exceptions via VS .NET
Chapter 18 - ASP.NET Web Pages and Web Controls
With this, are now able to debug your application, and automatically step into the debugger when a Chapter 19 you - ASP.NET Web Applications given exception is raised.
Chapter 20 - XML Web Services Index 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 Figuresto 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# andObject the .NET Platform, Second Edition Understanding Lifetime by Andrew Troelsen
ISBN:1590590554
To close this chapter, we will switch topics completely and address garbage collection. Recall that unlike Apress © 2003 (1200 pages) C++, C# programmers (and .NET programmers in general) never directly This comprehensive text starts with a brief overview 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 moves to key technical and architectural issues .NET developers. onto a region of memory termed thefor managed heap, where they will be automatically deallocated by the runtime at "some time in the future." Table As you of Contents are building your C# applications, you are correct to assume that the managed heap will take care
of and itselfthe without your direct intervention. C# .NET Platform, Second Edition In fact, the golden rule of .NET memory management is simple. Introduction Part One - Introducing C# and the .NET Platform
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 Part Once Two "new-ed," - The C# the Programming CLR removes Language the 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 - Object-Oriented Programming with C#it is unreachable by the current application. To illustrate, assume5 you have a new application that makes use of the Car type as follows: Chapter - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
// Create a local Car object. Chapter 7 - Callback Interfaces, Delegates, and Events public int args) Chapter 8 static - Advanced C# Main(string[] Type Construction Techniques { Three - Programming with .NET Assemblies Part an object onto the managed heap. Chapter // 9 -Place Understanding .NET Assemblies c = new AppDomains, Car("Viper", 200, Chapter Car 10 - Processes, Contexts, and100); Threads Chapter ... 11 - Type Reflection, Late Binding, and Attribute-Based Programming
} Four // - If c is the only reference Part Leveraging the .NET Libraries
to the Car object, // it may be destroyed when Main() exits. Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter A Better Painting (c) Framework Notice 14 that- the Car variable has been(GDI+) created within the scope of Main(). Thus, once the application Chapter 15 Programming with Windows Controls shuts down, this reference is no longer Forms valid, and therefore is a candidate for garbage collection. Chapter 16 - The System.IO Understand, however, that Namespace you cannot guarantee that this object will be reclaimed from memory when Chapter 17 Data Access with ADO.NET Main() has completed. All you can assume at this point in the game is that when the CLR performs the Part - Webcollection, Applications XML Web nextFive garbage "c"and is ready to beServices destroyed.
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The CIL of "new" by Andrew Troelsen
ISBN:1590590554
Under the hood, when C# (1200 compiler Apressthe © 2003 pages)encounters the "new" keyword, it will emit a CIL "newobj" instruction to the This codecomprehensive module. Thus,text if you were to aopen the previous starts with briefup overview of the assembly using ildasm.exe, you would find the following CIL: C# language and then quickly moves to key technical and architectural issues for .NET developers.
.method public hidebysig static int32 Main(string[] args) cil managed { Table of Contents .entrypoint C# and the .NET Platform, Second Edition // Code size 24 (0x18) Introduction .maxstack 4 Part One - Introducing C# and the .NET Platform .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" PartIL_0005: Two - The C# ldc.i4 Programming Language 0xc8 Chapter 3 - C# Language Fundamentals IL_000a: ldc.i4.s 100 Chapter 4 - Object-Oriented Programming with GC.Car::.ctor C# IL_000c: newobj instance void Chapter(string, 5 - Exceptions and Object Lifetime int32, int32) Chapter IL_0011: 6 - Interfaces stloc.0 and Collections IL_0012: ldc.i4.0 Chapter 7 - Callback Interfaces, Delegates, and Events IL_0013: stloc.1 Chapter 8 - Advanced C# Type Construction Techniques IL_0014: br.s with .NET IL_0016 Part Three - Programming Assemblies IL_0016: ldloc.1 Chapter 9 - Understanding .NET Assemblies IL_0017: ret AppDomains, Contexts, and Threads Chapter 10 - Processes, } // end of Chapter 11 - Type method Reflection,GCApp::Main Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
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 Painting (GDI+)of memory accessed by the CLR. The .NET garbage managed is more than Framework just a raw chunk Chapter 15 Programming with Windows Forms Controls collector is quite a tidy housekeeper, given that it will compact empty blocks of memory (when necessary) Chapter 16 The System.IO Namespace for purposes of optimization. To aid in this endeavor, the managed heap maintains a pointer (commonly Chapter Data with ADO.NET referred17to- as theAccess new object pointer) that identifies exactly where the next object will be placed on the Part Five Web Applications and XML Servicesinstruction informs the CLR to perform the following heap itself. These things being said,Web the newobj Chapter 18 ASP.NET Web Pages and Web Controls sequence of events: Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 19 - ASP.NET Web Applications
Calculate theWeb total amount of memory required for the object about to be allocated. As you would Chapter 20 - XML Services
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 Figures is also taken into account (i.e., the "is-a" relationship). Index
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents
Figure 5-11: Reference types are allocated on the managed heap.
C# and the .NET Platform, Second Edition Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
the .NET Platform, Second Edition The BasicsC# ofand Garbage Collection by Andrew Troelsen
ISBN:1590590554
As you are busy creating managed heap may eventually become full. When the newobj Apress © objects, 2003 (1200the pages) instruction is being processed, if the CLR determines that the managed heap does not have sufficient This comprehensive text starts with a brief overview 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 moves to key technical and architectural issues for .NET developers. memory. Thus, the next rule of garbage collection is quite simple. Rule: If the managed heap does not have sufficient memory to allocate a new object, a garbage Table of Contents collection occur. Second Edition C# and the .NETwill Platform, Introduction
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. Part One - Introducing C# and the .NET Platform
Chapter 2
- Building C# Applications
Part Simply Twoput, - The a C# rootProgramming is a storage location Language 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 - Object-Oriented Programming with C# a root can fall into any of the following categories: Chapter 5
- Exceptions and Object Lifetime
References to global objects (while not allowed in C#, raw CIL does permit allocation of global - Interfaces and Collections objects)
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# objects Type Construction Techniques References to static Part Three - Programming with .NET Assemblies
References to local objects within a given method Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
References to object parameters passed into a method
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four Leveraging Librariesa local Any -CPU registerthe that.NET references
object
Chapter 12 - Object Serialization and the .NET Remoting Layer
When a13garbage collection runtime will investigate all objects on the managed heap to Chapter - Building a Betteroccurs, Windowthe (Introducing Windows Forms) determine is still in use (aka "rooted")(GDI+) in the application. To do so, the CLR will build an object graph, Chapter 14 -if Ait Better Painting Framework which represents each object the heap thatControls is still reachable. We will explore object graphs in more Chapter 15 - Programming with on Windows Forms
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 with ADO.NET collection through the construction of an object graph that documents all codependencies for the current Part Five - Web Applications and XML Web Services 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 Controls thus avoiding the nasty circular reference count found in classic COM programming. Chapter 16 - The System.IO Namespace
Chapter 19 - ASP.NET Web Applications
Chapter 20 -once XML the Webgarbage Servicescollector determines that a given root is no longer used by a given Now then, Index application, the object is marked for termination. When the entire heap has been searched for "severed List roots," of Figures the 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).
and the .NET Platform, Second Edition Finalizing aC#Type by Andrew Troelsen
ISBN:1590590554
As you might have gathered previous discussion, the .NET garbage collection scheme is rather Apress © 2003from (1200the pages) nondeterministic This in nature. In other words, you are unable to exactly when an object comprehensive text starts withtypically a brief overview of determine the will be deallocated from memory. Although this approach to memory management can simplify your C# language and then quickly moves to key technical and architectural forleft .NET developers. coding efforts at some levels,issues 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 Table of Contents invocation and COM interoperability), you will most likely wish to ensure that this resource is released in a C# and the .NET rather Platform, Second timely manner than at theEdition whim of the .NET garbage collector. Introduction
To account for such situations, choice you Part One - Introducing C# and theone .NET Platform
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 required to do so is if your Part Two you - The C#be Programming Language
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 - Object-Oriented Programming with C# implement a custom Finalize() method at all. Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - Interfaces Nevertheless, assumeand youCollections have a type that has acquired various unmanaged resources and wish to Chapter 7 Callback Interfaces, Delegates, and Events to ensure proper cleanup of the internal unmanaged support a custom version of System.Object.Finalize() Chapter 8 - While Advanced C#allType Techniques resources. this is wellConstruction and good, the odd thing is that the C# language does not allow you to Part Three - Programming with .NET Assemblies directly override the Finalize() method using standard
Chapter 9
C# syntax:
- Understanding .NET Assemblies
Chapter 10 class - Processes, AppDomains, Contexts, and Threads public FinalizedCar Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming { Part Four// - Leveraging .NETerror! Libraries Compile the time
Chapter protected 12 - Object Serialization the .NET Remoting Layer overrideand void Finalize(){ } Chapter 13 - Building a Better Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Rather,16 when you wish to configure your custom C# class types to override the Finalize() method, you Chapter - The System.IO Namespace make use of the following (C++-like) destructor syntax to achieve the same effect:
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
// This overrides Chapter 18 -Car ASP.NET Web PagesSystem.Object.Finalize(). and Web Controls class19FinalizedCar Chapter - ASP.NET Web Applications { Chapter 20 - XML Web Services Index
~FinalizedCar() {Console.WriteLine("=> Finalizing car..."); }
List of Figures
}
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# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
.method family hidebysig virtual instance void Apress © 2003 (1200 pages) Finalize() cil managed This comprehensive text starts with a brief overview of the { C# language and then quickly moves to key technical and // Code size (0x14) architectural 20 issues for .NET developers. .maxstack 1 .try { Table of Contents ldstrSecond Edition "=> Finalizing car..." C# andIL_0000: the .NET Platform, IL_0005: call void [mscorlib]System.Console::WriteLine(string) Introduction IL_000a: leave.s IL_0013 Part One - Introducing C# and the .NET Platform } // .try Chapter 1 -end The Philosophy of .NET .finally Chapter 2 - Building C# Applications Part{Two - The C# Programming Language IL_000c: ldarg.0 Chapter 3 - C# Language Fundamentals IL_000d: call instance void [mscorlib]System.Object::Finalize() Chapter 4 - Object-Oriented Programming with C# IL_0012: endfinally Chapter 5 - Exceptions and Object Lifetime } // end handler Chapter 6 - Interfaces and Collections IL_0013: ret Chapter 7 - Callback Interfaces, Delegates, and Events } Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
(Indirectly) Invoking System.Object.Finalize()
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer run for lengthy periods of time (such as a background service), garbage collections may occur few and far Chapter 13over - Building a Better Window (Introducing Windows Forms) between the course of the application's lifetime. Part Four - Leveraging the .NET Libraries
Chapter 14 - A Better Painting Framework (GDI+)
It is important to note thatwith finalization will automatically Chapter 15 - Programming Windows Forms Controls take place when an application domain is unloaded by the CLR. Application domains (or simply AppDomains) will be examined in greater detail later in this Chapter 16 - The System.IO Namespace text. For time Access being, with simply assume that an AppDomain is the application itself. Thus, you can rest Chapter 17the - Data ADO.NET assured finalizable object will Web haveServices its cleanup Part Five -that WebaApplications and XML
logic triggered upon application shutdown. This
brings us the next rule garbage collection. Chapter 18 to - ASP.NET Web of Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 -When XML Web Services Rule: an AppDomain is unloaded, the Finalize() method is invoked for all finalizable objects. Index
To of illustrate, List Figures 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# and the .NET Platform, Second Edition
}
by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
The output of thisThis program can be seen Figure 5-12. Notice that the finalization message is comprehensive text in starts with a brief overview of the C# language and then quickly moves toexits. key technical anda proper finalizer would free up automatically printed to the console once the program Of course, architectural issues for developers. some set of unmanaged resources, but.NET I think the point has been made. Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Figure 5-12: Finalizers are called automatically upon application shutdown.
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The Finalization Process by Andrew Troelsen
ISBN:1590590554
Given that finalization is ©guaranteed to take place when your application exits, you may be tempted to Apress 2003 (1200 pages) support C#-style This destructors on all of yourstarts types. Buta don't. First of all, always remember that the role of a comprehensive text with brief overview 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 moves to key technical and issues for .NET developers. type that does notarchitectural make use of unmanaged entities, finalization is of little use. However, there is a more practical reason to avoid supporting a finalize method: Finalization takes time. Table When of you Contents place an object onto the managed heap using the new operator, the runtime automatically
determines if your objectSecond supports a custom Finalize() method. If so, the object is marked as finalizable, C# and the .NET Platform, Edition and a pointer to this object is stored on an internal queue named (of course) the finalization queue. Simply Introduction put,One the -finalization queue is athe table maintained Part Introducing C# and .NET Platform
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 - Object-Oriented Programming with C# reachable"). At this point, a separate thread is spawned to invoke the Finalize() method for each object on Chapter 5 - Exceptions Lifetimecollection. the freachable table at and the Object next garbage Part Two - The C# Programming Language
Chapter 6
- Interfaces and Collections The bottom line is that when you build a custom type that overrides the System.Object.Finalize() method, Chapter 7 - Callback Interfaces, Delegates, and Events
the .NET will ensure this member is called once your object is removed from the managed Chapter 8 runtime - Advanced C# Typethat Construction Techniques heap. However, this comes at.NET a cost in terms of Part Three - Programming with Assemblies Chapter 9
application performance.
- Understanding .NET Assemblies
SOURCE CODE
The SimpleFinalize project is included under the Chapter 5 subdirectory.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
andHoc the .NET Platform, Second Edition Building anC#Ad Destruction Method by Andrew Troelsen
ISBN:1590590554
As you have seen, the process of finalizing an object is quite time consuming. Ideally, you should design Apress © 2003 (1200 pages) your objects in such a way so they do not need to bea marked as finalizable This comprehensive text starts with brief overview of the in the first place. However, when a type manipulates unmanaged resources, you do need to ensure C# language and then quickly moves to key technical and they are released in a timely and architectural issues .NET developers. predictable manner. While you couldforsupport a C# destructor (and incur the overhead of being finalized), there are better ways. Table Oneof alternative Contentsis to define a custom ad hoc method that you can assume all objects in your system
implement. Let's call thisSecond methodEdition Dispose(). The assumption is that when the object user is finished using C# and the .NET Platform, your type, it manually calls Dispose() before allowing the object reference to drop out of scope. In this way, Introduction yourOne objects can perform anythe amount of cleanup necessary of Part - Introducing C# and .NET Platform
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 Part Two - The C# Programming Language
// Equipping our class with an ad hoc destruction method. Chapter 3 - C# Language Fundamentals public Chapter 4 Car - Object-Oriented Programming with C# { Chapter 5
- Exceptions and Object Lifetime
... 6 Chapter
- Interfaces and Collections isInterfaces, a custom methodand weEvents expect the object user to call manually. Chapter // 7 -This Callback Delegates,
public void Dispose() - Advanced C# Type Construction Techniques { /* Clean up your internal unmanaged resources. */} Part Three - Programming with .NET Assemblies } Chapter 8 Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 -the Type Reflection, Binding, and Attribute-Based Programming Of course, name of this Late method is completely up to you. While Dispose() is a very common name, if Part - Leveraging thethat .NETmanipulates Libraries youFour are building a class
a physical file, you may opt to call this member Close().
Chapter 12 any - Object Serialization and the .NET Remoting Layer However, name will do (ShutDown(), Kill(), DestroyMeNow(), and so forth). Chapter 13 - Building a Better Window (Introducing Windows Forms)
Note that unmanaged resources Chapter 14 To - Aensure Better Painting Framework (GDI+) are always cleaned up appropriately, the implementation a Dispose() method shouldForms be safely callable multiple times without throwing an exception. Chapter 15 of - Programming with Windows Controls Chapter 16 - The System.IO Namespace
The IDisposable Interface
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
In order18to-provide symmetry among all objects Chapter ASP.NET Web Pages and Web Controlsthat 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 Applications Dispose(): Chapter 20 - XML Web Services Index
public interface IDisposable List of Figures { 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# and the .NET Platform, Second Edition public void Dispose() ISBN:1590590554 by Andrew Troelsen { Apress © 2003 (1200 pages) // Clean up your internal unmanaged resources. This comprehensive text starts with a brief overview of the } }
C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 the .NET Platform, Second Edition calling logic is straightforward:
Table of Contents Introduction
Part One - Introducing C# and the .NET Platform
namespace DisposeMe - The Philosophy of .NET { Chapter 2 - Building C# Applications public class App Part Two - The C# Programming Language { Chapter 3 - C# Language Fundamentals public static int Main(string[] args) Chapter 4 - Object-Oriented Programming with C# { Chapter 5 - Exceptions and Object Lifetime Car c1 = new Car("Car one", 40, 10); Chapter 6 - Interfacesc1.Dispose(); and Collections Chapter 7 - Callback Interfaces, Delegates, and Events return 0; Chapter 8 - Advanced C# is Typestill Construction Techniques } // C1 on the heap and may be collected at this point. Part Three } - Programming with .NET Assemblies Chapter } 9 - Understanding .NET Assemblies Chapter 1
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
ThisFour example exposes yet.NET another rule Part - Leveraging the Libraries
of working with garbage collected types.
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 -Always Building a Better Window (Introducing Windows Forms) Rule: call Dispose() for any object you manually allocate to the heap. The assumption you Chapter should 14 - make A Better is that Painting if theFramework class designer (GDI+) chose to support the Dispose() method (or a named
alternative such as Close()), the type has Controls some cleanup to perform. Chapter 15 - Programming with Windows Forms Chapter 16 - The System.IO Namespace
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 with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Reusing the C# "using" Keyword
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
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 Figures runtime exception: Index
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# and the .NET Platform, Second Edition thrilled by the prospects of wrapping each and every type within a try/catch/finally block just to ensure the by Andrew Troelsen type's Dispose() method is called. To achieve the same result ISBN:1590590554 in a much less obtrusive manner, C# Apress © 2003 (1200 supports a special bit of syntax thatpages) looks like this: This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and public void SomeMethod() architectural issues for .NET developers.
{ using(Car c = new Car()) { Table of Contents // Use theSecond car. Edition C# and the .NET Platform, // Dispose() is called automatically when the Introduction // using block Part One - Introducing C# and theexits. .NET Platform Chapter}1 - The Philosophy of .NET } Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Unfortunately, the "using" keyword now has a double meaning (specifying namespaces and triggering a Object-Oriented Programming with C# Dispose() -method). Nevertheless, when you are working with .NET types that support the IDisposable Chapter 5 Exceptions and Object Lifetime interface, this syntactical construct will ensure that the object "being used" will automatically have its Chapter 6 Interfaces 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 Interfaces, Events does not IDisposableDelegates, within theand using declaration, you are issued a compile time error. Chapter 4
Chapter 8
- Advanced C# Type Construction Techniques
SOURCE The with DisposableCar project Part Three - Programming .NET Assemblies
is included under the Chapter 5 subdirectory.
CODE Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Garbage Collection Optimizations by Andrew Troelsen
ISBN:1590590554
Now that you have seen©two Apress 2003approaches (1200 pages) that may be used to ensure the proper cleanup of your custom types, let's dig a bit deeper into the functionality of the .NEToverview garbageofcollector and check out the topic of This comprehensive text starts with a brief the objectgenerations. C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 Table time,ofespecially Contentsin larger (i.e., real-world) applications. C# and the .NET Platform, 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 Part One - Introducing C# and the .NET Platform 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 Part Two - The C# Programming Language of the following generations (as of .NET version 1.1): Introduction
Chapter 3
- C# Language Fundamentals
Chapter 4 - Object-Oriented with C# Generation 0: IdentifiesProgramming a newly allocated object that has never been marked for collection. Chapter 5 - Exceptions and Object Lifetime
Generation 1: Identifies an object that has survived a garbage collection sweep (i.e., it was marked for Chapter 6 - Interfaces and Collections collection, but was not removed due to theEvents fact that the heap had enough free space). Chapter 7 - Callback Interfaces, Delegates, and Chapter 8
- Advanced C# Type Construction Techniques Generation 2: Identifies an object that has survived more than one sweep of the garbage collector.
Part Three - Programming with .NET Assemblies
Chapter 9 -a Understanding .NET Assemblies Now, when collection occurs, the GC marks and sweeps all generation 0 objects first. If this results in the Chapter required 10amount - Processes, of memory, AppDomains, the remaining Contexts, objects and Threads are promoted to the next available generation. If all
generation objects have been from the heap, but Programming more memory is still necessary, generation 1 Chapter 11 - 0Type Reflection, Late removed Binding, and Attribute-Based objects marked and followed Part Fourare - Leveraging the swept, .NET Libraries
(if necessary) by generation 2 objects. In this way, the newer
objects12 (i.e., local variables) areand removed quickly whileLayer an older object (i.e., the object defining the Main() Chapter - Object Serialization the .NET Remoting method) be inWindow use. In a nutshell, the GC is able to quickly free heap space using the Chapter 13is- assumed Building ato Better (Introducing Windows Forms) generation a baseline. Chapter 14 - as A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and Type the .NET Platform, Second Edition The System.GC by Andrew Troelsen
ISBN:1590590554
Like everything inApress the .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 you toofinteract with the garbage collector comprehensive text startsThis withtype a brief overview 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 moves to key technical and architectural issues for .NET developers.
Table 5-2: Select Members of the System.GC Type System.GC Member Table of Contents
Meaning in Life
C# and the .NET Platform, Second Edition
Collect()
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 - Introducing C# and the .NET Platform sweep .
Introduction Part One
Chapter 1
- The Philosophy of .NET GetGeneration() Returns the generation to which an object currently belongs. Chapter 2 - Building C# Applications Part Two - The C# Programming Language
MaxGeneration
Chapter 3
This property returns the maximum of generations supported on the target system.
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# ReRegisterForFinalize() SetsLifetime a flag indicating that a suppressed object should be reregistered Chapter 5 - Exceptions and Object Chapter 6
as finalizable. This (of course) assumes the object was marked as - Interfaces and Collections
Chapter 7
nonfinalizable using SuppressFinalize(). - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# TypeSets Construction Techniques SuppressFinalize() a flag indicating that a given object should not have its Finalize() Part Three - Programming with method .NET Assemblies called.
Chapter 9
- Understanding .NET Assemblies
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 Attribute-Based Programming destroyed. This method takes a Boolean parameter that is used to Part Four - Leveraging the .NET Libraries specify if a garbage collection should occur during the method Chapter 12 - Object Serialization and the .NET Remoting Layer invocation. Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Building Finalizable and Disposable Types
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with 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:
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
// Memory clean up. public class Car : IDisposable Index { List of Figures ... 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 Services
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# and the .NET Platform, Second Edition
ISBN:1590590554 by Andrew Troelsen To illustrate the interplay between explicit and implicit object deallocation, assume the following updated Apress © 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 logic due theoverview call to GC.SuppressFinalize(): comprehensive texttriggered starts with a to brief of the
C# language and then quickly moves to key technical and architectural issues for .NET developers.
// Interacting with the GC. public class GCApp { of Contents Table public static int Main(string[] args) C# and the .NET Platform, Second Edition { Introduction // Add these cars to the managed heap. Part One - Introducing C# and the .NET Platform 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); Part Two - The C# Programming Language c3 = new Car("Car three", 200, 100); Chapter 3 - C# Language Fundamentals c4 = new Car("Car four", 140, 80); Chapter 4
- Object-Oriented Programming with C#
Chapter 5 Chapter 6
- Exceptions and Object Lifetime some objects. // Manually dispose - Interfaces and Collections c1.Dispose();
Chapter 7
- Callback Interfaces, Delegates, and Events c3.Dispose();
Chapter 8
- Advanced returnC#0;Type Construction Techniques
Part Three } - Programming with .NET Assemblies
Chapter } 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
TheFour output can be seen Figure 5-13. Part - Leveraging the in .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Figure 5-13: The interplay of finalization and disposal
Index
List ofSOURCE Figures
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# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
© 2003 (1200 pages) Note that you callApress GC.WaitForPendingFinalizers() after forcing a garbage collection cycle. In this way, you can rest assured This that comprehensive all finalizable objects have hada a chance to perform text starts with brief overview of the any necessary cleanup before C#Do language andthis then quickly moves to key technical and during the process (which is a continuing forward. note that call will suspend the current thread architectural issuesinvoke for .NET developers. good thing, as it ensures you don't methods on a type that is currently being destroyed! ).
Programmatically Interacting with Generations
Table of Contents
C# and the .NET Platform, 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, Part One - Introducing C# and the .NET Platform 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: Introduction
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
// Just -how old are you? C# Language Fundamentals public static int Main(string[] args) Chapter 4 - Object-Oriented Programming with C# { Chapter 5 - Exceptions and Object Lifetime // Add these cars to the managed heap. Chapter 6 - Interfaces and Collections Car c1, c2, c3, c4; Chapter 7 - Callback Interfaces, Delegates, and Events c1 = new Car("Car one", 40, 10); Chapter c2 8 -=Advanced C# Type Construction new Car("Car two", 70,Techniques 5); Part Three with .NET Assemblies c3- Programming = new Car("Car three", 200, 100); Chapter c4 9 -=Understanding .NET Assemblies new Car("Car four", 140, 80); Chapter 3
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter // 11 -Display Type Reflection, Late Binding, and Attribute-Based Programming generations. Part FourConsole.WriteLine("C1 - Leveraging the .NET Libraries is
gen {0} ", GC.GetGeneration(c1));
Chapter Console.WriteLine("C2 12 - Object Serialization and theis .NET Remoting Layer gen {0} ", GC.GetGeneration(c2)); Chapter Console.WriteLine("C3 13 - Building a Better Window (Introducing is gen {0} Windows ", GC.GetGeneration(c3)); Forms)
is(GDI+) gen {0} ", GC.GetGeneration(c4)); Chapter Console.WriteLine("C4 14 - A Better Painting Framework Chapter 15 - Programming with Windows Forms Controls
someNamespace cars manually. Chapter // 16 -Dispose The System.IO Chapter c1.Dispose(); 17 - Data Access with ADO.NET Part Fivec3.Dispose(); - Web Applications and XML Web Services
allPages genand 0 objects? Chapter // 18 -Collect ASP.NET Web Web Controls GC.Collect(0);
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
// Display generations again Console.WriteLine("C1 is gen List of Figures Console.WriteLine("C2 is gen List of Tables Console.WriteLine("C3 is gen Console.WriteLine("C4 is gen return 0; } Index
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - 5-14: ObjectInfluencing Serialization the .NET Remoting Layer Figure anand object's current generation Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (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 System.IO Namespace that if you request a collection of generation 2 objects, the objects that have survived the current garbage Chapter 17 - Data Access with ADO.NET collection remain at generation 2 (there is no generation greater than 2 as of .NET version 1.1). Chapter 15 - Programming with Windows Forms Controls
Part Five - Web Applications and XML Web Services
Chapter 18 considered, - ASP.NET Web Pages and that Webyour Controls All things keep in mind interactions with the System.GC type should be slim to none. Chapter 19 - point ASP.NET Web Applications The whole of having a managed heap is to move the responsibility of memory management from Chapter your hands 20 - into XMLthe Web hands Services of the runtime. Index
SOURCE CODE
List of Figures List of Tables
The Generations project is included under the Chapter 5 subdirectory.
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
This chapter examined OOP-centric Apress two © 2003 (1200 pages) topics. First, you were shown how the .NET runtime makes use of structured exception handling to contend with runtime problems. Using a small set of keywords ("try", This comprehensive text starts with a brief overview of the "catch", "throw", "finally"), C# programmers are able to raise and handle C# language and then quickly moves key technical and system-level and applicationlevel exceptions. architectural issues for .NET developers. Next, you were exposed to various aspects of object lifetime. Given that the CLR makes use of runtime Table garbage of Contents collections, the basic rule of thumb is to assume that the runtime will destroy an object when it is
"noand longer needed." However, your C# types make use of unmanaged resources that need to be freed C# the .NET Platform, Secondif Edition in a timely and predictable manner, you are free to override the virtual System.Object.Finalize() method Introduction and/or theC# IDisposable interface. Finally, Part Oneimplement - Introducing and the .NET Platform
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
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
the .NET Platform, Second Edition Chapter C# 6:and Interfaces and Collections ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) This chapter builds on your current understanding of object-oriented development by introducing the topic This comprehensive textyou starts with a brief overview of the and implement custom of interface-based programming. Here learn how to use C# to define C# language and then quickly moves to key technical and interfaces, and come to understand the benefits of building types that support multiple behaviors. Along architectural issues for .NET developers. the way, a number of related topics are also discussed, such as obtaining interface references, explicit interface implementation, and the construction of interface hierarchies. Table of Contents
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 Introduction to support a number of advanced behaviors such as object cloning, object enumeration, and object Part One - Introducing C# and the .NET Platform sorting. To wrap things up, you will check out the numerous predefined interfaces that are implemented by Chapter - The Philosophy of .NET various1collection classes (ArrayList, Stack, etc.) defined by the System.Collections namespace. C# and the .NET Platform, Second Edition
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Defining Interfaces Using C# - C# Language Fundamentals
Chapter 3
Chapter 4 - Object-Oriented Programming with COM programmers have lived and died by theC# notion of interface-based programming for years. In fact, Chapter 5 Exceptions and Object Lifetime 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 - Interfaces Collections interface (not aand direct object reference). Although the .NET universe still honors the use of Chapter 7 Callback Interfaces, Events 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, Construction thatTechniques this does not in any way imply that interfaces are obsolete! Part These Three syntactic - Programming entities are with still .NET theAssemblies most elegant
manner by which you can safely extend the functionality
of a custom type without breaking existing code. Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, 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 Part Four - Leveraging the .NET Libraries exact behavior you are attempting to model. Yes, it's true. An interface expresses a behavior that a given Chapter 12 - Object Serialization and the .NET Remoting Layer class may support. At a syntactic level, an interface is defined using the C# "interface" keyword. Unlike Chapter 13 - Building a Better Window (Introducing Windows Forms) other .NET types, interfaces never specify a base class (not even System.Object) and contain members Chapter 14 - A Better Painting Framework (GDI+) that do not take an access modifier (given that interface methods are implicitly public, in order to allow the Chapter 15 - type Programming with the Windows FormsTo Controls supporting to implement members). get the ball rolling, here is a custom interface definition: Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
// This interface defines the behavior of 'having points'. // Interfaces don't have base classes! Chapter 18 - ASP.NET Web Pages and Web Controls public interface IPointy Chapter 19 - ASP.NET Web Applications { Chapter byte 20 - XML Web Services GetNumberOfPoints(); // Implicitly public and abstract. Index } Part Five - Web Applications and XML Web Services
List of Figures 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# and the .NET Platform, Second Edition
by Andrewmay Troelsen Note .NET interfaces also contain event and indexer ISBN:1590590554 method definitions. Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the Implementing an Interface Using C# C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 first.of When your class type derives directly from System.Object, you are free to simply list the interface(s) Table Contents supported by the class, as the C# compiler will extend your types from System.Object if you do not say C# and the .NET Platform, Second Edition otherwise. On a related note, given that structures always derive from System.ValueType, simply list each Introduction interface directly after the structure definition: Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET // This from System.Object and Chapter 2 -class Buildingderives C# Applications
// Two implements a single Language interface. Part - The C# Programming public class SomeClass : ISomeInterface - C# Language Fundamentals {...}
Chapter 3 Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
// This class derives from a specific base class - Interfaces and Collections // and implements a single interface. Chapter 7 - Callback Interfaces, Delegates, and Events public class AnotherClass : MyBaseClass, ISomeInterface Chapter {...}8 - Advanced C# Type Construction Techniques Chapter 6
Part Three - Programming with .NET Assemblies
Chapter 9 -struct Understanding .NET Assemblies // This derives from System.ValueType and Chapter 10 - Processes, AppDomains, Contexts, and Threads // implements a single interface. Chapter 11 struct - Type Reflection, Late Binding, and Attribute-Based Programming public SomeStruct : ISomeInterface Part Four - Leveraging the .NET Libraries {...}
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Understand implementing an interface is an all-or-nothing proposition. The supporting class is not Chapter 14 - Athat Better Painting Framework (GDI+) able to 15 selectively choosewith which members it will implement. Given that the IPointy interface defines a Chapter - Programming Windows Forms Controls
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 System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five Applications and XML Services Note- Web Abstract base classes areWeb permitted to support
interfaces without implementing the interface
Chapter 18 members - ASP.NET so Web Pages and explicitly Web Controls long as they define them as abstract. By doing so, derived types will be Chapter 19 responsible - ASP.NET Web Applications each member and thus become compatible with the interface in for implementing Chapter 20 question. - XML Web Services Index
Here is the implementation of the updated shapes hierarchy: List of Figures 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# and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen public Triangle() { } Apress © 2003 (1200 pages) public Triangle(string name) : base(name) { } This comprehensive text starts with a brief overview of the public override void Draw() C# language and then quickly moves to keyTriangle", technical and PetName); } { Console.WriteLine("Drawing {0} the architectural issues for .NET developers. // IPointy Implementation. public byte GetNumberOfPoints() { return 3; } Table of Contents } C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Each class now returns the number of points to 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 Part Two - Theusing C# Programming Language represented a lollipop (aka jack) for
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 Object-Oriented Programming with C# base class (again illustrating the stark differences implement and derive from a common Chapter between 5 COM - Exceptions and .NET). and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - 6-1: ASP.NET Applications Figure The Web updated shapes hierarchy Chapter 20 - XML Web Services Index List of Figures
Contrasting Interfaces to Abstract Base Classes
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# and the .NET Platform, Second Edition behaviors. by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the Members .NET Platform,at Second Invoking Interface the Edition Object Level by Andrew Troelsen
ISBN:1590590554
Now that you have a set©of2003 types that support the IPointy interface, the next question is how you interact Apress (1200 pages) with the defined members. The most straightforward interactofwith This comprehensive text starts with a way briefto overview thefunctionality supplied by a given interface is to invoke the methods directly from the object level. For example: C# language and then quickly moves to key technical and architectural issues for .NET developers.
Hexagon hex = new Hexagon(); Console.WriteLine("Points: {0}", hex.GetNumberOfPoints());
Table of Contents
C# and the .NET Platform, Second Edition Introduction This approach works fine in this case, given that you are well aware that the Hexagon type has Part One - Introducing C# and .NET Platform implemented the interface in the question. Many times,
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 Part - The C#toProgramming Language typeTwo at runtime trigger the functionality
Chapter 3
on the fly.
- C# Language Fundamentals
Furthermore, in a number ofProgramming circumstances Chapter 4 - Object-Oriented with(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 Object Lifetime two scenarios, let's check out a number of techniques that can be used to test for interface support and Chapter 6 - Interfaces and Collections see how to obtain a stand-alone interface reference from an implementing type. Chapter 5 Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Obtaining Interface References: Explicit Casting
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
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 Attribute-Based Programming in order to obtain an interface reference: Chapter 10 - Processes, AppDomains, Contexts, and Threads Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
// Cast for the interface reference. Hexagon hex = new Hexagon("Bill"); Chapter 14 - A Better Painting Framework (GDI+) IPointy itfPt = (IPointy)hex; Chapter 15 - Programming with Windows Forms Controls Console.WriteLine(itfPt.GetNumberOfPoints());
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five Webrequire Applications and XMLinterface Web Services If you do- not a stand-alone reference,
you could shorten the previous code into a single
Chapter - ASP.NET Web Pages and Web Controls step as18 follows: Chapter 19 - ASP.NET Web Applications Chapter 20 -end XML Web Services // Same result, less code. Index Hexagon hex = new Hexagon("Bill"); List of Figures 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# and the .NET Platform, Second Edition catch(InvalidCastException e) by Andrew Troelsen { Console.WriteLine("OOPS! Not pointy..."); }ISBN:1590590554 Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Obtaining Interface References: The "as" Keyword The second way you can test for interface support (as well as obtain an interface from an object reference) is to make use of the "as" keyword, which was first introduced in Chapter 4 during our Table of Contents examination of explicit casting operations. For example: C# and the .NET Platform, Second Edition Introduction Part - Introducing and the .NET Platform // One Second way toC#test for an interface:
Chapter Hexagon 1 -hex2 The Philosophy = new Hexagon("Peter"); of .NET
IPointy Chapter 2 -itfPt2; Building C# Applications itfPt2 = hex2 as IPointy; Part Two - The C# Programming Language if(itfPt2 != null) Fundamentals Chapter 3 - C# Language Chapter Console.WriteLine(itfPt2.GetNumberOfPoints()); 4 - Object-Oriented Programming with C#
else 5 Chapter
- Exceptions and Object Lifetime Not pointy..."); Chapter Console.WriteLine("OOPS! 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
Advanced C# Type Construction 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 - Understanding .NET Assemblies exception. Part Three - Programming with .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Obtaining Interface References: The "is" Keyword
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
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 Better Window (Introducing Windows Forms) not IPointy the condition fails: Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
// Third way to test for an interface. Triangle t = new Triangle(); Chapter 17 IPointy) - Data Access with ADO.NET if(tis Part FiveConsole.WriteLine(t.GetNumberOfPoints()); - Web Applications and XML Web Services Chapter else 18 - ASP.NET Web Pages and Web Controls Chapter Console.WriteLine("OOPS! 19 - ASP.NET Web Applications Not pointy..."); Chapter 16 - The System.IO Namespace
Chapter 20 - XML Web Services Index List of Figures List of Tables
the .NET Platform, Second Edition Exercising C# theandShapes Hierarchy by Andrew Troelsen
ISBN:1590590554
In these examples, you could havepages) avoided checking the outcome of asking for the IPointy reference, given that Apress © 2003 (1200 you knew ahead This of time which shapes were IPointy compatible. However, comprehensive text starts with a brief overview 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 moves to key technical andsubclass? You may make use of any of architectural issues at forruntime .NET developers. 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 the .NET Platform, Second Edition new Circle("JoJo")} ; Introduction for(int i = 0; i < s.Length; i++) Part One - Introducing C# and the .NET Platform { 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. Part Twos[i].Draw(); - The C# Programming Language Chapter // 3 -Who's C# Language Fundamentals pointy? Chapter if(s[i] 4 - Object-Oriented Programming with C# is IPointy) Chapter 5 - Exceptions and Object Lifetime Points: {0} ", ((IPointy)s[i]).GetNumberOfPoints()); Console.WriteLine("-> Chapter else 6 - Interfaces and Collections Console.WriteLine("-> {0}\'s Chapter 7 - Callback Interfaces, Delegates, and Events not pointy!", s[i].PetName); } Chapter 8 - Advanced C# Type Construction Techniques
Table of Contents
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
The output follows in Figure 6-2.
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Figure 6-2: Dynamically determining implemented interfaces
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Interfaces As Parameters
Chapter 20 - XML Web Services
Index Given that interfaces are strongly typed entities, you may construct methods that take interfaces as parameters as List of as Figures 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# and the .NET Platform, Second Edition { Console.WriteLine("Drawing Circle in 3D!"); } by Andrew Troelsen Apress © 2003 (1200 pages)
}
ISBN:1590590554
This comprehensive text starts with a brief overview of the tack them // If your types support multiple interfaces, simply C# language and then quickly moves to key technical and // to the end of the class definition. architectural issues for .NET developers. public class Hexagon : Shape, IPointy, IDraw3D { ... Table of Contents public void Draw3D() C# and the .NET Platform, Second Edition { Console.WriteLine("Drawing Hexagon in 3D!"); } Introduction } Part One - Introducing C# and the .NET Platform
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 Part Twosupporting - The C# Programming Language object IDraw3D. Consider the
Chapter 3
following:
- C# Language Fundamentals
Chapter 4 -some Object-Oriented with be C# rendered in 3D, do it! // Make shapes. Programming If they can Chapter 5 Exceptions and Object Lifetime public class ShapesApp Chapter 6 {
- Interfaces and Collections
Chapter // 7 -I'll Callback Interfaces, Delegates, and Events draw anyone supporting IDraw3D! Chapter public 8 - Advanced C# Type Construction Techniques static void DrawThisShapeIn3D(IDraw3D itf3d) Part Three { - Programming with .NET Assemblies
Chapter 9
- Understanding Console.WriteLine("-> .NET Assemblies Drawing IDraw3D compatible type");
itf3d.Draw3D(); Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter } 11 - Type Reflection, Late Binding, and Attribute-Based Programming
static intLibraries Main(string[] Part Fourpublic - Leveraging the .NET
args)
Chapter { 12 - Object Serialization and the .NET Remoting Layer
Shape[] s =Window { new(Introducing Hexagon(), new Forms) Circle(), Chapter 13 - Building a Better Windows new Triangle(), new Circle("JoJo")} ; Chapter 14 - A Better Painting Framework (GDI+) for(int i = 0; i < s.Length; i++) { Chapter 16 - The System.IO Namespace ... Chapter 17 - Data Access with ADO.NET // Can I draw you in 3D? Part Five - Web Applications and XML Web Services if(s[i] is IDraw3D) Chapter 18 - ASP.NET Web Pages and Web Controls DrawThisShapeIn3D((IDraw3D)s[i]); Chapter 19 - ASP.NET Web Applications } Chapter 20 - XML Web Services return 0; Index } List } of Figures Chapter 15 - Programming with Windows Forms Controls
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andExplicit the .NET Platform, Second Edition Understanding Interface Implementation by Andrew Troelsen
ISBN:1590590554
In our previous definition IDraw3D, you were forced to name your method Draw3D() in order to avoid Apress ©of 2003 (1200 pages) clashing with the This abstract Draw() method defined inathe Shapes base comprehensive text starts with brief overview of class: the C# language and then quickly moves to key technical and architectural issues for .NET developers. // The 3D drawing behavior. public interface IDraw3D { void Draw3D(); }
Table of Contents
C# and the .NET Platform, Second Edition Introduction While there is nothing horribly wrong with this interface definition, a more natural method name would Part Onebe - Introducing C# and the .NET Platform simply Draw():
Chapter 1
- The Philosophy of .NET
Chapter 2 3D - Building C# Applications // The drawing behavior. Part Two - The C# Programming Language public interface IDraw3D
Chapter 3 -Draw(); C# Language { void } Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime If you were create aand newCollections class that derives from Shape and implements IDraw3D, you would be in for Chapter 6 - to Interfaces
some problematic behavior. Before seeingand theEvents problem firsthand, assume you have defined the following Chapter 7 - Callback Interfaces, Delegates, new class Line: Chapter 8 -named Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
// Problems... Chapter 9 - Understanding .NET Assemblies public LineAppDomains, : Shape,Contexts, IDraw3D Chapter 10 class - Processes, and Threads // Both define a Draw() method! { Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming public override void Draw() Part Four - Leveraging the .NET Libraries Chapter{12 - Object Serialization and the .NET Remoting Layer
Console.WriteLine("Drawing a line..."); Chapter 13 - Building a Better Window (Introducing Windows Forms) }
Chapter 14 - A Better Painting Framework (GDI+)
}
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 class - Data Access with ADO.NET The Line compiles without a hitch. But, consider the following object user code: Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
// Calls Line.Draw() Line myLine = new Line(); Chapter 20 - XML Web Services myLine.Draw();
Chapter 19 - ASP.NET Web Applications Index List Figures //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# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
// Using explicit method implementation we are able Apress © 2003 (1200 pages) // to provide distinct Draw() implementations. This comprehensive text starts with a brief overview of the public class C# Line : Shape, IDraw3D language and then quickly moves to key technical and { architectural issues for .NET developers. // You can only call this method using an IDraw3D interface reference. void IDraw3D.Draw() Console.WriteLine("Drawing a 3D line..."); } Table of{ Contents C# and the .NET Platform, Second Edition
// You can only call this using a Line (or base class) reference. Introduction public override Draw() Part One - Introducing C# andvoid the .NET Platform a line..."); } Chapter{1 Console.WriteLine("Drawing - The Philosophy of .NET } Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
There are a few odds and ends to be aware of when using explicit interface implementation. First and - Object-Oriented Programming with C# foremost, you cannot make use of an access modifier when using this technique. For example, the Chapter 5 Exceptions and Object Lifetime following is- illegal syntax: Chapter 4 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
// Nope! Illegal. Chapter 8 - Advanced C# Type Construction Techniques public class Line : Shape, IDraw3D Part Three - Programming with .NET Assemblies { Chapterpublic 9 - Understanding .NET Assemblies // = maxSpeed) Index carIsDead = true; List of Figures else List of Tables Console.WriteLine("\tCurrSpeed = {0} ", currSpeed); } } Chapter 15 - Programming with Windows Forms Controls
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# and the .NET Platform, Second Edition c1.Advise(sink); ISBN:1590590554 by Andrew Troelsen will generate the events). // Speed up (this Apress © 2003 (1200 pages) for(int i = 0; i < 6; i++) This comprehensive text starts with a brief overview of the c1.SpeedUp(20); C# language then quickly moves to key technical and // Detach fromand events. architectural issues for .NET developers. c1.Unadvise(sink); return 0; }
Table of Contents
}
C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter The Philosophy of .NET Figure 17-1-shows the end result of this interface-based event protocol. Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8 - 7-1: Advanced C# Type Construction Techniques Figure An interface-based event protocol Part Three - Programming with .NET Assemblies
Chapter - Understanding .NET Assemblies Do note9 that the Unadvise() method can be very helpful in that it allows the caller to selectively detach Chapter from events 10 - Processes, at will. Here, AppDomains, you call Unadvise() Contexts, before and Threads exiting Main(), although this is not technically
necessary. assume that the application now wishesProgramming to register two sinks, dynamically remove a Chapter 11 - However, Type Reflection, Late Binding, and Attribute-Based particular sink during the the .NET flow of execution, Part Four - Leveraging Libraries
and continue processing the program at large:
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 static - Buildingint a Better Window (Introducing Windows Forms) public Main(string[] args) Chapter { 14 - A Better Painting Framework (GDI+)
a car with as Windows usual. Forms Controls Chapter // 15 -Make Programming c1 System.IO = new Car("SlugBug", 100, 10); Chapter Car 16 - The Namespace sink with objects. Chapter // 17 -Make Data Access ADO.NET Creating Part FiveConsole.WriteLine("***** - Web Applications and XML Web Services
sinks *****");
sink"); Chapter CarEventSink 18 - ASP.NET Websink Pages = andnew WebCarEventSink("First Controls = new CarEventSink("Other sink"); Chapter CarEventSink 19 - ASP.NET WebmyOtherSink Applications // Hand sinks to Car. Console.WriteLine("\n***** Sending 2 sinks into Car *****"); Index c1.Advise(sink); List of Figures 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 Services
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
Event interfaces will always have place under any programming architecture. However, as you may Apress © 2003 (1200their pages) be suspecting, the .NET platform supplies native support enabling communications. To This comprehensive text starts with a brieffor overview of bidirectional the understand this intrinsic event protocol, we begin by examining the role of the delegate type. C# language and then quickly moves to key technical and architectural issues for .NET developers.
SOURCE CODE
The EventInterface project is located under the Chapter 7 subdirectory.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, SecondType Edition Understanding .NET Delegate by Andrew Troelsen
ISBN:1590590554
Before formally defining delegates, Apress ©.NET 2003 (1200 pages) let's gain a bit of perspective. Historically speaking, the Windows API makes frequent use of C-style pointers create entities callback functions or simply This comprehensivefunction text starts with atobrief overview of termed the callbacks. Using C# callbacks, programmers were able to configure one function to report back to (call back) language and then quickly moves to key technical and architectural issuesUnderstand for .NET developers. 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). Table of Contents
The problem with standard C-style callback functions is that they represent little more than a raw address C# and the .NET Platform, Second Edition in memory. Ideally, callbacks could be configured to include additional type-safe information such as the Introduction number (and typesC# of)and parameters and the return Part One -of Introducing the .NET Platform
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 Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# essence, a delegate is an object that points to another method in the application. Specifically speaking, a Chapter 5 maintains - Exceptions andimportant Object Lifetime delegate three pieces of information: Chapter 3
Chapter 6
- Interfaces and Collections
The of the Interfaces, method onDelegates, which it makes calls Chapter 7 name - Callback and Events Chapter 8
- Advanced C# Type Construction Techniques
Thearguments (if any) of this method
Part Three - Programming with .NET Assemblies
Chapter 9 return - Understanding .NET Assemblies The value (if any) of this method Chapter 10 - Processes, AppDomains, Contexts, and Threads
Once a11 delegate has been created and provided the aforementioned information, it may dynamically Chapter - Type Reflection, Late Binding, and Attribute-Based Programming invoke method it represents at runtime. Part Fourthe - Leveraging the .NET Libraries
As you will see, the .NET Framework automatically supports
the use12 of -synchronous and asynchronous Chapter Object Serialization and the .NETdelegates Remoting (both Layer of which are seen over the course of this chapter). Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Defining a Delegate in C#
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
When you createwith a delegate Chapter 17 -want Datato Access ADO.NETin C#, you make use of (surprise, surprise) the "delegate" keyword. Under hood, the delegate expands Part Fivethe - Web Applications andkeyword XML Web Servicesto
a sealed class type deriving from
System.MulticastDelegate. For example, if you write the following C# delegate definition: Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
public delegate PlayAcidHouse(Person theDJ, int volume); Chapter 20 - XML Webvoid Services Index List of Figures
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# and the .NET Platform, Second Edition
ISBN:1590590554 by Andrew Troelsen class has been automatically As you can see, the PlayAcidHouse endowed (thanks to the C# compiler) Apress © 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 comprehensive the method text it is currently starts withpointing a brief overview to. Noticeofthat the the parameters that are sent into C# language and then quickly moves to key technical andBeginInvoke() and EndInvoke() Invoke() are identical to the declaration of the PlayAcidHouse delegate. issues for .NET developers. provide the abilityarchitectural to call the current 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 Table of Contents appropriate C# syntax.
C# and the .NET Platform, Second Edition
Introduction Now, how exactly does the compiler know how to prototype the Invoke(), BeginInvoke(), and EndInvoke() Part One - Introducing C# and .NET Platform methods? To understand thethe process, here is 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 Part Two - The C# Programming Language sealed class PlayAcidHouse : System.MulticastDelegate
Chapter 3 {
- C# Language Fundamentals
Chapter public 4 - Object-Oriented Programming with target, C# PlayAcidHouse(object uint functionAddress); Chapter public 5 - Exceptions Object Lifetime theDJ, int volume); void and Invoke(Person Chapter public 6 - Interfaces IAsyncResult and Collections BeginInvoke(Person theDJ, int volume,
AsyncCallback cb, object state); - Callback Interfaces, Delegates, and Events public void EndInvoke(IAsyncResult Chapter 8 - Advanced C# Type Construction Techniques result); } Three - Programming with .NET Assemblies Part Chapter 7
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, 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 Part Four - Leveraging the .NET Libraries same number of, and type of, the original C# delegate declaration. Likewise, the return value of Invoke() Chapter 12 - Object Serialization and the .NET Remoting Layer and EndInvoke() is identical to the original C# delegate declaration. And obviously, the name of the Chapter 13 - Building a Better Window (Introducing Windows Forms) constructor is based on the name of the original C# delegate declaration. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 14 - A Better Painting Framework (GDI+)
Chapter Now assume 15 - Programming you have defined with Windows anotherForms C# delegate Controlstype that represents a method returning a string and
taking three Booleans: Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services public delegate string TakeSomeBools(bool
a, bool b, bool c);
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
This time, auto-generated Chapter 20 -the XML Web Services class breaks down as follows: Index
sealed class TakeSomeBools : System.MulticastDelegate List of Figures { 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# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
sealed class TakeSomeBoolsByRefAndAsOut : System.MulticastDelegate Apress © 2003 (1200 pages) { This comprehensive text starts with a brief overview of the public TakeSomeBoolsByRefAndAsOut (object target, uint functionAddress); C# language and then quickly moves to key technical and public architectural string Invoke(out bool a, out bool b, ref bool c); issues for .NET developers. public IAsyncResult BeginInvoke(out bool a, out bool b, ref bool c, AsyncCallback cb, object state); public Table of Contents string EndInvoke(out bool a, out bool b, boolSecond c, IAsyncResult result); C# and the .NETref Platform, Edition } Introduction Part One - Introducing C# and the .NET Platform
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 - Object-Oriented Programming with C# out the System.MulticastDelegate base class. Part Two - The C# Programming Language
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Members ofC#System.MulticastDelegate by Andrew Troelsen
ISBN:1590590554
So then, when you build©a2003 type(1200 using the C# "delegate" keyword, you indirectly declare a type that derives Apress pages) from System.MulticastDelegate. The MulticastDelegate type in turn of derives This comprehensive text starts with a brief overview the from System.Delegate (as well as implements two standard interfaces). Here is the formal definition of MulticastDelegate: C# language and then quickly moves to key technical and architectural issues for .NET developers.
public abstract class MulticastDelegate : Delegate, ICloneable, ISerializable Table of Contents { C# and the .NET Platform, Second Edition public MethodInfo Method { get; } Introduction public object Target { get; } Part One - Introducing C# and the .NET Platform 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); Part Two - The C# Programming Language public virtual int GetHashCode(); Chapter 3 - C# Language Delegate[] Fundamentals GetInvocationList(); public virtual Chapter 4 - Object-Oriented Programming with C# public virtual void Chapter 5 GetObjectData(SerializationInfo - Exceptions and Object Lifetime info, StreamingContext context); Chapter public 6 - Interfaces Type GetType(); and Collections public virtual string ToString(); Chapter 7 - Callback Interfaces, Delegates, and Events } Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
And here is the definition of System.Delegate:
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
public class Delegate Part Four - abstract Leveraging the .NET Libraries
: object, ICloneable, ISerializable Chapter 12 - Object Serialization and the .NET Remoting Layer { Chapter 13 - Building a Better Window (Introducing Windows Forms) public MethodInfo Method { get; } Chapter 14 - A Better Painting Framework (GDI+) public object Target { get; } Chapter 15 - Programming with Windows Forms Controls public virtual object Clone(); Chapter 16 - The System.IO Namespace public static Delegate Combine(Delegate a, Delegate b); Chapter 17 - Data Access with ADO.NET public static Delegate Combine(Delegate[] delegates); Part Five - Web Applications and XML Web Services public static Delegate Chapter 18 CreateDelegate(Type - ASP.NET Web Pages and Web Controls type, System.Reflection.MethodInfo method); Chapter 19 - ASP.NET Web Applications public static Delegate Chapter 20 CreateDelegate(Type - XML Web Services type, object target, string method); Indexpublic static Delegate CreateDelegate(Type type, Type target, string method); List ofpublic Figures 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# and the .NET Platform, Second Edition
Inherited Member
Meaning by Andrew Troelsen in Life Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the This property returns the name of a static method that is maintained by the C# language and then quickly moves to key technical and delegate. architectural issues for .NET developers.
Method 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. Table of Contents If the value returned from Target equals null, the method to be called is a C# and the .NET Platform, Second Edition static member. Introduction
Combine() Thisthe static method adds Part One - Introducing C# and .NET Platform
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
Part Two - The C# Programming Language
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. - Object-Oriented Programming with C#
Remove() This static method removes a delegate from the list methods to call. In C#, Chapter 5 - Exceptions and Object Lifetime Chapter 6
trigger this method using the overloaded -= operator as a shorthand - Interfaces andyou Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction 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 - Understanding .NET Assemblies given delegate. Additional methods can be added to this internal list using the static Combine() method (or Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming method (or the C# overloaded -= operator). As you may know, the ability for a delegate to call multiple Part Four - Leveraging the .NET Libraries functions is termed multicasting . You see this technique action a bit later in this chapter. Part Three - Programming with .NET Assemblies
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The Simplest Possible Delegate Example by Andrew Troelsen
ISBN:1590590554
Delegates can tend to cause great deal of confusion when encountered for the first time. Thus, to get Apress © 2003a(1200 pages) the ball rolling, let's take a look at a very example. is the code, with analysis to This comprehensive text simple starts with a brief Here overview of complete the follow: C# language and then quickly moves to key technical and architectural issues for .NET developers.
namespace SimpleDelegate { Table of Contents class DelegateApp C# and the .NET Platform, Second Edition { Introduction // This is the method that will be called Part One - Introducing C# and the .NET Platform // 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); } Part Two - The C# Language // Programming Define a delegate type. Chapter 3 - C# Language Fundamentals public delegate void AnyMethodTakingAString(string s); Chapter 4 - Object-Oriented Programming with C# public static void Main() Chapter 5 - Exceptions and Object Lifetime { Chapter 6 - Interfaces //and Make Collections the delegate. del; Chapter 7 - CallbackAnyMethodTakingAString Interfaces, Delegates, and Events del = new AnyMethodTakingAString(PlainPrint); Chapter 8 - Advanced C# Type Construction Techniques // AnyMethodTakingAString.Invoke() called here! Part Three - Programming with .NET Assemblies del("Hello there..."); Chapter 9 - Understanding .NET Assemblies // AppDomains, Dump infoContexts, about and theThreads delegate. Chapter 10 - Processes, Console.WriteLine("I just called: {0}", del.Method); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Part Four - Leveraging the .NET Libraries } Chapter 12 - Object Serialization and the .NET Remoting Layer } Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 -begin Programming withaWindows Forms Controls Here, you by declaring .NET delegate type using the C# "delegate" keyword. The Chapter 16 The System.IO Namespace AnyMethodTakingAString delegate represents an object that maintains a reference to some method that Chapter - Data Access with ADO.NET takes a17 single string parameter and returns nothing. When you want to assign the target (i.e., the method Part Fiveof - Web Applications XMLpass Webin Services to call) a given delegate,and simply the name
of the method to the delegate's constructor. At this
Chapter 18 -are ASP.NET Pagesinvoke and Web point, you able toWeb indirectly theControls member using a syntax that looks like a direct function Chapter invocation: 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index // Make the delegate. List of Figures 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# and the .NET Platform, { Console.WriteLine("Msg is: Second {0}", Edition msg); } by Andrew Troelsen public static void UpperCasePrint(string ISBN:1590590554 msg) Apress © 2003 (1200 pages) is: {0}", msg.ToUpper()); } { Console.WriteLine("Msg This comprehensive text starts with a brief overview of the public static void XXXXYYYYZZZZ888777aaa(string msg) C# language and then moves tomsg); key technical and { Console.WriteLine("Msgquickly is: {0}", } architectural issues for .NET developers. public delegate void AnyMethodTakingAString(string s); public static void Main() { Table of Contents AnyMethodTakingAString del; C# and the .NET Platform, Second Edition del = new AnyMethodTakingAString(PlainPrint); Introduction del("Hello there..."); Part One - Introducing C# and the .NET Platform 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); Part Two - The C# Programming Language del("Hello there..."); Chapter 3 - C# Language Fundamentals Console.WriteLine("->I just called: {0}\n", del.Method); Chapter 4 - Object-Oriented withdelegate. C# // ReassignProgramming and invoke Chapter 5 - Exceptions and Object Lifetime del= new AnyMethodTakingAString(XXXXYYYYZZZZ888777aaa); Chapter 6 - Interfaces and Collections del("Hello there..."); Chapter 7 - Callback Interfaces, Delegates, and Events Console.WriteLine("->I just called: {0}\n", del.Method); Chapter}8 - Advanced C# Type Construction Techniques Part } Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
The final output can be seen in Figure 7-3.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Figure 7-3: Dynamically "pointing to" various methods
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Services If you attempt to Web assign the address of a method that did not match the delegate's declaration: Index List Figures //ofBad target! 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# and the .NET Platform, Second Edition SimpleDelegate.DelegateApp.AnyMethodTakingAString(string)' by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the
Multicasting .NET Delegates C#with language and then quickly moves to key technical and architectural issues for .NET developers.
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 list maintained by the System.Delegate base class, you are able to make use of the overloaded += Table of Contents operator. The topic of operator will be examined in detail in the next chapter, but for the time C# and the .NET Platform, Secondoverloading Edition being simply understand that when you apply the += operator to a type derived from Introduction System.MulticastDelegate, the hidden Combine() method is triggered automatically (so be sure to check Part One - Introducing C# and the .NET Platform out the CIL via ildasm.exe). Chapter 1 - The Philosophy of .NET Chapter 2
- Building C# Applications
// Two Now- The some Part C# multicasting. Programming Language AnyMethodTakingAString myMultiCaster; Chapter 3 - C# Language Fundamentals myMultiCaster = new AnyMethodTakingAString(PlainPrint); Chapter 4 - Object-Oriented Programming with C# myMultiCaster += and newObject AnyMethodTakingAString(UpperCasePrint); Chapter 5 - Exceptions Lifetime myMultiCaster +=and new AnyMethodTakingAString(XXXXYYYYZZZZ888777aaa); Chapter 6 - Interfaces Collections myMultiCaster("Here is a string"); - Callback Interfaces, Delegates, and Events
Chapter 7 Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies project is located under the Chapter 7 subdirectory. SOURCE The SimpleDelegate Chapter 10 Processes, AppDomains, Contexts, and Threads CODE Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and Elaborate the .NET Platform, Second Edition Building a More Delegate Example by Andrew Troelsen
ISBN:1590590554
To illustrate a more advanced use pages) of delegates, let's begin by updating the Car class to include two new Boolean Apress © 2003 (1200 member variables. The first is used determine if your automobile is due This comprehensive to text starts with a brief overview of the for a wash (isDirty); the other represents if the car in question is in need of a tire rotation (shouldRotate). C# language and then quickly moves to key technical and To enable the object user to interact architectural issues for .NET developers. with this new state data, Car also defines some additional properties and an updated constructor. Here is the story so far: Table of Contents
// Another updated Car class. public class Car Introduction { Part One - Introducing C# and the .NET Platform ... 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; Part Twoprivate - The C# Programming Language bool shouldRotate; C# and the .NET Platform, Second Edition
Chapter 3
- C# Language Fundamentals
Chapter // 4 -Extra Object-Oriented with C# paramsProgramming to set bools. Chapter public 5 - Exceptions and Object Lifetime Car(string name, int max, int curr, bool dirty, bool rotate) Chapter { 6 - Interfaces and Collections Chapter 7
... - Callback Interfaces, Delegates, and Events
Chapter 8
isDirtyC#= Type dirty; - Advanced Construction Techniques
shouldRotate = rotate; Part Three - Programming with .NET Assemblies Chapter } 9
- Understanding .NET Assemblies public boolAppDomains, Dirty //and Get and set isDirty. Chapter 10 - Processes, Contexts, Threads Chapter { 11 - Type Reflection, Late Binding, and Attribute-Based Programming
get{ return Part Four - Leveraging the .NETisDirty; Libraries Chapter Chapter Chapter Chapter Chapter Chapter
} set{ isDirty = value; } 12 - Object Serialization and the .NET Remoting Layer } 13 - Building a Better Window (Introducing Windows Forms) public bool Rotate // Get and set shouldRotate. 14 - A Better Painting Framework (GDI+) { 15 - Programming with Windows Forms Controls get{ return shouldRotate; } 16 - The System.IO Namespace set{ shouldRotate = value; } 17 - Data Access with ADO.NET }
Part } Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Now, assume you have declared the following delegate (which, again, is nothing more than an object-oriented Chapter 20 - XML Web Services wrapper around a function pointer) within your current namespace: Index List of Figures 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
{ the .NET Platform, Second // This C# isand represented in CIL as Edition ISBN:1590590554 by Andrew Troelsen // Car$CarDelegate (i.e., a nested type). Apress © 2003 (1200 pages) public delegate void CarDelegate(Car c); This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
... }
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 the .NET Platform, Second Edition the matter.
Table of Contents Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure 7-4: Remember! C# delegate types alias System.MulticastDelegate
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Using the CarDelegate
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 you - A have BetteraPainting Framework (GDI+)function" taking a Car parameter and returning nothing, you can Now that type that points to "some Chapter 15 Programming with Windows Forms Controls create other functions that take this delegate as a parameter. To illustrate, assume you have a new class named Chapter 16This - The System.IO Namespace Garage. type maintains a collection of Car types contained in an ArrayList. Upon creation, the ArrayList is Chapter 17 Data Access with ADO.NET filled with some initial Car types. Part Five - Web Applications and XML Web Services
More importantly, theWeb Garage class a public ProcessCars() method, which takes a single argument of Chapter 18 - ASP.NET Pages and defines Web Controls type Car.CarDelegate. In Applications the implementation of ProcessCars(), you pass each Car in your collection as a Chapter 19 - ASP.NET Web parameter theWeb "function pointed to" by the delegate. Chapter 20 -to XML Services Index
To help keep your wits about you, ProcessCars() also makes use of two members defined by the
List of Figures 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# and the .NET Platform, Second100, Edition theCars.Add(new Car("Stan", 0, false, true)); ISBN:1590590554 by Andrew Troelsen } Apress © 2003 (1200 pages) // This method takes a Car.CarDelegate as a parameter. This comprehensive starts with a briefthan overview of the // Therefore 'proc' istext nothing more a function pointer! C# language and then quickly moves to key technical public void ProcessCars(Car.CarDelegate proc)and architectural issues for .NET developers. { // Diagnostics: Where are we forwarding the call? Console.WriteLine("***** Calling: {0} *****", Table of Contents d.Method.ToString()); C# and the .NET Platform, Second Edition // Diagnostics: Are we calling an instance method or a static method? Introduction if(proc.Target != null) Part One - Introducing C# and the .NET Platform 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"); Part Two - The C# Programming Language // Real Work: Now call the method, passing in each car. Chapter 3 - C# Language Fundamentals foreach(Car c in theCars) Chapter 4 - Object-Oriented Programming with C# proc(c); Chapter } 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections }
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
When the-object user calls ProcessCars(), it will Part Three Programming with .NET Assemblies
send in the name of the method that should handle this request. For the sake of argument, assume these are static members named WashCar() and RotateTires(). Consider the Chapter 9 - Understanding .NET Assemblies following usage: Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Four The - garage delegates all work Part Leveraging the .NET Libraries
orders to these static functions
// (finding a Serialization good mechanic problem...) Chapter 12 - Object and the is .NETalways RemotingaLayer public CarApp Chapter 13 class - Building a Better Window (Introducing Windows Forms) { Chapter 14 - A Better Painting Framework (GDI+) // A target for the delegate. public static void WashCar(Car c) Chapter 16 - The System.IO Namespace { Chapter 17 - Data Access with ADO.NET if(c.Dirty) Part Five - Web Applications and XML Web Services Console.WriteLine("Cleaning a car"); Chapter 18 - ASP.NET Web Pages and Web Controls else Chapter 19 - ASP.NET Web Applications Console.WriteLine("This car is already clean..."); Chapter } 20 - XML Web Services Index // Another target for the delegate. List of Figures 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 - Programming with Windows Forms Controls
} C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
© 2003 pages) Notice (of course)Apress that the two(1200 static methods are an exact match to the delegate type (void return value and a single Car argument). Also, recall that when you pass in the name of This comprehensive text starts with a brief overview of your the function as a constructor parameter, C#item language then quickly moves to key technical and you are adding this to theand internal linked list maintained by System.MulticastDelegate. Figure 7-5 shows the for .NET developers. output of this testarchitectural run. (Noticeissues the output messages supplied by the Target and Method properties.)
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - 7-5: Interfaces andthe Collections Figure Passing buck Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Analyzing the Delegation Code
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter As you 10 can- see, Processes, the Main() AppDomains, method begins Contexts, by and creating Threads an instance of the Garage type. This class has been
configured delegate all work other named static functions. Now, when you write the following: Chapter 11 - to Type Reflection, Lateto Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 -all Object Serialization // Wash dirty cars.and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) g.ProcessCars(new Car.CarDelegate(WashCar)); Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
what you effectively saying is "Add a pointer to the WashCar() function to the CarDelegate type, and pass this Chapter 16 are - The System.IO Namespace 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 Part Five - Web Applications and XML Web Services ProcessCars()actually looks like the following under the hood: Chapter 17 - Data Access with ADO.NET
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
// CarDelegate Chapter 20 - XML Webpoints Services to the WashCar function: public void ProcessCars(Car.CarDelegate proc) { List of Figures ... List of Tables foreach(Car c in theCars) proc(c); // proc(c) => CarApp.WashCar(c) } Index
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# and Platform, Second Edition foreach(Car c the in .NET theCars) ISBN:1590590554 by Andrew Troelsen proc(c); // proc(c) => CarApp.RotateTires(c) Apress © 2003 (1200 pages)
... }
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Also notice that when you are calling ProcessCars(), you must create a new instance of the custom delegate: Table of Contents
// Wash all dirty cars. g.ProcessCars(newCar.CarDelegate(WashCar)); Introduction // Rotate the tires. Part One - Introducing C# and the .NET Platform g.ProcessCars(newCar.CarDelegate(RotateTires)); C# and the .NET Platform, Second Edition
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part - The C# Programming Language ThisTwo might seem odd at first, given that a 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 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections Multicasting with the Car.CarDelegate
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter Type Construction Recall 8that- aAdvanced multicastC# delegate is an objectTechniques that is capable of calling any number of functions. In the current Part Three -you Programming with .NET Assemblies example, do not make use of this feature.
Rather, you make two calls to Garage.ProcessCars(), sending in a
Chapter 9 - Understanding .NET Assemblies new instance of the CarDelegate each time. However, assume you have updated Main() to look like the Chapter following: 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Leveraging the .NET Libraries // Four Add - two function pointers
to the internal linked list.
Chapter 12 static - Object Serialization and the .NET Remoting public int Main(string[] args) Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) { Chapter // 14 -Make A Better the Painting garage. Framework (GDI+)
g = newwith Garage(); Chapter Garage 15 - Programming Windows Forms Controls two new delegates. Chapter // 16 -Create The System.IO Namespace wash = new Car.CarDelegate(WashCar); Chapter Car.CarDelegate 17 - Data Access with ADO.NET rotate = Services new Car.CarDelegate(RotateTires); Part FiveCar.CarDelegate - Web Applications and XML Web overloaded can be applied to multicast delegates. Chapter // 18 -The ASP.NET Web Pages + andoperator Web Controls result is a new delegate that maintains pointers to Chapter // 19 -The ASP.NET Web Applications // both functions. g.ProcessCars(wash + rotate); return 0;
Chapter 20 - XML Web Services Index
List of Figures
}
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 internal 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# and d the= .NET Platform, Second Edition MulticastDelegate wash + rotate; ISBN:1590590554 by Andrew Troelsen // Send the new delegate into the ProcessCars() method. Apress © 2003 (1200 pages) g.ProcessCars((Car.CarDelegate)d); This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers. Regardless of how you configure a multicast delegate, 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 you Table of Contents wish to manipulate, while the second parameter marks the item to remove: C# and the .NET Platform, Second Edition Introduction
// 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); Part One - Introducing C# and the .NET Platform
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
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 - Object-Oriented with C# stored in linked list usingProgramming Delegate.GetInvocationList(). This method returns an array of Delegate objects, Chapter 5 -iterate Exceptions and Object Lifetime which you over using foreach: Chapter 6
- Interfaces and Collections
Chapter 7 print - Callback Interfaces, Delegates, Events // Now out each member inand the linked list. Chapter 8 void - Advanced C# Type Construction Techniques proc) public ProcessCars(Car.CarDelegate Part { Three - Programming with .NET Assemblies
Chapter // 9 -Where Understanding .NET Assemblies are we passing the call? Chapter 10 foreach(Delegate - Processes, AppDomains, d in Contexts, proc.GetInvocationList()) and Threads Chapter { 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Console.WriteLine("***** Part Four - Leveraging the .NET Libraries
Calling: {0} *****",
d.Method.ToString()); Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter } 13 - Building a Better Window (Introducing Windows Forms)
... 14 - A Better Painting Framework (GDI+) Chapter } Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Instance Methods As Callbacks
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Currently, CarDelegate type is storing pointers to static functions. This is not a requirement of the delegate Chapter 19 -the ASP.NET Web Applications protocol callbacks, which require static members). It is also possible to delegate a call to a Chapter 20(unlike - XML C-based Web Services
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:
Index
List of Figures 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# and the .NET Platform, Second Edition else by Andrew Troelsen Console.WriteLine("Don't need ISBN:1590590554 to be rotated..."); }
Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
}
You could now update Main() as follows: Table of Contents
// Delegate to instance methods of the ServiceDept type. public static int Main(string[] args) Introduction { Part One - Introducing C# and the .NET Platform // Make the garage. Chapter 1 - The Philosophy of .NET Garage g = new Garage(); Chapter 2 - Building C# Applications // Make the service department. Part Two - The C# Programming Language ServiceDept sd = new ServiceDept(); Chapter 3 - C# Language Fundamentals // The garage delegates the work to the service department. Chapter Car.CarDelegate 4 - Object-Oriented Programming withCar.CarDelegate(sd.WashCar); C# wash = new Chapter Car.CarDelegate 5 - Exceptions and Object Lifetime rotate = new Car.CarDelegate(sd.RotateTires); Chapter MulticastDelegate 6 - Interfaces and Collections d = wash + rotate; Chapter // 7 -Tell Callback Interfaces, and Events the garageDelegates, to do some work. Chapter g.ProcessCars((Car.CarDelegate)d); 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies return 0; Chapter } 9 - Understanding .NET Assemblies C# and the .NET Platform, Second Edition
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure shows the the final.NET fruits of our labor. Part Four7-6 - Leveraging Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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 to invoke methods asynchronously. First off, what exactly warrants an asynchronous method invocation? As you are 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# and the .NET Platform, Second Edition are quite simple to program; however, in the case of the word processor application, the end user is far less than ISBN:1590590554 by Andrew pleased. The reason has to Troelsen do with the fact that while the application's single thread of execution is crunching out Apress © 2003 (1200 pages) the 1000-page document, all other aspects of this program (such as menu activation, toolbar clicking, and Thisunresponsive. comprehensive text starts with a brief overview of the keyboard input) are C# language and then quickly moves to key technical and
architectural issues for .NET developers. When programmers wish to build applications that are 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.
Table of Contents
C# and thedoes .NET threading Platform, Second So, what have toEdition do with .NET delegates? Well, to illustrate the potential problem with Introduction synchronous delegate invocations, ponder the following simple application: Part One - Introducing C# and the .NET Platform
Chapter - The Philosophy of .NET using1 System; Chapter - Building C# Applications using2 System.Threading; Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals namespace AsyncDelegate Chapter 4 {
- Object-Oriented Programming with C#
Chapter // 5 -AExceptions new delegate and Object type. Lifetime
delegate string NewCarDelegate(Car carToDetail); Chapter public 6 - Interfaces and Collections class Car{...} Chapter public 7 - Callback Interfaces, Delegates, and Events App C# Type Construction Techniques Chapter class 8 - Advanced { - Programming with .NET Assemblies Part Three Chapter 9
public static string DetailCar(Car c) - Understanding .NET Assemblies
{ Chapter 10 - Processes, AppDomains, Contexts, and Threads // Detailing a car takes 10 seconds. Console.WriteLine("Detailing car on thread {0}", Part Four - Leveraging the .NET Libraries Thread.CurrentThread.GetHashCode()); Chapter 12 - Object Serialization and the .NET Remoting Layer Thread.Sleep(10000); Chapter 13 - Building a Better Window (Introducing Windows Forms) return "Your car is ready!"; Chapter 14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls static void Main(string[] args) Chapter 16 - The { System.IO Namespace Chapter 17 - Data Access with ADO.NET Console.WriteLine("Main() is on thread {0}", Part Five - Web Applications and XML Web Services Thread.CurrentThread.GetHashCode()); Chapter 18 - ASP.NET NewCarDelegate Web Pages and Web Controls d = new NewCarDelegate(DetailCar); Chapter 19 - ASP.NET Web Car Applications myCar = new Car(); Chapter 20 - XML WebConsole.WriteLine(d(myCar)); Services Index Console.WriteLine("Done invoking delegate"); List of Figures } } List of Tables } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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# and the .NET Platform, Second Edition perfectly acceptable. However, given that the DetailCar() method takes 10 seconds to complete, your application ISBN:1590590554 by Andrew appears to be hanging until Troelsen the call has completed (just like the printing of the 1000-page document). Apress © 2003 (1200 pages)
The question therefore is: How can you a delegate to invoke a method This comprehensive texttell starts with a brief overview of the on a separate thread of execution and C# main language andonce thenthe quickly moves key technicalThe andgood news is that every .NET delegate "report back" to the thread method hastocompleted? architectural for .NET developers. type is automatically equippedissues with this ability. The even better news is that you are not required to directly dive into the details of the System.Threading namespace to do so (although these entities can quite naturally work hand in hand).
Table of Contents
C# and the Platform, Second Edition Again, full .NET details of multithreaded programming will be examined later in this text, but for the time being, let's Introduction check out how System.MulticastDelegate provides automatic support for asynchronous method invocations. Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET Invoking Methods Asynchronously
Chapter 2
- Building C# Applications
Part Tworecall, - The C# Programming Language As you when the C# compiler processes
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 - Object-Oriented Programming with C# members: Chapter 5
- Exceptions and Object Lifetime
Chapter 6 IAsyncResult - Interfaces and Collections public BeginInvoke(Car carToDetail, Chapter System.AsyncCallback 7 - Callback Interfaces, Delegates, and Events callback, object state); Chapter 8 string - Advanced C# Type Construction Techniques public EndInvoke(IAsyncResult result); Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies Note that returns an IAsyncResult Chapter 10 BeginInvoke() - Processes, AppDomains, Contexts, andinterface, Threads while EndInvoke() requires an IAsyncInvoke type as
parameter. (defined in the System namespace) breaks down as follows: Chapter 11 - This Type interface Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
public IAsyncResult Chapter 12 interface - Object Serialization and the .NET Remoting Layer { Chapter 13 - Building a Better Window (Introducing Windows Forms) object { get; }(GDI+) Chapter 14 - A AsyncState Better Painting Framework WaitHandle AsyncWaitHandle { get; } Chapter 15 - Programming with Windows Forms Controls bool CompletedSynchronously { get; } bool IsCompleted { get; }
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
}
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET In the simplest case, Web one Applications is able to effectively ignore directly interacting with these members. All you have to do is Chapter 20 -returned XML Web Services cache the IAsyncResult type in a local variable in order to pass it to EndInvoke() when you are ready to Index obtain the result of the method invocation. Thus, to invoke DetailCar() asynchronously, you simply need to make List Figures 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# and the .NET Platform, Second Edition previous code updates, you may have noticed that IntelliSense failed to show you the BeginInvoke() and by Andrew EndInvoke() members. TheTroelsen reason is due to the fact that theseISBN:1590590554 methods don't exist until the current assembly Apress © 2003 (1200 has been compiled! Recall that thepages) C# compiler will autogenerate a type derived from System.MulticastDelegate This comprehensive text starts with a brief overview of thealways remember that you are smarter atcompile time. Thus, when you are invoking members asynchronously, C# language and then quickly moves 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, architectural issues for .NET developers. you will be able to type in the code for BeginInvoke()/EndInvoke() accordingly. Now, check out Figure 7-7. Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2 - 7-7: Building C# Applications Figure Asynchronous invocations increase program responsiveness. Part Two - The C# Programming Language
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 unique hash codes, you with will also Chapter 4 -toObject-Oriented Programming 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 (in Chapter 5 delegate" - Exceptions and Object Lifetime this case, sleeping on the job for 10 seconds). - Interfaces and Collections
Chapter 6
Chapter 7 - Callback Interfaces, Delegates,project and Events SOURCE The AsyncDelegate is located under the Chapter 7 subdirectory. Chapter 8 - Advanced C# Type Construction Techniques CODE Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Callbacks for Asynchronous Delegates
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter Type At Reflection, Programming So far, 11 so -good. this point,Late youBinding, are ableand to Attribute-Based trigger a method via a custom delegate and obtain the result at Part Four - Leveraging the(e.g., .NET when Libraries some time in the future you
call the EndInvoke() method). While this is all well and good, there may
Chapter 12when - Object .NET Remoting Layer be times youSerialization would ratherand notthe manually call EndInvoke() to obtain the results of your invocation, but would Chapter 13 Building a Better Window (Introducing Windows Forms) rather that the delegate call you when the method has been completed. In many ways, this functionality is quite Chapter - A callback Better Painting Framework (GDI+) similar 14 to the interface pattern examined at the opening of this chapter. To understand the connection, Chapter 15 -down Programming with Windows Controlsmethod generated for the NewCarDelegate type: let's break the parameters to the Forms BeginInvoke() Chapter 16 - The System.IO Namespace Chapter 17 IAsyncResult - Data Access withBeginInvoke( ADO.NET public Part Five Applications and XML Web Services Car- Web carToDetail,
// All delegate parameters are listed first. // A standard delegate for the callback. Chapter - ASP.NET Web Applications //19Allows the calling thread to pass information to the callback. Chapter object 20 - XML state Web Services ); Index Chapter 18 - ASP.NET Web Pages and Web Controls System.AsyncCallback callback,
List of Figures 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 an 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# and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen // The delegate. Apress © 2003 (1200 pages) public delegate string NewCarDelegate(Car carToDetail); This comprehensive text starts with a brief overview of the public class Car{...} C# language and then quickly moves to key technical and class App architectural issues for .NET developers. { public static void DetailCarCallBack(IAsyncResult itfAR) { Table of Contents Console.WriteLine("DetailCarCallBack on thread {0}", C# and the .NET Platform, Second Edition Thread.CurrentThread.GetHashCode()); Introduction Getthe message from DetailCar(). Part One - Introducing// C# and .NET Platform 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)); Part Two - The C# Programming Language } Chapter 3 - C# Language Fundamentals public static string DetailCar(Car c) Chapter 4 - Object-Oriented Programming with C# { Chapter 5 - Exceptions and Object Lifetime // Detail car for 10 seconds. Chapter 6 - Interfaces and Collections Console.WriteLine("Detailing car on thread {0}", Chapter 7 - Callback Interfaces, Delegates, and Events Thread.CurrentThread.GetHashCode()); Chapter 8 - AdvancedThread.Sleep(10000); C# Type Construction Techniques Part Three - Programming with .NET Assemblies return "Your car is ready!"; Chapter 9 - Understanding .NET Assemblies } Chapter 10 - Processes, Contexts, and Threads static AppDomains, void Main(string[] args) Chapter 11 - Type { Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging Console.WriteLine("Main() the .NET Libraries is on thread {0}", Chapter 12 - Object Serialization and the .NET Remoting Layer Thread.CurrentThread.GetHashCode()); Chapter 13 - Building aNewCarDelegate Better Window (Introducing d = new Windows NewCarDelegate(DetailCar); Forms) Car myCar = new Car(); Chapter 14 - A Better Painting Framework (GDI+) // Call asynchronously via callback. Chapter 15 - Programming with Windows Forms Controls d.BeginInvoke(myCar, new AsyncCallback(DetailCarCallBack), null); Chapter 16 - The System.IO Namespace Console.WriteLine("Done invoking delegate"); Chapter 17 - Data Access with ADO.NET // Keep console alive until call completes. Part Five - Web Applications and XML Web Services Console.ReadLine(); Chapter 18 - ASP.NET Web Pages and Web Controls } Chapter 19 - ASP.NET Web Applications } Chapter 20 - XML Web Services } Index
List of Figures 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# and the .NET Platform, Second Edition
Recall that the DetailCar() method returns a string message that informs the user that the operation has ISBN:1590590554 by Andrew Troelsen completed. In theApress previous interaction of this example, Main() directly called EndInvoke() to obtain the return © 2003 (1200 pages) value of the "method pointed to" by the NewCarDelegate. However, now that the delegate will call This comprehensive text starts with a brief overview of the DetailCarCallBack() at some time in the future,moves this method needs toand be the entity in charge of this task. C# language and then quickly to key technical architectural issues for .NET developers.
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 defines numerous types used when leveraging the .NET Remoting layer, as you will see later in this text). Once Table of Contents you have handle to theSecond delegate that is calling your callback method, you are able to indeed call EndInvoke() to C# and the a.NET Platform, Edition obtain the textual message from DetailCar(). Introduction Part One - Introducing C# and the .NET Platform
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 Part Two is - The Programming Language pattern usedC#when invoking file access
Chapter 3
methods, remote types, XML Web services, and whatnot.
- C# Language Fundamentals
SOURCE The AsyncCallbackDelegate Chapter 4 - Object-Oriented Programming with C# project is located under the Chapter 7 subdirectory. CODE Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and(and the .NET Platform, Second Edition Understanding Using) Events by Andrew Troelsen
ISBN:1590590554
Delegates are fairly interesting constructs Apress © 2003 (1200 pages) because you can resolve the name of a function to call at runtime, rather than at compile time. Admittedly, syntactic take a bit of getting used to. However, This comprehensive textthis starts with a orchestration brief overview can of the because the ability for one object to call back to another object is such a C# language and then quickly moves to key technical and helpful construct, C# provides the architectural forof.NET developers. "event" keyword to lessen theissues burden using delegates in the raw. The most prevalent use of the "event" keyword would be found in GUI-based applications, in which Button, Table TextBox, of Contents and Calendar 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 the .NET Platform, Second Edition helpful when creating non-GUI-based projects (as you will now see). Introduction Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language 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
- Object-Oriented Programming with C#
Chapter 5 - Exceptions andtoObject Lifetime Let's reconfigure the Car send two events to those who happen to be listening. The first event Chapter (AboutToBlow) 6 - Interfaces will be and sentCollections when the current speed is 10 miles below the maximum speed. The second event
(Exploded) be sent when the user attempts to speed up a car that is already dead. Establishing an event is Chapter 7 - will Callback Interfaces, Delegates, and Events a two-step you need to defineTechniques a delegate, which will be used to hold onto the set of methods Chapter 8 -process. AdvancedFirst, C# Type Construction thatThree will be- Programming called when the event Next, Part with .NEToccurs. Assemblies
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 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
// This 'talk back' toand the user. Chapter 11 -car Type can Reflection, Late Binding, Attribute-Based Programming public Carthe .NET Libraries Part Four - class Leveraging { Chapter 12 - Object Serialization and the .NET Remoting Layer ... 13 - Building a Better Window (Introducing Windows Forms) Chapter the Painting car alive or dead? Chapter // 14 -Is A Better Framework (GDI+) bool carIsDead; Chapter private 15 - Programming with Windows Forms Controls // Holds the function(s) to call when the event occurs. public delegate void EngineHandler(string msg); Chapter 17 - Data Access with ADO.NET // This car can send these events. Part Five - Web Applications and XML Web Services public static event EngineHandler Exploded; Chapter 18 - ASP.NET Web Pages and Web Controls public static event EngineHandler AboutToBlow; Chapter 19 - ASP.NET Web Applications ... Chapter 20 - XML Web Services } Chapter 16 - The System.IO Namespace
Index List of Figures 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; and thedead? .NET Platform, Second // C# Almost Send about toEdition blow event. ISBN:1590590554 by Andrew Troelsen if(10 == maxSpeed - currSpeed) Apress © 2003 (1200 pages) if(AboutToBlow != null) This comprehensive text starts with a brief approaching overview of the terminal speed!"); AboutToBlow("Careful, C# language and then quickly moves to key technical and // Still OK! Proceed as usual. architectural issues for .NET developers. if(currSpeed >= maxSpeed) carIsDead = true; else Table of Contents Console.WriteLine("\tCurrSpeed = {0} ", currSpeed); C# and the .NET Platform, Second Edition } Introduction } Part One - Introducing C# and the .NET Platform
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 Part - The C# Programming Language the Two usage of this new automobile in just a
Chapter detail. 3
moment, but first, let's check the event architecture in a bit more
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# Note how you checking the event against a null object reference before firing. This is to ensure Chapter 5 Notice - Exceptions andare Object Lifetime
if the caller not register to listen to a given event, it is not sent into sweet oblivion. Chapter 6 that - Interfaces and did Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Events- Under Advanced the C# Type Hood Construction Techniques
Chapter 8
Part Three - Programming with .NET Assemblies
A given9event actually expands into two hidden public functions, one having an "add_" prefix, the other having Chapter - Understanding .NET Assemblies a "remove_" prefix. ForAppDomains, example, theContexts, Exploded event expands to the following methods: Chapter 10 - Processes, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Four The - following expands Part Leveraging theevent .NET Libraries
in CIL code to:
// add_Exploded() Chapter 12 - Object Serialization and the .NET Remoting Layer // remove_Exploded() Chapter 13 - Building a Better Window (Introducing Windows Forms) public Chapter 14 static - A Betterevent PaintingEngineHandler Framework (GDI+) Exploded; Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 -toData Access with ADO.NET In addition defining hidden add_XXX() and remove_XXX() methods, each event also actually maps to a Part Fiveclass, - Webwhich Applications and XML Web Services private associates the corresponding
delegate to a given event. In this way, when an event is
Chapter - ASP.NET Pages and Webdelegate Controls 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 Applications broadcast event to multiple event sinks. To illustrate, check out Figure 7-8, which shows the Car type as Chapter 20 - XML seen through theWeb eyesServices of ildasm.exe. Index List of Figures List of Tables
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter Figure 6 - 7-8: Interfaces Asynchronous and Collections invocations via callbacks Chapter 7
- Callback Interfaces, Delegates, and Events
As you 8can- see, each C# event (Exploded and Techniques AboutToBlow) is internally represented as the following members: Chapter Advanced Type Construction Part Three - Programming with .NET Assemblies
A private class
Chapter 9
- Understanding .NET Assemblies
Chapter - Processes, AppDomains, Contexts, and Threads An10 add_XXX() method Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
A remove_XXX() method Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
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 Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
.method public hidebysig specialname static void add_AboutToBlow(class CarEvents.Car/EngineHandler 'value') Chapter 17 - Data Access with ADO.NET cil managed synchronized Part Five - Web Applications and XML Web Services { Chapter - ASP.NET and(0x16) Web Controls //18Code sizeWeb Pages22 Chapter 19 - ASP.NET2Web Applications .maxstack Chapter 20 - XML Web Services IL_0000: ldsfld class CarEvents.Car/EngineHandler CarEvents.Car::AboutToBlow IndexIL_0005: ldarg.0 List ofIL_0006: Figures 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 System.IO Namespace
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# and the .NET CarEvents.Car/EngineHandler Platform, Second Edition IL_0000: ldsfld class CarEvents.Car::AboutToBlow ISBN:1590590554 by Andrew Troelsen IL_0005: ldarg.0 Apress class © 2003 (1200 pages) IL_0006: call [mscorlib]System.Delegate This comprehensive text starts with a brief overview of the [mscorlib]System.Delegate::Remove C# language and then quickly moves to key[mscorlib]System.Delegate) technical and (class [mscorlib]System.Delegate, class architectural issues for .NET developers. IL_000b: castclass CarEvents.Car/EngineHandler IL_0010: stsfld class CarEvents.Car/EngineHandler CarEvents.Car::AboutToBlow Table of Contents IL_0015: ret C# and the .NET Platform, Second Edition } // end of method Car::remove_AboutToBlow Introduction
Part One - Introducing C# and the .NET Platform
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): Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals .event CarEvents.Car/EngineHandler AboutToBlow
Chapter 4 {
- Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime .addon void CarEvents.Car::add_AboutToBlow(class CarEvents.Car/EngineHandler) Chapter 6 Interfaces and Collections .removeon void CarEvents.Car::remove_AboutToBlow Chapter (class 7 - Callback Interfaces, Delegates, and Events CarEvents.Car/EngineHandler) Chapter 8 - Advanced C# Car::AboutToBlow Type Construction Techniques } // end of event Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies So, now you understand how toContexts, build a class can send events, the next big question is how you can Chapter 10that - Processes, AppDomains, and that Threads
configure object to receive these events. Chapter 11 an - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Listening to Incoming Events
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Assume now created an instance of the Car class and wish to listen to the events it is capable of Chapter 14you - Ahave Better Painting Framework (GDI+) sending. goal is to create a methodForms that represents Chapter 15The - Programming with Windows Controls 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 with ADO.NET cannot call the CIL add_XXX() and remove_XXX() directly, but rather use the overloaded += and -= operators. Part Five - Web Applications and XML Web Services Thus, when you wish to listen to an event, follow the pattern shown here: Chapter 16 - The System.IO Namespace
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
// I'm listening... // ObjectVariable.EventName += new ObjectVariable.DelegateName(functionToCall); Index Car.Exploded += new Car.EngineHandler(OnBlowUp); Chapter 20 - XML Web Services List of Figures 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# and the .NET Second Edition Car.Exploded += Platform, new Car.EngineHandler(OnBlowUp); ISBN:1590590554 by Andrew Troelsen Car.AboutToBlow += new Car.EngineHandler(OnAboutToBlow); Apress © 2003 (1200 pages) // Speed up (this will generate the events.) This comprehensive startsi++) with a brief overview of the for(int i = 0; i text < 10; C# language and then quickly moves to key technical and c1.SpeedUp(20); architectural issues for .NET developers. // Detach from events. Car.Exploded -= new Car.EngineHandler(OnBlowUp); Car.Exploded -= new Car.EngineHandler(OnAboutToBlow); Table of Contents // No response! C# and the .NET Platform, Second Edition for(int i = 0; i < 10; i++) Introduction c1.SpeedUp(20); Part One - Introducing C# and the .NET Platform return 0; Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications // OnBlowUp event sink. Part Two - The C# Programming Language public static void OnBlowUp(string s) Chapter 3 - C# Language Fundamentals { Chapter Console.WriteLine("Message 4 - Object-Oriented Programming withfrom C# car: {0} ", s); Chapter 5 Exceptions and Object Lifetime } Chapter // 6 -OnAboutToBlow Interfaces and Collections event sink. Chapter public 7 - Callback Interfaces, and Events static voidDelegates, OnAboutToBlow(string s) Chapter { 8 - Advanced C# Type Construction Techniques Part Three - Programming Console.WriteLine("Message with .NET Assemblies from car: {0} ", s); Chapter } 9 - Understanding .NET Assemblies } Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
If you wish to have multiple event sinks called by a given event, simply repeat the process:
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
// Multiple event sinks. Chapter 14 - A Better Painting Framework (GDI+) public class CarApp { Chapter 16 - The System.IO Namespace public static int Main(string[] args) Chapter 17 - Data Access with ADO.NET { Part Five - Web Applications and XML Web Services // Make a car as usual. Chapter 18 - ASP.NET Web Pages and Web Controls Car c1 = new Car("SlugBug", 100, 10); Chapter 15 - Programming with Windows Forms Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML // Web HookServices into events. Index Car.Exploded += new Car.EngineHandler(OnBlowUp); List of Figures 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# and the .NET Platform, Edition { Console.WriteLine("AGAIN I Second say: {0} ", s); } ISBN:1590590554 by Andrew Troelsen // OnAboutToBlow event sink. Apress © 2003 (1200 pages) public static void OnAboutToBlow(string s) This comprehensive text startsfrom with acar: brief overview the } { Console.WriteLine("Message {0} ",ofs); C# language and then quickly moves to key technical and architectural issues for .NET developers.
}
Now, when the Exploded event is sent, the associated delegate calls OnBlowUp() as well as OnBlowUp2(), as shown in Figure 7-9.
Table of Contents
C# and the .NET Platform, Second Edition Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Figure 7-9: Hooking into the engine events
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Note .NET 2003 further event handling. When you apply the + syntax to an object's event, Chapter 11 VS - Type Reflection, Late simplifies Binding, and Attribute-Based Programming you may use the TabLibraries key to automatically generate Part Four - Leveraging the .NET
the delegate target.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Objects As Event Sinks
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
At this point, you have thewith background buildControls objects that can participate in a two-way conversation. Chapter 15 - Programming Windows to Forms However, that you are free to build a helper object to respond to an object's event set, much in the Chapter 16 understand - The System.IO Namespace same way you created helper class to be called by all delegates. For example, let's move your event Chapter 17 -that Data Access withaADO.NET sinkFive methods of the CarApp class and into a new class Part - Web out Applications and XML Web Services
named CarEventSink:
Chapter 18 - ASP.NET Web Pages and Web Controls
// Car sink Chapter 19 event - ASP.NET Web Applications public CarEventSink Chapter 20 class - XML Web Services { Index // OnBlowUp event handler. List of Figures 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# and the .NET Platform, Second Edition public static int Main(string[] args) by Andrew Troelsen {
ISBN:1590590554
Apress © 2003 (1200 pages) text starts with a100, brief overview CarThis c1comprehensive = new Car("SlugBug", 10); of the C# language and then quickly moves to key technical and // Make the sink object. architectural issues for .NET developers. CarEventSink sink = new CarEventSink(); // Hook into events using sink object. Car.Exploded += new Car.EngineHandler(sink.OnBlowUp); Table of Contents Car.Exploded += new Car.EngineHandler(sink.OnBlowUp2); C# and the .NET Platform, Second Edition Car.AboutToBlow += new Car.EngineHandler(sink.OnAboutToBlow); Introduction for(int i = 0; i < 10; i++) Part One - Introducing C# and the .NET Platform 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); Part Two - The C# Programming Language Car.Exploded -= new Car.EngineHandler(sink.OnBlowUp2); Chapter 3 - C# Language Fundamentals Car.Exploded -= new Car.EngineHandler(sink.OnAboutToBlow); Chapter 4 - Object-Oriented return 0; Programming with C# Chapter } 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections } Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
TheThree output is (of course) with identical. Part - Programming .NET Assemblies Chapter 9
- Understanding .NET Assemblies
SOURCE CODE
The CarEvents project is located under the Chapter 7 subdirectory.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
In this chapter, you have©examined a number of ways in which multiple objects can partake in a Apress 2003 (1200 pages) bidirectional conversation under .NET. First, you examined the use of interfaces, which provide a This comprehensive text starts with a brief overview 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 moves to key technical and architectural for .NET developers. pattern is not specific to .NET,issues but may be employed in any language or platform that honors the use of interface types. Table Next,ofyou Contents examined 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 the .NET Platform, Second Edition methods to call when told to do so. These invocations may be made synchronously (using the Invoke() Introduction method) asynchronously BeginInvoke() Part One - or Introducing C# and(via the the .NET Platform 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, Part Two - The C# Programming Language 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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
the .NET Platform, Second Edition Chapter C# 8:and Advanced C# Type Construction ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) Techniques This comprehensive text starts with a brief overview of the C#up language and then quickly to key technical and by examining a number of This chapter wraps our investigation of the moves C# programming language architectural issues for .NET developers. 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 Table of Contents create an "unsafe" code context in order to directly manipulate pointer types using C#. C# and the .NET Platform, Second Edition
Introduction Next, you learn how to construct and use an indexer method. This C# mechanism enables you to build Part One -types Introducing C# and the .NET Platform custom that expose internal subtypes using
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 Part Two - The C#, and so forth) and create
custom conversion functions (the C# equivalent to
Chapter overloading 3 - C# theLanguage () operator Fundamentals under C++) for a type. Chapter 4
- Object-Oriented Programming with C#
- Exceptions and Object Lifetime The Advanced Keywords of C#
Chapter 5 Chapter 6
- Interfaces and Collections Over the of the previousDelegates, seven chapters, you have seen a majority of the C# keywords in action. In Chapter 7 course - Callback Interfaces, and Events
addition8 to-those already C# does have a set of lesser used, but still intriguing, keywords, Chapter Advanced C# investigated, Type Construction Techniques specifically Part Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
"checked"/"unchecked"
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming "unsafe"/"stackalloc"/"fixed"/"volatile"/"sizeof" Part Four - Leveraging the .NET Libraries
"lock" Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
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 - Programming with Windows Forms Controls "unsafe", "stackalloc", "fixed", "volatile", and "sizeof") will be the focus of the first part of this chapter. To Chapter 16 - The System.IO Namespace start, let's check out how C# provides automatic detection of arithmetic overflow (and underflow). Chapter 14 - A Better Painting Framework (GDI+)
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
The "checked" Keyword
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
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 Index operations on a specific type, it is very possible that you may accidentally overflow the maximum storage List of Figures of the type (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 Services
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# and the .NET Platform,value Secondof Edition Console.WriteLine("Max byte is {0}.", byte.MaxValue); by Andrew Troelsen Console.WriteLine("Min value of byteISBN:1590590554 is {0}.", byte.MinValue); (1200 pages) byteApress b1 =© 2003 100; text starts with a brief overview of the byteThis b2comprehensive = 250; C# language and then moves to key technical and byte b3 = (byte)(b1quickly + b2); architectural issues for .NET developers. // b3 should hold the value 350, however... Console.WriteLine("b3 = {0}", b3); }
Table of Contents
}
C# and the .NET Platform, Second Edition
}
Introduction Part One - Introducing C# and the .NET Platform
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 Part Two - 0 The C#255 Programming Language between and (inclusive, for 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 Object-Oriented Programming with cause C# exception. times, this hidden overflow may no harm whatsoever in your project. Other times, this Chapter loss of 5data - Exceptions is completely andunacceptable. Object Lifetime Chapter 6
- Interfaces and Collections
To handle-overflow or underflow conditions in your application, you have two possibilities. Your first choice Callback Interfaces, Delegates, and Events is to leverage your wits and programming skills to handle all overflow conditions manually. Assuming you Chapter 8 - Advanced C# Type Construction Techniques were indeed able to find each overflow condition in your program, you could resolve the previous overflow Part Three - Programming with .NET Assemblies error as follows: Chapter 7
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
// Store sum in an integer to prevent overflow. byte b1 = 100; Part Four - Leveraging the .NET Libraries byte b2 = 250; Chapter 12 - Object Serialization and the .NET Remoting Layer int answer = b1 + b2;
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Chapter 16 -the Theproblem System.IO Of course, withNamespace this technique is the simple fact that we are humans, and even our best Chapter 17may - Data Access with ADO.NET attempts result in errors that have escaped our eyes. Given this, C# provides the "checked" keyword. Part Fiveyou - Web Applications and Web When wrap a statement (orXML block of Services statements)
within the scope of the "checked" keyword, the C#
Chapter compiler 18will - ASP.NET emit specific Web Pages CIL instructions and Web Controls that 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 WeborApplications throw a20 System.OverflowException type. To illustrate, observe the following update: Chapter - XML Web Services Index List class of Figures TheChecker
{ 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# and the .NET Platform, Second Edition
Here, you wrap the addition of b1 and b2 within the scope of the "checked" keyword. If you wish to force ISBN:1590590554 Troelsen overflow checkingbytoAndrew occur over a block of code, you can interact with the "checked" keyword as follows: Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
try {
checked { Table of Contents byte b3 = (byte)(b1 + b2); byte b4, b5 = 100, b6 = 200; C# and the .NET Platform, Second Edition Introduction b4 = (byte)(b5 + b6); Console.WriteLine("b3 = {0}", b3); Part One - Introducing C# and the .NET Platform Chapter}1 - The Philosophy of .NET } Chapter 2 - Building C# Applications catch(OverflowException e) Part Two - The C# Programming Language { Chapter 3 - C# Language Fundamentals Console.WriteLine(e.Message); Chapter 4 - Object-Oriented Programming with C# } Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter - Callback Interfaces, Delegates, Events for possible overflow conditions automatically, which In either7 case, the code in question will beand evaluated Chapter 8 -an Advanced Type Construction Techniques will trigger overflowC# exception. Part Three - Programming with .NET Assemblies
Chapter 9 -Project-Wide Understanding .NET Assemblies Setting Overflow Checking Chapter 10 - Processes, AppDomains, Contexts, and Threads
Now, if 11 you- are an application that should never allow silent overflow to occur, you may find Chapter Typecreating Reflection, Late Binding, and Attribute-Based Programming yourself the annoying of wrapping numerous Part Four -inLeveraging the position .NET Libraries
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 - Object Serialization and the .NET Remoting Layer arithmetic will be evaluated for overflow without the need to make use of the C# "checked" keyword. If Chapter 13 - Building a Better Window (Introducing Windows Forms) overflow has been discovered, you will still receive a runtime exception. To enable this flag under VS Chapter 14 - A Better Painting Framework (GDI+) .NET, activate the Check for Arithmetic Overflow/Underflow option from the project's property page Chapter 15 - Programming with Windows Forms Controls (Figure 8-1). Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition where silent overflow is acceptable? Given that the /checked flag will evaluate all arithmetic logic, the C# ISBN:1590590554 bythe Andrew Troelsen keyword to disable the throwing language provides "unchecked" of System.OverflowException on a Apress © 2003 (1200 pages) case-by-case basis. The use of this keyword is identical to the "checked" keyword in that you can specify a text starts with a brief overview of the single statement This or a comprehensive block of statements. For example: C# language and then quickly moves to key technical and architectural issues for .NET developers.
// Assuming +checked is enabled, // this block will not trigger // a Table of runtime Contents exception. unchecked C# and the .NET Platform, Second Edition { Introduction byte b3 = (byte)(b1 + b2); Part One - Introducing C# and the .NET Platform Console.WriteLine("b3 Chapter 1 - The Philosophy of .NET = {0}", b3); } Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
So, to summarize the C# "checked" and "unchecked" keywords, recall that the default behavior of the - Object-Oriented Programming with C# .NET runtime is to ignore arithmetic overflow. When you want to selectively handle discrete statements, Chapter 5 and Object Lifetime make use -ofExceptions the "checked" keyword. If you wish to trap overflow errors throughout your application, enable Chapter 6 Interfaces 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 Interfaces, and Events overflow (and thusDelegates, should not trigger a runtime exception). Chapter 4
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Regarding Underflow Conditions - Understanding .NET Assemblies
Chapter 9
Chapter - Processes, Contexts, 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 Attribute-Based Programming Rather, in the event of an underflow condition, the runtime will again throw an OverflowException: Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
// Underflow conditions also trigger an OverflowException!
Chapter try 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) { Chapterbyte 15 - Programming a = 9, b =with 9;Windows Forms Controls Chapterbyte 16 - The Namespace c =System.IO (byte)(a + b + -100); // c is less than zero! Chapter 17 - Data Access with ADO.NET } Part Five - Web Applications and XML Web Services catch(OverflowException e){Console.WriteLine(e);}
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
SOURCE CODE
Index
The CheckedUnchecked project can be found under the Chapter 8 subdirectory.
List of Figures 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# and the Meaning in Life .NET Platform, Second Edition Centric by Andrew Troelsen Operator Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the Used to create a pointer variable, a variable that represents a direct C# language and then quickly moves to key technical and location memory. Like C(++), this same operator is used to represent architectural issuesinfor .NET developers.
*
pointer indirection. &
Table of Contents
Used to obtain the address of a pointer.
C#–> and the .NET Platform, Second This operator Edition is used to access fields of a type that is represented by a Introduction
pointer variable (the unsafe version of the C# dot operator).
Part One - Introducing C# and the .NET Platform
[]
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
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4 - Object-Oriented C#out the fact that you will seldom ifever need to make use Now, before we dig into the Programming details, let mewith point Chapter of the techniques 5 - Exceptions we are and about Object to Lifetime examine. 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 - Interfaces and Collections you mismanage a pointer, you are the oneand in charge Chapter 7 - Callback Interfaces, Delegates, Events 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 Construction Techniques Table 8-1)? There are two common situations: Part Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
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 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four Leveraging theto .NET Libraries You -are attempting trigger the functionality of
a C-based *.dll (such as the Win32 API or a custom
Chapter 12 - Object the pointer .NET Remoting Layer C-based *.dll) Serialization and need to and create variables to call various methods. Chapter 13 - Building a Better Window (Introducing Windows Forms)
Beyond14these two reasons, will never be a need to declare, dereference, or manipulate direct Chapter - A Better Paintingthere Framework (GDI+)
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 System.IO Namespace the /unsafe flag. From VS .NET, you will need to access your project's Property page and enable the Chapter 17 - Data Access with ADO.NET Allow Unsafe Code Blocks setting (Figure 8-2). Chapter 15 - Programming with Windows Forms Controls
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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 and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
When you wish to work with pointers in C#, you must specifically declare a block of "unsafe" code using Apress © 2003 (1200 pages) the "unsafe" keyword (as you might guess, any code that is not marked with the "unsafe" keyword is This comprehensive text starts with a brief overview of the considered "safe"C# automatically, thus there is not a "safe" keyword in C#): language and then quickly moves to key technical and architectural issues for .NET developers.
unsafe { Table of// Contents Work with pointers here! C# } and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language
// This structure is 'unsafe' and can Chapter 3 -entire C# Language Fundamentals // only used in an unsafe context. Chapter 4 -be Object-Oriented Programming with C# public struct Node Lifetime Chapter 5 unsafe - Exceptions and Object { Chapter 6
- Interfaces and Collections int Interfaces, Value; Delegates, and Events Chapterpublic 7 - Callback
public Node* Left; - Advanced C# Type Construction Techniques public Node* Right; Part Three - Programming with .NET Assemblies } Chapter 9 - Understanding .NET Assemblies // This struct is safe, but the Node* members Chapter 10 - Processes, AppDomains, Contexts, and Threads // are not. Technically, you may access 'Value' from Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming // outside a unsafe context, but not 'Left' and 'Right'. Part Four - Leveraging the .NET Libraries public struct Node Chapter 12 - Object Serialization and the .NET Remoting Layer { Chapterpublic 13 - Building Better Window (Introducing Windows Forms) int aValue; Chapter// 14 These - A Better Painting (GDI+) in an unsafe context! can onlyFramework be accessed Chapterpublic 15 - Programming with Windows unsafe Node* Left;Forms Controls Chapterpublic 16 - Theunsafe System.IO Namespace Node* Right; Chapter 17 - Data Access with ADO.NET } Chapter 8
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Methods or instance level) may be marked as unsafe as well. For example, assume that you know Chapter 19(static - ASP.NET Web Applications a given20 static method will make use of pointer logic. To ensure that this method can only be called from an Chapter - XML Web Services unsafe context, you could define the method as follows:
Index
List of Figures
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# and the .NET Platform, Second Edition
public static void SomeUnsafeCode() ISBN:1590590554 by Andrew Troelsen { Apress © 2003 (1200 pages) unsafe This comprehensive text starts with a brief overview of the { C# language and then quickly moves to key technical and // Work with pointers here! architectural issues for .NET developers. } } Table of Contents C# and the .NET Platform, Second Edition Introduction
which would simplify the call to:
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET static Main() Chapter 2 void - Building C# Applications
{ Two - The C# Programming Language Part SomeUnsafeCode(); - C# Language Fundamentals
Chapter 3
}
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
Interfaces and Collections Working- with the * and & Operators
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8 -have Advanced C# Type Techniques Once you established an Construction unsafe context, you are then free to build pointers to data types using the * Part Three as - Programming Assemblies operator well as obtainwith the .NET address of said
pointer using the & operator. Using C#, the * operator is
Chapter Understanding .NETonly, Assemblies applied9to -the underlying type not as a prefix to each pointer variable name. For example, the Chapter following 10 declares - Processes, two AppDomains, variables, both Contexts, of type int* and (a Threads pointer to an integer). Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Leveraging the .NET Libraries // Four No! - This is incorrect under
C#!
Chapter 12 - Object int *pi, *pj; Serialization and the .NET Remoting Layer Chapter 13 -This Building Window Windows Forms) // Yes! isa Better the way of (Introducing C#. Chapter int* pi, 14 - Apj; Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Given this, check out the following example:
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
unsafe Chapter 18 - ASP.NET Web Pages and Web Controls { Chapter 19 - ASP.NET Web Applications myInt; Chapter int 20 - XML Web Services // Define an int pointer, and // assign it the address of myInt. List of Figures 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); } Index
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# and the .NET Platform, Second Edition by Andrew Troelsen *j = temp;
ISBN:1590590554
Apress © 2003 (1200 pages)
}
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
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:
Table of Contents
C# and the .NET Platform, Second Edition
public static void SafeSwap(ref int i, ref int j) { Part One - Introducing C# and the .NET Platform int temp = i; Chapter 1 - The Philosophy of .NET i = j; Chapter 2 - Building C# Applications j = temp; Part Two - The C# Programming Language } Introduction
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object is Lifetime The functionality of each method identical, thus reinforcing the point that direct pointer manipulation is Chapter not a mandatory 6 - Interfaces task under and Collections C#. Chapter 7
- Callback Interfaces, Delegates, and Events
Field 8Access via C# Pointers (the –>Techniques Operator) Chapter - Advanced Type Construction Part Three - Programming with .NET Assemblies
Now assume that you have a Point structure and wish to declare a pointer to a Point type. Like C(++), - Understanding .NET Assemblies when you wish to invoke methods or trigger fields of a pointer type, you will need to make use of the Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming (safe) dot operator (.). In fact, using the pointer indirection operator (*), it is possible to dereference a Part Four - Leveraging the .NET Libraries pointer to (once again) apply the dot operator notation. Check out the following: Chapter 9
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
struct Point { Chapter 15 - Programming with Windows Forms Controls public int x; Chapter 16 - The System.IO Namespace public int y; Chapter public 17 - Data override Access with ADO.NET string ToString() Part Five{- Web Applications Web return "(" + and x +XML "," + Services y + ")"; } Chapter 18 ASP.NET Web Pages and Web Controls } Chapter 19 void - ASP.NET Web Applicationsargs) static Main(string[] Chapter 20 - XML Web Services { Index // Access members via pointer. List of Figures unsafe { 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 Painting Framework (GDI+)
} C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive The "stackalloc" Keyword text starts with a brief overview of the C# language and then quickly moves to key technical and
architectural .NET developers. In an unsafe context, you mayissues need for to declare a local 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 Table of Contents example: C# and the .NET Platform, Second Edition Introduction
unsafe {
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
char* p = stackalloc char[256]; - Building C# Applications for (int k = 0; k < 256; k++) Part Two - The C# Programming Language p[k] = (char)k; Chapter 3 - C# Language Fundamentals } Chapter 2
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6 -aInterfaces andthe Collections Pinning Type via "fixed" Chapter 7
Keyword
- Callback Interfaces, Delegates, and Events
As seen previous allocatingTechniques a chunk of memory within an unsafe context may be facilitated Chapter 8 in-the Advanced C#example, Type Construction via Three the "stackalloc" keyword. theAssemblies very nature Part - Programming with By .NET
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 - Understanding .NET Assemblies assume a more complex example. During our examination Chapter 10 - Processes, AppDomains, Contexts, and Threads of the –> operator, you created a value type named11 Point. LikeReflection, all value Late types, the allocated memory is popped off the stack once the executing scope Chapter - Type Binding, and Attribute-Based Programming has terminated. For the sake of argument, assume Point was instead defined as a reference type: Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
class13Point // a are overloaded as a Part Three - Programming with .NET Assemblies set. The same holds true for the = operators. If the Car type you developed in Chapter 6 Chapter 9 - Understanding .NET Assemblies overloaded these comparison operators, the object user could now compare types as follows: Chapter 7
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Exercise the overloaded < operator for the Car class. public class CarApp Chapter 12 - Object Serialization and the .NET Remoting Layer { Chapter 13 - Building a Better Window (Introducing Windows Forms) public static int Main(string[] args) Chapter 14 - A Better Painting Framework (GDI+) { Chapter 15 - Programming with Windows Forms Controls // Make an array of Car types. Chapter 16 - The System.IO Namespace Car[] myAutos = new Car[5]; Chapter 17 - Data Access with myAutos[0] ADO.NET = new Car(123, "Rusty"); Part Five - WebmyAutos[1] Applications and Services = XML newWeb Car(6, "Mary"); Chapter 18 - ASP.NET Web Pages and Web Controls myAutos[2] = new Car(6, "Viper"); Chapter 19 - ASP.NET Web Applications myAutos[3] = new Car(13, "NoName"); Chapter 20 - XML Web Services= new Car(6, "Chucky"); myAutos[4] Part Four - Leveraging the .NET Libraries
Index List of Figures // 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# and the .NET Platform, Second Edition { ISBN:1590590554 Andrew=Troelsen Carby temp (Car)o; Apress © 2003 (1200 pages) if(this.CarID > temp.CarID) Thisreturn comprehensive 1; text starts with a brief overview of the C# language and quickly moves to key technical and if(this.CarID (Car c1, Car c2) Chapter { 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming C# IComparable itfComp with = (IComparable)c1; Chapter 5 - Exceptions and Object Lifetime return (itfComp.CompareTo(c2) > 0); Chapter } 6 - Interfaces and Collections Chapter public 7 - Callback Interfaces, and =Forms) 0); Chapter 13 - Building a Better Window (Introducing Windows } Chapter 14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services SOURCE The ObjCompWithOps project
Chapter 18 - ASP.NET Web Pages and Web Controls CODE Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
is located under the Chapter 8 subdirectory.
and the .NET Platform,of Second Edition The InternalC#Representation Overloaded Operators by Andrew Troelsen
ISBN:1590590554
Like any C# programming element, overloaded operators are represented using specific CIL instructions. To Apress © 2003 (1200 pages) begin examining what takes place behind the scenes, openoverview up yourof OverLoadOps.exe assembly (created This comprehensive text starts with a brief the previously) using C# ildasm.exe. As you can see from Figure 8-3, the +, -, = =, and != operators are internally language and then quickly moves to key technical and architectural issues forin.NET expressed via hidden methods, which this developers. case are named op_Addition(), op_Subtraction(), op_Equality(), and op_Inequality(). Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - 8-3: TypeInternal Reflection, Binding, andofAttribute-Based Programming Figure CILLate representation overloaded operators Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
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 Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
.method public hidebysig specialname static valuetype OverLoadOps.Point op_Addition(valuetype OverLoadOps.Point p1, Chapter 17 - Data Access with ADO.NET valuetype OverLoadOps.Point p2) cil managed Part Five - Web Applications and XML Web Services { Chapter 18 - ASP.NET Web Pages and Web Controls ... Chapter 19 - ASP.NET Web Applications } Chapter 16 - The System.IO Namespace
Chapter 20 - XML Web Services Index
List of truth Figures The of the matter is that any operator that you may overload equates to a specially named method in 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# and the .NET Platform, Second Edition
Binary +
by Andrew Troelsen Apress © 2003 (1200 pages)
Binary -
This comprehensive text starts with a brief overview ofop_Subtraction() the C# language and then quickly moves to key technical and op_Multiply() architectural issues for .NET developers.
Binary *
op_OnesComplement() ISBN:1590590554
/
op_Division()
% of Contents Table C# and the .NET Platform, Second Edition
^
Introduction
Binary Part One -&Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
|
op_Addition()
&&Two - The C# Programming Language Part
op_Modulus() op_ExclusiveOr() op_BitwiseAnd() op_BitwiseOr() op_LogicalAnd()
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
= Chapter 5
- Exceptions and Object Lifetime
op_Assign()
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
op_LeftShift()
>> 8 Chapter
- Advanced C# Type Construction Techniques
||
Chapter 10 - Processes, AppDomains, Contexts, and Threads
op_LogicalOr()
op_RightShift() op_Equality() op_GreaterThan()
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming < op_LessThan() Part Four - Leveraging the .NET Libraries
!= Chapter 12 - Object Serialization and the .NET Remoting Layer
op_Inequality()
Chapter >= 13 - Building a Better Window (Introducing Windows Forms)
op_GreaterThanOrEqual()
Chapter 14 - A Better Painting Framework (GDI+)
op_MemberSelection()
Chapter 17 - Data Access with ADO.NET
>>= Part Five - Web Applications and XML Web Services
op_RightShiftAssignment()
Chapter *= 18 - ASP.NET Web Pages and Web Controls
op_MultiplicationAssignment()
Chapter 19 - ASP.NET Web Applications
->* 20 - XML Web Services Chapter
op_PointerToMemberSelection()
Index -=
op_SubtractionAssignment()
List of Figures
^=
op_ExclusiveOrAssignment()
PID: {0}\tName: {1}", Part One - Introducingp.Id, C# and the .NET Platform p.ProcessName); Chapter 1 - The Philosophy of .NET Console.WriteLine(info); Chapter } 2 - Building C# Applications Part TwoConsole.WriteLine("************************************\n"); - The C# Programming Language } Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Notice how the static Process.GetProcesses() method returns an array of Process types that represent the - Interfaces and Collections running processes on the target machine (the dot notation seen here represents the local computer).
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8 -have Advanced C# the Type Construction Techniques Once you obtained array of Process types, you are able to trigger any of the members seen in Part Three - Programming .NET Table 10-2. Here, simplywith dump theAssemblies process identifier
(PID) and the name of each process. Assuming the
Chapter 9 - Understanding .NET Assemblies Main() method has been updated to call this helper function, you will see something like the output in Figure Chapter 10-3. 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NETSorry...bad Platform, Second Edition} { Console.WriteLine("-> PID!"); by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Investigating a Process' Thread Set
Now that you understand how to gain access to a Process type, you are able to programmatically investigate the set of all threads currently alive in the process at hand. This set of threads is represented by Table of Contents the strongly typed ProcessThreadCollection collection, which contains any number of individual C# and the .NET Platform, Second Edition ProcessThread types. To illustrate, assume the following additional static helper function has been added Introduction to your current application: Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET public EnumThreadsForPid(int pID) Chapter 2 static - Buildingvoid C# Applications
{ Two - The C# Programming Language Part theProc; Chapter Process 3 - C# Language Fundamentals Chapter try 4 - Object-Oriented Programming with C#
= and Process.GetProcessById(pID); } Chapter { 5 theProc - Exceptions Object Lifetime Chapter catch 6 - Interfaces and Collections
{ - Callback Interfaces, Delegates, and Events Console.WriteLine("-> Sorry...bad PID!"); Chapter 8 - Advanced C# Type Construction Techniques Console.WriteLine("************************************\n"); Part Three - Programming with .NET Assemblies return; Chapter 9 - Understanding .NET Assemblies } Chapter 10 - Processes, AppDomains, Contexts, and Threads // List out stats for each thread in the specified process. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Console.WriteLine("Here are the thread IDs for: {0}", Part Four - Leveraging the .NET Libraries theProc.ProcessName); Chapter ProcessThreadCollection 12 - Object Serialization and the .NET Remoting Layer theThreads = theProc.Threads; Chapter foreach(ProcessThread 13 - Building a Better Window (Introducing Windows Forms) pt in theThreads) Chapter { 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls string info = Chapter 16 - The System.IO Namespace string.Format("-> Thread ID: {0}\tStart Time {1}\tPriority {2}", Chapter 17 - Data Access pt.Id with ADO.NET , pt.StartTime.ToShortTimeString(), pt.PriorityLevel); Part Five - Web Applications Console.WriteLine(info); and XML Web Services Chapter } 18 - ASP.NET Web Pages and Web Controls Chapter Console.WriteLine("************************************\n"); 19 - ASP.NET Web Applications } Chapter 20 - XML Web Services Chapter 7
Index List of Figures
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Figure 10-4: Enumerating the threads within a running process
Part Two - The C# Programming Language
Chapter 3 - C# Language The ProcessThread type Fundamentals has additional members of interest beyond Id, StartTime, and PriorityLevel. Table Chapter 10-3 documents 4 - Object-Oriented some members Programming of interest. with C# Chapter 5
- Exceptions and Object Lifetime
Table 10-3: Select Members of the ProcessThread Type Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Member of Meaning in Life Chapter 8 - Advanced C# Type Construction Techniques System.Diagnostics.ProcessThread Part Three - Programming with .NET Assemblies
Chapter BasePriority 9 - Understanding .NET Assemblies
Gets the base priority of the thread
Chapter 10 - Processes, AppDomains, Contexts, and Threads
CurrentPriority
Gets the current priority of the thread
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Id Four - Leveraging the .NET Libraries
Gets the unique identifier of the thread
Chapter 12 - Object Serialization and the .NET Remoting Layer
IdealProcessor
Sets the preferred processor for this thread to run on
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
PriorityLevel Chapter 15 - Programming with Windows Forms Controls Gets or sets the priority level of the thread Chapter 16 - The System.IO Namespace
ProcessorAffinity
Chapter 17 - Data Access with ADO.NET
Sets the processors on which the associated thread can run
Part Five - Web Applications and XML Web Services
StartAddress Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index StartTime List of Figures 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 and the .NET Platform, Second Edition property, you areC# able to enumerate over all modules in a process; .NET-based, COM-based, or traditional ISBN:1590590554 by Andrew Troelsen C-based binaries. Ponder the following helper function: Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
public staticC#void EnumModsForPid(int pID) language and then quickly moves to key technical and { architectural issues for .NET developers. Process theProc; try theProc = Process.GetProcessById(pID); } Table of { Contents catch C# and the .NET Platform, Second Edition { Introduction Console.WriteLine("-> Sorry...bad PID!"); Part One - Introducing C# and the .NET Platform Console.WriteLine("************************************\n"); Chapter 1 - The Philosophy of .NET return; Chapter 2 - Building C# Applications } Part Two - The C# Programming Language Console.WriteLine("Here are the loaded modules for: {0}", Chapter 3 - C# Language Fundamentals theProc.ProcessName); Chapter 4 - Object-Oriented Programming with C# try Chapter 5 - Exceptions and Object Lifetime { Chapter 6 - Interfaces and Collections ProcessModuleCollection theMods = theProc.Modules; Chapter 7 - Callback Interfaces, Delegates, and Events foreach(ProcessModule pm in theMods) Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies string info = string.Format("-> Mod Name: {0}", pm.ModuleName); Chapter 9 - Understanding .NET Assemblies Console.WriteLine(info); Chapter 10 - Processes, AppDomains, Contexts, and Threads } Chapter Console.WriteLine("************************************\n"); 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four} - Leveraging the .NET Libraries Chapter catch{Console.WriteLine("No 12 - Object Serialization and the .NET Remoting Layer mods!");} Chapter } 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
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 with ADO.NET PID assigned to ProcessManipulator.exe, and pass this value to the EnumModsForPid() method (be sure to Part Five - Web Applications and XML Web Services 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 Controls a simple console application (atl.dll, mfc42u.dll, oleaut32.dll and so forth.) Figure 10-5 shows a test run. Chapter 16 - The System.IO Namespace
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 10-5: Enumerating the loaded modules within a running process
C# and the .NET Platform, Second Edition Starting and Killing Processes Programmatically ISBN:1590590554 by Andrew Troelsen
2003 (1200 pages) The final aspectsApress of the ©System.Diagnostics.Process type examined here are the Start() and Kill() methods. This text starts with provide a brief overview the As you can gather by comprehensive their names, these members a way toofprogrammatically launch and terminate C# language and then quickly moves to key technical and a process. For example:
architectural issues for .NET developers.
public static void StartAndKillProcess() { of Contents Table // .NET Launch Internet Explorer. C# and the Platform, Second Edition Process ieProc = Process.Start("IExplore.exe", Introduction "www.intertech-inc.com"); Part One - Introducing C# and the .NET Platform 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. Part Two - The C# Programming Language try { ieProc.Kill(); } Chapter 3 - C# Language Fundamentals catch{} // In case user already killed it... Chapter 4 - Object-Oriented Programming with C# } Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7 -Process.Start() Callback Interfaces, Delegates, and Events The static method has been overloaded a few times, however. At minimum you will need to Chapter specify8the- friendly Advanced name C# Type of theConstruction process youTechniques wish to launch (such as MS Internet Explorer). This example Part makes Three use - Programming of a variation with of the.NET Start() Assemblies method
that allows you to specify any additional arguments to pass
into the9program's entry point (i.e., the Main() method). Chapter - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, 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 Part Four - Leveraging the .NET Libraries definition of ProcessStartInfo (see online Help for full details of this type): Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
public sealed class System.Diagnostics.ProcessStartInfo : object Chapter 15 - Programming with Windows Forms Controls { Chapter 16 - The System.IO Namespace public ProcessStartInfo(); Chapter 17 - Data Access with ADO.NET public ProcessStartInfo(string fileName); Part Five - Web Applications and XML Web Services public ProcessStartInfo(string fileName, string arguments); Chapter 18 - ASP.NET Web Pages and Web Controls public string Arguments { get; set; } Chapterpublic 19 - ASP.NET Applications boolWeb CreateNoWindow { get; set; } Chapterpublic 20 - XMLStringDictionary Web Services EnvironmentVariables { get; } Index public bool ErrorDialog { get; set; } List of Figures 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 Painting Framework (GDI+)
Regardless of which version of the Process.Start() method you invoke, do note that you are returned a C# and the .NET Platform, Second Edition reference to the newly activated process. When you wish to terminate the process, simply call the instance ISBN:1590590554 by Andrew Troelsen level Kill() method. Apress © 2003 (1200 pages)
SOURCE CODE
ProcessManipulator includedofunder ThisThe comprehensive text startsapplication with a briefisoverview the the Chapter 10 subdirectory. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, Second Edition Type Understanding System.AppDomain by Andrew Troelsen
ISBN:1590590554
Now that you understand how(1200 to interact Apress © 2003 pages) with a Win32 process from managed code, we need to examine more closely the new (but related) concept of astarts .NETwith application domain. of Asthe I mentioned briefly in the introduction, This comprehensive text a brief overview unlike a traditional (non-.NET) Win32 *.exe application, .NET assemblies C# language and then quickly moves to key technical and are hosted in a logical partition within issues for .NET aprocess termedarchitectural an application domain (akadevelopers. 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: Table of Contents
AppDomains are a key aspect of the OS-neutral nature of the .NET platform, given that this logical division C# and the .NET Platform, Second Edition abstracts away the differences in how an underlying operating system represents a loaded executable. Introduction Part One - Introducing C# and the .NET Platform
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
Part Two - The C# Programming Language
Chapter 3 - C# Language AppDomains provideFundamentals a deeper level of isolation for hosting a loaded application. If one AppDomain within a Chapter 4 - Object-Oriented Programming with C# process fails, the remaining AppDomains remain functional. Chapter 5
- Exceptions and Object Lifetime As suggested in the previous hit-list, a single process can host any number of AppDomains, each of which is Chapter 6 - Interfaces and Collections
fully and isolated from other AppDomains Chapter 7 completely - Callback Interfaces, Delegates, and Events 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 Construction Techniques any kind (global variables or static fields) unless they make use of the .NET Remoting protocol (examined in Part Three - Programming with .NET Assemblies Chapter 12) to marshal the data. Chapter 8 Chapter 9
- Understanding .NET Assemblies
Chapter 10 In - Processes, AppDomains, Contexts, and Threads Note some respects, .NET application domains are reminiscent of the "apartment" architecture of classic Chapter 11 COM. - TypeOf Reflection, Late Binding, and Attribute-Based course, .NET AppDomains are managedProgramming types whereas the COM apartment architecture is Part Four - Leveraging the .NET Libraries built on an unmanaged (and hideously
complex) structure.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Understand that while a single process may host Windows multiple AppDomains, this is not always the case. At the very Chapter 13 - Building a Better Window (Introducing Forms) least an14OS will hostFramework what is termed the default application domain. This specific application domain is Chapter - Aprocess Better Painting (GDI+) automatically created by the at theForms time the process launches. After this point, the CLR creates additional Chapter 15 - Programming withCLR Windows Controls
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 with ADO.NET given process using static methods of the System.AppDomain class. This class is also useful for low-level Part Five - Web Applications and XML Web Services control of application domains. Key members of this class are shown in Table 10-4. Chapter 16 - The System.IO Namespace
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Table 10-4: Select Members of AppDomain
Chapter 20 - XML Web Services
AppDomain Index
Meaning in Life
ListMember of Figures 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() Gets thePlatform, set of .NET assemblies C# and the .NET Second Editionthat have been loaded into this application domain. Unlike the Process type, the GetAssemblies() method will only ISBN:1590590554 by Andrew Troelsen return the list of true-blue .NET binaries. COM-based or C-based binaries are Apress © 2003 (1200 pages) ignored. This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and Used to dynamically load an assembly into the current application domain. architectural issues for .NET developers.
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).
Table of Contents
C# and the .NET Platform, Second Edition Introduction
Table 10-5: Events of the AppDomain Type
Part One - Introducing C# and the .NET Platform
Events Chapter 1 - of The Philosophy of .NET
Meaning in Life
System.AppDomain Chapter 2 - Building C# Applications Part Two - The C# Programming Language
AssemblyLoad
Chapter 3
Occurs when an assembly is loaded
- C# Language Fundamentals
Chapter AssemblyResolve 4 - Object-Oriented Programming Occurs with when C# the resolution of an assembly fails Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
DomainUnload
Occurs when an AppDomain is about to be unloaded
ProcessExit Occurs onEvents the default application domain when the default Chapter 7 - Callback Interfaces, Delegates, and Chapter 8
application domain's parent process exits - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
ResourceResolve
Chapter 9
Occurs when the resolution of a resource fails
- Understanding .NET Assemblies
TypeResolve Occurs when the resolution of a type fails Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
UnhandledException
Occurs when an exception is not caught by an event handler
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Fun with AppDomains
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
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 with ADO.NET method17makes of AppDomain.GetAssemblies() to obtain a list of all .NET binaries hosted within the Part Five Web Applications and XML Web Services application domain in question. Chapter 16 - The System.IO Namespace
Chapter 18 - ASP.NET Web Pages and Web Controls
This list19 is -represented by Applications an array of System.Reflection.Assembly types, and thus we are required to use the Chapter ASP.NET Web System.Reflection namespace Chapter 20 - XML Web Services (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 Index version of each module: List of Figures 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# and the .NET Platform, Second Edition before invoking PrintAllAssembliesInAppDomain(), using the AppDomain.CurrentDomain property. To make ISBN:1590590554 Andrew Troelsen things a bit more by interesting, notice that the Main() method launches a message box to force the assembly Apress © 2003 (1200 pages) resolver to load the System.Windows.Forms.dll and System.dll assemblies (so be sure to set a reference to text starts with a brief overview of the these assembliesThis andcomprehensive update your "using" statements appropriately): C# language and then quickly moves to key technical and architectural issues for .NET developers.
public static int Main(string[] args) { The Amazing AppDomain app *****\n"); Table of Console.WriteLine("***** Contents // Get info for current AppDomain. C# and the .NET Platform, Second Edition AppDomain defaultAD= AppDomain.CurrentDomain; Introduction MessageBox.Show("This loaded System.Windows.Forms.dll and System.dll"); Part One - Introducing C# and the .NET call Platform PrintAllAssembliesInAppDomain(defaultAD); Chapter 1 - The Philosophy of .NET 0; C# Applications Chapter return 2 - Building } Part Two - The C# Programming Language Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# Figure 10-6 shows the output.
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - 10-6: A Better Painting Framework (GDI+) Figure Enumerating assemblies within a given app domain (within a given process) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Programmatically Creating New AppDomains
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Recall 18 that- aASP.NET single process is capable hosting multiple AppDomains. While it is true that you will seldom (if Chapter Web Pages and WebofControls ever) need manually create AppDomains directly (unless you happen to be creating a custom host for the Chapter 19 - to ASP.NET Web Applications CLR), you able toServices do so via the static CreateDomain() method. As you would guess, this method has been Chapter 20 -are XML Web overloaded a number of times. At minimum you will simply specify the friendly name of the new application Index domain as seen here: List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter Figure 1 - 10-7: The Philosophy A single process of .NET with two application domains Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# question, "How can I programmatically load an assembly into an application domain?" Answer? The Chapter 5 - Exceptions and Object Lifetime AppDomain.Load() method (or alternatively, AppDomain.ExecuteAssembly()). I'll hold off on this topic until I Chapter 6 Interfaces and Collections discuss the process of dynamically loading assemblies in Chapter 11 during our examination of .NET reflection Chapter 7 - Callback Interfaces, Delegates, and Events services. Chapter 3
Chapter 8
- Advanced C# Type Construction Techniques
To solidify relationshipwith between processes, Part Three - the Programming .NET Assemblies
application domains, and assemblies, Figure 10-8 diagrams the internal composition of the AppDomainManipulator.exe process you have just constructed. Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List ofFigure Figures10-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# and the .NET Platform, Second Edition ... ISBN:1590590554 Andrew Troelsen event. // Hook into by DomainUnload Apress © 2003 (1200 pages) anotherAD.DomainUnload += This comprehensive text starts with a brief overview of the new EventHandler(anotherAD_DomainUnload); language and then quickly moves to key technical and // Now unloadC#anotherAD. architectural issues for .NET developers. AppDomain.Unload(anotherAD); Table of Contents
If you wish to be notified when the default AppDomain is unloaded, modify your application to support the following event logic:
C# and the .NET Platform, Second Edition Introduction
Part One - Introducing C# and the .NET Platform
private static void defaultAD_ProcessExit(object sender, EventArgs e) - The Philosophy of .NET { Console.WriteLine("***** Unloaded defaultAD! *****\n"); } Chapter 2 - Building C# Applications ... Part Two - The C# Programming Language defaultAD.ProcessExit +=new EventHandler(defaultAD_ProcessExit); Chapter 1
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter SOURCE 6 - InterfacesThe andAppDomainManipulator Collections project is included under the Chapter 10 subdirectory.
CODE Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andContext the .NET Platform, Second Edition Understanding (or How Low Can You Go?) by Andrew Troelsen
ISBN:1590590554
As you have just Apress seen, AppDomains are logical partitions within a process used to host .NET assemblies. A given © 2003 (1200 pages) application domain may be further subdivided context In a nutshell, a .NET context This comprehensive text startsinto withnumerous a brief overview ofboundaries. the provides a way for a single AppDomain to partition .NET objects that have similar execution requirements. Using C# language and then quickly moves to key technical and issuesthat for objects .NET developers. context, the CLR architectural is able to ensure that have special runtime requirements are handled appropriately 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 type. Table of Contents
Just asthe a process definesSecond a default AppDomain, every application domain has a default context. This default context C# and .NET Platform, Edition (sometimes referred to as context 0, given that it is always the first context created within an application domain) is Introduction used to -group together objects have Part One Introducing C#.NET and the .NET that Platform
no specific or unique contextual needs. As you may expect, a vast
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 the Chapter - Building Applications process, context relationship. Part Two - AppDomain, The C# Programming Language Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - 10-9: ObjectProcesses, Serializationapplication and the .NET Remoting Figure domains, andLayer context boundaries Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Context-Agile and Context-Bound Types
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
.NET types not demand any special contextual treatment are termed context-agile objects. These objects Chapter 17 - that Datado Access with ADO.NET canFive be accessed from anywhere within hosting Part - Web Applications and XML Webthe Services
AppDomain without interfering with the object's runtime
requirements. Building context-agile objects is a no-brainer, given that you simply do nothing (specifically, you do not Chapter 18 - ASP.NET Web Pages and Web Controls adorn the with any contextual attributes and do not derive from the System.ContextBoundObject base class): Chapter 19 type - ASP.NET Web Applications Chapter 20 - XML Web Services
// A context-agile object is loaded into context 0. Index public class IAmAContextAgileClassType{} List of Figures 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 special 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 type 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# and TypeId the .NET { Platform, Second public object virtual get;Edition } ISBN:1590590554 by Andrew Troelsen public virtual bool Equals(object o); Apress © 2003 (1200 pages) public virtual void Freeze(System.Runtime.Remoting.Contexts.Context newContext); This comprehensive text starts with a brief overview of the public virtual int GetHashCode(); C# language and then quickly moves to key technical and public virtual void GetPropertiesForNewContext( architectural issues for .NET developers. System.Runtime.Remoting.Activation.IConstructionCallMessage ctorMsg); public Type GetType(); public virtual bool IsContextOK( Table of Contents System.Runtime.Remoting.Contexts.Context ctx, C# and the .NET Platform, Second Edition System.Runtime.Remoting.Activation.IConstructionCallMessage ctorMsg); Introduction public virtual bool IsDefaultAttribute(); Part One - Introducing C# and the .NET Platform 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); Part Two - The C# Programming Language public virtual string ToString(); Chapter 3 - C# Language Fundamentals } Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime The .NET class libraries define numerous context attributes that describe specific runtime requirements (such Chapter 6 -base Interfaces and Collections
as thread and URL activation). Given the role of .NET context, it should stand to reason that if a Chapter 7 synchronization - Callback Interfaces, Delegates, and Events context-bound object were to somehow endTechniques up in an incompatible context, bad things are guaranteed to occur at Chapter 8 - Advanced C# Type Construction the Three most inopportune times. Part - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
Creating a Context-Bound Object
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
So,Four what-sort of bad things might occur Part Leveraging the .NET Libraries
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 .NET Chapter - Objecton Serialization the .NET contextual Remoting Layer type that thread-safe in nature, even though you have not hard-coded thread-safe-centric logic Chapter 13is- automatically Building a Better Window (Introducing Windows Forms) within the implementations. To do so, you may apply the Chapter 14 method - A Better Painting Framework (GDI+)
System.Runtime.Remoting.Contexts.SynchronizationAttribute attribute as follows:
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
using17System.Runtime.Remoting.Contexts; Chapter - Data Access with ADO.NET ...Five - Web Applications and XML Web Services Part // This will only be loaded into a Chapter 18 -context-bound ASP.NET Web Pagestype and Web Controls // synchronized (and hence, thread safe) context. [Synchronization] Chapter 20 - XML Web Services public class MyThreadSafeObject : ContextBoundObject Index {} Chapter 19 - ASP.NET Web Applications
List of Figures List of Tables
As you will see in greater detail later in this chapter, classes that are attributed with the [Synchronization] attribute 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 massive data corruption, as numerous threads are attempting to interact with the (now thread-volatile) reference object. This is obviously a huge problem, given that the code base has not specifically wrapped thread-sensitive resources with 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 and the .NET Platform, Second Edition class type within C# online Help (as of .NET version 1.1). The remaining members are considered usable only by the ISBN:1590590554 by Andrew CLR, and are intended to beTroelsen ignored (which you should do, given that many members of this namespace are Apress © 2003 (1200 pages) subject to change in future releases of .NET). This comprehensive text starts with a brief overview of the language and then moves to key types, technical and as an academic endeavor. Thus, by way of Nevertheless, it isC# possible to make usequickly of these hands-off simply architectural issues developers. a friendly heads-up, understand thatfor the.NET following example is purely illustrative in nature. As a .NET programmer, you can safely ignore these low-level primitives in 99.99 percent of your applications. If you wish to see the formal definition of the any of the following context-centric types, make use of the wincv.exe utility.
Table of Contents
C# and the COM+ .NET Platform, Second Note developers are Edition already aware of the notion of context. Using COM IDL attributes and the IntroductionComponent Services utility, developers are able to establish contextual settings for a given COM+ type. Part One - Introducing C# and .NETboth Platform Although .NET andthe COM+ make
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
Part Two - The C# Programming Language
Fun with Context
Chapter 3
- C# Language Fundamentals
Chapter 4 assume - Object-Oriented with C# To begin, you haveProgramming a new console application named ContextManipulator. This application defines two Chapter context-agile 5 - Exceptions types andand a single Objectcontext-bound Lifetime type: Chapter 6
- Interfaces and Collections
Chapter - Callback Interfaces, Delegates, and Events using7 System.Runtime.Remoting.Contexts;
// For Context type.
Chapter - Advanced C# Type Construction using8 System.Threading; // For Techniques Thread type. Part ...Three - Programming with .NET Assemblies
Chapter // These 9 - Understanding classes have .NETno Assemblies special contextual
// needs and willAppDomains, be loaded into and theThreads Chapter 10 - Processes, Contexts, // default context the app and domain. Chapter 11 - Type Reflection,of Late Binding, Attribute-Based Programming public NoSpecialContextClass Part Four - class Leveraging the .NET Libraries { Chapter 12 - Object Serialization and the .NET Remoting Layer NoSpecialContextClass() Chapterpublic 13 - Building a Better Window (Introducing Windows Forms) Chapter{14 - A Better Painting Framework (GDI+)
// Get context information and print out context ID. Context ctx = Thread.CurrentContext; Chapter 16 - The System.IO Namespace Console.WriteLine("Info about context {0}", ctx.ContextID); Chapter 17 - Data Access with ADO.NET foreach(IContextProperty itfCtxProp in ctx.ContextProperties) Part Five - Web Applications and XML Web Services Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name); Chapter 18 - ASP.NET Web Pages and Web Controls } Chapter 19 - ASP.NET Web Applications } Chapter 20 class - XML Web Services public NoSpecialContextClass2 Index { List of Figures 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 - Programming with Windows Forms Controls
{ and the .NET information Platform, Second Edition // C# Get context and print out context ID. ISBN:1590590554 by Andrew Troelsen Context ctx = Thread.CurrentContext; Apress © 2003 (1200 pages) Console.WriteLine("Info about context {0}", ctx.ContextID); This comprehensive text starts with a brief overview the foreach(IContextProperty itfCtxProp in of ctx.ContextProperties) C# language and then quickly moves to key technical and Console.WriteLine("-> Ctx Prop: {0}", itfCtxProp.Name); architectural issues for .NET developers.
} } Table of Contents
C# and the .NET Platform, Second Edition
Notice that each of the class constructors obtains a System.Runtime.Remoting.Contexts.Context type from the
Introduction current thread of execution, via the static Thread.CurrentContext property. Using this type, you are able to print out Part One - Introducing C# and the .NET Platform
statistics about the 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. Part Two - The C# Programming Language
Now, assume has Fundamentals been updated to allocate an instance of each class type. As the objects come to life, the Chapter 3 - C#Main() Language class constructors will dumpProgramming out various bits context-centric information (Figure 10-10): Chapter 4 - Object-Oriented withofC# Chapter 5
- Exceptions and Object Lifetime static Main(string[] Chapter 6 void - Interfaces and Collectionsargs)
{ Chapter 7
- Callback Interfaces, Delegates, and Events
The Amazing Context Application *****\n"); Chapter Console.WriteLine("***** 8 - Advanced C# Type Construction Techniques // Make each class type and print contextual info. Part Three - Programming with .NET Assemblies NoSpecialContextClass noBigDealObj = new NoSpecialContextClass(); Chapter 9 - Understanding .NET Assemblies Console.WriteLine(); Chapter 10 - Processes, AppDomains, Contexts, and Threads NoSpecialContextClass2 noBigDealObj2 = new NoSpecialContextClass2(); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Console.WriteLine(); Part Four - Leveraging the .NET Libraries SynchContextClass synchObj = new SynchContextClass(); Chapter 12 - Object Serialization and the .NET Remoting Layer Console.WriteLine(); Chapter 13 - Building a Better Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 10-10: Investigating an object's context
Given that the NoSpecialContextClass and NoSpecialContextClass2 types have not been qualified with a specific 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 the 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# and the .NET Platform, Second Edition and Context Summarizing Processes, AppDomains, by Andrew Troelsen
ISBN:1590590554
So then, at this point in the game have seen how the .NET runtime has altered the composition of a Apress © 2003 (1200you pages) traditional Win32 This process to function within the with common comprehensive text starts a brieflanguage overview runtime of the (CLR). To summarize the key points, rememberC# thelanguage following: and then quickly moves to key technical and architectural issues for .NET developers.
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 Table of programmatically Contents via the System.AppDomain type). C# and the .NET Platform, 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. Part One - Introducing C# and the .NET Platform Introduction
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 Part Two However, - The C# Programming Language behalf. this background 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 - Object-Oriented Programming with C# some underlying CLR concepts). Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The Process/AppDomain/Context/Thread Relationship by Andrew Troelsen
ISBN:1590590554
As mentioned at the opening thispages) chapter, a thread is a path of execution within a loaded application. Apress © 2003 of (1200 While many .NETThis applications can live single-threaded lives, the primary thread may comprehensive texthappy startsand withproductive a brief overview of the spawn secondaryC# threads of execution to perform additional units of work. In just a moment, you will be language and then quickly moves to key technical and issues for .NET developers. introduced to the architectural System.Threading namespace, which defines numerous types used to create multithreaded .NET applications. First however, we need to check out exactly "where" a thread lives within a .NET process. Table of Contents
The first must understand is that under the .NET platform, there is not a direct one-to-one C# and thething .NETyou Platform, Second Edition correlation between application domains and threads. In fact, a given AppDomain can have numerous Introduction threads within at any givenPlatform time. Furthermore, Part One -executing Introducing C# it and the .NET
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 Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# be doing work in more than one AppDomain). If you wish to gain access to the AppDomain that is currently Chapter Exceptions and Object Lifetime hosting5the- Thread type, call the static Thread.GetDomain method: Chapter 3
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
// Thread.GetDomain() returns an AppDomain type. Chapter 8 - Advanced C# Type Construction Techniques Console.WriteLine(Thread.GetDomain().FriendlyName); Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter - Processes, AppDomains, and Threads A single10thread may also be moved Contexts, 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 Attribute-Based to programmatically Programming discover the current context a Part thread Fourhappens - Leveraging to bethe executing .NET Libraries in, make
use of the static Thread.CurrentContext property:
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window a(Introducing // CurrentContext returns Context Windows type. Forms) Chapter 14 - A Better Painting Framework (GDI+) Console.WriteLine(Thread.CurrentContext.ContextID); Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
As you 17 would guess, thewith CLRADO.NET is the entity that is in charge of moving threads into (and out of) application Chapter - Data Access domains As aand .NET developer, you are Part Five - and Webcontexts. Applications XML Web Services
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 Controls the underlying model. Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
The Problem of Concurrency and Thread Synchronization
Index
List of Figures
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# and the .NET Platform, Second Edition very few operations in .NET that are guaranteed to be atomic. Even a simple assignment statement to a ISBN:1590590554 by Andrew Troelsen double is not atomic! Unless the .NET Framework documentation specifically says an operation is atomic, Apress © 2003 (1200 pages) you must assume it is thread-volatile and take precautions. This comprehensive text starts with a brief overview of the
C# be language andmultithreaded then quickly moves to key domains technical are and in themselves quite volatile, as Given this, it should clear that application architectural issues for .NET developers. 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 Table of Contents the executing threads. C# and the .NET Platform, Second Edition
Introduction Although the .NET platform cannot make the difficulties of building robust multi-threaded applications Part One - Introducing and the .NET Platform completely disappear,C# the process has been simplified
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 Part Two - The C# Programming Language same functionality as the raw Win32 threading
primitives (using a much cleaner object model).
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform,via Second Edition Multithreaded Programming Delegates by Andrew Troelsen
ISBN:1590590554
Before checking out the©details of programming with threads under the .NET platform, it is worth Apress 2003 (1200 pages) reiterating that the whole point of creating additional is to increase This comprehensive text starts with athreads brief overview 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 moves to key technical and issues for .NET developers. required manual architectural creation of threads (e.g., remote method invocations, manipulating IO streams, and so forth) are automated using asynchronous delegates (first examined in Chapter 7). Table As you of Contents have seen 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 theasynchronously, .NET Platform, Second Edition However, if you have an application-specific task to account for (such as printing a lengthy document or Introduction working a GUI display), required Part One -with Introducing C# and you the will .NETbe Platform
to manually manipulate threads if you wish to keep your
primary1thread This disclaimer aside, allow me to formally introduce the System.Threading Chapter - Theresponsive. Philosophy of .NET namespace. Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The System.Threading Namespace by Andrew Troelsen
ISBN:1590590554
Under the .NET platform, the System.Threading namespace provides a number of types that enable Apress © 2003 (1200 pages) multithreaded programming. In addition to providing that represent This comprehensive text starts with atypes brief overview of thea specific CLR thread, this namespace also C# defines types that can manage a collection of threads language and then quickly moves to key technical and(ThreadPool), a simple (non-GUI architectural issues for used .NET to developers. based) Timer class, and various types provide synchronized access to shared resources. Table 10-6 lists some (but not all) of the core members of this namespace. Table of 10-6: Contents Table Select Types of the System.Threading Namespace C# and the .NET Platform, Second Edition
System.Threading Introduction Type Part One
Meaning in Life
- Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET Interlocked Provides atomic operations for objects that are shared by multiple - Building C# Applications threads.
Chapter 2
Part Two - The C# Programming Language
Monitor Provides the synchronization of threading objects using locks and Chapter 3 - C# Language Fundamentals Chapter 4
wait/signals. - Object-Oriented Programming with C#
Chapter Mutex5 Chapter 6
- Exceptions and Object Lifetime Synchronization primitive that can be used for interprocess - Interfaces and Collections synchronization.
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 9
- Understanding .NET Assemblies
Thread Represents a thread that executes within the CLR. Using this type, Chapter 8 - Advanced C# Type Construction Techniques you are able to spawn additional threads in the originating Part Three - Programming with .NET Assemblies AppDomain. Chapter 10 - Processes, AppDomains, Contexts, and Threads ThreadPool This type manages related threads in a given process. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Timer
Provides a mechanism for executing a method at specified intervals.
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization Delegate and the .NET ThreadStart thatRemoting specifies Layer the method to call for a given Thread. Chapter 13 - Building a Better Window (Introducing Windows Forms)
ThreadState
This enum specifies the valid states a thread may take (Running, Aborted, etc.).
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
TimerCallback Delegate type used in conjunction with Timer types. Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
ThreadPriority
This enum specifies the valid levels of thread priority.
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Examining the Thread Class
Chapter 20 - XML Web Services Index
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 Figures
Table 10-7: Key Static Members of the Thread Type
Thread Static in Life C# and theMeaning .NET Platform, Second Edition Member by Andrew Troelsen CurrentContext CurrentThread Table of Contents GetDomain()
ISBN:1590590554
Apress © 2003 (1200 pages)
This (read-only) property returns the context the thread is currently
This comprehensive text starts with a brief overview of the running. C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 the .NET Platform, Second domain) Edition in which the current thread is running. Introduction
Sleep() the current Part One - Introducing C# andSuspends the .NET Platform
thread for a specified time.
Chapter 1
- The Philosophy of .NET Thread2also supports the object level members shown in Table 10-8. Chapter - Building C# Applications Part Two - The C# Programming Language
Table 10-8: Select Instance Level Members of the Thread Type Chapter 3 - C# Language Fundamentals Chapter 4 - Instance Object-Oriented Programming within C#Life Thread Meaning Chapter 5 Member - Exceptions and Object Lifetime Level Chapter 6
- Interfaces and Collections Abort() This method instructs the CLR to terminate the thread ASAP. Chapter 7 - Callback Interfaces, Delegates, and Events Chapter IsAlive8
- Advanced C# Type Construction Techniques This property returns a Boolean that indicates if this thread has
Part Three - Programming with .NETbeen Assemblies started.
Chapter 9
- Understanding .NET Assemblies IsBackground Gets or sets and a value indicating whether or not this thread is a Chapter 10 - Processes, AppDomains, Contexts, Threads
background thread.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries Name This property
allows you to establish a friendly textual name of the
Chapter 12 - Object Serialization and the .NET Remoting Layer thread. Chapter 13 - Building a Better Window (Introducing Windows Forms)
Priority
Gets or Sets the priority of a thread, which may be assigned a value from the ThreadPriority enumeration.
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter ThreadState 16 - The System.IO Namespace Gets the state of this thread, which may be assigned a value from
the ThreadState enumeration. Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Interrupt()
Interrupts the current thread.
Chapter 18 - ASP.NET Web Pages and Web Controls
Join()19 - ASP.NET Web Applications Instructs a thread to wait for another thread to complete. Chapter Chapter 20 - XML Web Services
Resume()
Index
Resumes a thread that has been previously suspended.
ListStart() of Figures
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# and the .NET Platform, Second Edition // Get some info about the current thread. ISBN:1590590554 by Andrew Troelsen Thread primaryThread = Thread.CurrentThread; Apress © 2003 (1200 pages) // Get name of current AppDomain and context ID. This comprehensive text starts with aThread brief overview of the Console.WriteLine("***** Primary stats *****"); C# language and then quickly moves to key technical Console.WriteLine("Name of current AppDomain:and {0}", architectural issues for .NET developers. Thread.GetDomain().FriendlyName); Console.WriteLine("ID of current Context: {0}", Thread.CurrentContext.ContextID); Table of Contents Console.WriteLine("Thread Name: {0}", primaryThread.Name); C# and the .NET Platform, Second Edition Console.WriteLine("Apt state: {0}", primaryThread.ApartmentState); Introduction Console.WriteLine("Alive: {0}", primaryThread.IsAlive); Part One - Introducing C# and the .NET Platform 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(); Part Two - The C# Programming Language } Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Naming Threads - Interfaces and Collections
Chapter 6 Chapter 7
Callback Interfaces, Delegates, and Events When you-run this application, notice how the name of the default thread is currently an empty string. Chapter 8 - Advanced C# Type Construction Techniques string to a thread using the Name property. Thus, if Under .NET, it is possible to assign a human-readable Part - Programming with .NET Assemblies youThree wish to be able to programmatically identify the primary thread via the moniker "ThePrimaryThread," Chapter 9 -write Understanding .NET Assemblies you could the following: Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Name the thread. primaryThread.Name = "ThePrimaryThread"; Chapter 12 - Object Serialization and the .NETis Remoting Layer{0}", primaryThread.Name); Console.WriteLine("This thread called: Part Four - Leveraging the .NET Libraries
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
.NET Threads and Legacy COM Apartments
Chapter 16 - The System.IO Namespace
Chapter 17 - that Dataevery Access with ADO.NET Also notice Thread type has a property named ApartmentState. Those of you who come from a Part Five - Web XML Web Services background inApplications classic COMand may already be aware
of apartment boundaries. In a nutshell, COM
Chapter 18 - ASP.NET Web andused Web to Controls apartments were a unit of Pages isolation group COM objects with similar threading needs. Under the Chapter 19 - ASP.NET Webapartments Applicationsare no longer used by managed objects. If you happen to be making .NET platform however, Chapter 20 - XML Webfrom Services use of COM objects managed code (via the interoperability layer), you are able to establish the Index apartment settings that should be simulated to handle the coclass in question. To do so, the .NET base List class of Figures libraries 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# and the .NET Platform, Main(string[] args) Second Edition ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) objects will be placed into the MTA. This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 Table of Contents your part. If you don't make use of COM types within the Main() method, the [STAThread] attribute does C# and the .NET Platform, Second Edition nothing. Introduction
Part One - Introducing C# and the .NET Platform
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 - Object-Oriented Programming with C# be changed at any point in the thread's lifetime using the ThreadPriority property and the related Chapter 5 Exceptions and Object Lifetime ThreadPriority enumeration: Part Two - The C# Programming Language
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events public enum System.Threading.ThreadPriority Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies AboveNormal, BelowNormal, Chapter Highest, 9 - Understanding .NET Assemblies Lowest, Chapter Normal, 10 - Processes, Contexts, and Threads // AppDomains, Default value. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Always13 keep in mindathat a thread with the value of ThreadPriority.Highest is not necessarily guaranteed to Chapter - Building Better Window (Introducing Windows Forms) given the precedence. Again, if the thread scheduler is preoccupied with a given task (e.g., Chapter 14 highest - A Better Painting Framework (GDI+) synchronizing an object, switching threads, moving threads, or whatnot) the priority level will most likely be Chapter 15 - Programming with Windows Forms Controls 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 with ADO.NET thread priority should each receive the same amount of time to perform their work. Chapter 16 - The System.IO Namespace
Part Five - Web Applications and XML Web Services
Chapter 18 Again, - ASP.NET Pages and Web Controls Note you Web will seldom (if ever) need to directly alter a thread's priority level. In theory, it is Chapter 19 possible - ASP.NET to Web jack Applications up the priority level on a set of threads, thereby preventing lower priority threads Chapter 20 from - XMLexecuting Web Services at their required levels (so use caution). Index List of Figures List of Tables
C# and the .NETThreads Platform, Second Edition Spawning Secondary by Andrew Troelsen
ISBN:1590590554
When you wish toApress create© additional threads to carry on some unit of work, you need to interact with the 2003 (1200 pages) Thread class as well as a special threading-related delegate namedofThreadStart. The general process is This comprehensive text starts with a brief overview the quite simple. FirstC# and foremost, you need to create a function (static or instance-level) to perform the language and then quickly moves to key technical and architectural for the .NET developers. additional work. For example,issues assume current SimpleThreadApp project defines the following additional static method, which mimics the work seen in Main(): Table of Contents
static void MyThreadProc() { Introduction Console.WriteLine("***** Secondary Thread stats *****"); Part One - Introducing C# and the .NET Platform 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); Part TwoConsole.WriteLine("Apt - The C# Programming Language state? {0}", secondaryThread.ApartmentState); Chapter Console.WriteLine("Alive? 3 - C# Language Fundamentals {0}", secondaryThread.IsAlive); Chapter Console.WriteLine("Priority? 4 - Object-Oriented Programming with C# {0}", secondaryThread.Priority); Chapter Console.WriteLine("State? 5 - Exceptions and Object Lifetime {0}", secondaryThread.ThreadState); Chapter Console.WriteLine(); 6 - Interfaces and Collections } Chapter 7 - Callback Interfaces, Delegates, and Events C# and the .NET Platform, Second Edition
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Note The target for the ThreadStart delegate cannot take any arguments and must return void.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Attribute-Based Now, within Main(), create aLate newBinding, Thread and class and specify a Programming new ThreadStart delegate as a constructor Part Four - Leveraging the .NET Libraries parameter (note the lack of parentheses
in the constructor when you give the method name). To inform
Chapter 12that - Object Serialization theto.NET Layer method (but always remember that Start() the CLR this new thread is and ready run,Remoting call the Start() Chapter 13 Building a Better Window (Introducing Windows Forms) doesn't actually start the thread). Starting a thread is a nondeterministic operation under the total control of Chapter 14 you - A Better Painting Framework the CLRcan't do anything to force (GDI+) the CLR to execute your thread. It will do so on its own time and Chapter on its own 15 -terms: Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET [STAThread] Part Five - Web and XML Web Services static voidApplications Main(string[] args)
Chapter 18 - ASP.NET Web Pages and Web Controls { Chapter ... 19 - ASP.NET Web Applications
a Services secondary thread. Chapter // 20 -Start XML Web Index
Thread secondaryThread = new Thread(new ThreadStart(MyThreadProc));
secondaryThread.Start(); List of Figures } of Tables List The output is seen in Figure 10-11.
Figure 10-11: Your first multithreaded application
C# and the .NET Platform, Second Edition
One question that may be on your mind is exactly when a thread terminates. By default, a thread ISBN:1590590554 by Andrew Troelsen terminates as soon as the function used to create it in the ThreadStart delegate has exited. Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
language andand then quickly moves to key technical and ForegroundC#Threads Background Threads architectural issues for .NET developers.
The CLR assigns a given thread to one of two broad categories: Foreground Table of Contents threads: Foreground threads have the ability to prevent the current application from terminating. The CLR will not shut down an application (which is to say, unload the hosting C# and the .NET Platform, Second Edition AppDomain) until all foreground threads have ended. Introduction Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language background threads are automatically killed. Chapter 1
Chapter 3
- C# Language Fundamentals
Chapter 4 - Object-Oriented Programming C# It is important to note that foreground andwith background threads are not synonymous with primary and Chapter worker 5threads. - Exceptions By default, and Object every thread Lifetimeyou 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. Interfaces and this Collections have completed theirInterfaces, units of work. In mostand cases, this is exactly the behavior you require. Chapter 7 - Callback Delegates, Events Chapter 8
- Advanced C# Type Construction 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 - Understanding .NET Assemblies ThreadStart delegate) should be able to halt safely as soon as all foreground threads are done with their Chapter 10 - Processes, AppDomains, Contexts, and Threads work. Configuring such a thread is as simple as setting the IsBackground property to true: Part Three - Programming with .NET Assemblies
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
// Start a new background thread. Thread secondaryThread = new Thread(new ThreadStart(MyThreadProc)); Chapter 13 - Building a Better Window (Introducing Windows Forms) secondaryThread.Priority = ThreadPriority.Highest; Chapter 14 - A Better Painting Framework (GDI+) secondaryThread.IsBackground = true; Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five Web Applications and XML Web Services Now, to -illustrate the distinction, assume that the MyThreadProc()
method has been updated to print out
Chapter 1000 lines 18 -toASP.NET the console, Web Pages pausing andfor Web 5 milliseconds Controls between iterations using the Thread.Sleep() method
(more on Thread.Sleep() method later in this chapter): Chapter 19 the - ASP.NET Web Applications Chapter 20 - XML Web Services Index static void MyThreadProc() List { of Figures
... 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# and the .NET Platform, Second Edition the main task of the program is over. by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
The VS .NET Threads Window This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and
To wrap up our initial investigation threads, it is worth pointing out that the Visual Studio .NET IDE architectural issuesoffor .NET developers. 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 executing threads in your .NET assembly. Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals Figure The VS .NET Threadswith window Chapter 4 - 10-12: Object-Oriented Programming C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - InterfacesThe andThreadStats Collections project is included under the Chapter 10 subdirectory. SOURCE Chapter 7 Callback Interfaces, Delegates, and Events CODE Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and theThreading .NET Platform,Example Second Edition A More Elaborate by Andrew Troelsen
ISBN:1590590554
Now that you have seen©the of creating a new thread of execution, we can turn to a more Apress 2003basic (1200 process pages) illustrative example. Create a new console application named SimpleMultiThreadApp. Next, define a This comprehensive text starts with a brief overview of the helper class that C# supports a public method named DoSomeWork(): language and then quickly moves to key technical and architectural issues for .NET developers.
internal class WorkerClass { Table of Contents public void DoSomeWork() C# and the .NET Platform, Second Edition { Introduction // Get hash code for this worker thread. Part One - Introducing C# and the .NET Platform 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. Part Two - The C# Programming Language Console.Write("Worker says: "); Chapter 3 - C# Language i Fundamentals for(int = 0; i < 10; i++) Chapter 4 - Object-Oriented Programming with C# { Chapter 5 - Exceptions and Object Lifetime Console.WriteLine(i + ", "); Chapter 6 - Interfaces and Collections } Chapter 7 - Callback Console.WriteLine(); Interfaces, Delegates, and Events } Chapter 8 - Advanced C# Type Construction Techniques } Three - Programming with .NET Assemblies Part Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, 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 Part Four - Leveraging the .NET Libraries DoSomeWork() method of the WorkerClass type: Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
public class MainClass { Chapter 15 - Programming with Windows Forms Controls public static int Main(string[] args) Chapter 16 - The System.IO Namespace { Chapter 17 - Data Access with ADO.NET // Get hash code of the current thread. Part Five - Web Applications and XML Web Services Console.WriteLine("ID of primary thread is: {0} ", Chapter 18 - ASP.NET Web Pages and Web Controls Thread.CurrentThread.GetHashCode()); Chapter 19 - ASP.NET Webworker Applications // Make class. Chapter 20 - XML Web Services WorkerClass w = new WorkerClass(); Index // Now make (and start) the worker thread. List of Figures Thread workerThread = List of Tables new Thread(new ThreadStart(w.DoSomeWork)); workerThread.Start(); return 0; } } Chapter 14 - A Better Painting Framework (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# and the .NET Platform, Second Edition account for a more labor-intensive process: by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
internal class WorkerClass This comprehensive text starts with a brief overview of the { C# language and then quickly moves to key technical and public void DoSomeWork() architectural issues for .NET developers. { ... // Do a lot of work. Table of Contents says: "); C# and the .NETConsole.Write("Worker Platform, Second Edition for(int i = 0; i < 30000; i++) Introduction { Console.WriteLine(i + ", "); } Part One - Introducing C# and the .NET Platform Console.WriteLine(); Chapter 1 - The Philosophy of .NET Chapter } 2 - Building C# Applications } Two - The C# Programming Language Part Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# Next, update the MainClass such that it launches a Windows Forms message box directly after it creates
Chapter 5 - thread Exceptions and Object Lifetime the worker (don't forget to set a reference to System.Windows.Forms.dll): Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
public class MainClass Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies public static int Main(string[] args) Chapter { 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, // Create workerContexts, threadand asThreads before. Chapter 11 Type Reflection, Late Binding, and Attribute-Based Programming ... Part Four - Leveraging the .NET Libraries // Now while worker thread is busy, Chapter 12 - Object Serialization and the .NET Remoting // do some additional work onLayer primary thread. Chapter 13 - Building a Better Window (Introducing Windows Forms) MessageBox.Show("I'm buzy"); Chapter 14 - A return Better Painting 0; Framework (GDI+) Chapter } 15 - Programming with Windows Forms Controls } Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
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 Applications 13). Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 20 - XML Web Services Index List of Figures 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# and the .NET= Platform, Second Edition string threadCount Console.ReadLine(); ...
ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) // Make worker class. This comprehensive text starts with a brief overview of the WorkerClass w = new WorkerClass(); C# language and then quickly to key said technical and // Only make a new thread if moves the user so. architectural issues for .NET developers.
if(threadCount == "2") { // Now make the thread. Table of Contents Thread workerThread = C# and the .NET Platform, Second Edition new Thread(new ThreadStart(w.DoSomeWork)); Introduction workerThread.Start(); Part One - Introducing C# and the .NET Platform } Chapter 1 - The Philosophy of .NET else // Execute this method on the single thread. Chapter 2 - Building C# Applications w.DoSomeWork(); Part Two - The C# Programming Language // Do some additional work. Chapter MessageBox.Show("I'm 3 - C# Language Fundamentals buzy"); Chapter return 4 - Object-Oriented Programming with C# 0; Chapter 5 - Exceptions and Object Lifetime } Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
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 Construction Techniques before seeing the message box appear, given Part Three - Programming with .NET Assemblies that there is only a single thread in the AppDomain. However, user enters.NET "2" he or she is able to interact with the message box while the secondary Chapter 9 if - the Understanding Assemblies thread spins right along. Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Putting a Thread to Sleep
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
The static method can be used toWindows currentlyForms) suspend the current thread for a specified Chapter 13 -Thread.Sleep() Building a Better Window (Introducing amount14of -time (specified in milliseconds). In particular, you can use this to pause a program. To illustrate, Chapter A Better Painting Framework (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 System.IO Namespace worker thread is put to sleep for approximately 2 seconds. Chapter 15 - Programming with Windows Forms Controls Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
internal class WorkerClass Chapter 18 - ASP.NET Web Pages and Web Controls {
Chapter 19 - ASP.NET Web Applications
public void DoSomeWork() { Index // Get some information about the worker thread. List of Figures 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 Services
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# and .NET Platform, Second Edition The the SimpleMultiThreadApp project is included under the Chapter 10 subdirectory. ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Concurrency Revisited by Andrew Troelsen
ISBN:1590590554
Given this previous example, Apress © 2003 you (1200might pages)be thinking that threads are the magic bullet you have been looking for. Simply create threads for each partwith of your application the result will be increased This comprehensive text starts a brief overview and of the application performance to the user. You already know this is a loaded C# language and then quickly moves to key technical andquestion, as the previous statement issues for .NETand developers. is not necessarilyarchitectural true. If not used carefully thoughtfully, multithreaded programs are slower than single threaded programs. Table Evenofmore Contents important 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 the .NET Platform, SecondInEdition happen if the primary and secondary threads were both modifying a shared point of data. As you know, the Introduction thread will C# force threads to Platform suspend Part Onescheduler - Introducing and the .NET
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
Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# DoSomeWork() helper function. Also notice that this helper function also leverages a for loop to printout Chapter 5 of - Exceptions Object Lifetime the value this privateand integer, the iterator's value as well as the name of the current thread. Finally, to Chapter 6 Interfaces and Collections simulate additional work, each iteration of this logic places the current thread to sleep for approximately Chapter 7 - Callback one second. Here is Interfaces, the type in Delegates, question: and Events Chapter 3
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
internal class WorkerClass
Chapter 9 {
- Understanding .NET Assemblies
Chapter private 10 - Processes, int AppDomains, theInt; Contexts, and Threads Chapter public 11 - Type void Reflection, Late Binding, and Attribute-Based Programming DoSomeWork() Part Four{ - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer theInt++; Chapter 13 - Building a Better for(int i =Window 0; i (Introducing < 5; i++)Windows Forms) Chapter 14 - A { Better Painting Framework (GDI+)
Console.WriteLine("theInt: {0}, i: {1}, current thread: {2}", Chapter 15 - Programming with Windows Forms Controls theInt, i, Thread.CurrentThread.Name); Chapter 16 - The System.IO Namespace Thread.Sleep(1000); Chapter 17 - Data Access with ADO.NET Part Five - Web}Applications and XML Web Services
Chapter } 18 - ASP.NET Web Pages and Web Controls
} Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index
The Main() method is responsible for creating three uniquely named secondary threads of execution, each
List of Figures of which is 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# and the .NET Platform, Second Edition workerThreadC.Name = "C"; ISBN:1590590554 by Andrew Troelsen // Now start each one. Apress © 2003 (1200 pages) workerThreadA.Start(); This comprehensive text starts with a brief overview of the workerThreadB.Start(); C# language and then quickly moves to key technical and workerThreadC.Start(); architectural issues for .NET developers. return 0; } } Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Now before you see some test runs, let's recap the 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 Part - The Programming Language lockTwo down theC# object's shared resources,
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 - Object-Oriented withwe C#are bound to get unpredictable results. For example, you know exactly when (or if) thisProgramming might happen, Chapter might find 5 -the Exceptions output shown and Object in Figure Lifetime 10-14. Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - 10-14: ASP.NET Web Applications Figure Possible output of the MultiThreadSharedData application Chapter 20 - XML Web Services Index Now run the application a few more times. Figure 10-15 shows another possibility (note the ordering
among thread names). List of Figures List of Tables
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Figure Another possible output of the MultiThreadSharedData application Chapter 3 - 10-15: C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Humm. There are clearly some problems here. As each thread is telling the WorkerClass to "do some - Exceptions and Object Lifetime work," the thread scheduler is happily swapping threads in the background. The result is inconsistent Chapter 6 - Interfaces and Collections output. What we need is a way to programmatically enforce synchronized access to the shared resources. Chapter 5 Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter - Advanced C# System.Threading Type Construction Techniques As you 8would guess, the namespace provides a number of synchronization-centric Part Three withlanguage .NET Assemblies types. The- Programming C# programming also provides
a particular keyword for the very task of synchronizing
Chapter - Understanding .NET Assemblies shared9data in multithreaded applications. Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Edition Synchronization Using the C#Second "lock" Keyword by Andrew Troelsen
ISBN:1590590554
The first approach to providing synchronized access to our DoSomeWork() method is to make use of the C# Apress © 2003 (1200 pages) "lock" keyword. This intrinsic keyword allows you to alock down a block of code so that incoming threads must This comprehensive text starts with brief overview 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 moves to key technical and architecturalthat issues forbe .NET developers. token (an object reference) must acquired by a 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: Table of Contents C# and the .NET Platform, Second Edition
internal class WorkerClass { Part One - Introducing C# and the .NET Platform private int theInt; Chapter public 1 - The Philosophy of .NET void DoSomeWork() Chapter { 2 - Building C# Applications Part Two - The C# Programming Language lock(this) Chapter 3 - C# { Language Fundamentals Chapter 4 - Object-Oriented Programming with C# theInt++; Chapter 5 - Exceptions and Object for(int i Lifetime = 0; i < 5; i++) Chapter 6 - Interfaces{and Collections Console.WriteLine("theInt: {0}, i: {1}, current thread: {2}", Chapter 7 - Callback Interfaces, Delegates, and Events theInt, i, Thread.CurrentThread.Name); Chapter 8 - Advanced C# Type Construction Techniques Thread.Sleep(1000); Part Three - Programming with .NET Assemblies } Chapter 9 - Understanding .NET Assemblies } // Lock tokenContexts, released here! Chapter 10 - Processes, AppDomains, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Four - Leveraging the .NET Libraries Part Introduction
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
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 Painting Framework is inaccessible by other threads until the(GDI+) lock is released. Thus, if threadA has obtained the lock token, and Chapter 15 Programming with Windows Forms Controls threadB or threadC are attempting to enter, they must wait until threadA relinquishes the lock. Chapter 16 - The System.IO Namespace
Note attempting to lock down code in a static method, you obviously cannot use the "this" Chapter 17 If- you Dataare Access with ADO.NET keyword. If this isand the XML case,Web youServices can simply Part Five - Web Applications
pass in the System.Type of the current class using the C#
operator (although anyControls object reference will work). Chapter 18 "typeof" - ASP.NET Web Pages and Web Chapter 19 - ASP.NET Web Applications
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 Services Index
List of Figures List of Tables
Figure 10-16: Consistent output of the MultiThreadSharedData application
SOURCE CODE
C# and the .NET Platform, Second Edition
The MultiThreadSharedData application isISBN:1590590554 included under the Chapter 10 subdirectory.
by Andrew Troelsen Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and Synchronization Using the System.Threading.Monitor Type architectural issues for .NET developers.
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 Table of Contents (which can be verified using ildasm.exe): C# and the .NET Platform, Second Edition Introduction
internal class WorkerClass { Chapter private 1 - The Philosophy of .NET int theInt; Chapter public 2 - Building C# Applications void DoSomeWork() Part Two{- The C# Programming Language Chapter 3 - C# Language // Enter Fundamentals the monitor with token. Chapter 4 - Object-Oriented Programming with C# Monitor.Enter(this); Chapter 5 - Exceptions and Object Lifetime try Chapter 6 - Interfaces { and Collections theInt++; Chapter 7 - Callback Interfaces, Delegates, and Events for(int i = 0; i Techniques < 5; i++) Chapter 8 - Advanced C# Type Construction { Part Three - Programming with .NET Assemblies Console.WriteLine("theInt: {0}, i: {1}, current thread: {2}", Chapter 9 - Understanding .NET Assemblies theInt, i, Thread.CurrentThread.Name); Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Thread.Sleep(1000); Late Binding, and Attribute-Based Programming Part Four - Leveraging }the .NET Libraries } Chapter 12 - Object Serialization and the .NET Remoting Layer finally Chapter 13 - Building a Better Window (Introducing Windows Forms) { Chapter 14 - A Better Painting Framework (GDI+) // Error or not, you must exit the monitor Chapter 15 - Programming with Windows Forms Controls // and release the token. Chapter 16 - The System.IO Namespace Monitor.Exit(this); Chapter 17 - Data } Access with ADO.NET Part Five}- Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls } Part One - Introducing C# and the .NET Platform
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
If you run the modified application, you will see no changes in the output (which is good). Here, you make use of Index theofstatic Enter() and Exit() members of the Monitor type, to enter (and leave) a locked block of code. Now, List Figures 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# and the .NET Platform, Second Edition Synchronization Using the System.Threading.Interlocked Type by Andrew Troelsen
ISBN:1590590554
Although it always is hard to believe until you look at the underlying CLR code, assignments and simple Apress © 2003 (1200 pages) arithmetic operations are not atomic. For starts this reason, the System.Threading namespace also provides a This comprehensive text with a brief overview 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 moves to key technical and architectural issues for .NET developers. static members shown in Table 10-9. Table 10-9: Members of the Interlocked Type
Table of Contents
of Platform, the C#Member and the .NET Second Edition
Meaning in Life
System.Threading.Interlocked Type Introduction Part One - Introducing C# and the .NET Platform
Increment()
Chapter 1
- The Philosophy of .NET
Decrement() Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Exchange()
Chapter 3
- C# Language Fundamentals
CompareExchange() Chapter 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Safely increments a value by one Safely decrements a value by one Safely swaps two values Safely tests two values for equality, and if so, changes one of the values with a third
Chapter 6
- Interfaces and Collections Although notInterfaces, seem like Delegates, it from the and onset, the process of atomically altering a single value is quite Chapter 7 it- might Callback Events
common multithreaded environment. rather than writing synchronization code such as the Chapter 8 in - a Advanced C# Type ConstructionThus, Techniques following: Part Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
int i10= -9; Chapter Processes, AppDomains, Contexts, and Threads lock(this) Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming { i++; Part Four - } Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
you can simply write:
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
// Pass by reference the value you wish to alter. int i = 9; Chapter 17 - Data Access with ADO.NET Interlocked.Increment(ref i); Chapter 16 - The System.IO Namespace
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 if- you ASP.NET Applications Likewise, wish Web to assign the value of a previously assigned System.Int32 to the value 83, you can Chapter 20 need - XMLtoWeb Serviceslock statement (or Monitor logic) and make use of the Interlocked.Exchange() avoid the an explicit Index method: List of Figures 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# and the .NET Platform, Second Edition Synchronization Using the [Synchronization] Attribute by Andrew Troelsen
ISBN:1590590554
The final synchronization primitive here is the [Synchronized] attribute, which, as you recall, is a Apress © 2003 (1200 examined pages) contextual attribute that can be applied to context-bound When you apply this attribute on a .NET This comprehensive text starts with a briefobjects. overview of the class type, you are effectively locking down all members of the object for C# language and then quickly moves to key technical and thread safety: architectural issues for .NET developers.
using System.Runtime.Remoting.Contexts; ... Table of Contents // This context-bound type will only be loaded into a C# and the .NET Platform, Second Edition // synchronized (and hence, thread-safe) context. Introduction [Synchronization] Part One - Introducing C# and the .NET Platform public class MyThreadSafeObject : ContextBoundObject Chapter 1 - The Philosophy .NET are now thread safe */} { /* all methods on ofclass Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
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 dive into Programming the details about Chapter - Object-Oriented withwhich C# aspects of the type are truly manipulating threadsensitive The major of this approach, however, is that even if a given method is not making Chapter 5 data. - Exceptions anddownfall Object Lifetime use of thread-sensitive data, the CLR will still lock invocations to the method. Obviously, this could Chapter 6 - Interfaces and Collections degrade overall functionality of the type, soEvents use this technique with care. Chapter 7 the - Callback Interfaces, Delegates, and Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the the .NET Platform, Second Edition Libraries Thread Safety and .NET Base Class by Andrew Troelsen
ISBN:1590590554
Although this chapter has illustrated how you can build custom thread-safe types, you should also be Apress © 2003 (1200 pages) aware that many This of the types of the base class with libraries have been preprogrammed to be thread-safe. In comprehensive text starts a brief overview 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 moves to key technical and issues(Figure for .NET developers. regarding its levelarchitectural of thread safety 10-17).
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies Figure Many (but not all)Contexts, .NET types already thread-safe . Chapter 10 - 10-17: Processes, AppDomains, andare Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer multiple requests from the thread base. Part Four - Leveraging the .NET Libraries
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Programming with Timer Callbacks by Andrew Troelsen
ISBN:1590590554
At this point you have seen a number of ways in which you are able to provide synchronized access to shared Apress © 2003 (1200 pages) blocks of data. ToThis be comprehensive sure, there aretext additional types underoverview the System.Threading namespace, which I will allow starts with a brief of the you to explore at C# yourlanguage leisure. and However, to wrap up our examination of thread programming, allow me to introduce then quickly moves to key technical and architectural issues for developers. 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 may Table haveofanContents application that needs to display the current time on a status bar via a given helper function. As another
example, wish to have your application call a helper function every so often to perform noncritical C# and the you .NETmay Platform, Second Edition background tasks such as checking for new e-mail messages. For situations such as these, the Introduction System.Threading.Timer typethe can be Platform used in conjunction Part One - Introducing C# and .NET 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 hits - 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 type:
Chapter 2
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
class TimePrinter - Object-Oriented Programming with C# { Chapter 5 - Exceptions and Object Lifetime static void PrintTime(object state) Chapter 6 - Interfaces and Collections { Chapter 7 - Callback Interfaces, Delegates, and Events Console.WriteLine("Time is: {0}", Chapter 8 - Advanced C# Type Construction Techniques DateTime.Now.ToLongTimeString()); Part Three - Programming with .NET Assemblies } Chapter ... 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads } Chapter 4
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Notice 12 how- this method has a single parameter of typeLayer System.Object and returns void. This is not optional, given Chapter Object Serialization and the .NET Remoting that the13 TimerCallback delegate can(Introducing only call methods that match this signature. The value passed into the target Chapter - Building a Better Window Windows Forms) of your14 TimerCallback delegate can be any bit of information whatsoever (in the case of the e-mail example, this Chapter - A Better Painting Framework (GDI+) parameter represent theWindows name ofForms the MS Exchange server to interact with during the process). Also note Chapter 15 -might Programming with Controls that given parameter is indeed a System.Object, you are able to pass in multiple arguments using a Chapter 16 -that Thethis System.IO Namespace System.Array type.
Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
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 addition18to-aASP.NET TimerCallback delegate, theControls Timer constructor also allows you to specify the optional parameter Chapter 19 - to ASP.NET Webthe Applications information pass into delegate target, the interval to poll the method, as well as the amount of time to wait Chapter - XMLthe Web Services before 20 making first call. For example: Index List of Figures static void 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 information
to said method. If you did wish to send in some information for use by the delegate target, simply substitute the null C# and the .NET Platform, Second Edition value of the second constructor parameter with the appropriate information. For example, ponder the following ISBN:1590590554 by Andrew Troelsen updates: Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
static void PrintTime(object state) C# language and then quickly moves to key technical and { architectural issues for .NET developers. Console.WriteLine("Time is: {0}, Param is: {1}", DateTime.Now.ToLongTimeString(), state.ToString()); } Table of Contents ... C# and the .NET Platform, Second Edition Timer t = new Timer(timeCB, "Hi", 0, 1000); Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Figure 10-18 shows the output.
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Figure The (very useful) console-based clock application Chapter 9 - 10-18: Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
SOURCE CODE
The TimerApp application is included under the Chapter 10 subdirectory.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - up Object the .NET Remoting Layer That wraps our Serialization examinationand of multithreaded programming under .NET. To be sure, the System.Threading Chapter 13 Building a Better Window (Introducing Windows Forms) namespace defines numerous types beyond what I had the space to examine in this chapter. Nevertheless, at this Chapter 14 should - A Better Painting point you have a solidFramework foundation(GDI+) to build on. Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
The point of this chapter expose Apress ©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 alteredofunder This comprehensiveWin32 text starts with has a brief overview 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 moves to key technical and architectural type) issuesisfor .NET developers. System.Diagnostics.Process now composed on multiple application domains, which represent 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. Table of Contents Furthermore, a single application domain can contain any number of contextual boundaries. Using this C# and the .NET Second Edition additional level Platform, of type isolation, the CLR can ensure that special-need objects are handled correctly. Introduction
TheOne remainder of thisC# chapter examined the role Part - Introducing and the .NET Platform
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 ofadditional .NET able to 2carry out numerous tasks at (what appears to be) the same time. Finally, the chapter examined Chapter - Building C# Applications various in which you can mark thread-sensitive Part Two manners - The C# Programming Language
blocks of code to ensure that shared resources
do not become unusable Fundamentals units of bogus data. Chapter 3 - C# Language Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Chapter C# 11: Type Reflection, Late Binding, and AttributeISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) Based Programming This comprehensive text starts with a brief overview of the language and quicklyunit moves to key technical As you have seenC# ,assemblies arethen the basic of deployment in theand in the .NET universe. Tools such as architectural issues for .NET developers. 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 Table of Contents this design-time investigation of .NET assemblies, you are also able to programmatically obtain this same C# and the .NET Platform, Second Edition information using the types defined within the System.Reflection namespace. Introduction
Part - Introducing and the .NET Platform TheOne remainder of theC# chapter examines a number
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 Part Two - all The Language together ofC# theProgramming topics presented in 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
- Object-Oriented Programming with C#
- Exceptions and Object Lifetime The Necessity of Type Metadata
Chapter 5 Chapter 6
- Interfaces and Collections The ability fully qualify the definition of types using metadata is a key element of the .NET runtime. Numerous Chapter 7 -toCallback Interfaces, Delegates, and Events
.NET technologies such serialization, remoting, and XML Web services (among other things) all hinge on the Chapter 8 - Advanced C#as Type Construction Techniques ability to discover the format types at runtime. Part Three - Programming withof.NET Assemblies
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 - Understanding .NET Assemblies concrete description of type. As mentioned numerous times thus far, a .NET type is any member from the set Chapter 10 - Processes, AppDomains, Contexts, and Threads {class, interface, structure, enumeration, delegate}. .NET metadata is the vehicle used to describe the internal Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming composition of said members. Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
Regardless of (or perhaps due to) its importance, metadata is not a new idea supplied by the .NET Framework.
Chapter 13 - Building a Better (Introducing Windows Forms) under COM, IDL (Interface Definition Java, CORBA, and COM all Window have similar concepts. For example, Chapter 14 - is A used BettertoPainting Framework (GDI+) Language) describe the internal COM types found within a given COM server. Like COM, .NET code Chapter - Programming Windows Forms Controls libraries15also support typewith metadata. Understand, of course, that the .NET type metadata does not have the Chapter 16 - The same syntax as System.IO COM IDL! Namespace Rather, type metadata is internally documented as a more tabular (i.e., indexed) Chapter format.17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
As you 18 are- already usingand ildasm.exe, you are able to view an assembly's type metadata using the Chapter ASP.NETaware, Web Pages Web Controls "Ctrl+M" option (see Chapter 1). Thus, if you were to open any of the *.dll or *.exe assemblies created Chapter 19keyboard - ASP.NET Web Applications
over the course of this book (such as CarLibrary.dll) using ildasm.exe and hit Ctrl+M, you would find the relevant metadata visible for viewing (Figure 11-1).
Chapter 20 - XML Web Services Index
List of Figures 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# and the .NET Platform, Second Edition (where TypeDef is short for type definition). If the type being described uses a type defined within a separate ISBN:1590590554 by Andrew Troelsen .NET assembly, the referenced type is documented using the "TypeRef #n" token (where TypeRef is short for Apress © 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 comprehensive text starts with a brief overview of the nutshell, .NET metadata is a set of tables that clearly mark all internal type definitions (TypeDefs) and C# language and then quickly moves to key technical and referenced entities (TypeRefs), all offor which be viewed using ildasm.exe's metadata window. architectural issues .NETcan developers. 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: Table of Contents C# and the .NET Platform, Second Edition
TypeDef #1 Introduction ------------------------------------------------------Part One - Introducing C# and the .NET Platform 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 Part Two - The C# Programming Language ... Chapter 3 - C# Language Fundamentals Field #2 Chapter 4 - Object-Oriented Programming with C# ------------------------------------------------------Chapter 5 - Exceptions and Object Lifetime Field Name: engineAlive (04000002) Chapter 6 - Interfaces and Collections Flags : [Public] [Static] [Literal] [HasDefault] (00008056) Chapter DefltValue: 7 - Callback Interfaces, (I4) 0Delegates, and Events Chapter CallCnvntn: 8 - Advanced C# Type Construction Techniques [FIELD] Part Three - Programming .NET Assemblies Field type: with ValueClass CarLibrary.EngineState Chapter ... 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Here, the- Leveraging "TypDefName" token is used to Part Four the .NET Libraries
establish the name of the given type. The "Extends" metadata token
is used12 to -document the base class of a.NET given .NET type (in this case, the referenced type, System.Enum). Chapter Object Serialization and the Remoting Layer Each field an enumeration is marked using theWindows "Field #n" token. For brevity, I have simply listed the metadata Chapter 13 -ofBuilding a Better Window (Introducing Forms) for EngineState.engineAlive. Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Viewing (Partial) Metadata for the Car Type
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Each of -our automobiles is and alsoXML completely documented Part Five Web Applications Web Services
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 Controls 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 Applications methods are documented via .NET metadata, and (c) how a single type property is mapped to two discrete Chapter 20 - XML Web Services member functions: Index
List of Figures
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# and the: .NET Platform, Second(00000000) Edition ImplFlags [IL] [Managed] ISBN:1590590554 by Andrew Troelsen CallCnvntn: [DEFAULT] Apress © 2003 (1200 pages) hasThis This comprehensive ReturnType: Void text starts with a brief overview of the C# language and No arguments. then quickly moves to key technical and architectural issues for .NET developers.
...
Property #1 ------------------------------------------------------Table of Contents Prop.Name : PetName (17000001) C# and the .NET Platform, Second Edition Flags : [none] (00000000) Introduction CallCnvntn: [PROPERTY] Part One - Introducing C# and the .NET Platform hasThis Chapter 1 - The Philosophy of .NET ReturnType: String Chapter 2 - Building C# Applications No arguments. Part Two - The C# Programming Language DefltValue: Chapter 3 - C# Language Fundamentals Setter : (06000004) set_PetName Chapter 4 - Object-Oriented Programming with get_PetName C# Getter : (06000003) Chapter 5 - Exceptions and Object Lifetime 0 Others Chapter ... 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
First, note-that the Car class marks the Part Three Programming withmetadata .NET Assemblies
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 - Understanding .NET Assemblies are described in regard to their parameters, return value, Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming the derived Car types (SportsCar and MiniVan) are described in a similar manner. Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
Examining a TypeRef
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (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 System.IO Namespace enumerations, we find a TypeRef block for the System.Enum type: Chapter 15 - Programming with Windows Forms Controls Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
TypeRef (01000001) Chapter 18 -#1 ASP.NET Web Pages and Web Controls ------------------------------------------------------Token: 0x01000001 Chapter 20 - XML Web Services ResolutionScope: 0x23000001 Index TypeRefName: System.Enum List of Figures MemberRef #1 List of Tables ------------------------------------------------------Member: (0a00000f) ToString: CallCnvntn: [DEFAULT] hasThis ReturnType: String No arguments. Chapter 19 - ASP.NET Web Applications
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# and the .NET Platform, Second Edition Token: 0x20000001 ISBN:1590590554 by Andrew Troelsen Name : CarLibrary Apress © 2003 (1200 pages) Public Key : This comprehensive text starts with a brief overview of the Hash Algorithm : 0x00008004 C# language and then quickly moves to key technical and Major Version: 0x00000001 architectural issues for .NET developers. Minor Version: 0x00000000 Build Number: 0x000003d6 Revision Number: 0x00005da4 Table of Contents Locale: C# and the .NET Platform, Second Edition Flags : [SideBySideCompatible] (00000000) Introduction CustomAttribute #1 (0c000001) Part One - Introducing C# and the .NET Platform ------------------------------------------------------Chapter 1 - The Philosophy of .NET CustomAttribute Type: 0a000001 Chapter 2 - Building C# Applications CustomAttributeName: Part Two - The C# Programming Language System.Reflection.AssemblyKeyNameAttribute :: Chapter instance 3 - C# Language void Fundamentals .ctor(class System.String) Chapter Length: 4 - Object-Oriented Programming with C# 5 Chapter Value 5 - Exceptions and Object : 01 00 00 00 Lifetime 00 Chapter ctor 6 - Interfaces and Collections args: ("") Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Documenting Referenced Assemblies - Understanding .NET Assemblies
Chapter 9
Chapter 10 -toProcesses, AppDomains, Contexts, Threads and TypeRef blocks, .NET metadata also makes use In addition the Assembly token and the set and of TypeDef Chapter 11 - Type Reflection, Binding, and Attribute-Based Programming of "AssemblyRef #n" tokensLate to document each external assembly. Given that our CarLibrary.dll makes use of Part - Leveraging the Four MessageBox type,the we.NET find Libraries an AssemblyRef
for System.Windows.Forms. For example:
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building AssemblyRef #2 a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) ------------------------------------------------------Chapter 15 0x23000002 - Programming with Windows Forms Controls Token: Chapter 16 Key - Theor System.IO Public Token:Namespace b7 7a 5c 56 19 34 e0 89 Chapter Name:System.Windows.Forms 17 - Data Access with ADO.NET Part Major Five -Version: Web Applications 0x00000001 and XML Web Services
Minor18Version: Chapter - ASP.NET 0x00000000 Web Pages and Web Controls Build19Number: Chapter - ASP.NET0x00000ce4 Web Applications Revision Number: 0x00000000 Chapter 20 - XML Web Services Locale: Index HashValue List of Figures 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 " the .NET Platform, Second Edition 700000cd : ( C# 2)and L"!!" by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Now, don't be tooThis concerned with thetext exact syntax and every comprehensive starts withof a each brief overview ofpiece the of .NET metadata. The bigger point C# language andisthen moves to lists key technical and to absorb is that .NET metadata veryquickly descriptive and each internally defined (and externally referenced) .NET developers. type found within architectural a given codeissues base.for The next question on your mind may be (in the best-case scenario), "How 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 headTable of Contents scratcher until this chapter's endgame. So hang tight. C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andReflection the .NET Platform, Second Edition Understanding by Andrew Troelsen
ISBN:1590590554
In the .NET universe, reflection is the process of runtime type discovery. Using reflection services, you are Apress © 2003 (1200 pages) able to load an assembly at runtime and discover same sort of information presented by the This comprehensive text starts withthe a brief overview of the ildasm.exe metadata window, using a friendly object model. For example, through reflection, you can C# language and then quickly moves to key technical and issues for .NET developers. obtain a list of all architectural 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 Table ofclass Contents (base details, namespace information, manifest data, and so forth). C# and the .NET Platform, Second Edition
To understand how to use reflection services to read .NET metadata, you need to come to terms with the Introduction Type class (defined inC# the System namespace) Part One - Introducing and the .NET Platform
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 Philosophyclass of .NET information the current type you happen to be observing. The System.Reflection namespace Chapter 2 - about Building C# Applications contains related types to facilitate Part Two - numerous The C# Programming Language
late binding and dynamic loading of assemblies. To begin,
let's investigate System.Type in some detail. Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The System.Type Class by Andrew Troelsen
ISBN:1590590554
Many of the itemsApress defined within thepages) System.Reflection namespace make use of the abstract System.Type © 2003 (1200 class. This class This provides a number of methods thata can used toofdiscover the details behind a given item. comprehensive text starts with briefbe overview the The complete setC# of language membersand is quite expansive; however, Table 11-1 offers a partial snapshot of the then quickly moves to key technical and architectural issues for .NET developers. members supported by System.Type. Table 11-1: Select Members of System.Type
Table of Contents
Member in Life C#Type and the .NET Platform,Meaning Second Edition Introduction
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 Part One - Introducing C# and the .NET Platform
Part Two - The C# Programming Language IsCOMObject
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
IsEnum
IsInterface Chapter 5 - Exceptions and Object Lifetime IsPrimitive Chapter 6 - Interfaces and Collections Chapter 7 - Callback Interfaces, Delegates, and Events IsNestedPublic Chapter 8
- Advanced C# Type Construction Techniques
IsNestedPrivate
Part Three - Programming with .NET Assemblies
IsSealed Chapter 9 - Understanding .NET Assemblies IsValueType Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer returns a related array (e.g., GetFields() returns a FieldInfo array, GetFields() Chapter 13 - Building a Better Window (Introducing Windows Forms) GetMethods() returns a MethodInfo array, etc.). Chapter 14 - A Better Painting Framework (GDI+) GetInterfaces() Be aware that each of these methods has a singular form (e.g., GetMethod(), Part Four - Leveraging the .NET Libraries
Chapter 15 - Programming with Windows Forms Controls
GetMethods()
GetProperty()) that allows you to retrieve a specific item by name, rather than an array of all related items.
Chapter 16 - The System.IO Namespace
GetMembers()
Chapter 17 - Data Access with ADO.NET
GetNestedTypes() Part Five - Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls GetProperties() Chapter 19 - ASP.NET Web Applications
FindMembers()
Returns an array of MemberInfo types, based on search criteria.
Chapter 20 - XML Web Services Index GetType() List of Figures
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# and the .NET Platform, Second Edition examining (and optionally, a System.Boolean to indicate case sensitivity): by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
// Get a Type using the static Type.GetType() method. This comprehensive text starts with a brief overview of the Type t = null; C# language and then quickly moves to key technical and t = Type.GetType("Foo"); architectural issues for .NET developers.
Table of Contents
Here, are able to simply pass in the friendly name of the Type.GetType() method, assuming a type C# and you the .NET Platform, 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 Part One - Introducing C# and the .NET Platform 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: Introduction
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
// Get a- Object-Oriented nested typeProgramming in a distinct assembly. with C# Type t = Chapter 5 - Exceptions and Object Lifetime Type.GetType("MyNamespace.OuterType+NestedType, myOtherAsm"); Chapter 4 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter C# Type Techniques Finally,8you- Advanced can also obtain an Construction instance of Type using the C# typeof() operator: Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies // Get the Type using typeof.
Chapter 10 =- Processes, AppDomains, Contexts, and Threads Type t typeof(Foo); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter Notice 12 that- Type.GetType() Object Serialization andand typeof() the .NET areRemoting helpful inLayer that you do not need to first create an object instance
to extract information (which is obviously quite helpful Forms) when employing late binding), whereas the use of Chapter 13 type - Building a Better Window (Introducing Windows the inherited Chapter 14 - ASystem.Object.GetType() Better Painting Framework method (GDI+) does. In any case, now that you understand how to obtain a Type reference, let's examine how you Forms can exercise it. Chapter 15 - Programming with Windows Controls Chapter 16 - The System.IO Namespace
Fun with the Type Class
Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
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 Controls follows19 (the implementation of the various methods is irrelevant for this example): Chapter - ASP.NET Web Applications Chapter 20 - XML Web Services
// These are the items we will discover at runtime. Index namespace List of Figures 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# and Platform, Second Edition get the { .NET return myIntField; } by Andrew Troelsen set { myIntField = value; } ISBN:1590590554 } Apress © 2003 (1200 pages) comprehensive text starts with a brief overview of the // This IFaceOne and IFaceTwo methods. C# language and then quickly moves public void MethodA() {...} to key technical and architectural issues for .NET developers.
public void MethodB() {...}
} }
Table of Contents C# and the .NET Platform, Second Edition Introduction Now, let's create a program that is able to discover the methods, properties, supported interfaces, and fields Part One - Introducing C# and the .NET Platform
for a given Foo object (in addition 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: Part Two - The C# Programming Language
Chapter 3
C# Language Fundamentals // Suck -out all method names from Foo.
Chapter 4 static - Object-Oriented Programming with C#f) public void ListMethods(Foo Chapter 5 Exceptions and Object Lifetime { Chapter Console.WriteLine("***** 6 - Interfaces and Collections Methods of Foo *****"); Chapter Type 7 - Callback Interfaces, Delegates, and Events t = f.GetType(); Chapter MethodInfo[] 8 - Advanced C# mi Type= Construction Techniques t.GetMethods(); Part Three - Programming with .NETm Assemblies foreach(MethodInfo in mi)
Chapter 9
- Understanding Console.WriteLine("Method: .NET Assemblies {0} ", m.Name); Chapter Console.WriteLine("*************************\n"); 10 - Processes, AppDomains, Contexts, and Threads
} Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
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 Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
// Suck out all fields from Foo. public static void ListFields(Foo f) Chapter 17 - Data Access with ADO.NET { Part Five - Web Applications and XML Web Services Console.WriteLine("***** Fields of Foo *****"); Chapter 18 - ASP.NET Web Pages and Web Controls Type t = f.GetType(); Chapter 19 - ASP.NET Web Applications FieldInfo[] fi = t.GetFields(); Chapter 20 - XML Web Services foreach(FieldInfo field in fi) Index Console.WriteLine("Field: {0} ", field.Name); List of Figures Console.WriteLine("*************************\n"); List } of Tables Chapter 16 - The System.IO Namespace
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# and the .NET Platform, Second Edition } ISBN:1590590554 Andrew Troelsen // Gather allby properties. Apress © 2003 (1200 pages) public static void ListProps(Foo f) This comprehensive text starts with a brief overview of the { C# language and then quickly moves to key and Console.WriteLine("***** Properties of technical Foo *****"); architectural issues for .NET developers. Type t = f.GetType(); PropertyInfo[] pi = t.GetProperties(); foreach(PropertyInfo prop in pi) Table of Contents Console.WriteLine("Prop: {0} ", prop.Name); C# and the .NET Platform, Second Edition Console.WriteLine("*****************************\n"); Introduction } Part One - Introducing C# and the .NET Platform // Dump all interfaces supported by Foo. Chapter 1 - The Philosophy of .NET public static void ListInterfaces(Foo f) Chapter 2 - Building C# Applications { Part Two - The C# Programming Language Console.WriteLine("***** Interfaces of Foo *****"); Chapter Type 3 - C# Fundamentals t Language = f.GetType(); Chapter Type[] 4 - Object-Oriented with C# ifaces =Programming t.GetInterfaces(); Chapter foreach(Type 5 - Exceptions and Object Lifetime i in ifaces) Chapter 6 - Interfaces and Collections Console.WriteLine("Interface: {0} ", i.Name); Chapter Console.WriteLine("*****************************\n"); 7 - Callback Interfaces, Delegates, and Events Chapter } 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies The Main() of the FooReader class simply calls each static method: Chapter 10 - method Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Four Put - Foo underthethe Part Leveraging .NETmagnifying Libraries
glass.
using12System; Chapter - Object Serialization and the .NET Remoting Layer // Needed to gain definitions of MethodInfo, FieldInfo, etc. Chapter 13 - Building a Better Window (Introducing Windows Forms) using14System.Reflection; Chapter - A Better Painting Framework (GDI+) namespace TheType { Chapter 16 - The System.IO Namespace public class FooReader Chapter 17 - Data Access with ADO.NET { Part Five - Web Applications and XML Web Services // ...Static methods seen previously... Chapter 18 - ASP.NET Web Pages and Web Controls public static int Main(string[] args) Chapter 19 - ASP.NET Web Applications { Chapter 20 - XML Web// Services Make a new Foo object. Index Foo theFoo = new Foo(); List of Figures // Now examine everything. List of Tables ListVariousStats(theFoo); ListMethods(theFoo); ListFields(theFoo); ListProps(theFoo); ListInterfaces(theFoo); return 0; } } } Chapter 15 - Programming with Windows Forms Controls
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# and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen public enum MyNestedEnum{} Apress © 2003 (1200 pages) ... This comprehensive text starts with a brief overview of the } C# language and then quickly moves to key technical and architectural issues for .NET developers.
Recall that nested items can be identified using the "+" token. Thus, to obtain metadata information for MyNestedEnum, you could write the following:
Table of Contents
C# and the .NET Platform, Second Edition
// Get info on nested enum. Type t = Type.GetType("TheType.Foo+MyNestedEnum"); Part One - Introducing C# and the .NET Platform 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); Introduction
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4 -System.Type Object-Oriented Programming with C# Obviously, provides additional members beyond the items seen thus far. One especially Chapter 5 -member Exceptions and Object Lifetime interesting is named GetInterfaceMap(). Recall that explicit interface implementation allows you to Chapter map a 6given - Interfaces interface and method Collections to a particular class method. GetInterfaceMap() can be used to obtain these
relationships at runtime. To illustrate, update Foo type to make use of explicit interface implementation: Chapter 7 - Callback Interfaces, Delegates, andthe Events Chapter 8
- Advanced C# Type Construction Techniques
Part Programming with .NET Assemblies // Three Use -explicit interface impl.
Chapter 9 class - Understanding .NET Assemblies public Foo: IFaceOne, IFaceTwo Chapter { 10 - Processes, AppDomains, Contexts, and Threads
IFaceOne.MethodA(){} Chapter void 11 - Type Reflection, Late Binding, and Attribute-Based Programming IFaceTwo.MethodB(){} Part Fourvoid - Leveraging the .NET Libraries Chapter ... 12 - Object Serialization and the .NET Remoting Layer
} Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Now, create the following additional helper method:
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
public static void MapInterfaceMethodsToClassMethods(Foo f) { Chapter 18 - ASP.NET Web Pages and Web Controls Console.WriteLine("***** Explicit interface impl mappings *****"); Chapter 19 - ASP.NET Web Applications Type t = f.GetType(); Chapter 20 - XML Web Services // Get all interfaces on type. Index Type[] iFaces = t.GetInterfaces(); List of //Figures Do the following for each interface on type. List of Tables i = 0; i < iFaces.Length; i ++) for(int { 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(); } Part Five - Web Applications and XML Web Services
} C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
© 2003 (1200 pages) This example is aApress bit more involved. First, we obtain a list of each interface supported by the Foo type using GetInterfaces(), which is held in a System.Type array. Next, we loopofthrough each member in the array and This comprehensive text starts with a brief overview the C# language and then moves key technical and extract an array of MethodInfo types to quickly represent the to names class methods, and another MethodInfo array architectural for .NET developers. representing the names of theissues interface methods. Once we have all the necessary information, we simply print out the association to the console window. Figure 11-2 shows partial output of your first reflection application.
Table of Contents
C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - 11-2: The System.IO Figure ReflectingNamespace on Foo Chapter 17 - Data Access with ADO.NET Part Interesting Five - Web stuff, Applications huh? Whileand theXML System.Type Web Services class
can be very helpful on its own, reflection becomes even
more powerful when Web you make theControls Assembly class defined within the System.Reflection namespace. Chapter 18 - ASP.NET Pages use and of Web Chapter 19 - ASP.NET Web Applications
SOURCE CODE
The TheType project can be found under the Chapter 11 subdirectory.
Chapter 20 - XML Web Services Index
List of Figures List of Tables
C# and .NET Platform, Second Edition Investigating thethe System.Reflection Namespace by Andrew Troelsen
ISBN:1590590554
Like any namespace, System.Reflection Apress © 2003 (1200 pages) contains a number of related types. Like any namespace, some types are of moreThis immediate interesttext thanstarts others. 11-2 lists some comprehensive withTable a brief overview 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 moves to key technical andexample. architectural issues for .NET developers.
Table 11-2: A Sampling of Members of the System.Reflection Namespace System.Reflection Table of Contents
Meaning in Life Type C# and the .NET Platform, Second Edition Introduction
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. Part One - Introducing C# and the .NET Platform
Chapter 2
- Building C# Applications
AssemblyName This class Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime EventInfo Holds information for a given event. Chapter 6 - Interfaces and Collections
FieldInfo Holds information for a given field. Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8 - Advanced C# Type Construction Techniques MemberInfo This is the abstract base class that defines common behaviors for Part Three - Programming with .NET theAssemblies EventInfo,
Chapter 9
FieldInfo, MethodInfo, and PropertyInfo types.
- Understanding .NET Assemblies
MethodInfo
Contains information for a given method.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Allows Binding, and Module you toAttribute-Based access a givenProgramming module within a multifile assembly. Part Four - Leveraging the .NET Libraries
ParameterInfo
Holds information for a given parameter.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Forms) PropertyInfo Holds informationWindows for a given property. Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Reflecting on a Private Assembly by Andrew Troelsen
ISBN:1590590554
The real workhorse of System.Reflection Apress © 2003 (1200 pages) is the Assembly class. Using this type, you are able to dynamically load an assembly, invoke class members at runtime well as discover properties about the This comprehensive text starts with a (late brief binding), overview 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 moves to key technical and issues for .NET developers. Assume you havearchitectural a 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: Table of Contents C# and the .NET Platform, Second Edition
using System; using System.Reflection; Part One - Introducing C# and the .NET Platform using System.IO; // Needed for FileNotFoundException definition. Chapter 1 - The Philosophy of .NET // Investigate the CarLibrary assembly. Chapter 2 Building C# Applications namespace CarReflector Part { Two - The C# Programming Language Chapter public 3 - C# Language Fundamentals class CarReflector Chapter { 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions Object int Lifetime public and static Main(string[] args) Chapter 6 - Interfaces { and Collections // Use Assembly class to load the CarLibrary. Chapter 7 - Callback Interfaces, Delegates, and Events Assembly a = null; Chapter 8 - Advanced C# Type Construction Techniques trywith .NET Assemblies Part Three - Programming { Chapter 9 - Understanding .NET Assemblies a = Assembly.Load("CarLibrary"); Chapter 10 - Processes, AppDomains, Contexts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming e) Part Four - Leveraging catch(FileNotFoundException the .NET Libraries { Console.WriteLine(e.Message);} Chapter 12 - Object Serialization and the .NET Remoting Layer return 0; Chapter 13 - Building a Better Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls } Introduction
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Fivethat - Web and XML Web Services Notice theApplications static Assembly.Load() method has
been passed in the friendly name of the assembly we are
Chapter 18 -inASP.NET Web memory Pages and Webthus Controls interested loading into (and assumes that the CarLibrary.dll is contained within the application Chapter directory 19of - the ASP.NET executable). Web Applications As you may 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 Services information sent into Assembly.Load() may contain additional string segments beyond the friendly name. Index Specifically, List of Figures 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# and the .NET Platform, Second Edition @"CarLibrary, Version=1.0.982.23972, PublicKeyToken=null, Culture="""); by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C#the language and then quickly moves tosupplies key technical and Also be aware that System.Reflection namespace the AssemblyName type, which allows you to architectural issues for in .NET developers. represent the above string information a handy object variable. Typically, this class is used in conjunction with 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:
Table of Contents
C# and the .NET Platform, Second Edition
// Our OO-Aware display name. AssemblyName asmName; Part One - Introducing C# and the .NET Platform 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"); Part Two - The C# Programming Language asmName.Version = v; Chapter 3 - C# Language Fundamentals a = Assembly.Load(asmName); Introduction
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections Note Assembly type also definesand a static LoadFrom() method that allows you to load an assembly Chapter 7 The - Callback Interfaces, Delegates, Events
a given (for example, C:\MyAsms). Chapter 8 using - Advanced C#code Typebase Construction Techniques Part Three - Programming with .NET Assemblies
- Understanding .NET in Assemblies Enumerating Types a Referenced Assembly
Chapter 9
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Now that have a reference the CarLibrary assembly, you can discover the name of each type it contains Chapter 11 you - Type Reflection, LatetoBinding, and Attribute-Based Programming using the- static Assembly.GetTypes() Part Four Leveraging the .NET Librariesmethod.
Here is a helper method named ListAllTypes() that does this very
thing (assume this Serialization method is called within afterLayer loading the CarLibrary.dll): Chapter 12 - Object and the .NETMain() Remoting Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter // List 14 -all A Better types Painting within Framework the (GDI+) assembly.
private voidwith ListAllTypes(Assembly a) Chapter 15 -static Programming Windows Forms Controls { Chapter 16 - The System.IO Namespace Types in Assembly *****"); Chapter Console.WriteLine("***** 17 - Data Access with ADO.NET a.FullName); Part FiveConsole.WriteLine("->{0}\n", - Web Applications and XML Web Services Type[] types = a.GetTypes(); Chapter 18 - ASP.NET Web Pages and Web Controls in types) Chapter foreach(Type 19 - ASP.NET WebtApplications Console.WriteLine("Type: {0}", t); Console.WriteLine("******************************\n");
Chapter 20 - XML Web Services Index
}
List of Figures 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# and the .NETm Platform, foreach(MemberInfo in mi) Second Edition ISBN:1590590554 by Andrew Troelsen Console.WriteLine("{0}: {1} ", Apress © 2003 (1200 pages) m.MemberType.ToString(), m); This comprehensive text starts with a brief overview of the Console.WriteLine("******************************\n"); C# language and then quickly moves to key technical and architectural issues for .NET developers.
}
Enumerating Method Parameters
Table of Contents
C# and the .NET Platform, Second Edition
Not only can you use reflection to gather information for the members of a type, you can also obtain information Introduction about the parametersC# of and a given member. To illustrate, Part One - Introducing the .NET Platform
let's assume that the Car class has defined the following
additional Chapter 1 -method: The Philosophy of .NET Chapter 2
- Building C# Applications
// Two A new of the Language Car class. Part - Themember C# Programming public TurnOnRadio(bool Chapter 3 void - C# Language Fundamentals state, MusicMedia mm) { Chapter 4
- Object-Oriented Programming with C# Chapter if(state) 5 - Exceptions and Object Lifetime
MessageBox.Show("Jamming with {0} ", mm.ToString()); - Interfaces and Collections else Chapter 7 - Callback Interfaces, Delegates, and Events MessageBox.Show("Quiet time..."); Chapter 8 - Advanced C# Type Construction Techniques } Chapter 6
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads TurnOnRadio() takes two parameters, the second of which is a custom enumeration: Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
// Holds source of music. public enum MusicMedia Chapter 13 - Building a Better Window (Introducing { musicCD, musicTape, musicRadio } Windows Forms) Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Extracting for the parameters of TurnOnRadio() requires using MethodInfo.GetParameters(). This Chapter 16 -information The System.IO Namespace method17returns ParameterInfo array. Each item in this array contains numerous properties for a given Chapter - DataaAccess with ADO.NET parameter. Here is anotherand static method of the CarReflector Part Five - Web Applications XML Web Services
class, GetParams(), which displays various details
for each thePages TurnOnRadio() method (see Figure 11-3 for partial output): Chapter 18parameter - ASP.NETof Web and Web Controls Chapter 19 - ASP.NET Web Applications
// Get information for the TurnOnRadio() method. Chapter 20 parameter - XML Web Services private static void GetParams(Assembly a) Index { of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction
Figure 11-3: Reflecting on a private assembly
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET SOURCE The CarReflector project is included in the Chapter 11 subdirectory. Chapter 2 Building C# Applications CODE Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NETAssemblies Platform, Second Edition Reflecting on Shared by Andrew Troelsen
ISBN:1590590554
The Assembly type can ©also used to load a shared assembly (i.e., a GAC deployed .NET binary). To do so, Apress 2003be (1200 pages) your Load() method must specify a full the assembly to be loaded. Assume you wish to load This comprehensive textdisplay starts name with a for brief overview of the version 1.0.0.0 ofC# thelanguage SharedAssembly.dll you created in Chapter 9. The and then quickly moves to key technical and following code prints out various architectural issues developers. statistics of this binary and then lists for the.NET names of each type (be sure to update the value of publickeytoken to use your own! ): Table of Contents
namespace SharedAsmReflector { Introduction public class SharedAsmReflector Part One - Introducing C# and the .NET Platform { Chapter 1 - The Philosophy of .NET void DisplayInfo(Assembly a) private static Chapter 2 - Building C# Applications { Part Two - The C# Programming Language Console.WriteLine("***** Info about Assembly *****"); Chapter 3 - C# Language Fundamentals Console.WriteLine("Loaded from GAC? {0}", a.GlobalAssemblyCache); Chapter 4 - Object-Oriented Programming with C# Console.WriteLine("Asm Name: {0}", a.GetName().Name); Chapter 5 - Exceptions and Object Lifetime Console.WriteLine("Asm Version: {0}", a.GetName().Version); Chapter 6 - InterfacesConsole.WriteLine("Asm and Collections Culture: {0}", Chapter 7 - Callback Interfaces,a.GetName().CultureInfo.DisplayName); Delegates, and Events = a.GetTypes(); Chapter 8 - AdvancedType[] C# Type types Construction Techniques foreach(Type t in types) Part Three - Programming with .NET Assemblies Console.WriteLine("Type: {0}", t); Chapter 9 - Understanding .NET Assemblies Console.WriteLine("******************************\n"); Chapter 10 - Processes, AppDomains, Contexts, and Threads } Reflection, Late Binding, and Attribute-Based Programming Chapter 11 - Type publicthestatic int Main(string[] args) Part Four - Leveraging .NET Libraries { Chapter 12 - Object Serialization and the .NET Remoting Layer // Load from GAC (without error checking...) Chapter 13 - Building a Better Window (Introducing Windows Forms) // Adjust your publickeytoken value! Chapter 14 - A Better Painting Framework (GDI+) Assembly a = null; Chapter 15 - Programming with Windows Forms Controls string displayName = "SharedAssembly," + Chapter 16 - The System.IO Namespace "Version=1.0.0.0," + Chapter 17 - Data Access with"PublicKeyToken=82fbc820d160f2b8," ADO.NET + Part Five - Web Applications and XML Web Services @"Culture="""; Chapter 18 - ASP.NET a Web and Web Controls = Pages Assembly.Load(displayName); Chapter 19 - ASP.NET DisplayInfo(a); Web Applications Chapter 20 - XML Webreturn Services 0; Index } List of Figures } } of Tables List C# and the .NET Platform, 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# and .NET Platform, Second The the SharedAsmReflector projectEdition is included in the Chapter 11 subdirectory. ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages)
Sweet! At this point you understand how usewith some of the core items defined within the System.Reflection This comprehensive text to starts a brief overview of the namespace to discover a wealth of information at runtime. And, maybe C# language and then quickly moves to key technical andyou are already envisioning the code issues .NET developers. behind tools sucharchitectural as ildasm.exe andfor wincv.exe. Next up, let's check out how to create and interact with types on the fly via .NET late binding. Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andDynamic the .NET Platform, Second Edition Understanding Invocation (Late Binding) by Andrew Troelsen
ISBN:1590590554
The System.Reflection provides additional functionality beyond runtime type discovery. .NET Apress namespace © 2003 (1200 pages) reflection servicesThis also provides the to exercise "lateoverview binding" of to the a type. Simply put, late binding is a comprehensive ability text starts with a brief technique in which you are able create a given type and invoke its members at runtime without having C# language and then quickly moves to key technical and architectural for .NET developers. compile-time knowledge of itsissues 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 Table of Contents search heuristics when searching for the location of the dynamically referenced type (code bases, public C# and the .NET Platform, Secondfiles, Edition key tokens, XML configuration and the like). Introduction
TheOne value of late binding maythe not.NET be immediately Part - Introducing C# and Platform
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 a place builders, asLanguage well as COM/.NET Part Two among - The C#tool Programming
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 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
The Activator - InterfacesClass and Collections
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
The System.Activator class is the key to .NET late binding. Beyond the methods inherited from Object, Chapter 8 - Advanced C# Type Construction Techniques Activator only defines a small set of members. Activator.CreateInstance() is one core method that creates Part Three - Programming with .NET Assemblies an instance of a type at runtime. This method has been overloaded numerous times to provide a good Chapter 9 - Understanding .NET Assemblies deal of flexibility. The simplest variation of the CreateInstance() member takes a valid Type variable that Chapter 10 - Processes, AppDomains, Contexts, and Threads describes the entity you wish to invoke: Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
// Create a type dynamically. public class LateBind Chapter 13 - Building a Better Window (Introducing Windows Forms) { Chapter 14 - A Better Painting Framework (GDI+) public static int Main(string[] args) Chapter 15 - Programming with Windows Forms Controls { Chapter 16 - The System.IO Namespace // Assume the CarLibrary is in the app directory. Chapter 17 - Data Access with Assembly a ADO.NET = null; Part Five - Webtry Applications and XML Web Services Chapter 18 - ASP.NET Pages and Web Controls { a =Web Assembly.Load("CarLibrary"); } Chapter 19 - ASP.NET Web Applications catch(FileNotFoundException e) Chapter 20 - XML Services { Web Console.WriteLine(e.Message);} Index // Specify the fully qualified name of the Minivan type. List of Figures Type miniVan = a.GetType("CarLibrary.MiniVan"); List of Tables // Create the Minivan on the fly. object obj = Activator.CreateInstance(miniVan); } } Chapter 12 - Object Serialization and the .NET Remoting Layer
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# and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen // Use Assembly class to load the CarLibrary. Apress © 2003 (1200 pages) ... This comprehensive text starts with a brief overview of the // Get the MiniVan type. C# language and then quickly moves to key technical and Type miniVan = a.GetType("CarLibrary.MiniVan"); architectural issues for .NET developers. // Create the MiniVan on the fly. object obj = Activator.CreateInstance(miniVan); Get info for TurboBoost. Table of // Contents MethodInfo miSecond = miniVan.GetMethod("TurboBoost"); C# and the .NET Platform, Edition // Invoke method ('null' for no parameters). Introduction mi.Invoke(obj, null); Part One - Introducing C# and the .NET Platform return 0; Chapter 1 - The Philosophy of .NET } Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3 - C# Fundamentals At this point youLanguage are happy to see Figure 11-4. Chapter 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure Late bound method invocation Chapter 11 - 11-4: Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
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 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
// Quiet down the troops... public void TellChildToBeQuiet(string kidName, int shameIntensity) Chapter 16 - The System.IO Namespace { Chapter 17 - Data Access with ADO.NET for(int i = 0 ; i < shameIntensity; i++) Part Five - Web Applications and XML Web Services MessageBox.Show("Be quiet {0} !!", kidName); Chapter 18 - ASP.NET Web Pages and Web Controls } Chapter 15 - Programming with Windows Forms Controls
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Index TellChildToBeQuiet() takes two parameters. In this case, the array of parameters must be fleshed out as List follows: of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andAttributed the .NET Platform, Second Edition Understanding Programming by Andrew Troelsen
ISBN:1590590554
The official metalanguage of the component object model (COM) is IDL. As you may know, IDL is used to Apress © 2003 (1200 pages) describe the set of types defined within a given classic COM server.of Tothe describe these types in completely This comprehensive text starts with a brief overview unambiguous terms, IDL makes use of "attributes," which are simply IDL C# language and then quickly moves to key technical and keywords placed in square issues for .NET developers. brackets. A givenarchitectural attribute block always applies to the 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 Table of Contents an example of a classic COM interface, making use of various IDL attributes: C# and the .NET Platform, Second Edition Introduction
[object, uuid(4CB8B79A-E991-4AA4-8DB8-DD5D8751407D), oleautomation] Chapter 1 - The Philosophy of .NET interface IRememberCOM : IUnknown Chapter 2 Building C# Applications { Part Two[helpstring("If - The C# Programming Language you send me a string, I will change it...")] Chapter 3 HRESULT - C# Language Fundamentals TextManipulation([in] BSTR myStr, [out, retval] BSTR* newStr); Chapter } ; 4 - Object-Oriented Programming with C# Part One - Introducing C# and the .NET Platform
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections Once a7COM type has been assigned various it can be discovered at runtime programmatically, Chapter - Callback Interfaces, Delegates, and attributes, Events
or at design time usingC# various tools. For example, notice how the TextManipulation() method has been Chapter 8 - Advanced Type Construction Techniques assigned [helpstring] attribute, which is used to Part Three -a Programming with .NET Assemblies
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 - Understanding .NET Assemblies automatically extracted and displayed (Figure 11-5). Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Figure 11-5: Attributes in action
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Attributes have proven to be so helpful, that C# (as well as other .NET-aware languages) has integrated Index them as official aspects of the language. Using attributes, you are able to extend the metadata generated List of Figures 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# and the .NET Platform, Second Edition
Predefined .NET Meaning in Life by Andrew Troelsen Attribute Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the
CLSCompliant C# language Enforces all types in the assembly to the Common and thenthat quickly moves to key technicalconform and Language (CLS). This is the .NET equivalent of the IDL architectural issues forSpecification .NET developers. [oleautomation] attribute. DllImport
Table of Contents
Used to make calls to the native OS.
C#StructLayout and the .NET Platform, Second UsedEdition to configure the underlying representation of a structure. Introduction
Dispid
Specifies the DISPID for a member in a COM dispinterface.
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET a class or structure as being serializable. Serializable Marks Chapter 2 - Building C# Applications
NonSerialized
Specifies that a given field in a class or structure is not serializable.
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals WebMethod Marks a method as being invokable via HTTP requests. Chapter 4 - Object-Oriented Programming with C# Chapter As an example, 5 - Exceptions assume and that Object you wish Lifetime to assign 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 - Interfaces and Collections see, C#7 attributes look very much like IDL and attributes, Chapter - Callback Interfaces, Delegates, Events in that they are enclosed within square brackets: Chapter 8
- Advanced C# Type Construction Techniques
Part .NET Assemblies // Three This- Programming class can with be saved to disk.
Chapter [Serializable] 9 - Understanding .NET Assemblies
public Motorcycle Chapter 10 class - Processes, AppDomains, Contexts, and Threads { Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming hasRadioSystem; Part Fourbool - Leveraging the .NET Libraries hasHeadSet; Chapter bool 12 - Object Serialization and the .NET Remoting Layer hasSissyBar; Chapter bool 13 - Building a Better Window (Introducing Windows Forms) when you Framework do, don't bother with this field. Chapter // 14 -But A Better Painting (GDI+) [NonSerialized] float weightOfCurrentPassengers;
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
}
Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web 11-6), Pages and Controls Using ildasm.exe (Figure you Web can see that these attributes are now specified within the type Chapter 19 (note - ASP.NET Web Applications metadata the "serializable" and "notserialized" metadata tags). Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition [AttOne] by Andrew Troelsen [AttTwo] [AttThree] © 2003 (1200 pages) public class Apress SomeOtherClass{...}
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and issues for .NET Now at this point,architectural don't concern yourself withdevelopers. who or what is on the lookout for the presence of these
attributes. Just understand that attributed programming allows you to extend an assembly's metadata with annotations.
Table of Contents
C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Building Custom Attributes by Andrew Troelsen
ISBN:1590590554
C# (as well as other .NET-aware allows you to build custom attributes. Recall that attributes are Apress © 2003 (1200languages) pages) in fact a class derived from System.Attribute. Thus, when applied This comprehensive text starts with a briefwe overview ofthe 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 moves to key technical and issues for view, an attribute architectural is a class instance that.NET candevelopers. be applied to some other type. In the world of OOP, this approach is termed aspect-oriented programming . Table The of first Contents step to building your custom attribute is to create a new class deriving from System.Attribute. The
naming convention you should C# and the .NET Platform, 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 Introduction describing a particularC# automobile: Part One - Introducing and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter // A custom 2 - Building attribute. C# Applications Part public Two - The class C# Programming VehicleDescriptionAttribute Language
: System.Attribute { Chapter 3 - C# Language Fundamentals string description; Chapter private 4 - Object-Oriented Programming with C# public string Chapter 5 - Exceptions andDesc Object Lifetime Chapter { 6 - Interfaces and Collections get {Interfaces, return Delegates, description; } Chapter 7 - Callback and Events set { description = value; } Chapter 8 - Advanced C# Type Construction Techniques } Part Three - Programming with .NET Assemblies public VehicleDescriptionAttribute(string desc) Chapter 9 - Understanding .NET Assemblies { description = desc;} Chapter 10 - Processes, AppDomains, Contexts, and Threads public VehicleDescriptionAttribute(){ } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter Building a Better Window (Introducing Windows Forms) As you 13 can- see, VehicleDescriptionAttribute maintains a private internal string (description) that can be Chapter 14 - Ausing BetteraPainting manipulated custom Framework constructor(GDI+) and a named property (Desc). Now assume you wish to apply this Chapter attribute 15to- aProgramming new class named with Windows Winnebago. Forms Notice Controls how the constructor signature determines the exact
syntax of attribute: Chapter 16 the - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part - Web Applications XML Webattributes. Services // Five This class using and a custom
Chapter 18 - ASP.NET Web Pages and Web Controls [VehicleDescriptionAttribute("A very long, slow but feature rich auto")] Chapter public 19 class - ASP.NET Winnebago Web Applications
{ Chapter 20 - XML Web Services Index
public Winnebago(){ }
// Various methods... List of Figures } 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# CILand itself, you notice that custom attributes the .NET Platform, Second Editionare marked using the CIL instruction ".custom." by Andrew Troelsen
ISBN:1590590554
.class publicApress auto© 2003 ansi beforefieldinit Winnebago (1200 pages) extends [mscorlib]System.Object This comprehensive text starts with a brief overview of the { C# language and then quickly moves to key technical and architectural issues for .NET developers. .custom instance void CustomAtt.VehicleDescriptionAttribute::.ctor(string) ... Table of end Contents } // of class Winnebago C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Attribute Shorthand Notation - The Philosophy of .NET
Chapter 1
Chapter - Building C# offer Applications The C#2language does a shorthand notation for assigning an attribute to a given item. If the name of Part - Theattribute C# Programming Language yourTwo custom class does indeed have
a "-Attribute" suffix, you are allowed to omit this same suffix in
Chapter 3 base: - C# Language Fundamentals the code Chapter 4 - Object-Oriented Programming with C# Chapter 5
Exceptions and Object Lifetime // This -shortcut only works if the class is named VehicleDescriptionAttribute.
Chapter 6 - Interfaces and Collections [VehicleDescription("A very long, slow but feature rich auto")] Chapter 7 class - Callback Interfaces, Delegates, and Events public Winnebago Chapter 8 {
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET } Assemblies public Winnebago(){
Chapter // 9 -Various Understanding .NET Assemblies methods... Chapter 10 - Processes, AppDomains, Contexts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Be aware this is a courtesyand provided by Remoting C#. Not allLayer .NET-enabled languages support this feature. Chapter 12 that - Object Serialization the .NET Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition RestrictingC# Attribute Usage by Andrew Troelsen
ISBN:1590590554
Currently, the custom attribute haspages) no mechanism to prevent a developer from making illogical aspect Apress © 2003 (1200 specifications. ForThis example, the following is syntactically butofsemantically out of whack: comprehensive text starts with a briefcorrect, overview the C# language and then quickly moves to key technical and architectural issues for .NET developers. // Syntactically OK, but an odd use of this custom attribute... public class Winnebago { Table of Contents [VehicleDescriptionAttribute] // Calls default ctor of attribute class. C# and the .NET Platform, Second Edition public void TurnOnRadio() Introduction { Part One - Introducing C# and the .NET Platform } Chapter 1 - The Philosophy of .NET } Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
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 (and perhapsProgramming a structure),with but nothing else. If you wish to constrain your attributes in this way, Chapter - Object-Oriented C# you need make use and of the AttributeTargets enumeration: Chapter 5 to - Exceptions Object Lifetime Chapter 6
- Interfaces and Collections
Chapter // This 7 -enumeration Callback Interfaces, is Delegates, used to and control Events how a custom attribute can be applied.
public AttributeTargets Chapter 8 enum - Advanced C# Type Construction Techniques { Three - Programming with .NET Assemblies Part Assembly, .NET Class, Constructor, Chapter All, 9 - Understanding Assemblies Enum, Event, Field, Chapter Delegate, 10 - Processes, AppDomains, Contexts, and Threads Method, Module, Chapter Interface, 11 - Type Reflection, Late Binding, andParameter, Attribute-Based Programming Part FourProperty, - Leveraging ReturnValue, the .NET Libraries Struct
} Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
These values are passed as a parameter to the AttributeUsage attribute. This pre-defined attribute is used by
Chapter - Programming with Forms Controls the C# 15 compiler to enforce theWindows correct application of a custom attribute. The first parameter is an OR-ing Chapter 16 The System.IO Namespace together of members from the AttributeTarget enumeration. The second (optional) parameter is typically a
Chapter - Data Access with ADO.NET named17 argument (AllowMultiple), which specifies if the custom attribute can be used more than once on the Part Five - Web Applications and XML Web parameter Services same type. The final (optional) Boolean
determines if the attribute should be inherited by derived
Chapter 18 - ASP.NET Web Pages and Web Controls classes. Chapter 19 - ASP.NET Web Applications
Thus, you now configure Chapter 20 -can XML Web Services the VehicleDescriptionAttribute to apply only to classes or structures as follows: Index
//ofThis time, we are using the predefined AttributeUsage attribute List Figures //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!
and Module-) the .NET Platform, Second Edition Assembly- C# (and Level Attributes by Andrew Troelsen
ISBN:1590590554
It is also possibleApress to apply attributes on all types within a given module, or all modules within a given © 2003 (1200 pages) assembly using the [assembly: ] and [module: tags. This comprehensive text starts ]with a For briefexample, overview assume of the you wish to ensure that every type defined within your assembly is compliant with the CLS. C# language and then quickly moves to key technical and architectural issues for .NET developers.
// Enforce CLS compliance! using System; Table of Contents [assembly:System.CLSCompliantAttribute(true)] C# and the .NET Platform, Second Edition namespace MyAttributes Introduction { Part One - Introducing C# and the .NET Platform [VehicleDescriptionAttribute("A very long, slow but feature rich auto")] Chapter public 1 - The Philosophy of .NET class Winnebago Chapter { 2 - Building C# Applications Part Two - The C# Programming Language } public Winnebago(){ Chapter } 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# } Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections If we now a bit ofInterfaces, code that Delegates, falls outside the CLS specification: Chapter 7 add - Callback and Events Chapter 8
- Advanced C# Type Construction Techniques
// Three Ulong types don't with the Part - Programming withjive .NET Assemblies
CLS. public class Winnebago Chapter 9 - Understanding .NET Assemblies { Chapter 10 - Processes, AppDomains, Contexts, and Threads } Chapter public 11 - Type Winnebago(){ Reflection, Late Binding, and Attribute-Based Programming public ulong notCompliant; Part Four - Leveraging the .NET Libraries } Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (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 Programming with Windows Forms Controls numerous languages, the [CLSCompliant] attribute is extremely helpful. Chapter 16 - The System.IO Namespace
Note .NET [CLSCompliant] Chapter 17 The - Data Access with ADO.NETattribute can be applied to any item defined by the AttributeUsage enumeration. Thus, you Web only Services wish to selectively Part Five - Web Applications andifXML
mark specific items as CLS compliant, you
do so.Web Pages and Web Controls Chapter 18 may - ASP.NET Chapter 19 - ASP.NET Web Applications
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 Index aware of is that the [assembly:] and [module:] modifiers must be placed outside a namespace definition. Chapter 20 - XML Web Services List of Figures 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 Attribute in Life C# and the .NET Platform,Meaning Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
AssemblyCompanyAttribute
ISBN:1590590554
Holds basic company information.
AssemblyConfigurationAttribute This comprehensive text starts Build with information, a brief overview such of asthe "retail" or "debug." C# language and then quickly moves to key technical and
AssemblyCopyrightAttribute any copyright information for the product or architectural issues for .NET Holds developers. assembly. AssemblyDescriptionAttribute
Table of Contents
C# and the .NET Platform, Second Edition Introduction AssemblyInformationalVersionAttribute
A friendly description of the product or modules that make up the assembly. Additional or supporting version information, such as a product version number.
Part One - Introducing C# and the .NET Platform commercial
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
AssemblyProductAttribute
Part Two - The C# Programming Language AssemblyTrademarkAttribute
Product information. Trademark information.
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
AssemblyCultureAttribute
AssemblyKeyFileAttribute Chapter 6 - Interfaces 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 Interfaces, Delegates, and Events
Chapter 8
name). - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
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 - Processes, AppDomains, Contexts,container and Threads in the CSP. If you choose this option, this Chapter 11 - Type Reflection, Late Binding, andattribute Attribute-Based Programming will contain the name of the key container. Chapter 9
- Understanding .NET Assemblies
Part Four - Leveraging the .NET Libraries
AssemblyOperatingSystemAttribute Information on which operating system the assembly Chapter 12 - Object Serialization and the .NET Remoting Layer was built to support.
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) AssemblyProcessorAttribute Information on which processors the assembly was Chapter 15 - Programming with Windows Forms Controls built to support. Chapter 16 - The System.IO Namespace
AssemblyVersionAttribute
Chapter 17 - Data Access with ADO.NET
Specifies the assembly's version information, in the format .
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Reflecting on Attributes at Runtime by Andrew Troelsen
ISBN:1590590554
As you have seen, it is possible to obtain Apress © 2003 (1200 pages) attributes at runtime using the Type class. The logic behind doing so should be no surprise at this point: This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and issues for .NET developers. // Reflectingarchitectural on the custom attributes... public class AttReader { Table of Contents public static int Main(string[] args) C# and the .NET Platform, Second Edition { Introduction // Get the Type of Winnebago. Part One - Introducing C# and the .NET Platform 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); Part Two - The C# Language // Programming List all info. Chapter 3 - C# Language Fundamentals Console.WriteLine("***** Value of VehicleDescriptionAttribute *****\n"); Chapter 4 - Object-Oriented Programming with C# foreach(VehicleDescriptionAttribute v in customAtts) Chapter 5 - Exceptions and Object Lifetime Console.WriteLine("-> {0}\n", v.Desc); Chapter 6 - Interfaces returnand 0;Collections Chapter } 7 - Callback Interfaces, Delegates, and Events } Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
As the name implies, Type.GetCustomAttributes() returns an array (of System.Object types) that represent all the 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 Attribute-Based Programming attribute on the fly. What you do with this information is (of course) up to you. Chapter 10 - Processes, AppDomains, Contexts, and Threads Part Four - Leveraging the .NET Libraries
Chapter 12 Be - Object andAttribute.GetCustomAttribute() the .NET Remoting Layer Note awareSerialization that the static method allows you to obtain information for a Chapter 13 specific - Building a Better Window (Introducing Forms) attribute, rather than an array ofWindows all attributes on a given type. Chapter 14 - A Better Painting Framework (GDI+)
SOURCE The CustomAtt and AttReader applications are included under the Chapter 11 subdirectory. Chapter 15 - Programming with Windows Forms Controls CODE Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Putting Reflection, Late Binding, and Custom Attributes in ISBN:1590590554 by Andrew Troelsen PerspectiveApress © 2003 (1200 pages) text starts briefneed overview of the At this point, you This may comprehensive really be wondering if youwith will aever to make use of reflection, late binding, or C# language and then quickly moves to key technical and custom attributes. To be sure, these topics (while fascinating) can seem a bit on the academic side of architectural issues for .NET developers. 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. Table of Contents
Assume for the moment that you are on a programming team that is building an application that has the following requirement:
C# and the .NET Platform, Second Edition Introduction
Part One Introducing the .NETby Platform The- product mustC# beand extendible the use
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 Part Two - Thethis C# Programming Language
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 - Object-Oriented Programming with C# VS .NET team had to provide a mechanism by which other individuals (including yourself) could plug in new Chapter 5 - Exceptions and Object Lifetime behaviors. Chapter 6
- Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events Extendability is an awesome benefit, as third-party vendors can build (and profit from) custom software Chapter 8 We - Advanced C#developers Type Construction modules. benefit as as well,Techniques in that we are not required to by a brand-new (full price) IDE Part Three - Programming withfunctionality. .NET Assemblies simply to gain augmentative So, how
is it that tools such as VS .NET (and numerous other
Chapter applications) 9 - Understanding have been programmed .NET Assemblies for extendability? Chapter 10 - Processes, AppDomains, Contexts, 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 Part Four - Leveraging the .NET Libraries flag, or whatnot). Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13the - Building a Better Windowmust (Introducing Forms) Second, application in question be able Windows to determine if the module in question supports the correct Chapter 14 - AtoBetter Paintinginto Framework (GDI+) This advertisement of functionality could be provided via a functionality be plugged the environment. Chapter - Programming with Windows Forms specific15 interface or custom attribute. The key,Controls however, is to make the entity as generic as possible. Given Chapter 16 - The System.IO Namespace that attributes are nothing but advertisements, they seem like the most logical choice. Chapter 17 - Data Access with ADO.NET
Finally, the extendible application able to determine Part Five if- Web Applications and XML is Web Services
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 Controls 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 Applications be cached for further use or discarded (at the whim of the extendible application). Chapter 20 - XML Web Services
Index Simply put, if the extendible application has been preprogrammed to query for specific interfaces (and/or List of Figuresit is able to determine at runtime if the item in question is worthy of activation. Once this attributes), List of Tablestest 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# and the .NET Platform, Second Edition CommonSnappableTypes.dll.
ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) VbNetSnapIn.dll: A simple snap-in written in VB .NET, which leverages the types of This comprehensive text starts with a brief overview of the CommonSnappableTypes.dll. C# language and then quickly moves to key technical and architectural issues for .NET developers. MyPluggableApp.exe: This 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 Table of Contents foreknowledge about. C# and the .NET Platform, Second Edition Introduction
Building the Common Snappable Types
Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language new C# code library (CommonSnappableTypes) that defines the following two types: Chapter 2 Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
namespace CommonSnappableTypes - Exceptions and Object Lifetime { Chapter 6 - Interfaces and Collections public interface IUseMyFunctionality Chapter { 7 void - Callback Interfaces, DoIt(); } Delegates, and Events Chapter 5
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies [AttributeUsage(AttributeTargets.Class)]
Chapter public 9 - Understanding .NET Assemblies class SnappableAttribute : System.Attribute Chapter { 10 public - Processes, AppDomains, Contexts, and Threads SnappableAttribute(){} } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Here, the assemblyWindows offers a Forms) public interface (IUseMyFunctionality) that Chapter 13 CommonSnappableTypes.dll - Building a Better Window (Introducing provides interface for all snap-ins Chapter 14a-polymorphic A Better Painting Framework (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 System.IO Namespace snapper to generate scripting code, render an image onto the application's toolbox, or integrate into the Chapter 17 - Data Access with ADO.NET main menu. Chapter 15 - Programming with Windows Forms Controls
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Webtype Pages Web Controls The SnappableAttribute is aand custom attribute that will be applied on any class type that wishes to be Chapter 19in- to ASP.NET Web Applications snapped the container. Again, the theory here is that if (and only if) a type has been adorned with the Chapter 20 - XML Web Services [Snappable] attribute, it will support the functionality of the IUseMyFunctionality type. Index List of Figures
Building the C# Snap-In
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# and the .NET Platform, Second Edition public TheCSharpSnapIn(){} ISBN:1590590554 by Andrew Troelsen void IUseMyFunctionality.DoIt() Apress © 2003 (1200 pages) { ThisMessageBox.Show("You comprehensive text starts with a briefjust overview of the have used the C# snap in!"); C# language and then quickly moves to key technical and } architectural issues for .NET developers.
} } Table of Contents
C# and the .NET Platform, Second Edition
Note that the TheCSharpSnapIn type has been marked with the [SnappableAttribute] type to flag itself as a
Introduction type that can be plugged into the extendible application you have yet to build. Given that it has advertised its Part One - Introducing C# and the .NET Platform
support for snap-in-ability, you also implement the IUseMyFunctionality.
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Building the VB .NET Snap-In
Part Two - The C# Programming Language
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 - Object-Oriented Programming C#external assemblies as the previous CSharpSnapIn project. library (VbNetSnapIn) that references thewith same Chapter 5 Exceptions and Object Lifetime The code is (again) straightforward: Chapter 6
- Interfaces and Collections
Chapter 7
Callback Interfaces, Delegates, and Events Imports -System.Windows.Forms Chapter 8 -CommonSnappableTypes Advanced C# Type Construction Techniques Imports Part Three - Programming with .NET Assemblies Public Class VbNetSnapIn ChapterImplements 9 - Understanding .NET Assemblies IUseMyFunctionality Chapter Public 10 - Processes, AppDomains, Contexts, and Threads Sub DoIt() Implements IUseMyFunctionality.DoIt Chapter 11 -MessageBox.Show("You Type Reflection, Late Binding,have and Attribute-Based just used Programming the VB .NET snap in!") Part Four - Leveraging the .NET Libraries End Sub Chapter 12 - Object Serialization and the .NET Remoting Layer End Class Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
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 with ADO.NET brackets (< >) rather than square brackets ([ ]). Chapter 16 - The System.IO Namespace
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Building the Extendable Windows Forms Application
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
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 Figures 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). Index
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
Building C# Applications Figure- 11-8: Input for a snap-in module
Part Two - The C# Programming Language
Chapter C# Language Fundamentals Behind3the- Click event handler for this menu item (which may be created simply by double-clicking the Chapter 4 - from Object-Oriented Programming withgoal C# is to extract the path to the selected file, and using this menu item the design-time editor), our Chapter path, perform 5 - Exceptions the following and Object tasks: Lifetime Chapter 6
- Interfaces and Collections
Check- to see if the user-selected assembly has any types marked with the [Snappable] attribute (by Callback Interfaces, Delegates, and Events reflecting over custom attributes).
Chapter 7 Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming withsupport .NET Assemblies For each type that does the [Snappable]
aspect, obtain the IUseMyFunctionality interface and
Chapter - Understanding Assemblies call9 the DoIt() method .NET (via late binding). Chapter 10 - Processes, AppDomains, Contexts, and Threads
Here is11 the- relevant code behind the Form type: Chapter Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 class - ObjectMainForm: Serialization and the .NET Remoting Layer public System.Windows.Forms.Form Chapter { 13 - Building a Better Window (Introducing Windows Forms) Chapter ... 14 - A Better Painting Framework (GDI+)
" Toolswith | Windows Snap InForms Something..." event handler. Chapter // 15 -The Programming Controls void mnuToolsSnapIn_Click(object sender, System.EventArgs e) Chapter private 16 - The System.IO Namespace Chapter { 17 - Data Access with ADO.NET Part Five - Webif(myOpenFileDialog.ShowDialog() Applications and XML Web Services
== DialogResult.OK) { Chapter 18 - ASP.NET Web Pages and Web Controls string pathToAsm = myOpenFileDialog.FileName; Chapter 19 - ASP.NET Web Applications if(TryToUseSnapIn(pathToAsm) == false) Chapter 20 - XML Web Services MessageBox.Show("This snap-in is bogus!"); Index } List of Figures } 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# and the .NET // Platform, Second Edition Get the IUseMyFunctionality interface. by Andrew Troelsen foundSnapIn = true; ISBN:1590590554 Apress © 2003 (1200 object pages) o = This comprehensive text starts with a brief overview of the theSnapInAsm.CreateInstance(theTypes[i].FullName); C# language and then quickly moves to key technical and IUseMyFunctionality itfUseMe; architectural issues for .NET developers.
itfUseMe = o as IUseMyFunctionality; if(itfUseMe != null) { Table of Contents itfUseMe.DoIt(); C# and the .NET Platform, Second Edition lstBoxSnapIns.Items.Add(theTypes[i].FullName); Introduction } Part One - Introducing C# and the .NET Platform } Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications } Part Two - The C# Programming Language return foundSnapIn; Chapter } 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# } Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
This really summarize allConstruction the information presented over the course of this chapter. Note how the Chapter 8 -does Advanced C# Type Techniques application is able to determine a bogus assembly (i.e., an assembly that contains no type that is Part Three - Programming with .NET Assemblies [Snappable]-aware) via the Boolean value returned from TryToUseSnapIn() helper function. Within this Chapter 9 - Understanding .NET Assemblies helper method, we first leverage the Assembly.LoadFrom() Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming [Snappable] attribute. If so, we set our Boolean flag and trigger the IUseMyFunctionality.DoIt() Part Four - Leveraging the .NET Libraries implementation of the given snap-in (to return the correct value to the caller). Finally, for good measure, we Chapter 12 - Object Serialization and the .NET Remoting Layer log the name of the snap-in within the Form's ListBox type. Figure 11-9 shows the result. Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
Reflection is a very interesting aspect of a robust OO environment. In the world of .NET, the keys to Apress © 2003 (1200 pages) reflection servicesThis revolve around the System.Type the System.Reflection namespace. As you comprehensive text starts with aclass briefand overview 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 moves to key technical and architectural issues forof .NET developers. the "who, what, where, why, and how" a given item. Late binding is the process of creating a type and invoking its members without foreknowledge of the Table specific of Contents names of said members. As shown during our extendible application example, this is a very
powerful usedSecond by tool Edition builders as well as tool consumers. C# and thetechnique .NET Platform, Introduction
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 Part Two - The C# Programming Language assemblies, or leveraging .NET serialization services and the .NET Remoting layer. Part One - Introducing C# and the .NET Platform
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Part Four: Leveraging the .NET ISBN:1590590554 Libraries by Andrew Troelsen Apress © 2003 (1200 pages)
Chapter List This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Chapter 12: Object Serialization and the .NET Remoting Layer Table of Contents
Chapter 13: Building a Better Window (Introducing Windows Forms)
C# and the .NET Platform, Second Edition
Introduction Chapter 14: A Better Painting Framework (GDI+) Part One - Introducing C# and the .NET Platform
Chapter 15:Philosophy Programming with Windows Forms Controls Chapter 1 - The of .NET Chapter 2
- Building C# Applications
Chapter 16: The System.IO Namespace
Part Two - The C# Programming Language
Chapter 3 - C# Fundamentals Chapter 17:Language Data Access with ADO.NET Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Chapter C# 12: Object SerializationISBN:1590590554 and the .NET by Andrew Troelsen Apress © 2003 (1200 pages) Remoting Layer
Overview
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Developers who are new to the .NET platform naturally assume that .NET is all about building InternetTable centric of Contents applications (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 the .NET Platform, Second the .NET platform. In this same vein of misinformation, many new .NET developers tend to assume that Introduction XMLOne Web services are only interact Part - Introducing C#the and theway .NETtoPlatform
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 youTwo are -able peer-to-peer distributed applications Part The to C#build Programming Language
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 - Object-Oriented Programming with C# Chapter 5 goal - Exceptions and Object Lifetime a critical remoting-centric topic: object serialization. Simply put, The first of this chapter is to describe Chapter 6 Interfaces 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 Interfaces, Delegates, and Events physical etc.). Deserialization, on the other hand, is the process of reading the persisted data from Chapter 8 - Advanced C# Type Construction Techniques said location and recreating a new type based on the preserved stateful values. As you might imagine, the Part Three - Programming .NET Assemblies ability to serialize types iswith critical when attempting
to copy an object to a remote machine (e.g., marshal-
Chapter 9 -Understand, Understanding .NET Assemblies by-value). however, that serialization is quite useful in its own right, and will likely play a role in Chapter many of 10your - Processes, .NET applications AppDomains, (distributed Contexts, orand not). Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Once you have seen the the .NET .NETLibraries serialization Part Four - Leveraging
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 - Object Serialization and the .NET Remoting Layer come to understand the numerous terms used when discussing .NET Remoting, such as proxies, Chapter 13 - Building a Better Window (Introducing Windows Forms) channels, marshaling by reference (as opposed to by value), server-activated (versus client-activated) Chapter 14 - A Better Painting Framework (GDI+) objects, and so forth. With these background elements complete, the remainder of this chapter offers Chapter 15 - Programming with Windows Forms Controls numerous code examples that illustrate the process of building distributed systems using the .NET Chapter 16 - The System.IO Namespace platform. Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Object Persistence in the .NET Framework by Andrew Troelsen
ISBN:1590590554
Object serialization is one of the key underlying technologies used by the .NET Remoting layer. Simply Apress © 2003 (1200 pages) put,serialization isThis thecomprehensive term describing thestarts process theofstate text withof a converting brief overview the of an object to a linear sequence of data. This data sequence contains all necessary information C# language and then quickly moves to key technical and needed to reconstruct (or architectural issuesfor foruse .NET developers. deserialize) the state of the object 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 Table of in Contents object the chain of inheritance is able to write its own custom state data into the data stream. C# and the .NETif Platform, Second Edition Furthermore, a given type contains serializable member variables, the member variables themselves Introduction also automatically participate in the serialization process. Part One - Introducing C# and the .NET Platform
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, you serialized an object graph into a memory location using the Chapter 2 imagine - Building C#have Applications System.IO.MemoryStream type. This stream Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# XML elements) correctly represents the state of the serialized objects. Chapter 5
- Exceptions and Object Lifetime
Chapter 6 The - Interfaces andnamespace Collections defines numerous types that allow you to read (and write) Note System.IO Chapter 7 information - Callback Interfaces, Delegates, and Events to (and from) files, memory locations, and character buffers. Chapter 16 examines Chapter 8 this - Advanced C# Type Construction Techniques namespace in detail; however, by necessity, you will be introduced to some System.IO types Part Three -during Programming with .NET Assemblies this chapter's examination of object
Chapter 9
serialization.
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition The Role ofC#Object Graphs by Andrew Troelsen
ISBN:1590590554
As mentioned, when a type is (1200 serialized Apress © 2003 pages) by the CLR, the runtime will account for each related object. The chain of related objects serialized to a stream collectively referredoftothe as an object graph. Object graphs This comprehensive text starts iswith a brief overview provide a simple C# waylanguage to document how a set of objects refer to each other and then quickly moves to key technical and and are not intended to directly issues foras .NET model classic OOarchitectural relationships (such the developers. "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 Table of Contents members in an object graph are arbitrary and have no real meaning to the outside world. C# and the .NET Platform, Second Edition
As a simple example, assume you have created a set of classes that model some automobiles (of Introduction course). have a topmost type.NET named Car, Part One - You Introducing C# and the Platform
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
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure 12-1: A simple object graph
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter In Figure 1212-1 - Object you can Serialization see that and the Car the .NET classRemoting refers to Layer the Radio class (given the "has-a" relationship). The
JamesBondCar refers to theWindow Car (given the "is-a"Windows relationship) as well as the Radio (as it inherits this Chapter 13 - Building a Better (Introducing Forms) protected Given that (GDI+) we have assigned an arbitrary value to each member in the object Chapter 14 member - A Bettervariable). Painting Framework graph, 15 we -could representwith theWindows relationship documented Chapter Programming Forms Controls in the previous diagram with the following formula: Chapter 16 - The System.IO Namespace
[Car 3, [Radio 2], [JamesBondCar 1, ref 3, ref 2] Chapter 17 -ref Data 2], Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
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 Services a lone wolf. If you serialize an instance of JamesBondCar to a stream, the object graph ensures that the Index Radio and Car types also participate in the process. The beautiful thing about the default serialization List of Figures 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 Applications
and the .NET Platform, Second Edition ConfiguringC#Objects for Serialization by Andrew Troelsen
ISBN:1590590554
To make an object available .NET serialization services, all you need to do is decorate each class with Apress © 2003to (1200 pages) the [Serializable] This attribute. That's it (really). If you determine that a given comprehensive text starts with a brief overview 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 moves to key technical and for .NET developers. attribute. This canarchitectural be helpful ifissues 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): Table of Contents C# and the .NET Platform, Second Edition
// The Radio class can participate in the .NET serialization scheme. [Serializable] Part One - Introducing C# and the .NET Platform public class Radio Chapter 1 - The Philosophy of .NET { Chapter // 2 -This Building C# Applications member will not be persisted. Part Two[NonSerialized] - The C# Programming Language Chapter private 3 - C# Language Fundamentals int objectIDNumber = 9; Chapter // 4 -Other Object-Oriented Programming C# serialized statewith data Chapter ... 5 - Exceptions and Object Lifetime Chapter public 6 - Interfaces Radio(){ and Collections } void On(bool state)and Events Chapter public 7 - Callback Interfaces, Delegates, { Chapter 8 - Advanced C# Type Construction Techniques if(statewith == .NET true) Part Three - Programming Assemblies MessageBox.Show("Music is on..."); Chapter 9 - Understanding .NET Assemblies else Chapter 10 - Processes, AppDomains, Contexts, and Threads MessageBox.Show("No tunes..."); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Part Four - Leveraging the .NET Libraries } Chapter 12 - Object Serialization and the .NET Remoting Layer Introduction
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter - A Better Framework As you 14 would guess,Painting these attributes are(GDI+) embedded within the type's metadata, as you can see using Chapter 15 Programming with Windows Forms Controls ildasm.exe (Figure 12-2). Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform,int Second Edition public Car(string petName, maxSpeed) ISBN:1590590554 by Andrew Troelsen { Apress © 2003 (1200 pages) this.petName = petName; This comprehensive text starts with a brief overview of the this.maxSpeed = maxSpeed; C# language and then quickly moves to key technical and } architectural issues for .NET developers. public Car() { } public String PetName { Table of Contents get { return petName; } C# and the .NET Platform, Second Edition set { petName = value; } Introduction } Part One - Introducing C# and the .NET Platform public int MaxSpeed Chapter 1 - The Philosophy of .NET { Chapter 2 - Building C# Applications get { return maxSpeed; } Part Two - The C# Programming Language set { maxSpeed = value; } Chapter } 3 - C# Language Fundamentals Chapter public 4 - Object-Oriented Programming with C# void TurnOnRadio(bool state) Chapter { 5 theRadio.On(state); - Exceptions and Object Lifetime } Chapter 6 - Interfaces and Collections } Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter // The 8 JamesBondCar - Advanced C# Type class Construction is also Techniques serializable! Part [Serializable] Three - Programming with .NET Assemblies
public JamesBondCar : Car Chapter 9 class - Understanding .NET Assemblies { Chapter 10 - Processes, AppDomains, Contexts, and Threads public for easy access. Chapter // 11 -Made Type Reflection, Late Binding, and Attribute-Based Programming Feel free use Part Four// - Leveraging the to .NETmake Libraries
of type properties.
bool isFlightWorthy; Chapter public 12 - Object Serialization and the .NET Remoting Layer bool isSeaWorthy; Chapter public 13 - Building a Better Window (Introducing Windows Forms) public JamesBondCar(){ } public JamesBondCar(string petName, int maxSpeed, Chapter 15 - Programming with Windows Forms Controls bool canFly, bool canSubmerge) Chapter 16 - The System.IO Namespace : base(petName, maxSpeed) Chapter 17 - Data Access with ADO.NET { Part Five - Web Applications and XML Web Services this.isFlightWorthy = canFly; Chapter 18 - ASP.NET Web Pages and Web Controls this.isSeaWorthy = canSubmerge; Chapter } 19 - ASP.NET Web Applications Chapter public 20 - XML Web voidServices Fly() Index { List of Figures 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 Painting Framework (GDI+)
Choosing a Serialization Formatter
C# and the .NET Platform, Second Once you have configured your types to participate in Edition the .NET serialization scheme, your next step is to ISBN:1590590554 choose which format by Andrew shouldTroelsen be used when persisting your object graph. The System.Runtime.Serialization.Formatters Apress © 2003 (1200 pages) namespace contains two additional nested namespaces (*.Binary and *.Soap) that provide twotext out-of-the-box As of you can guess, the BinaryFormatter This comprehensive starts with a formatters. brief overview the C#object language andto then quicklyusing moves to key technical type serializes your graph a stream a compact binary and format. The SoapFormatter type architectural issues(Simple for .NETObject developers. represents your graph as a SOAP Access Protocol) message that is expressed using XML data representation. Table Contents The of System.Runtime.Serialization.Formatters.Binary.BinaryFormatter type is defined within mscorlib.dll. C# and the .NET Platform, Second Edition Therefore, to serialize your objects using a binary format, all you need to do is specify the following C# Introduction using directive: Part One - Introducing C# and the .NET Platform
Chapter 1 - Theobject Philosophy of .NETusing a binary format! // Persist graph Chapter 2 Building C# Applications using System.Runtime.Serialization.Formatters.Binary; Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals However, System.Runtime.Serialization.Formatters.Soap.SoapFormatter type is defined in a separate Chapter 4 the - Object-Oriented Programming with C#
assembly. format your into a SOAP message, you must set a reference to Chapter 5 -To Exceptions and object Object graph Lifetime System.Runtime.Serialization.Formatters.Soap.dll and make the following C# using directive: Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
// Persist object using a Techniques SOAP format! Chapter 8 - Advanced C# graph Type Construction using System.Runtime.Serialization.Formatters.Soap; Part Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, 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 Part Four - Leveraging the .NET Libraries interfaces. IFormatter defines the key Serialize() and Deserialize() methods, which do the grunt work to Chapter 12 - Object Serialization and the .NET Remoting Layer move your object graphs into and out of a specific stream (represented by the System.IO.Stream abstract Chapter 13 - Building Better Window (Introducing Windows Forms) base class). Here is athe formal definition of IFormatter: Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
public interface System.Runtime.Serialization.IFormatter { ChapterSerializationBinder 17 - Data Access with ADO.NET Binder { get; set; } Part Five - Web Applications and XML Web{Services StreamingContext Context get; set; } ChapterISurrogateSelector 18 - ASP.NET Web Pages SurrogateSelector and Web Controls { get; set; } Chapterobject 19 - ASP.NET Web Applications Deserialize(System.IO.Stream serializationStream); Chaptervoid 20 - XML Web Services Serialize(System.IO.Stream serializationStream, object graph); Index } Chapter 16 - The System.IO Namespace
List of Figures 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 and the .NET Platform,Formatter Second Edition Serialization a Binary by Andrew Troelsen
ISBN:1590590554
To illustrate how Apress easy it ©is2003 to persist an instance of our JamesBondCar to a physical file, let's make use of (1200 pages) the BinaryFormatter type. Again, the two key methods of the BinaryFormatter type to be aware of are This comprehensive text starts with a brief overview of the Serialize() and Deserialize() (Table 12-1). C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 12-1: BinaryFormatter Members BinaryFormatter Member Table of Contents
Meaning in Life
C# and the .NET Platform, Second Edition
Deserialize()
Introduction
Deserializes a stream of bytes to an object graph
Part Serialize() One - Introducing C# and the .NETSerializes Platform
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 of properties configure specific details Part Two - The that C# Programming Language
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 - Object-Oriented Programming with C#of this chapter. Chapter 5
- Exceptions and Object Lifetime
Now, assume you have created an instance of JamesBondCar, modified some state data, and want to - Interfaces 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 Interfaces, Delegates, and Events using the static System.IO.File.Create() method, which returns an instance of the System.IO.FileStream Chapter 8 - Advanced Construction Techniques type (again, file IO willC# be Type examined in Chapter 16). Given that the BinaryFormatter.Serialize() method Part Threea- Stream-derived Programming with .NET Assemblies requires type as its first parameter, be sure to maintain this variable. Here is the Chapter 9 serialization - Understanding .NET Assemblies complete code: Chapter 6
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
using System.Runtime.Serialization.Formatters.Binary, using System.IO; Chapter 12 static - Object Serialization and the .NET Remoting Layer public void Main() Chapter 13 Building a Better Window (Introducing Windows Forms) { Chapter // 14 -Make A Better Framework a Painting car and change(GDI+) some state data. Chapter JamesBondCar 15 - Programming myAuto with Windows Forms Controls = new JamesBondCar("Fred", 50, false, true); Chapter myAuto.TurnOnRadio(true); 16 - The System.IO Namespace Chapter myAuto.GoUnderWater(); 17 - Data Access with ADO.NET Part Five// - Web Create Applications a file andstream XML Webto Services hold the object's state. myStream File.Create("CarData.dat"); Chapter FileStream 18 - ASP.NET Web Pages and= Web Controls the object graph into the file stream using a binary format. Chapter // 19 -Move ASP.NET Web Applications BinaryFormatter myBinaryFormat = new BinaryFormatter(); Chapter 20 - XML Web Services myBinaryFormat.Serialize(myStream, myAuto); Index myStream.Close(); List of Figures } List of Tables Part Four - Leveraging the .NET Libraries
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter Figure 1 - 12-3: The Philosophy JamesBondCar of .NET serialized using a BinaryFormatter Chapter 2
- Building C# Applications
NowTwo suppose youProgramming want to readLanguage the persisted Part - The C#
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 - Object-Oriented Programming with C# explicit cast, as shown here: Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections // Read the Interfaces, Car fromDelegates, the binary stream. Chapter 7 -in Callback and Events
myStream- Advanced = File.OpenRead("CarData.dat"); C# Type Construction Techniques JamesBondCar carFromDisk = Part Three - Programming with .NET Assemblies (JamesBondCar)myBinaryFormat.Deserialize(myStream); Chapter 9 - Understanding .NET Assemblies Console.WriteLine("{0} is alive!", carFromDisk.PetName); Chapter 10 - Processes, AppDomains, Contexts, and Threads carFromDisk.TurnOnRadio(true); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming myStream.Close(); Chapter 8
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter Building Better Window (Introducing Forms) Notice 13 that- when youa call Deserialize(), you pass Windows the Stream-derived type that represents the location of Chapter 14 - A objects Better Painting the persisted (again aFramework file stream(GDI+) in this case). Now if that is not painfully simple, I'm not sure what Chapter is. In a 15 nutshell, - Programming mark each with class Windows you wish Forms to persist Controls to a stream with the [Serializable] attribute. After this
point, use BinaryFormatter type to move your object graph to and from a binary stream. Chapter 16 -the The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# Using and the .NET Platform, Second Edition Serialization a SOAP Formatter by Andrew Troelsen
ISBN:1590590554
The other available formatter use when serializing your types is SoapFormatter. Remember you Apress © 2003 you (1200may pages) must set a reference to System.Runtime.Serialization.Formatters.Soap.dll This comprehensive text starts with a brief overview of the to use this type! The following block of code extends the previous serialization example to technical persist the JamesBondCar using the C# language and then quickly moves to key and architectural issues for .NET developers. SoapFormatter type: using System.Runtime.Serialization.Formatters.Soap; ... C# and the .NET Platform, Second Edition // Save the same car using a soap format. Introduction FileStream myStream = File.Create("CarSoapData.xml"); Part One - Introducing C# and the .NET Platform SoapFormatter mySoapFormat = new SoapFormatter(); Chapter 1 - The Philosophy of .NET mySoapFormat.Serialize(myStream, myAuto); Chapter 2 - Building C# Applications myStream.Close(); Part - The Programming // Two Read inC# the Car fromLanguage the XML file. Chapter 3 - C# Language Fundamentals myStream = File.OpenRead("CarSoapData.xml"); Chapter 4 - Object-Oriented Programming with C# JamesBondCar carFromSoap = Chapter 5 - Exceptions and Object Lifetime (JamesBondCar)mySoapFormat.Deserialize(myStream); Chapter Console.WriteLine("{0} 6 - Interfaces and Collections is alive!", carFromSoap.PetName); myStream.Close(); Chapter 7 - Callback Interfaces, Delegates, and Events
Table of Contents
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
As you can- see, the SoapFormatter type has the same public interface as the BinaryFormatter. As before, Understanding .NET Assemblies use Serialize() and Deserialize() to move the object graph in and out of the stream. If you open the Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming JamesBondCar (as well as the relationship maintained by the graph). Chapter 9
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 12-4: JamesBondCar serialized using a SoapFormatter
C# Using and the .NET Platform, Second Edition Serialization an XML Formatter by Andrew Troelsen
ISBN:1590590554
In addition to the Apress SOAP ©and binary formatters, the System.Xml.dll assembly provides a third formatter 2003 (1200 pages) (System.Xml.Serialization.XmlFormatter) that can usedoverview to persistofthe This comprehensive text starts withbe a brief 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 moves to key technical and architectural(and issues forhave .NETadevelopers. reference to System.Xml.dll you C# "using" directive specifying the System.Xml.Serialization namespace), you are able to serialize and deserialize your JamesBondCar as pure XML: Table of Contents
// Now save car using a pure XML format. Console.WriteLine("\n***** Saving car to CarXmlData.xml file *****"); Introduction myStream = File.Create("CarXmlData.xml"); Part One - Introducing C# and the .NET Platform XmlSerializer myXmlFormat = Chapternew 1 -XmlSerializer(typeof(JamesBondCar), The Philosophy of .NET "Cars"); Chapter 2 Building C# Applications myXmlFormat.Serialize(myStream, myAuto); Part Two - The C# Programming Language myStream.Close(); Chapter 3 -in C# the Language // Read Car Fundamentals from the XML file. Chapter 4 - Object-Oriented Programming with C#car from Xml file *****"); Console.WriteLine("\n***** Reading Chapter 5 - Exceptions and Object Lifetime myStream = File.OpenRead("CarXmlData.xml"); Chapter JamesBondCar 6 - Interfaces carFromXml and Collections = Chapter(JamesBondCar)myXmlFormat.Deserialize(myStream); 7 - Callback Interfaces, Delegates, and Events Console.WriteLine("{0} is alive!", carFromXml.PetName); Chapter 8 - Advanced C# Type Construction Techniques carFromSoap.TurnOnRadio(true); Part Three - Programming with .NET Assemblies myStream.Close(); Chapter 9 - Understanding .NET Assemblies C# and the .NET Platform, Second Edition
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer 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 Better Window (Introducing Windows Forms) constructor parameter. Part Four - Leveraging the .NET Libraries
Chapter 14 - A Better Painting Framework (GDI+)
Chapter Note 15 The - Programming XmlFormatter withdemands Windows that Forms allControls serialized types in the object graph support a default
(so be sure to add it back if you define custom constructors). Chapter 16 constructor - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
If you were to look within the newly generated CarXmlData.xml file you would find the following:
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter - ASP.NET Web Applications List of Tables Fred 50 false true Index
SOURCE CODE
The CarToFile application is located under the Chapter 12 subdirectory.
C# the and the .NET Platform, Second Edition Customizing Serialization Process by Andrew Troelsen
ISBN:1590590554
Now that you understand how(1200 the .NET Apress © 2003 pages) platform makes use of serialization services to persist an object to a given stream, youThis arecomprehensive just about ready tostarts checkwith out athe details of the text brief overview of.NET the Remoting layer. Before moving on however, let's digC# a bit deeper into the .NET serialization process. language and then quickly moves to key technical and architectural issues for .NET developers.
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 Table exactly of Contents the behavior you desire, the System.Runtime.Serialization namespace provides several ways to customize the .NET serialization process. C# and the .NET Platform, Second Edition Introduction
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. Part One - Introducing C# and the .NET Platform
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Table 12-2: System.Runtime.Serialization Namespace Core Types
Chapter 3
- C# Language Fundamentals
Chapter Types 4 of - Object-Oriented the Programming with C# Meaning in Life
System.Runtime.Serialization Chapter 5 - Exceptions and Object Lifetime Namespace Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Formatter
Part Three - Programming with .NET Assemblies
ObjectIDGenerator Chapter 9 - Understanding .NET Assemblies
An abstract base class that provides base functionality for runtime serialization formatters. Generates IDs for objects in an object graph.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
ObjectManager
Keeps track of objects as they are being deserialized.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
SerializationBinder Part Four - Leveraging the .NET Libraries
An abstract base class that provides functionality to
serialize Chapter 12 - Object Serialization and the .NET Remoting Layera type to a stream. Chapter 13 - Building a Better Window (Introducing Windows Forms)
SerializationInfo
Used by objects that have custom serialization behavior. SerializationInfo holds together all the data Chapter 15 - Programming with Windows Forms Controls needed to serialize or deserialize an object. In Chapter 16 - The System.IO Namespace essence, this class is a "property bag" that allows you Chapter 17 - Data Access with ADO.NET to establish name/value pairs to represent the state of Part Five - Web Applications and XML Web Services an object. Chapter 14 - A Better Painting Framework (GDI+)
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 -toASP.NET Web Applications In addition these types, there are two key interfaces used during the serialization process: IFormatter Chapter (mentioned 20 - XML previously) Web Services and 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 Index persist the object during the serialization process. Specifically, the necessary information includes: List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table Figure of Contents 12-5: The serialization process C# and the .NET Platform, Second Edition Introduction When you wish to "get involved" with the serialization process, your first step is to implement the standard Part ISerializable One - Introducing interfaceC# onand the the class .NET requiring Platform 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
Part - The C# wish Programming Language // Two When you to tweak the
serialization process,
Chapter 3 - C# Language Fundamentals // implement ISerializable. Chapter public 4 interface - Object-Oriented ISerializable Programming with C#
{ Chapter 5
- Exceptions and Object Lifetime virtual void GetObjectData(SerializationInfo info, Chapter public 6 - Interfaces and Collections
context); -StreamingContext Callback Interfaces, Delegates, and Events } Chapter 8 - Advanced C# Type Construction Techniques Chapter 7
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
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 Attribute-Based Programming pairs. If you check out this type using wincv.exe, you essentially find numerous variations on the overloaded Part Four - Leveraging the .NET Libraries AddValue() method, in addition to a small set of properties that allow the type to get and set the type's name, Chapter - Object Serialization and the .NET Layer defining12assembly, and member count. HereRemoting is a partial snapshot: Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
public sealed class SerializationInfo : object { Chapter public 16 - The System.IO Namespace SerializationInfo(Type type, Chapter 17 - Data Access with ADO.NET System.Runtime.Serialization.IFormatterConverter converter); Part Fivepublic - Web Applications and XML Web Services string AssemblyName { get; set; } Chapter public 18 - ASP.NET Web Pages and Web Controls string FullTypeName { get; set; } Chapter public 19 - ASP.NET Applications { get; } intWeb MemberCount Chapter public 20 - XML Web voidServices AddValue(string name, short value); Index public void AddValue(string name, UInt16 value); public void AddValue(string name, int value); List of Figures ... List of Tables } Chapter 15 - Programming with Windows Forms Controls
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# and the .NET Platform, Second Edition access to this member regardless of its visibility. These special constructors tend to be marked as private to ISBN:1590590554 by Andrew Troelsen ensure that the casual object user would never create an object in this manner. Apress © 2003 (1200 pages)
As you can see, the Thisfirst comprehensive parameter of text thisstarts constructor with a brief is anoverview instanceofofthe the SerializationInfo type (seen C# language and then quickly constructor moves to key and previously). The second parameter of special is technical a StreamingContext type, which contains architectural issues for .NET developers. 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). Table of Contents
Table 12-3: StreamingContextStates Enumeration Members
C# and the .NET Platform, Second Edition Introduction StreamingContextStates
Meaning in Life
Part Member One - Introducing Name C# and the .NET Platform
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.
Part Two - The C# Programming Language
Chapter Clone3 Chapter 4
- C# Language FundamentalsSpecifies that the object graph is being cloned. - Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
CrossAppDomain
Chapter 6
Specifies that the source or destination context is a new AppDomain.
- Interfaces and Collections CrossMachine Specifies that the source or destination context is a different Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8
machine. - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
CrossProcess
Chapter 9
Specifies that the source or destination context is a different process on the same machine.
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
File 11 - Type Reflection, Late Binding, Specifies that the source or destination context is a file. Chapter and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Other
Specifies that the serialization context is unknown.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Persistence Specifies that the source or destination context is a persisted Chapter 13 - Building a Better Window (Introducing Windows Forms) This could include databases, files, or other backing Chapter 14 - A Better Painting Frameworkstore. (GDI+) Users should assume that persisted data is more long Chapter 15 - Programming with Windowsstores. Forms Controls
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 with ADO.NET data from the current process. Chapter 16 - The System.IO Namespace
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controlsthat the source or destination context is remoting to an Remoting Specifies Chapter 19 - ASP.NET Web Applications unknown location. Users cannot make any assumptions as to Chapter 20 - XML Web Services
whether this is on the same machine.
Index List of Figures
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# and the .NET Platform, Second Edition { ISBN:1590590554 Andrew Troelsen is the stream? // by What context Apress © 2003 (1200 pages) Console.WriteLine("[GetObjectData] Context State: {0} ", This comprehensive text starts with a brief overview of the ctx.State.ToString()); C# language and then quickly moves to key technical and si.AddValue("CapPetName", petName.ToUpper()); architectural issues for .NET developers. si.AddValue("maxSpeed", maxSpeed); } // Rehydrate a new object based on incoming SerializationInfo type. Table of Contents private CustomCarType(SerializationInfo si, StreamingContext ctx) C# and the .NET Platform, Second Edition { Introduction // What context is the stream? Part One - Introducing C# and the .NET Platform 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"); Part Two - The C# Programming Language } Chapter 3 - C# Language Fundamentals } Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime Now that type has and beenCollections configured with the correct infrastructure, you will be happy to see that the caller's Chapter 6 the - Interfaces
serialization and deserialization process remains unaltered (see Figure 12-6 for output): Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Part Three -static Programming .NET Assemblies public int with Main(string[] args)
Chapter { 9
- Understanding .NET Assemblies myAuto Contexts, = new CustomCarType("Sid", 50); Chapter CustomCarType 10 - Processes, AppDomains, and Threads
= File.Create("CarData.dat"); Chapter Stream 11 - Type myStream Reflection, Late Binding, and Attribute-Based Programming ISerializable interface Part Four// - Leveraging the .NET Libraries
obtained!
myBinaryFormat = new Chapter BinaryFormatter 12 - Object Serialization and the .NET Remoting LayerBinaryFormatter(); myAuto); Chapter myBinaryFormat.Serialize(myStream, 13 - Building a Better Window (Introducing Windows Forms) Chapter myStream.Close(); 14 - A Better Painting Framework (GDI+)
myStream = File.OpenRead("CarData.dat"); // Special constructor called! Chapter 16 - The System.IO Namespace CustomCarType carFromDisk = Chapter 17 - Data Access with ADO.NET (CustomCarType)myBinaryFormat.Deserialize(myStream); Part Five - Web Applications and XML Web Services Console.WriteLine("{0} is alive!", carFromDisk.petName); Chapter 18 - ASP.NET Web Pages and Web Controls return 0; Chapter 19 - ASP.NET Web Applications } Chapter 15 - Programming with Windows Forms Controls
Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition technology is useful in a variety of circumstances, even when you are not building a distributed application. For ISBN:1590590554 by Andrew Troelsen example, you could save applicationspecific data, user preferences, or whatnot with these same techniques. Apress © 2003 (1200 pages) As you would expect however, the .NET Remoting layer makes substantial use of these serialization primitives. Thisexactly comprehensive text starts with a brief overview of the Next question: what is remoting? C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Defining .NET Remoting by Andrew Troelsen
ISBN:1590590554
As you recall from your © reading in Chapter 10, an application domain is a logical boundary for a .NET Apress 2003 (1200 pages) assembly, which This is itself contained within a Process comprehensive text starts with atype. briefUnderstanding overview 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 moves to key technical and architectural issuesacross for .NET developers. pieces of software communicating application domains. The two application domains in question could be physically configured in any of the following manners: Table of Two Contents application domains in the same process (and thus on the same machine) C# and the .NET Platform, Second Edition
Two application domains in separate processes on the same machine
Introduction
Part One - Introducing C# and the .NET Platform
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 Part more) Twonetworked - The C# Programming computers. InLanguage fact, each
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 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Regardless of the distance between two software entities, it is common to refer to each agent using the - Interfaces 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 Interfaces, Delegates, and Events object. The server is the software agent that provides remote access to select objects. As you will see over Chapter 8 - Advanced C# Type Construction Techniques the course of this chapter, a .NET server application is quite a different beast from that of classic DCOM. Chapter 6
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The .NET Remoting Namespaces by Andrew Troelsen
ISBN:1590590554
Before we dive too deep©into details Apress 2003the (1200 pages) of the .NET Remoting layer, we need to check out the functionality provided by the remoting-centric namespaces. The a.NET classoflibraries provide numerous This comprehensive text starts with briefbase overview the namespaces thatC# allow you to build distributed applications. The bulk of the types found within these language and then quickly moves to key technical and issues for .NET developers. namespaces arearchitectural contained within mscorlib.dll, however, the System.Runtime.Remoting.dll assembly does 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 Table of Contents this chapter, you are required to make use of many of the core types within the namespaces seen in Table C# andBe thesure .NETtoPlatform, Second 12-4. check out onlineEdition Help if you wish to view every possible entity. Introduction Part One12-4: - Introducing C#Remoting and the .NET Platform Table The .NET Namespaces
Chapter 1
- The Philosophy of .NET
Remoting-Centric Namespace - Building C# Applications
Chapter 2
Part Two - The C# Programming Language System.Runtime.Remoting
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
System.Runtime.Remoting.Activation - Interfaces and Collections
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies System.Runtime.Remoting.Channels
Chapter 9
- Understanding .NET Assemblies
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 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
System.Runtime.Remoting.Channels.Tcp This namespace contains types that use Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace System.Runtime.Remoting.Contexts Chapter 17 - Data Access with ADO.NET
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.
Part Five - Web Applications and XML Web Services
System.Runtime.Remoting.Lifetime Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services System.Runtime.Remoting.Messaging Index List of Figures
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 namespace defines a number of C# and the .NET Platform, Second Edition common base classes (and interfaces) ISBN:1590590554 by Andrew Troelsen that are typically only leveraged by other Apress © 2003 (1200 pages) intrinsic remoting agents. This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, Second Edition Understanding .NET Remoting Framework by Andrew Troelsen
ISBN:1590590554
When clients andApress servers exchange information across application boundaries, the CLR makes use of © 2003 (1200 pages) several low-level This primitives to ensure the starts entities in question are able communicate with each other as comprehensive text with a brief overview of to the transparently as possible. Meaning, as a .NET programmer, you are not C# language and then quickly moves to key technical and required to provide reams and issues .NET adevelopers. reams of grungy architectural networking code tofor invoke method 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 Table usingofaContents default set of remoting types (although you are certainly able to get involved with the process if you C# the .NET Platform, Second Edition soand choose). Introduction
Now, if you are coming .NET from Part One - Introducing C#to and theRemoting .NET Platform
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 Language use of dcomcnfg.exe Part Twovalue, - The which C# Programming 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 Object-Oriented Programming with C# there is no-need to manually author IDL code to describe your remotable types (given the advent of .NET Chapter 5 Exceptions Object metadata), and you canand forget all Lifetime about implementing IMarshal, IPropertyBag, or making use of ADO Chapter 6 Interfaces 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 andisEvents the remote into Interfaces, the caller'sDelegates, app domain) as simple as applying the [Serializable] attribute. Chapter 4
Chapter 8
- Advanced C# Type Construction Techniques
Basically, .NET Remoting layerAssemblies revolves around Part Three -the Programming with .NET
a careful orchestration that takes place between four
key players: Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
Proxies
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries Messages
Chapter 12 - Object Serialization and the .NET Remoting Layer
Channels Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Formatters
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - out The each System.IO Let's check entity Namespace in turn, and see how their combined functionality facilitates remote method Chapter 17 - Data Access with ADO.NET invocations. Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Understanding Proxies and Messages
Chapter 19 - ASP.NET Web Applications
Chapter XML Web Services Clients20 and- server objects do not communicate via a direct connection, but rather through the use of a Index middleman termed a proxy. Like Java RMI, CORBA and DCOM, the role of a .NET proxy is to fool the List client of Figures into 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# and the .NET Platform, Second Edition
}
by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
As you can see, the interface a single property (named ThisIMessage comprehensive textdefines starts with a brief overview of the Properties) that provides access C# to language then quickly moves to keyOnce technical to a collection used hold theand client-supplied arguments. this and message object has been populated architectural issues for .NETrelated developers. by the CLR, it is then passed into a closely type termed the real proxy. The real proxy is the entity that literally passes the message object into the channel (described Table of Contents momentarily). Unlike the transparent proxy, the real proxy can be extended by the programmer, and is C# and the .NET Second represented by Platform, a base class typeEdition named (of course) RealProxy. Again, it is worth pointing out that the CLR Introduction will always generate a default implementation of the client-side real proxy, which will serve your needs Part One Introducing andNevertheless, the .NET Platform most (if -not all) of theC# time. to 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
Part Two - The C# Programming Language public abstract class RealProxy
Chapter 3 {
: object
- C# Language Fundamentals
Chapterpublic 4 - Object-Oriented Programming with C# virtual ObjRef CreateObjRef(Type requestedType); Chapterpublic 5 - Exceptions virtual and bool Object Equals(object Lifetime obj);
virtual Chapterpublic 6 - Interfaces and IntPtr CollectionsGetCOMIUnknown(bool fIsMarshalled); virtual int Delegates, GetHashCode(); Chapterpublic 7 - Callback Interfaces, and Events virtual void GetObjectData(SerializationInfo info, Chapterpublic 8 - Advanced C# Type Construction Techniques StreamingContext context); Part Three - Programming with .NET Assemblies Type GetProxiedType(); Chapterpublic 9 - Understanding .NET Assemblies staticAppDomains, object GetStubData(RealProxy rp); Chapterpublic 10 - Processes, Contexts, and Threads public virtual object GetTransparentProxy(); public Type GetType(); Part Four - Leveraging the .NET Libraries public IConstructionReturnMessage InitializeServerObject( Chapter 12 - Object Serialization and the .NET Remoting Layer IConstructionCallMessage ctorMsg); Chapter 13 - Building a Better Window (Introducing Windows Forms) public virtual IMessage Invoke(IMessage msg); Chapter 14 - A Better Painting Framework (GDI+) public virtual void SetCOMIUnknown(IntPtr i); Chapter 15 - Programming with Windows Forms Controls public static void SetStubData(RealProxy rp, object stubData); Chapterpublic 16 - Thevirtual System.IO IntPtr Namespace SupportsInterface(ref Guid iid); Chapterpublic 17 - Data Access with ADO.NET virtual string ToString(); Part } Five - Web Applications and XML Web Services Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Again, unless youWeb areServices interested in building a custom implementation of the client-side real proxy, the only Chapter 20 - XML member of interest is RealProxy.Invoke(). Under the hood, the CLR-generated transparent proxy passes Index theofformatted List Figures 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# and the .NET Platform, Second Edition that use of the TcpChannel type tends to result in faster remote access. On the downside, TCP channels ISBN:1590590554 by Andrew are not firewall friendly, andTroelsen may require the services of a system administrator to allow messages to pass Apress © 2003 (1200 pages) across machine boundaries (which does indeed echo the same limitations of classic DCOM). This comprehensive text starts with a brief overview of the C# language then quickly by moves to key technical andtype, which converts message In contrast, the HTTP channeland is represented the HttpChannel class architectural issues for .NETsoap developers. objects into a SOAP format using 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 Table of Contents friendly, given that most firewalls allow textual packets to be passed over port 80. C# and the .NET Platform, Second Edition
Introduction Regardless of which channel type you chose to use, understand that both the HttpChannel and Part One - Introducing C# and the Platform TcpChannel type implement the .NET IChannel, IChannelSender,
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 channel types. The role of IChannelSender Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# TcpChannel types (as you would hope) are able to send and receive network packets, and therefore Chapter 5 - Exceptions and Object Lifetime implement all three channel-centric interfaces. Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events To allow the client and server applications to register their channel of choice, you will make use of the Chapter 8 - Advanced C# Type Construction Techniques ChannelServices.RegisterChannel() method, which (surprise, surprise) takes a type implementing Part Three -To Programming withto.NET Assemblies IChannel. preview things come, the following code snippet illustrates how a server-side application Chapter - Understanding .NETchannel Assemblies domain9can register an HTTP on port 32469 (you see the client's role in just a bit): Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Create and register a server side HttpChannel on port 32469. HttpChannel c = new HttpChannel(32469); Chapter 12 - Object Serialization and the .NET Remoting Layer ChannelServices.RegisterChannel(c); Part Four - Leveraging the .NET Libraries
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Revisiting the Role of .NET Formatters
Chapter 17 - Data Access with ADO.NET
Part Web Applications XML Web Services TheFive final- piece of the .NETand Remoting puzzle is the
role of formatter objects. A given channel object
Chapter 18 - ASP.NET Web Pagesleverages and Web Controls (TcpChannel or HttpChannel) a specific internal formatter, whose job it is to translate the Chapter 19 object - ASP.NET Applications message into Web protocol specific terms. As you would guess, the TcpChannel type makes use of the Chapter 20 - XML Web Services System.Runtime.Serialization.Formatters.Binary.BinaryFormatter type, while the HttpChannel type uses Index the functionality provided by the System.Runtime.Serialization.Formatters.Soap.SoapFormatter type. List Given of Figures your work 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! and the .NET Platform, Second Edition All Together by Andrew Troelsen
ISBN:1590590554
If your head is spinning the previous sections, fear not! The transparent proxy, real proxy, Apress from © 2003reading (1200 pages) message object, This and comprehensive dispatcher cantext typically completely ignored, you are happy with the startsbe with a brief overview ofprovided 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 moves to key technical and architectural issues for is .NET developers. channel object (and related formatter) as simple as 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 12Table of Contents 7, which illustrates the basic process of two objects communicating across distinct application domains. C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Figure 12-7: A high-level view of the default .NET Remoting architecture
Part Three - Programming with .NET Assemblies
Chapter 9
Understanding .NET Assemblies A Brief- Word Regarding the Extension of the Default Plumbing
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, Attribute-Based A key aspect of the .NET Remoting layerand (which is markedly Programming different from that of classic DCOM) is the Part Leveraging the .NET Librarieslayers factFour that -most of the default remoting
can be extended or completely replaced at the whim of the
Chapter 12 - Thus, Objectif Serialization and(or the .NET Remoting developer. you truly want possibly need) toLayer build a custom message dispatcher, custom Chapter 13 Building a Better Window (Introducing Forms) formatter, or custom real proxy, you are free to doWindows so. Chapter 14 - A Better Painting Framework (GDI+)
You are15also able to injectwith additional levels of Controls indirection by plugging in custom types that stand between a Chapter - Programming Windows Forms given layer custom sink used to perform preprocessing or post-processing of a given Chapter 16 - (for The example, System.IOa Namespace
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. Part Five - Web Applications and XML Web Services Chapter 17 - Data Access with ADO.NET
Chapter 18 This - ASP.NET Web Pages Web Controls Note chapter does not and address the topic of extending the default .NET Remoting layer. If you Chapter 19 wish - ASP.NET Web Applications to learn how to do so, check out Advanced .NET Remoting (Rammer, Apress 2002). Chapter 20 - XML Web Services Index List of Figures List of Tables
C# .NET and the Remoting .NET Platform,Trade Second Edition Terms of the by Andrew Troelsen
ISBN:1590590554
Like any new paradigm, Remoting Apress ©.NET 2003 (1200 pages) brings a number of TLAs (three-letter-acronyms) into the mix. Thus, before youThis see comprehensive your first code text example, to defineofa the number of terms used when starts we withdo a need brief overview describing the composition of a .NET Remoting application. As you would C# language and then quickly moves to key technical and guess, this terminology is used architectural issues for .NET developers. 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 Table of Contents of the related terminology, the act of building a distributed .NET application will be far an understanding C# and the .NET Platform, Second that Edition less perplexing. Do understand the acronyms that follow are mapped to specific code examples over Introduction the course of the chapter. Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the Choices .NET Platform, Secondor Edition Object Marshaling (MBR MBV?) by Andrew Troelsen
ISBN:1590590554
Under the .NET platform, you (1200 havepages) two options regarding how a remote object is marshaled to the client. Apress © 2003 First question: What the heck is marshaling? Simply a term that describes how a remote This comprehensive text starts with aput, briefmarshaling overview ofisthe object is passed between application domains. When you are designing C# language and then quickly moves to key technical and a remotable object, you may issues for .NET developers. choose to employarchitectural marshal-by-reference (MBR, for short) or marshal-by-value (MBV, for short) semantics. The distinction is as follows: Table of MBR Contents objects: The caller receives a proxy to the remote object C# and the .NET Platform, Second Edition
MBV objects: The caller receives a full copy of the object in its own application domain
Introduction
Part One - Introducing C# and the .NET Platform
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 Part The C# Programming Language overTwo the-show and will package, pass, 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 - Object-Oriented Programmingoptions with C#regarding their activation options and lifetime MBR objects have various configuration Chapter 5 - Exceptions and Object Lifetime management. Chapter 6
- Interfaces and Collections MBV objects, on the Interfaces, other hand,Delegates, are local and copies of remote objects (which as you can guess make use of Chapter 7 - Callback Events
the .NET serialization protocol examined at the beginning of this chapter). MBV objects have far fewer - Advanced C# Type Construction Techniques configuration settings, given that their lifetime is directly controlled by the client. Like any .NET object, once Part Three - Programming with .NET Assemblies a client has released all references to an MBV type, it is a candidate for garbage collection. Given that Chapter 9 - Understanding .NET Assemblies MBV types are local copies of remote objects, as a client invokes members on the type no network activity Chapter 10 - Processes, AppDomains, Contexts, and Threads occurs during the process. Chapter 8
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries To solidify the distinction between MBR
and MBV objects, think back to Chapter 3 when you examined the
Chapter Object and the Remoting Layer role of 12 the-C# "ref" Serialization keyword. Recall that.NET by default, parameters are passed into a method by value. Thus, Chapter 13 Building a Better Window (Introducing Windows Forms) if the receiving function attempts to reassign the value of the incoming parameters, the caller is unaware of Chapter the modification. 14 - A Better On Painting the otherFramework hand, if method (GDI+)parameters are modified using the "ref" keyword, a
reference the value type is passed into the method, Chapter 15 -toProgramming with Windows Forms Controls and thus any modifications are realized after the call. 16 - The System.IO Namespace Chapter Chapter 17 - Data Access with 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 Controls using the same object serialization technique presented at the start of this chapter. Part Five - Web Applications and XML Web Services
Chapter 19 - ASP.NET Web Applications
Chapter 20 - object XML Web If a remote hasServices been configured to be an MBR type, the client does not receive a local copy of the Index type. Rather, the remote object is bound to the application domain in which it was created, forcing the List caller of Figures to interact 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# and the .NET Platform, Second Edition
The other, more exotic, approach is to implement the ISerializable interface. Using this technique, you are ISBN:1590590554 by Andrew Troelsen able to customizeApress the serialization process to fit your needs (as illustrated previously in this chapter). © 2003 (1200 pages) This comprehensive text starts with a brief overview of the
language andObject then quickly moves to key technical and ConfiguringC#an MBR architectural issues for .NET developers.
MBR objects are not marked as such using a .NET attribute, but rather derive (directly or indirectly) from the System.MarshalByRefObject base class: Table of Contents C# and the .NET Platform, Second Edition
public class MyCustomMBRClass : MarshalByRefObject {...}
Introduction
Part One - Introducing C# and the .NET Platform
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: Part Two - The C# Programming Language
Chapter 3 abstract - C# Language Fundamentals public class MarshalByRefObject : object Chapter 4 - Object-Oriented Programming with C# { Chapter public 5 - Exceptions and Object Lifetime virtual ObjRef CreateObjRef(Type requestedType); Chapter public 6 - Interfaces and Collections virtual bool Equals(object obj); Chapter public 7 - Callback virtual Interfaces, intDelegates, GetHashCode(); and Events
virtual object GetLifetimeService(); Chapter public 8 - Advanced C# Type Construction Techniques public Type GetType(); Part Three - Programming with .NET Assemblies virtual .NET object InitializeLifetimeService(); Chapter public 9 - Understanding Assemblies virtual stringContexts, ToString(); Chapter public 10 - Processes, AppDomains, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Beyond the expected functionality provided by System.Object, Table 12-5 describes the role of the remaining members.
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Table 12-5: Key Members of System.MarshalByRefObject
Chapter 16 - The System.IO Namespace
System.MarshalByRefObject Chapter 17 - Data Access with ADO.NET
Meaning in Life
Member Part Five - Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls
CreateObjRef()
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object
Index ListGetLifetimeServices() of Figures 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# andtothe Platform, Second Edition Note As a corollary the.NET previous note, understand that if a .NET type is not serializable and does ISBN:1590590554 by Andrew Troelsen not include MarshalByRefObject in its inheritance chain, the type in question can only be Apress 2003 in (1200 activated and © used thepages) originating application domain (meaning, they are context bound types). This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, SecondObjects Edition Final NotesC#Regarding MBR/MBV by Andrew Troelsen
ISBN:1590590554
The .NET Remoting layer has(1200 a number Apress © 2003 pages) of intrinsic optimizations that help ensure that when a client interacts with remotable objects, network trafficwith is kept to aoverview minimum. This comprehensive text starts a brief of To the provide some insights to these internal tweaks, ponder the following points: C# language and then quickly moves to key technical and architectural issues for .NET developers.
Treatment of static members: Static type members are never invoked remotely, but are triggered within the client-side application domain. Table of Contents
Treatment object fields and accessor methods: For object-level fields and accessor methods, the C# and the .NET of Platform, 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. Part One - Introducing C# and the .NET Platform Introduction
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 Part Two - The C# Programming Language remote type overrides Equals() or ToString(),
Chapter 3
a network round-trip will occur.
- C# Language Fundamentals
Now that understand the distinct traitswith of MBR Chapter 4 you - Object-Oriented Programming C# and MBV types, let's check out some issues that are specific5to -MBR types (MBV types Lifetime need not apply). Chapter Exceptions and Object Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Second Edition Activation Choices for Platform, MBR Types (WKO or CAO?) by Andrew Troelsen
ISBN:1590590554
Another remoting-centric you face as a .NET programmer has to do with exactly when an MBR Apress © choice 2003 (1200 pages) object is activatedThis andcomprehensive when it shouldtext be starts a candidate for garbage on the server. This might with a brief overviewcollection 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 moves to key technical and architectural issuesthe forclient .NET developers. the client requests it and die when 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 Table of Contents this seemingly strange behavior has to do with the optimization. Specifically, every MBR type may be C# and the .NET Second configured to bePlatform, activated using Edition one of two techniques: Introduction
As a- Introducing Well KnownC# Object (WKO) Part One and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
As a Client Activated Object (CAO)
Part Two C# Programming Languageis Note- The A potential point of confusion
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 - Object-Oriented C#Help and find the terms WKO, server-activated object, or and books.Programming As you readwith online Chapter 5 SAO, - Exceptions and Object Lifetime understand that these three terms are one and the same. Given that WKO seems to be Chapter 6 the - Interfaces moniker and of choice Collections at present, I make use of this acronym in this chapter. Chapter 7
- Callback Interfaces, Delegates, and Events
WKO objects are MBR types whose lifetimes are directly controlled by the server's application domain. Chapter 8 - Advanced C# Type Construction Techniques The client-side application activates the remote type using a friendly, well-known string name (hence the Part Three - Programming with .NET Assemblies term, WKO). The server's application domain allocates WKO types only when the client makes the first Chapter 9 - Understanding .NET Assemblies method call on the object (via the transparent proxy), not when the client's code base makes use of the Chapter 10 - Processes, AppDomains, Contexts, and Threads "new" keyword or via the static Activator.GetObject() method. To illustrate: Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
// 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 Better Window (Introducing Windows Forms) // Invoke a method on remote WKO type. This WILL create the WKO object Chapter 14 - A Better Painting Framework (GDI+) // and invoke the ReturnMessage() method. Chapter 15 - Programming with Windows Forms Controls RemoteMessageObject simple = (RemoteMessageObject)remoteObj; Chapter 16 - The System.IO Namespace Console.WriteLine("Server says: {0}", simple.ReturnMessage()); Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Pages This and Web Controls 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 Applications interesting 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 Services client makes the initial member invocation. Thus, the runtime has no other option than to invoke the type's Index default constructor. List of Figures 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# and the .NET Platform, Second Edition that multiple clients could invoke the same method at the same time, the CLR places each client by Andrew invocation on a new thread. Troelsen It is your responsibility, however, toISBN:1590590554 ensure that your objects are thread-safe Apress © 2003 (1200 using the same techniques seen inpages) Chapter 10. This comprehensive text starts with a brief overview of the C# call language quickly moves to key technical andcontext of a single method In contrast, a single objectand is athen WKO type that exists only during the issues for .NET developers. invocation. Thus,architectural if there are 20 clients making use of 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 Table of Contents than singleton types, given that they are invariably stateless entities. C# and the .NET Platform, Second Edition
Introduction The server is the entity in charge of determining the stateful configuration of a given WKO type. Part One - Introducing C# and the .NET Platform Programmatically, these options are expressed
via the System.Runtime.Remoting.WellKnownObjectMode
Chapter enumeration: 1 - The Philosophy of .NET Chapter 2
- Building C# Applications
Part Two - The C# WellKnownObjectMode Programming Language public enum
Chapter 3 {
- C# Language Fundamentals
ChapterSingleCall, 4 - Object-Oriented Programming with C# ChapterSingleton 5 - Exceptions and Object Lifetime
} Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
- Understanding Assemblies Summarizing the .NET Traits of MBR Object Types
Chapter 9
Chapter 10 - Processes, AppDomains, Contexts, and Threads
As you 11 have seen, the configuration options an MBV objectProgramming are a no-brainer: apply the [Serializable] Chapter - Type Reflection, Late Binding, andof Attribute-Based attribute allow copies theLibraries type to be Part Four -toLeveraging theof .NET
returned to the client's application domain. At this point, all
interaction theSerialization MBV type takes place in Remoting the client's locale. When the client is finished using the MBV Chapter 12 -with Object and the .NET Layer type, it 13 is a-candidate garbage collection, and Windows all is wellForms) with the world. Chapter Building a for Better Window (Introducing Chapter 14 - A Better Painting Framework (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 System.IO Namespace summarize the array of possibilities, Table 12-6 documents how WKO and CAO types stack up against Chapter 17you - Data Access with ADO.NET the traits have just examined. Chapter 15 - Programming with Windows Forms Controls
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Table 12-6: Configuration Options for Controls MBR Types Chapter 19 - ASP.NET Web Applications
MBR 20 Object Behavior (aka ServerChapter - XML WebWKO Services
CAO Behavior
Trait Index
Activated Object)
ListInstantiation of Figures
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 WKOPlatform, types make use ofEdition a CAO types make use of a leaseC#Singleton and the .NET Second management by lease-based management scheme based management scheme ISBN:1590590554 Andrew Troelsen (described later in this chapter). Single (described later in this chapter). Apress © 2003 (1200 pages) call WKO types are a candidate for This comprehensive text starts with a brief overview of the after the current C#garbage languagecollection and then quickly moves to key technical and architectural method invocation. issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Second EditionProject Basic Deployment of aPlatform, .NET Remoting by Andrew Troelsen
ISBN:1590590554
Enough acronyms! At this point youpages) are almost ready to build your first .NET Remoting application. Before Apress © 2003 (1200 you do, however,This I need to discuss one detail—deployment. When you are building a .NET Remoting comprehensive textfinal starts with a brief overview of the application, you are almost certain to end up with three distinct .NET assemblies that will constitute the C# language and then quickly moves to key technical and architectural issues(yes, for .NET developers. entirety of your remote application three, not two). The first two assemblies I am sure you can already account for: Table of TheContents client: 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 the .NETapplication, Platform, Second Edition ASP.NET Web application. Introduction Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language IIS. Chapter 1
Chapter 3
- C# Language Fundamentals
Chapter 4 where - Object-Oriented Programming So then, does the third assembly fitwith in? C# Well, in reality, the server application is typically a host to a Chapter 5 - Exceptions and Object Lifetime third assembly that defines and implements the remote objects. For convenience, I'll call this assembly the Chapter 'general 6 assembly'. - Interfaces This anddecoupling Collections of the assembly containing the remote objects and server host is quite
important, that both the clientDelegates, and the server assemblies typically set a reference to the general Chapter 7 -inCallback Interfaces, and Events assembly order to obtain theConstruction metadata definitions of the remotable types. Chapter 8 in - Advanced C# Type Techniques Part Three - Programming with .NET Assemblies
In the simplest case, the general assembly is placed into the application directory of the client and server. - Understanding .NET Assemblies The only possible drawback to this approach is the fact that the client has a reference to an assembly that Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming cannot examine your custom proprietary code). Specifically, the only reason the client requires a reference Part Four - Leveraging the .NET Libraries to the general assembly is to obtain the metadata descriptions of the remotable types. There are several Chapter 12 - Object Serialization and the .NET Remoting Layer ways to overcome this glitch, for example: Chapter 9
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter Construct 14 - A Better your remote Paintingobjects Framework to make (GDI+) use of interface-based programming techniques. In this way,
you15can build an additional assembly that Controls contains nothing but interface definitions for the remote Chapter - Programming with Windows Forms types. this, the client is able to set a reference to a .NET binary that contains nothing but Chapter 16 -Given The System.IO Namespace interface definitions. Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
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 Applications use of soapsuds.exe later in this chapter. Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 20 - XML Web Services
Index Manually build an assembly that contains nothing but metadata descriptions of the remote types (from List ofscratch Figures 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 and theDistributed .NET Platform, Second Edition Building Our Application by Andrew Troelsen
ISBN:1590590554
There is nothing more than building a distributed application using a new platform. To illustrate how Apresssatisfying © 2003 (1200 pages) quickly you are able to get up and running with with the .NET This comprehensive text starts a briefRemoting overview 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 moves to key technical and architectural issues for .NET developers.
A general assembly named SimpleRemotingAsm.dll A client assembly named SimpleRemoteObjectClient.exe Table of Contents C# and the .NET Platform, Second Edition
A server assembly named SimpleRemoteObjectServer.exe
Introduction
Part Introducing C#example and the .NET Platform TheOne first-iteration of this makes use of
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 Part Two - The C# Programming Language
Building the General Assembly
Chapter 3
- C# Language Fundamentals
Chapter 4 -create Object-Oriented with C# First, let's the generalProgramming assembly (SimpleRemotingAsm.dll), which will be referenced by both the server Chapter 5 -binaries. Exceptions and Object Lifetime and client SimpleRemotingAsm.dll defines a single MBR type named RemoteMessageObject, which Chapter supports 6 two - Interfaces public 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 Interfaces, Delegates, Events class library: Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies namespace SimpleRemotingAsm Chapter { 10 - Processes, AppDomains, Contexts, and Threads
is a type will be Chapter // 11 -This Type Reflection, Late that Binding, and Attribute-Based Programming marshaled Part Four// - Leveraging the by .NETreference Libraries
(MBR) if accessed remotely.
class RemoteMessageObject: MarshalByRefObject Chapter public 12 - Object Serialization and the .NET Remoting Layer Chapter { 13 - Building a Better Window (Introducing Windows Forms)
The ctorFramework prints (GDI+) a message just to Chapter 14 - A // Better Painting // confirm has been Chapter 15 - Programming withit Windows Forms activated. Controls public RemoteMessageObject() { Console.WriteLine("RemoteMessageObject ctor called!");} Chapter 17 - Data Access with ADO.NET // This method takes an input string Part Five - Web Applications and XML Web Services // from the caller. Chapter 18 - ASP.NET Web Pages and Web Controls public void DisplayMessage(string msg) Chapter 19 - ASP.NET Web Applications { Console.WriteLine("Message is: {0}", msg);} Chapter 20 - XML Web Services // This method returns a value to the caller. Index public string ReturnMessage() List of Figures { return "Hello from the server!"; } List of Tables } } Chapter 16 - The System.IO Namespace
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# and the .NET Platform, Second Edition System.Runtime.Remoting; ISBN:1590590554 by Andrew Troelsen System.Runtime.Remoting.Channels; Apress © 2003 (1200 pages) System.Runtime.Remoting.Channels.Http; This comprehensive text starts with a brief overview of the SimpleRemotingAsm; C# language and then quickly moves to key technical and architectural issues for .NET developers.
namespace SimpleRemoteObjectServer { class SimpleObjServer Table of Contents { C# and the .NET Platform, Second Edition static void Main(string[] args) Introduction { Part One - Introducing C# and the .NET Platform 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 Part Two - The C# Programming Language HttpChannel c = new HttpChannel(32469); Chapter 3 - C# Language Fundamentals ChannelServices.RegisterChannel(c); Chapter 4 - Object-Oriented Programming with type, C# // Register a WKO using singleton activation. Chapter 5 - Exceptions and Object Lifetime RemotingConfiguration.RegisterWellKnownServiceType( Chapter 6 - Interfaces and Collections typeof(SimpleRemotingAsm.RemoteMessageObject), Chapter 7 - Callback Interfaces, Delegates, and Events "RemoteMsgObj.soap", Chapter 8 - Advanced C# Type WellKnownObjectMode.Singleton); Construction Techniques Part Three - Programming Console.ReadLine(); with .NET Assemblies } Chapter 9 - Understanding .NET Assemblies Chapter } 10 - Processes, AppDomains, Contexts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
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 Painting Framework (GDI+) the remote server assembly is now equipped to process incoming messages via port number 32469. Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 15 - Programming with Windows Forms Controls
Chapter 16 The - Thenumber System.IO Note you Namespace assign to a port is typically up to you (or your system administrator). Do be aware, Chapter 17 however, - Data Access that port with IDs ADO.NET below 1024 are reserved for use. Part Five - Web Applications and XML Web Services
Next, to18register the SimpleRemotingAsm.RemoteMessageObject type as a WKO requires the use of the Chapter - ASP.NET Web Pages and Web Controls
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 Services RegisterWellKnownServiceType() is a simple string (of your choosing) that will be used to identify the object Index across application domain boundaries (hence the notion of a well-known object). Chapter 19 - ASP.NET Web Applications
List of Figures
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# and the .NET Platform, Second Edition namespace SimpleRemoteObjectClient ISBN:1590590554 by Andrew Troelsen { Apress © 2003 (1200 pages) class SimpleObjClient This comprehensive text starts with a brief overview of the { C# language then quickly moves to key technical and static void and Main(string[] args) architectural issues for .NET developers. { Console.WriteLine("***** SimpleRemoteObjectClient started! *****"); Console.WriteLine("Hit enter to end."); Table of Contents // Create a new HttpChannel C# and the .NET Platform, Second Edition HttpChannel c = new HttpChannel(); Introduction ChannelServices.RegisterChannel(c); Part One - Introducing C# and the .NET Platform // 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), Part Two - The C# Programming Language "http://localhost:32469/RemoteMsgObj.soap"); Chapter 3 - C# Language Fundamentals // Now use the remote object. Chapter 4 - Object-Oriented Programming with C#simple = (RemoteMessageObject)remoteObj; RemoteMessageObject Chapter 5 - Exceptions and Object Lifetime simple.DisplayMessage("Hello from the client!"); Chapter 6 - InterfacesConsole.WriteLine("Server and Collections says: {0}", simple.ReturnMessage()); Chapter 7 - Callback Interfaces, Delegates, and Events Console.ReadLine(); Chapter 8 - Advanced } C# Type Construction Techniques Part Three } - Programming with .NET Assemblies } Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
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 client Chapter 13 - Building a Better Window (Introducing Windows Forms) is interacting with a registered WKO type, you are limited to triggering the type's default constructor. To do so, Chapter 14 - A Better Painting Framework (GDI+) make use of the Activator.GetObject() method, specifying two parameters. The first is the type information that Chapter 15 - Programming with Windows Forms Controls describes the remote object you are interested in interacting with. Read that last sentence again. Given that the Chapter 16 - The System.IO Namespace Activator.GetObject() method requires the object's metadata description, it should make more sense why the Chapter 17 Data Access with ADO.NET client is also required to reference the general assembly! Again, at the end of the chapter you examine various Part Five Web up Applications and Services ways to -clean this aspect of XML your Web client-side assembly. Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 18 - ASP.NET Web Pages and Web Controls
The second parameter to Applications Activator.GetObject() is termed the activation URL. Unlike classic DCOM which Chapter 19 - ASP.NET Web identified objects using a numerical GUID, .NET makes use of a friendlier, more readable string name. Chapter 20 remote - XML Web Services Activation URLs that describe a WKO type can be generalized into the following format: Index List of Figures
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.
and the .NET Application Platform, Second Edition Testing theC#Remoting by Andrew Troelsen
ISBN:1590590554
To test your application, by launching the server application, which will open an HTTP channel and Apress ©begin 2003 (1200 pages) register your remote object for access. Next, launch instance of the client application. If all is well, your This comprehensive text starts with aan brief overview 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 moves to key technical and architectural issues for .NET developers. Figure 12-9.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET Figure The output Chapter 2 - 12-8: Building C#server's Applications Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections Figure The client's output Chapter 7 - 12-9: Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, Second Edition Understanding ChannelServices Type by Andrew Troelsen
ISBN:1590590554
As you have seen, when©a2003 server wishes to advertise the existence of a remote type, it makes Apress (1200application pages) use of the System.Runtime.Remoting.Channels.ChannelServices ChannelServices provides a small This comprehensive text starts with a brief overviewtype. of the set of static methods that aid in the process of remoting channel registration, resolution, and URL C# language and then quickly moves to key technical and architectural issues .NET developers. discovery. Table 12-7 documents thefor members in question. Table 12-7: Select Members of the ChannelServices Type
Table of Contents
of Platform, Second Edition Meaning in Life C#Member and the .NET ChannelServices Introduction Part One - Introducing C# and the .NET Platform
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.
Part Two - The C# Programming Language
AsyncDispatchMessage() Chapter 3 - C# Language Fundamentals Asynchronously dispatches the given message to the Chapter 4
server-side - Object-Oriented Programming with C# chain(s) based on the URI embedded in the
Chapter 5
message. - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections CreateServerChannelSinkChain() Chapter 7
Creates a channel sink chain for the specified channel.
- Callback Interfaces, Delegates, and Events
DispatchMessage() Dispatches incoming remote calls. - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies GetChannel() Returns a registered channel with the specified name. Chapter 8 Chapter 9
- Understanding .NET Assemblies
GetChannelSinkProperties()
Returns an IDictionary of properties for a given proxy.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding,Returns and Attribute-Based Programming GetUrlsForObject() an array of all the URLs that can be used to reach Part Four - Leveraging the .NET Libraries
the specified object.
Chapter 12 - Object Serialization and the .NET Remoting Layer
RegisterChannel()
Registers a channel with the channel services.
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework Synchronously (GDI+) SyncDispatchMessage() dispatches the incoming message to the Chapter 15 - Programming with Windows Forms server-side Controls chain(s) based on the URI embedded in the Chapter 16 - The System.IO Namespace message. Chapter 17 - Data Access with ADO.NET
UnregisterChannel()
Unregisters a particular channel from the registered channels list.
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
In addition to the aptly named RegisterChannel() and UnregisterChannel() methods, ChannelServices
Chapter XML Web Services defines20 the- RegisteredChannels property. This member returns an array of IChannel interfaces, that each Index represent a handle to each channel registered in a given application domain. The definition of the List of Figures IChannel interface 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# and the .NET Platform,Priority: Second Edition Console.WriteLine("Channel {0}", i.ChannelPriority); by Andrew Troelsen Apress © 2003 (1200 pages)
}
ISBN:1590590554
This comprehensive text starts with a brief overview of the C#client language and then now quickly moves key technical You would find the side console looks like to Figure 12-10. and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1 - 12-10: The Philosophy of .NET Figure Enumerating client-side channels Chapter 2 - Building C# Applications Part - The of C#the Programming Languageof TheTwo majority remaining methods
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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, Second Edition Understanding RemotingConfiguration Type by Andrew Troelsen
ISBN:1590590554
Another key remoting-centric RemotingConfiguration, which as the name suggests, is used to Apress © 2003 type (1200 is pages) configure variousThis aspects of a remoting you have comprehensive textapplication. starts with aCurrently, brief overview of theseen this type in use on the server side (via the call to the RegisterWellKnownServiceType() method). Table C# language and then quickly moves to key technical and 12-8 lists additional static architectural members of interest, some ofissues whichfor you.NET seedevelopers. in action over the remainder of this chapter: Table 12-8: Members of the RemotingConfiguration Type
Table of Contents
of Platform, Second Edition C#Member and the .NET
Meaning in Life
RemotingConfiguration Introduction Part One - Introducing C# and the .NET Platform
ApplicationId
Chapter 1
- The Philosophy of .NET
ApplicationName Chapter 2 - Building C# Applications Part Two - The C# Programming Language
ProcessId
Chapter 3
- C# Language Fundamentals
Gets the ID of the currently executing application Gets or sets the name of a remoting application Gets the ID of the currently executing process
Configure() Reads the configuration file and configures the Chapter 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections GetRegisteredActivatedClientTypes() Chapter 7 Chapter 8
remoting infrastructure Retrieves an array of object types registered on the
- Callback Interfaces, Delegates, and Events client as types that will be activated remotely - Advanced C# Type Construction Techniques
GetRegisteredActivatedServiceTypes() Part Three - Programming with .NET Assemblies
Retrieves an array of object types registered on the service end that can be activated on request from a Chapter 9 - Understanding .NET Assemblies client Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming GetRegisteredWellKnownClientTypes() Retrieves an array of object types registered on the Part Four - Leveraging the .NET Libraries client end as well-known types Chapter 12 - Object Serialization and the .NET Remoting Layer
GetRegisteredWellKnownServiceTypes()
Retrieves an array of object types registered on the service end as well-known types
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter IsActivationAllowed() 15 - Programming with Windows Forms Controls Returns a Boolean value indicating whether the Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
IsRemotelyActivatedClientType()
specified Type is allowed to be client activated Checks whether the specified object type is registered as a remotely activated client type
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
IsWellKnownClientType() Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index RegisterActivatedClientType() List of Figures
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
List of Tables
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# and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen ... Apress © 2003 (1200 pages) // Set a friendly name for this server app. This comprehensive text starts with a brief overview of the RemotingConfiguration.ApplicationName = "First server app!"; C# language and then quickly moves to key technical and Console.WriteLine("App Name: {0}", architectural issues for .NET developers. RemotingConfiguration.ApplicationName); // Get an array of WellKnownServiceTypeEntry types // that represent all the registered WKOs. Table of Contents WellKnownServiceTypeEntry[] WKOs = C# and the .NET Platform, Second Edition RemotingConfiguration.GetRegisteredWellKnownServiceTypes(); Introduction // Now print their statistics. Part One - Introducing C# and the .NET Platform 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); Part Two - The C# Programming Language Console.WriteLine("URL to WKO: {0}", wko.ObjectUri); Chapter 3 - C# Language Fundamentals Console.WriteLine("Type of WKO: {0}", wko.ObjectType); Chapter 4 - Object-Oriented Programming with C# Console.WriteLine("Mode of WKO: {0}", wko.Mode); Chapter } 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections } Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
youThree will find a list of all WKO registered by Part - Programming withtypes .NET Assemblies
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 - Understanding .NET Assemblies WKO. Given that our server's application only registered Chapter 10 - Processes, AppDomains, Contexts, and Threadsa single type (SimpleRemotingAsm.RemoteMessageObject), we find the following output (Figure 12-11). Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter Figure 18 - 12-11: ASP.NET Server-side Web Pagesstatistics and Web Controls Chapter 19 - ASP.NET Web Applications
The other method of the RemotingConfiguration type is Configure(). As you see in just a bit, this static Chapter 20 -major XML Web Services member allows the client- and server-side application domains to make use of remoting configuration files.
Index
List of Figures List of Tables
C# and the .NET Platform, Second Edition Types Revisiting the Activation Mode of WKO by Andrew Troelsen
ISBN:1590590554
Recall that WKOApress types can be(1200 configured © 2003 pages) to function under singleton or single call activation. Currently, our server application has registered our starts WKO with to employ activation semantics: This comprehensive text a brief singleton overview of the C# language and then quickly moves to key technical and issues for .NET developers. // Singletonsarchitectural can service multiple clients. RemotingConfiguration.RegisterWellKnownServiceType( typeof(SimpleRemotingAsm.RemoteMessageObject), Table of Contents "RemoteMsgObj.soap", C# and the .NET Platform, Second Edition WellKnownObjectMode.Singleton); Introduction
Part One - Introducing C# and the .NET Platform
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 Part Two - run The the C# server Programming Language yourself, application (if it is
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 - Object-Oriented Programming with (Figure C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure SingletonLate WKOs are shared among remote clients. Chapter 11 - 12-12: Type Reflection, Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Now to test the behavior of single call objects, modify the server to register the WKO to support single call activation:
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
// Single call types maintain a 1-to-1 relationship // between client and WKO. Chapter 16 - The System.IO Namespace RemotingConfiguration.RegisterWellKnownServiceType( Chapter 17 - Data Access with ADO.NET typeof(SimpleRemotingAsm.RemoteMessageObject), Part Five - Web Applications and XML Web Services "RemoteMsgObj.soap", Chapter WellKnownObjectMode.SingleCall); 18 - ASP.NET Web Pages and Web Controls Chapter 15 - Programming with Windows Forms Controls
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Once you have recompiled and run the server application, again launch three clients. This time you can Index seeofthat a new RemoteMessageObject is created for each client request (Figure 12-13). List Figures 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# and the .NETto Platform, SecondMachine Edition Deploying the Server a Remote by Andrew Troelsen
ISBN:1590590554
So far so good! At this point, have just crossed an application and process boundary on a single Apress © 2003you (1200 pages) machine. If you are connected to an additional machine, extendofthis This comprehensive text starts with a brieflet's overview theexample to allow the client to interact with the RemoteMessageObject type across a machine boundary. C# language and then quickly moves to key technical and To do so, follow these steps: architectural issues for .NET developers.
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 server-
Table of side Contents share point. C# and the .NET Platform, Second Edition
3. Open your SimpleRemoteObjectClient project workspace and retrofit the activation URL to specify Introduction name of the For example: Part Onethe - Introducing C#remote and themachine. .NET Platform Chapter 1
- The Philosophy of .NET
Chapter // 2 -Get Building C# Applications a proxy to remote object. Part Twoobject - The C# remoteObj Programming = Language Activator.GetObject(
Chapter 3
- C# typeof(SimpleRemotingAsm.RemoteMessageObject), Language Fundamentals
Chapter 4
"http://YourRemoteBoxName:32469/RemoteMsgObj.soap"); - Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
4. Execute the SimpleRemoteObjectServer.exe application on the server machine.
Chapter 8 - Advanced C# Type Construction Techniques 5. Execute the SimpleRemoteObjectClient.exe application on the client machine. Part Three - Programming with .NET Assemblies
6. Sit and grin. .NET Assemblies Chapter 9 back - Understanding Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
andTCP the .NET Platform, Second Edition LeveragingC# the Channel by Andrew Troelsen
ISBN:1590590554
Currently, your remote is accessible via the HTTP network protocol. As mentioned, this protocol is Apressobject © 2003 (1200 pages) quite firewall-friendly, however the resulting SOAP are a bitofonthe the bloated side (given the nature This comprehensive text starts withpackets a brief overview of XML data representation). To lighten the payload, we can update the C# language and then quickly moves to key technical andclient and server assemblies to architectural issues for .NET developers. make use of the TCP channel, and therefore make use of the BinaryFormatter type behind the scenes. Here are the relevant updates to the server assembly: Table Note of Contents When you are defining an object to be URI-accessible via a TCP endpoint, it is common (but not
to make use Edition of the *rem" extension (i.e., remote). C# and the required) .NET Platform, Second Introduction Part - Introducing C# and the .NET Platform // One Server adjustments!
Chapter - The Philosophy of .NET using1 System.Runtime.Remoting.Channels.Tcp; Chapter ... 2
- Building C# Applications
Part static Two - The void C# Main(string[] Programming Language args)
{ Chapter 3
- C# Language Fundamentals
... 4 Chapter
- Object-Oriented Programming with C# a and newObject TcpChannel Chapter // 5 -Create Exceptions Lifetime
new TcpChannel(32469); Chapter TcpChannel 6 - Interfaces c and=Collections Chapter ChannelServices.RegisterChannel(c); 7 - Callback Interfaces, Delegates, and Events
// -Register a 'well-known' object in single call mode. Advanced C# Type Construction Techniques RemotingConfiguration.RegisterWellKnownServiceType( Part Three - Programming with .NET Assemblies typeof(SimpleRemotingAsm.RemoteMessageObject), Chapter 9 - Understanding .NET Assemblies "RemoteMsgObj.rem", Chapter 10 - Processes, AppDomains, Contexts, and Threads WellKnownObjectMode.SingleCall); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Console.ReadLine(); Part Four - Leveraging the .NET Libraries } Chapter 8
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter A Better Painting Framework (GDI+) Notice 14 that- we are now registering a System.Runtime.Remoting.Channels.Tcp.TcpChannel type to the Chapter .NET Remoting 15 - Programming layer. Also with note Windows that theForms objectControls URI has been altered to support a more generic name
(RemoteMsgObj.rem) rather than the SOAP centric *.soap extension. The client-side updates are equally Chapter 16 - The System.IO Namespace as simple: Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls // Client adjustments! Chapter using19System.Runtime.Remoting.Channels.Tcp; - ASP.NET Web Applications
... 20 - XML Web Services Chapter static void Main(string[] args) Index { of Figures 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# and the .NET Platform, Second Edition logic. by Andrew Troelsen
SOURCE CODE
ISBN:1590590554
Apress © 2003 (1200 pages) The TCPSimpleRemoteObjectServer and TCPSimpleRemoteObjectClient projects are located under the Chapter 12 directory (both projects use the SimpleRemotingAsm.dll This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and created previously). architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Remoting Configuration FilesSecond Edition by Andrew Troelsen
ISBN:1590590554
At this point you have successfully built a distributed application (leveraging two computers) using the .NET Apress © 2003 (1200 pages) Remoting layer. One issue you may havestarts noticed inathese first examples This comprehensive text with brief overview of theis that fact that the client and the server applications have a good deal of hard-coded logic within their respective binaries. For example, the C# language and then quickly moves to key technical and issues .NET developers. server specifies aarchitectural fixed port ID, fixedfor activation mode, and fixed channel type. The client, on the other hand, hard-codes the name of the remote object it is attempting to interact with. Table As you of Contents might agree, it is wishful thinking to assume that initial design notes remain unchanged once an
application is deployed. C# and the .NET Platform, 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 Introduction .NET Remoting scheme, all the Part One - Introducing C# and the aforementioned .NET Platform
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. Part Two - The C# Programming Language
Chapter 4
- Object-Oriented Programming with C#
Chapter 5 - Exceptions and *.config Object Lifetime When building a remoting file, the element is used to hold various Chapter remoting-centric 6 - Interfaces details. and Do Collections be aware that if you are building an application that already has a *.config file
that specifies assembly resolution details, and you Events are free to add remoting elements within the same file. Thus, Chapter 7 - Callback Interfaces, Delegates, a single8 *.config file that remoting and binding information would look something like this: Chapter - Advanced C#contains Type Construction Techniques Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with 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:
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Index List of Figures List of Tables Chapter 20 - XML Web Services
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# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
© 2003 with the followingApress *.config file: (1200 pages)
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents Chapter 1 - The Philosophy of .NET Chapter 2 - Building C# Applications Part Two - The C# Programming Language Chapter 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Notice that much of the relevant server-side remoting Part Three - Programming with .NET Assemblies
information is wrapped within the scope of the (not server) element. The child element makes use of three attributes (mode, type, Chapter 9 - Understanding .NET Assemblies and objectUri) to specify the well-known object to register Chapter 10 - Processes, AppDomains, Contexts, and Threads with the .NET Remoting layer. The child element contains any number of Attribute-Based elements that allow you to define the type of Chapter 11 - Type Reflection, Late Binding, and Programming channel (in this case HTTP) to open on the server. TCP channels would simply make use of the "tcp" string Part Four - Leveraging the .NET Libraries token in place of "http". Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing As the SimpleRemoteObjectServer.exe.config fileWindows containsForms) all the necessary information, the server-side Chapter 14 - A Better Painting Framework All (GDI+) Main() method cleans up considerably. you are required to do is make a single call to Chapter 15 - Programming with Windows Forms Controls RemotingConfiguration.Configure(), and specify the name of your configuration file. Chapter 16 - The System.IO Namespace Chapter 17 void - Data Main(string[] Access with ADO.NET static args) Part { Five - Web Applications and XML Web Services
Chapter // 18 -Register ASP.NET Web and Web Controls a Pages 'well-known' object using a *.config file. Chapter RemotingConfiguration.Configure("SimpleRemoteObjectServer.exe.config"); 19 - ASP.NET Web Applications Chapter Console.WriteLine("Server 20 - XML Web Services started! Hit enter to end"); Index Console.ReadLine(); List } of Figures 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 Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers. Table of Contents
C# and the .NET Platform, Second Edition Introduction You are able to update the client's Main() method as follows: Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
static void Main(string[] args) - Building C# Applications { Part Two - The C# Programming Language 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 - Object-Oriented Programming with= C# simple new RemoteMessageObject(); Chapter simple.DisplayMessage("Hello 5 - Exceptions and Object Lifetime from the client!"); Chapter Console.WriteLine("Server 6 - Interfaces and Collections says: {0}", simple.ReturnMessage()); Chapter Console.WriteLine("Client 7 - Callback Interfaces, Delegates, and Events started! Hit enter to end"); Chapter Console.ReadLine(); 8 - Advanced C# Type Construction Techniques Part } Three - Programming with .NET Assemblies Chapter 2
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Of course, run theLate application, the output is identical. If the client wishes to make use of the TCP Chapter 11 -when Type you Reflection, Binding, and Attribute-Based Programming channel, "url" property of the Part Four - the Leveraging the .NET Libraries
element and ref property must make use of the "tcp"" token in place of "http." Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building Better Window (Introducing Windows Forms) SOURCE The aSimpleRemoteObjectServerWithConfig and SimpleRemoteObjectClientWithConfig Chapter 14 - A Better Painting Framework (GDI+) CODE projects are located under the Chapter 12 subdirectory (both of which make use of the Chapter 15 - Programming with Windows Forms Controls SimpleRemotingAsm.dll created previously). Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Working with MBV Objects by Andrew Troelsen
ISBN:1590590554
Our first remotingApress applications allowed © 2003 (1200 pages)client-side access to a single WKO type. Recall that WKO types are (by definition) MBR types, and therefore takes place via This comprehensive text client starts access with a brief overview 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 moves to key technical andfrom a public member of an MBR architectural issues forto.NET developers. type. Although you already 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: Table of Contents
The assembly named CarGeneralAsm.dll C# and thegeneral .NET Platform, Second Edition Introduction
The client assembly named CarProviderClient.exe
Part One - Introducing C# and the .NET Platform
Chapter 1 server - The assembly Philosophynamed of .NETCarProviderServer.exe The Chapter 2
- Building C# Applications
Part As you Twomight - The C# assume, Programming the codeLanguage behind the
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 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
- Interfaces and Collections Building the Cars General Assembly
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
At the beginning of thisC#chapter (during our Techniques examination of object serialization), you created a type named Chapter 8 - Advanced Type Construction JamesBondCar. The CarGeneralAsm.dll code Part Three - Programming with .NET Assemblies library will reuse this type (in addition to the dependent Radio and Car so begin by using the Project | Add Existing Item... menu command, and include these *.cs Chapter 9 types), - Understanding .NET Assemblies files into this new Class Library project. Given and thatThreads each of these types have already been marked with the Chapter 10 - Processes, AppDomains, Contexts, [Serializable] attribute, they are ready to be marshaled by value to a remote client. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
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 Better two Window (Introducing CarProvider will alsoadefine members, which Windows allow theForms) caller to obtain a specific JamesBondCar, as well Chapter 14 -the A Better Framework (GDI+) as receive entirePainting ArrayList of types. Here is the complete code for our new class type: Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
namespace CarGeneralAsm
Chapter 17 - Data Access with ADO.NET { Part Five// - Web Applications Web Serviceswhich This type isand anXML MBR object
provides
Chapter // 18 -access ASP.NET to Webrelated Pages and Web MBV Controls types. Chapter public 19 - ASP.NET WebCarProvider Applications class : MarshalByRefObject Chapter { 20 - XML Web Services Index private ArrayList theJBCars = new ArrayList(); List of Figures // 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# and the .NET Platform, Second Edition by Andrew Troelsen Notice the GetAllAutos() method returns the internal ArrayList type. The obvious question is how this member Apress © 2003 (1200 pages) of the System.Collections namespace is marshaled back to the caller. If you look up this type using online comprehensive starts with briefdecorated overview of thethe [Serializable] attribute: Help, you may beThis surprise to find thattext ArrayList has abeen with ISBN:1590590554
C# language and then quickly moves to key technical and architectural issues for .NET developers.
[Serializable] public class ArrayList : IList, ICollection, Table IEnumerable, of Contents ICloneable{...} C# and the .NET Platform, Second Edition Introduction
Therefore, the entire contents of .NET the ArrayList Part One - Introducing C# and the Platform 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 Part Two - The C# Programming Language 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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Building the Server Assembly - Interfaces and Collections
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
The server host assembly (CarProviderServer.exe) has the following logic within Main():
Part Three - Programming with .NET Assemblies
using System; - Understanding .NET Assemblies using System.Runtime.Remoting; Chapter 10 - Processes, AppDomains, Contexts, and Threads using System.Runtime.Remoting.Channels; Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming using System.Runtime.Remoting.Channels.Http; Part Four - Leveraging the .NET Libraries using CarGeneralAsm; Chapter 9
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
namespace CarProviderServer
Chapter 14 - A Better Painting Framework (GDI+) { Chapter class 15 - Programming with Windows Forms Controls CarServer Chapter { 16 - The System.IO Namespace Chapter 17 - Data Access void with ADO.NET static Main(string[] args) Part Five - Web{Applications and XML Web Services
Chapter 18 - ASP.NET RemotingConfiguration.Configure("CarProviderServer.exe.config"); Web Pages and Web Controls Chapter 19 - ASP.NET Console.WriteLine("Car Web Applications server started! Hit enter to end"); Chapter 20 - XML WebConsole.ReadLine(); Services Index
}
} List of Figures } 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# and the .NET Platform, Second Edition ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and architectural issues for .NET developers.
Building the Client Assembly Table of Contents
Last but least, we have the client application which will make use of the MBR CarProvider type in order to C# and thenot .NET Platform, Second Edition obtain discrete JamesBondCars types as well as the ArrayList type. Once we obtain a type from the Introduction CarProvider, we'll send into.NET the UseCar() Part One - Introducing C#them and the Platform Chapter 1
helper function from processing:
- The Philosophy of .NET
using2 System; Chapter - Building C# Applications using Part Two -System.Runtime.Remoting; The C# Programming Language using3 System.Runtime.Remoting.Channels; Chapter - C# Language Fundamentals using4 System.Runtime.Remoting.Channels.Http; Chapter - Object-Oriented Programming with C# using5 CarGeneralAsm; Chapter - Exceptions and Object Lifetime using6 System.Collections; Chapter - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
namespace CarProviderClient Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies class CarClient Chapter 9 - Understanding .NET Assemblies { Chapter 10 - Processes, AppDomains, Contexts, and Threads private static void UseCar(JamesBondCar c) Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming { Part Four - Leveraging the .NET Libraries Console.WriteLine("-> Name: {0}", c.PetName); Chapter 12 - Object Serialization and the .NET Remoting Layer Console.WriteLine("-> Max speed: {0}", c.MaxSpeed); Chapter 13 - Building aConsole.WriteLine("-> Better Window (Introducing Windows Forms) Sea worthy? : {0}", c.isSeaWorthy); Chapter 14 - A Better Painting Framework (GDI+) Console.WriteLine("-> Flight worthy? : {0}", c.isFlightWorthy); Chapter 15 - Programming with Windows Forms Controls Console.WriteLine(); Chapter 16 - The System.IO Namespace c.TurnOnRadio(true); Chapter 17 - Data } Access with ADO.NET Part Five - Webstatic Applications void andMain(string[] XML Web Services args) { Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET RemotingConfiguration.Configure("CarProviderClient.exe.config"); Web Applications Make the car provider. Chapter 20 - XML Web// Services CarProvider cp = new CarProvider(); Index // Get first JBC. List of Figures 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# and the .NET Platform, Second Edition ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform Chapter 1 - The Philosophy of .NET Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3 your - C#server Language Now, run andFundamentals client applications (in that order, of course) and observe the output. Your client-side Chapter - Object-Oriented Programming with C# console4 window will whirl through the JamesBondCars and print out the statistics of each type. Recall that as Chapter 5 - Exceptions and Object you interact with the ArrayList andLifetime JamesBondCar types you are operating on their members within the Chapter client's 6application - Interfaces domain, and Collections as they have both been marked with the [Serializable] attribute. Chapter 7
- Callback Interfaces, Delegates, and Events
To prove that point, update the UseCar() helper function to call the TurnOnRadio() method on the incoming Chapter 8 - Advanced C# Type Construction Techniques JamesBondCar. Now, run the server and client applications once again. Notice that the message box Part Three - Programming with .NET Assemblies appears on the client machine! Had the Car, Radio, and JamesBondCar types been configured as MBR Chapter 9 - Understanding .NET Assemblies types, the server would be the machine displaying the message box prompts. If you wish to verify this, derive Chapter 10 - Processes, AppDomains, Contexts, and Threads each type from MarshalByRefObject, and recompile all three assemblies (to ensure VS .NET copies the Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming latest CarGeneralAsm.dll into the client's and server's application directory). When you run the application Part Four - Leveraging the .NET Libraries once again, the message boxes appear on the remote machine. Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - BuildingThe a Better Window (Introducing Windows Forms) SOURCE CarGeneralAsm, CarProviderServer, and CarProviderClient projects are located Chapter CODE 14 - A Better under Painting the Framework Chapter 12(GDI+) subdirectory. Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andClient-Activated the .NET Platform, Second Edition (CAO) Understanding Objects by Andrew Troelsen
ISBN:1590590554
All of our current Apress remoting examples have made use of so-called well-known objects (which again, sometimes © 2003 (1200 pages) go by the term server-activated objects). Recallwith thataWKOs have theoffollowing characteristics: This comprehensive text starts brief overview the C# language and then quickly moves to key technical and
WKOs can be configuredissues either for as .NET singleton or single call. architectural developers.
WKOs can only be activated using the type's default constructor. Table of Contents
WKOs are instantiated on the server on the first client-side member invocation.
C# and the .NET Platform, Second Edition
Introduction CAO types on the other hand, can be instantiated using any constructor on the type and are created at the point Part - Introducing andC# the"new" .NET Platform the One client makes use C# 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 Part factTwo that-CAOs The C# are Programming always aliveLanguage (and therefore
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- Object-Oriented Programming with C# centric general assembly. Assume that our MBR CarProvider class has defined an additional constructor that Chapter 5 - Exceptions and Object Lifetime allows the client to pass in an array of JamesBondCar types that will be used to populate the internal ArrayList: Chapter 4 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
public class CarProvider : MarshalByRefObject Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies private ArrayList theJBCars = new ArrayList(); Chapter 9 - Understanding .NET Assemblies public CarProvider(JamesBondCar[] theCars) Chapter 10 - Processes, AppDomains, Contexts, and Threads { Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Console.WriteLine("Car provider created with custom ctor"); Part Four - Leveraging the .NET Libraries theJBCars.AddRange(theCars); Chapter 12 - Object Serialization and the .NET Remoting Layer } Chapter ... 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
In order17to-allow caller to ADO.NET activate the CarProvider using our new constructor syntax, we need to build a server Chapter Data the Access with application thatApplications registers CarProvider as Services a CAO type Part Five - Web and XML Web
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 Controls 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 Applications need to20 do- isXML pass in the type information of the type(s) (after creating and registering a channel) as follows: Chapter Web Services Index
//ofHard code the fact that CarProvider is a CAO type. List Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural .NET developers. Finally, we need to update theissues clientfor application, not only by way of the *.config file (or programmatically in the
code base) to request access to the remote CAO, but to indeed trigger the custom constructor of the CarProvider type. Here are the relevant updates to the client side Main() method:
Table of Contents
C# and the .NET Platform, Second Edition
static void Main(string[] args) { Part One - Introducing C# and the .NET Platform // 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. Part Two - The C# Programming Language JamesBondCar[] cars = Chapter 3 - C# Language Fundamentals { Chapter 4 - Object-Oriented Programming with C# new JamesBondCar("One", 100, false, false), Chapter 5 - Exceptions and Object Lifetime new JamesBondCar("Two", 100, false, false), Chapter 6 - Interfaces and Collections new JamesBondCar("Three", 100, false, false) Chapter }; 7 - Callback Interfaces, Delegates, and Events Chapter // 8 -Now Advanced C# Type Construction Techniques trigger the custom ctor. Part Three - Programmingcp with CarProvider = .NET newAssemblies CarProvider(cars); Chapter ... 9 - Understanding .NET Assemblies } Chapter 10 - Processes, AppDomains, Contexts, and Threads Introduction
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
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 Better Window (Introducing Windows Forms) Recall that when the server registered the CarProvider as a WKO, the client specified such information within the Chapter 14 - A Better Painting Framework (GDI+) element. Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Part Five - Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 20 - XML Web Services Index List of Figures List of Tables Chapter 17 - Data Access with ADO.NET
If you would rather hard-code the client's request to the CAO type, you can make use of the RegistrationServices.RegisterActivatedClientType() method as follows: static void Main(string[] args) { // Use hard coded values. RemotingConfiguration.RegisterActivatedClientType( typeof(CAOCarGeneralAsm.CarProvider), "http://localhost:32469");
... }
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
If you were to now execute the updated This comprehensive textserver starts and with client a briefassemblies, overview of you the would be pleased to find that you are language and quickly moves to key technical and able to pass yourC# custom array of then JamesBondCar types to the remote CarProvider via the overloaded architectural issues for .NET developers. constructor. SOURCE
The CAOCarGeneralAsm, CAOCarProviderServer, and CAOCarProviderClient projects are
Table CODE of Contents located under the Chapter 12 subdirectory. C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and theLifetime .NET Platform, Second Edition The Lease-Based of CAO/WKO-Singleton Objects by Andrew Troelsen
ISBN:1590590554
As you have seen, WKO©types configured Apress 2003 (1200 pages) with single-call activation are only alive for the duration of the current method call. Given this fact, WKO single-call stateless entities. This comprehensive text startstypes with are a brief overview of the As soon as the current invocation has completed, the WKO single-call type is a candidate for garbage collection. C# language and then quickly moves to key technical and architectural issues for .NET developers.
On the other hand, CAO types and WKO types which have been configured to use singleton activation are both, by their nature, stateful entities. Given these two object configuration settings, the question which must be asked Table is: How of Contents does the server process know when to destroy these MBR objects? Clearly, it would be a huge bother if theand server machine garbage collected C# the .NET Platform, Second Edition MBR objects that were currently in use by a remote client. If the server machine waits too long to release its set of MBR types, this may place undo stress on the system, especially if the Introduction MBR object(s) in question maintain valuable system resources (database connections, unmanaged types, and Part One - Introducing C# and the .NET Platform whatnot). Chapter 1 - The Philosophy of .NET Chapter 2
- Building C# Applications
Unlike classic DCOM, the .NET Remoting layer obviously does not make use of an interface-based reference counting mechanism (or occasional pings) to control object lifetime. Rather, the lifetime of a CAO or WKOChapter 3 - C# Language Fundamentals singleton MBR type is governed by a lease time that is tightly integrated with the .NET garbage collector. If the Chapter 4 - Object-Oriented Programming with C# lease time of a CAO or WKO-singleton MBR type expires, the object is ready to be garbage collected on the next Chapter 5 cycle. - Exceptions and.NET Object Lifetime collection Like any type, if the remote object has overridden System.Object.Finalize() (via the C# Chapter 6 Interfaces and Collections destructor syntax), the .NET runtime will indeed trigger the finalization logic. Part Two - The C# Programming Language
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques The Default Leasing Behavior
Part Three - Programming with .NET Assemblies
Chapter 9 WKO-singleton - Understanding MBR .NET Assemblies CAO and types have what is known as a default lease, which lasts for 5 minutes. If the Chapter 10 Processes, AppDomains, Contexts, and Threads runtime detects 5 minutes of inactivity have passed for a CAO or WKO-singleton MBR type, the assumption is Chapter - Type Reflection, Late Binding, Attribute-Based Programming that the11 client is no longer making use of and the entity (or perhaps is no longer running), and therefore the remote Part Four - Leveraging thecollected. .NET Libraries object may be garbage Of course,
this does not imply that a given CAO or WKO-singleton object is
Chapter 12 - Object Serialization andcollection the .NET Remoting Layer The truth of the matter is that there are many ways automatically marked for garbage after 5 minutes! Chapter 13 Building a Better Window (Introducing Windows Forms) to alter the timing of the default lease. Chapter 14 - A Better Painting Framework (GDI+)
First and anytime theWindows remote Forms client invokes Chapter 15foremost, - Programming with Controlsa member of the remote CAO or WKO-singleton MBR type, the lease is renewed back to its 5 minute limit. In addition to the automatic client-invocation-centric renew policy, the .NET runtime provides three additional alternatives:
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services *.config files can be authored that override the
default lease settings for a given remote object.
Chapter 18 - ASP.NET Web Pages and Web Controls
Server-side leaseWeb sponsors can be used to act on behalf of a remote object whose lease time has expired. Chapter 19 - ASP.NET Applications Chapter 20 - XML Web Services Index
Client-side lease sponsors can be used to act on behalf of a remote object whose lease time has expired.
List Figures Weofwill check out these options over the next several sections, but for the time being let's come to understand List of Tables the default lease settings of a remote type. Recall that the MarshalByRefObject base class defines a member
named GetLifetimeService(). This method returns a reference to an internally implemented object that supports the System.Runtime.Remoting.Lifetime.ILease interface. As you would guess, the ILease interface can be used to interact with the leasing behavior of a given CAO or WKO-singleton type. Here is the formal definition: public interface ILease { TimeSpan CurrentLeaseTime { get; } LeaseState CurrentState { get; } TimeSpan InitialLeaseTime { get; set; } TimeSpan RenewOnCallTime { get; set; } TimeSpan SponsorshipTimeout { get; set; } void Register(System.Runtime.Remoting.Lifetime.ISponsor obj); void Register(System.Runtime.Remoting.Lifetime.ISponsor obj, TimeSpan renewalTime); TimeSpan Renew(TimeSpan renewalTime);
void Unregister(System.Runtime.Remoting.Lifetime.ISponsor obj); C# and the .NET Platform, Second Edition
}
by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
The ILease interface only allows text you starts to obtain regarding This not comprehensive withinformation a brief overview of thethe current lease (via C# CurrentState, language and then quickly moves to key and the ability to build lease sponsors CurrentLeaseTime, and InitialLeaseTime) buttechnical also provides architectural issues for (more later). Table 12-9 documents the.NET roledevelopers. of each ILease member. Table 12-9: Members of the ILease Interface
Table of Contents
C#Member and the .NET of Platform, Second Meaning Editionin Life
Ilease Introduction Part One - Introducing C# and the .NET Platform
CurrentLeaseTime
Gets the amount of time remaining before the object deactivates if it does not receive further method invocations.
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming CurrentState GetsLanguage the current
state of the lease, represented by the LeaseState
Chapter 3
- C# Language Fundamentals enumeration.
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 7
- Callback Interfaces, Delegates, and Events
InitialLeaseTime
Gets or sets the initial amount of time for a given lease. The initial lease time of an object is the amount of time following the initial activation before the lease Chapter 6 - Interfaces and Collections expires if no other method calls occur. RenewOnCallTime GetsConstruction or sets the amount of time by which a call to the remote object increases Chapter 8 - Advanced C# Type Techniques the CurrentLeaseTime. Part Three - Programming with .NET Assemblies Chapter 9 - Understanding .NET SponsorshipTimeout Gets Assemblies or sets the amount of time to wait for a sponsor to return with a lease Chapter 10 - Processes, AppDomains, Contexts, and Threads renewal time. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Register() Overloaded. Part Four - Leveraging the .NET Libraries
Registers a sponsor for the lease.
Chapter 12 - Object Serialization and the .NETfor Remoting Layer time. Renew() Renews a lease the specified Chapter 13 - Building a Better Window (Introducing Windows Forms)
Unregister() Removes a sponsor Chapter 14 - A Better Painting Framework (GDI+) from the sponsor list. Chapter 15 - Programming with Windows Forms Controls
To illustrate the characteristics of the default lease of a CAO or WKO-singleton remote object, assume that our current CAOCarGeneralAsm project has defined a new type named LeaseInfo. LeaseInfo supports a static Chapter 17 - Data Access with ADO.NET member named LeaseStats() which dumps select statistics regarding the current lease for the CarProvider type Part Five - Web Applications and XML Web Services to the server side console window (be sure to specify a "using" directive for the Chapter 18 - ASP.NET Web Pages and Web Controls System.Runtime.Remoting.Lifetime namespace to inform the compiler where the ILease type is defined): Chapter 16 - The System.IO Namespace
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
internal class LeaseInfo { List of Figures public static void LeaseStats(ILease itfLease) List of Tables { Console.WriteLine("***** Lease Stats *****"); Console.WriteLine("Lease state: {0}", itfLease.CurrentState); Console.WriteLine("Initial lease time: {0}:{1}", itfLease.InitialLeaseTime.Minutes, itfLease.InitialLeaseTime.Seconds); Console.WriteLine("Current lease time: {0}:{1}", itfLease.CurrentLeaseTime.Minutes, itfLease.CurrentLeaseTime.Seconds); Console.WriteLine("Renew on call time: {0}:{1}", itfLease.RenewOnCallTime.Minutes, itfLease.RenewOnCallTime.Seconds); Console.WriteLine(); } } Index
Now that we haveC# this helper type in place, assume is called within the GetJBCByIndex() and the .NET Platform, SecondLeaseInfo.LeaseStats() Edition and GetAllAutos()bymethods of the CarProvider type. Once we recompile the ISBN:1590590554 server and client assemblies (again, Andrew Troelsen simply to ensure Apress VS .NET copies the latest and greatest version of the CarGeneralAsm.dll to the client and © 2003 (1200 pages) server applicationThis directories), run the application once again. Your server's console window will now look comprehensive text starts with a brief overview of the something like soC# (Figure 12-14). language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Figure 12-14: The default lease information for CarProvider
Part Three - Programming with .NET Assemblies
Chapter Understanding Assemblies As you 9can- see, by default,.NET a type's initial lease time is 5 minutes. If and when a method invocation is made on Chapter 10 -after Processes, AppDomains, Contexts, and Threads the object its activation, the RenewOnCallTime property represents the minimum value the Chapter 11 - Type Reflection, Late Binding, Attribute-Based Programming CurrentLeaseTime is incremented by, upand to the InitialLeaseTime. Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Altering the Default Lease Characteristics
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 -the A Better Framework (GDI+) Obviously defaultPainting lease characteristics of a CAO/ WKO-singleton type may not be appropriate for each and Chapter 15 - or Programming with remote Windowsobject. Forms IfControls every CAO WKO-singleton you wish to alter these default settings, you have two approaches: Chapter 16 - The System.IO Namespace
As17 you- would guess,with youADO.NET are able to adjust the default lease settings using a *.config file. Chapter Data Access Part Five - Web Applications and XML Web Services
You are also able to programmatically alter the settings of a type's default lease by overriding members of the MarshalByRefObject base class.
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Chapter While each 20 - of XML these Weboptions Serviceswill indeed alter the default lease settings, there is a key difference. When you make
use of a server side *.config file, the lease settings affect all objects hosted by the server process! In contrast, Index when you override select members of the MarshalByRefObject type, you are able to change lease settings on an List of Figures object-by-object basis. List of Tables To illustrate changing the default lease settings via a remoting *.config file, assume you have updated the serverside XML data with the following additional element:
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Notice how the leaseTime and renewOnCallTime have been This comprehensive text starts withproperties a brief overview of themarked with the M suffix, which you C# for language and then quickly moves to key technical and might guess stands the number of minutes to set for each lease-centric unit of time. If you wish, your architectural issuesthe fornumerical .NET developers. element may also suffix values with MS (milliseconds), S (seconds), H (hours), or even D (days). Figure 12-15 shows the result of the updated *.config file: Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Figure Altering.NET leaseAssemblies timing via a server-side *.config file Chapter 9 - 12-15: Understanding Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - that Typewhen Reflection, Late Binding, and Attribute-Based Now recall you update the server's *.config file youProgramming have effectively changed the leasing characteristics Part Four -CAO/WKO-singleton Leveraging the .NET Libraries for each object hosted
by the server. As an alternative, you may choose to
Chapter 12 - Object override Serialization and the .NET Remoting Layer programmatically the InitializeLifetime() method in a specific remote type. Thus, assume you have not Chapter 13 Building a Better Window (Introducing Windows Forms) updated the server's configuration file, but rather updated the CarProviderType as follows: Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 class - Programming with Windows Forms Controls public CarProvider : MarshalByRefObject Chapter 16 - The System.IO Namespace { Chapter public 17 - Data override Access with ADO.NET object InitializeLifetimeService() Part Five{- Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages Web Controls // Obtain theand current lease info. Chapter 19 - ASP.NET Web Applications ILease itfLeaseInfo = Chapter 20 - XML Web(ILease) Services base.InitializeLifetimeService();
// Adjust settings.
Index
List of Figures itfLeaseInfo.InitialLeaseTime = TimeSpan.FromMinutes(50); List of Tables
itfLeaseInfo.RenewOnCallTime = TimeSpan.FromMinutes(10); return itfLeaseInfo;
} ... }
Here, the CarProvider has altered its InitialLeaseTime value to 50 minutes and its RenewOnCallTime value to 10. Again, the benefit of overriding InitializeLifetimeServices() is the fact that you can configure each remote type individually. Finally, on an odd note, if you wish to disable lease-based lifetime for a given CAO/WKO-singleton object type, you may override InitializeLifetimeServices() and simply return null. If you do so, you have basically configured an MBR type that will never die as long as the hosting server application is alive and kicking.
Server-Side Lease Adjustment As you have just seen, when an MBR type overrides InitializeLifetimeServices(), it is able to change its default
leasing behavior at the time of activation. However, for the sake of argument, what if a remote type desires to C# and the .NET Platform, Second Edition change its current lease after its activation cycle? For example, assume the CarProvider has a new method ISBN:1590590554 by Andrew Troelsen whose implementation requires a lengthy operation (such as connecting to a remote database and reading a Apress © 2003 (1200 pages) large set of records). Before beginning the task, you may programmatically adjust your lease such that if you comprehensive textlease startstime withto a brief overviewTo ofdo theso, you can make use of the inherited have less than 1 This minute, you renew the 10 minutes. C# language and then quickly moves to key technical and MarshalByRefObject.GetLifetimeService() and ILease.Renew() methods as follows: architectural issues for .NET developers.
// Server-side lease adjustment. // Assume this new method of the CarProvider type. Table of Contents public void DoLengthyOperation() C# and the .NET Platform, Second Edition { Introduction itfLeaseInfo = (ILease)this.GetLifetimeService(); Part OneILease - Introducing C# and the .NET Platform if(itfLeaseInfo.CurrentLeaseTime.TotalMinutes < 1.0) Chapter 1 - The Philosophy of .NET itfLeaseInfo.Renew(TimeSpan.FromMinutes(10)); Chapter 2 - Building C# Applications DoC# task... Part Two// - The Programming Language } Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Client-Side Lease Adjustment - Interfaces and Collections
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
On an additional ILease-related note, it is possible for the client's application domain to adjust the current lease Chapter 8 - Advanced C# Type Construction Techniques properties for a CAO/WKO-singleton type it is communicating with across the wire. To do so, the client makes Part Three - Programming with .NET Assemblies use of the static RemotingServices.GetLifetimeService() method. As a parameter to this member, the client Chapter 9 - Understanding .NET Assemblies passes in the reference to the remote type as follows: Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Four Client-side Part - Leveraging lease the .NETadjustment. Libraries CarProvider cp = new CarProvider(cars); ILease itfLeaseInfo = (ILease)RemotingServices.GetLifetimeService(cp); Chapter 13 - Building a Better Window (Introducing Windows Forms) if(itfLeaseInfo.CurrentLeaseTime.TotalMinutes < 10.0) Chapter 14 - A Better Painting Framework (GDI+) itfLeaseInfo.Renew(TimeSpan.FromMinutes(1000)); Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET This approach can be helpful if the client's application domain is about to enter a lengthy process on the same Part Fiveof- Web Applications and XML Services thread execution that is using the Web remote type.
For example, if a single threaded application is about to print out
Chapter 18 - ASP.NET Web and Web Controls a 100-page document, thePages chances are quite good that a remote CAO/WKO-singleton type may time out during Chapter the process. 19 - ASP.NET The other Web (more Applications elegant) solution, of course, is to spawn a secondary thread of execution, but I think
you get20 the- general Chapter XML Webidea. Services Index List of Figures List of Tables
and the .NET Platform, Second Server-SideC#(and Client-Side) LeaseEdition Sponsorship by Andrew Troelsen
ISBN:1590590554
The final topic regarding Apress ©the 2003lease-based (1200 pages) lifetime of a CAO/WKO-singleton object type considered here is the notion of lease sponsorship. As you seen, every CAO/WKO-singleton entity has a default This comprehensive texthave startsjust with a brief overview of the lease, which mayC# belanguage altered inand a number of ways on both the server side as well as the client side. Now, then quickly moves to key technical and for .NET eventually developers.an MBR object times will be up. At this point, the regardless of thearchitectural type's leaseissues configuration, runtime will garbage-collect the entity...well almost. Table The of truth Contents of the matter is that before an expired type is truly marked for garbage collection, the runtime will
check to see if the MBR object question has any registered lease sponsors. Simply put, a sponsor is a C# and the .NET Platform, SecondinEdition type that implements the ISponsor interface, which is defined as follows: Introduction Part One - Introducing C# and the .NET Platform
Chapter 1 interface - The Philosophy of .NET public System.Runtime.Remoting.Lifetime.ISponsor Chapter { 2 - Building C# Applications Part TwoTimeSpan - The C# Programming Renewal(ILease Languagelease);
} Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
If the runtime detects that an MBR object has a sponsor, it will not garbage-collect the type, but rather call - Interfaces and Collections the Renewal() method of the sponsor object to (once again) add time to the current lease. On the other Chapter 7 - Callback Interfaces, Delegates, and Events hand, if the MBR has no sponsor, the object's time is truly up. Chapter 6 Chapter 8
- Advanced C# Type Construction Techniques
Part Three - that Programming with .NET Assuming you have created a Assemblies custom class
that implements ISponsor, and thus implements
Chapter 9 -to Understanding .NETunit Assemblies Renewal() return a specific of time (via the TimeSpan type), the next question is how exactly to Chapter 10 the - Processes, and Threads associate type to a AppDomains, given remoteContexts, object. Again, this operation may be performed by either the server's Chapter application 11 - domain Type Reflection, or the client's Late Binding, application and domain. Attribute-Based Programming Part Four - Leveraging the .NET Libraries
To do so, interested party obtains ILease reference Chapter 12 the - Object Serialization and thean .NET Remoting Layer(via the inherited GetLifetimeService() method on the server or using the static RemotingServices.GetLifetimeService() method on the client) and calls Register():
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
// Server-side sponsor registration. Chapter 16 - The System.IO Namespace CarSponsor mySponsor = new CarSponsor(); ILease itfLeaseInfo = (ILease)this.GetLifetimeService(); Part Five - Web Applications and XML Web Services itfLeaseInfo.Register(mySponsor); Chapter 17 - Data Access with ADO.NET
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
// Client-side sponsor registration. CarSponsor mySponsor = new CarSponsor(); Index CarProvider cp = new CarProvider(cars); List of Figures ILease itfLeaseInfo = (ILease)RemotingServices.GetLifetimeService(cp); List of Tables itfLeaseInfo.Register(mySponsor); Chapter 20 - XML Web Services
In either case, if a client or server wishes to revoke sponsorship, it may do so using the ILease.Unregister() method. For example: // Remove the sponsor for a given object. itfLeaseInfo.Unregister(mySponsor);
Note Client-side sponsored objects, in addition to implementing ISponsor must also derive from MarshalByRefObject, given that the client must pass the sponsor to the remote application domain! So, as you can see, the lifetime management of stateful MBR types is quite different from classic DCOM.
On the plus side, you have a ton of control regarding when a remote type is destined to meet its maker. Platform, Second Edition However, as you C# mayand be the able.NET to gather, there is the chance that a remote type may be removed from by Andrew Troelsen memory without the client's knowledge. Should a client attemptISBN:1590590554 to invoke members on a type that has Apressfrom © 2003memory (1200 pages) already been removed the runtime will throw a This comprehensive text starts with a briefpoint overview of themay simply create a brand-new System.Runtime.Remoting.RemotingException, at which the client C# language and then quickly moves to key technical and instance of the remote type or simply take an alternative course of action. architectural issues for .NET developers.
SOURCE CODE
Table of Contents
The CAOCarGeneralAsmLease, CAOCarProviderServerLease, and CAOCarProviderClientLease projects are located under the Chapter 12 subdirectory.
C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and thefor .NET Platform, Second Edition Alternative C# Hosts Remote Objects by Andrew Troelsen
ISBN:1590590554
Over the course of this chapter, youpages) have constructed numerous console-based server hosts, which provide Apress © 2003 (1200 access to some set of remote objects. If you have in classic This comprehensive text starts withaabackground brief overview of the DCOM, this step may have seemed a bit odd. Under the world of DCOM, it was not unusual to build C# language and then quickly moves to key technical and a single server-side COM server issues for was .NETalso developers. that contained thearchitectural remote objects and in charge of receiving incoming ORCP requests from some remote client. This single *.exe DCOM application would quietly load in the background without presenting a looming command window. Table of Contents
When you.NET are building .NET server C# and the Platform,a Second Editionassembly, the chances are quite good that the remote machine does not need to display any sort of UI. Rather, all you really wish to do is build a server-side entity that opens the Introduction correct and the remote object(s) Part One channel(s) - Introducing C#registers and the .NET Platform
for client-side access. Moreover, when you build a
simple 1console you (or is required to manually run the server-side *.exe assembly, due to Chapter - The host, Philosophy of someone) .NET the fact2that the .NET Remoting will not automatically run a server-side *.exe when called by a remote Chapter - Building C# Applications client. two issues, Language the question Part TwoGiven - Thethese C# Programming
then becomes: How can you build an invisible listener that loads
automatically one wayFundamentals or another)? Chapter 3 - C#(in Language Chapter 4
- Object-Oriented Programming with C# Unlike classic DCOM, you are unable to simply pass your command windows a command line parameter
Chapter 5 - Exceptions andtoObject Lifetime that instructs the process appear invisibly in the background. Rather, .NET programmers have two major Chapter 6 Interfaces and Collections choices at their disposal, when they wish to build a transparent host for various remote objects: Chapter 7
- Callback Interfaces, Delegates, and Events
Build Windows Service application to host the remote objects Chapter 8 a - .NET Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Allow IIS to host your remote objects
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Hosting Remote Objects Using a Windows Service
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Perhaps the ideal host for remote objects is a Windows service, given that it (a) can be configured to load automatically on system start-up, (b) runs as an invisible background process, and (c) can be run under Chapter 13 - Building a Better Window (Introducing Windows Forms) discrete user accounts. As you would expect, building a custom Windows Service using the .NET platform Chapter 14 - A Better Painting Framework (GDI+) is extremely simple when contrasted to the raw Win32 API. To illustrate, let's create a Windows Service Chapter 15 - Programming with Windows Forms Controls project (named CarWinService) that will be in charge of hosting the remote types contained within the Chapter 16 - The System.IO Namespace CarGeneralAsm.dll. To begin, create a new Windows Service project workspace (Figure 12-16). Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 12-16: Creating a new Windows Service project workspace As you can see, VS .NET responds by generating a new class (named Service1 by default) which derives from System.ServiceProcess.ServiceBase. Given that Service1 is a rather nondescript name for your custom service, your first order of business is to change the values of the (Name) and ServiceName properties to CarService using the IDE's Properties window. The distinction between these two settings is that the (Name) value is used to define the name used to refer to our type in the code base, while the ServiceName property marks the name to display to Windows Service-centric configuration tools (such as
MMC, seen shortly).
C# and the .NET Platform, Second Edition
ISBN:1590590554 by Andrew Troelsen The generated class type defines three methods of interest, two of which (OnStart() and OnStop()) are Apress © 2003 (1200 pages) base class overrides:
This comprehensive text starts with a brief overview of the
Main(): This method is theand entry point of the Windows process. C# language then quickly moves to keyService technical and architectural issues for .NET developers.
OnStart(): This method is called each time the service is started. OnStop(): This method is called when the service is stopped. Table of Contents C# and the .NET Platform, Second Edition
First, let's take a peek at the Main() method. Before you do, be sure you set a reference to the
Introduction CarProviderAsm.dll and System.Remoting.dll assemblies, and specify the following additional "using" Part One - Introducing C# and the .NET Platform
directives:
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
using System.Runtime.Remoting; using System.Runtime.Remoting.Channels.Http; Chapter 3 - C# Language Fundamentals using System.Runtime.Remoting.Channels; Part Two - The C# Programming Language
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Implementing Main() Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
The Main() method of a ServiceBase-derived type is in charge of running each service defined in the project
Chapter 9 - an Understanding .NET Assemblies by passing array of ServiceBase types into the static Service.Run() method. Given that you have Chapter 10 Processes, AppDomains, Contexts, to and Threads be sure to update the autogenerated array: renamed your custom service from Service1 CarService, Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
static void Main() { Chapter System.ServiceProcess.ServiceBase[] 13 - Building a Better Window (Introducing WindowsServicesToRun; Forms) Chapter ServicesToRun 14 - A Better Painting (GDI+) = Framework new System.ServiceProcess.ServiceBase[] Chapter 15 - Programming with Windows Forms { new CarService() }; Controls Chapter System.ServiceProcess.ServiceBase.Run(ServicesToRun); 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET } Chapter 12 - Object Serialization and the .NET Remoting Layer
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Implementing OnStart()
Chapter 20 - XML Web Services
Index I would guess you can already assume what sort of logic should happen when your custom service is List of Figures started on a given machine. Recall that the role of CarService is to perform the same tasks as your custom List console-based of Tables service. Thus, if you wish to register CarService as a WKO singleton type which is available
via HTTP, you could add the following code to the OnStart() method (as you would hope, you may make use of the RemotingConfiguration type to load up a server side remoting *.config file, rather than hardcoding your implementation, when hosting remote objects using a Windows Service). using System.Diagnostics; // For the EventLog type. ... protected override void OnStart(string[] args) { // Create a new HttpChannel HttpChannel c = new HttpChannel(32469); ChannelServices.RegisterChannel(c); // Register as single call WKO. RemotingConfiguration.RegisterWellKnownServiceType( typeof(CarGeneralAsm.CarProvider), "CarProvider.soap",
WellKnownObjectMode.SingleCall); C# and the .NET Platform, Second Edition // Log our successful start-up. ISBN:1590590554 by Andrew Troelsen EventLog.WriteEntry("CarGeneralAsm", Apress © 2003 (1200 pages) "CarWinService started successful!", This comprehensive text starts with a brief overview of the EventLogEntryType.Information); C# language and then quickly moves to key technical and architectural issues for .NET developers.
}
Note that once the type has been registered, log a custom message to the Windows event log (via the System.Diagnostics.EventLog type) that informs the host machine of our successful start-up.
Table of Contents
C# and the .NET Platform, Second Edition Introduction
Implementing OnStop()
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Technically speaking, our CarService does not demand any sort of shutdown logic. For illustrative purposes - Building C# Applications let's post another event to the EventLog to log the termination of your custom Windows Service:
Chapter 2
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
protected override void OnStop() - Object-Oriented Programming with C# { Chapter 5 - Exceptions and Object Lifetime EventLog.WriteEntry("CarGeneralAsm", Chapter 6 - Interfaces and Collections "CarWinService stopped", Chapter 7 - Callback Interfaces, Delegates, and Events EventLogEntryType.Information); Chapter 8 - Advanced C# Type Construction Techniques } Chapter 4
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter As you 10 would - Processes, guess, you AppDomains, may choose Contexts, to makeand useThreads of the TcpChannel type as opposed to the HttpChannel,
post the11CarProvider MBR type a CAOand object (rather thanProgramming WKO), and so forth. Now that the service is Chapter - Type Reflection, Lateas Binding, Attribute-Based complete, the next task to install this Part Four - Leveraging theis.NET Libraries
service on the remote machine.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Adding a Service Installer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Before 15 you- can install your service on aForms given Controls machine, you need to add an additional type into your current Chapter Programming with Windows CarWinService Specifically speaking, any Windows service (written using .NET or the raw Win32 Chapter 16 - The project. System.IO Namespace API) requires a number registry entries to be made to allow the OS to interact with the service itself. Chapter 17 - Data Access of with ADO.NET Rather requiring us to and make these manually, Part Fivethan - Web Applications XML Webentries Services
you can simply add an Installer type to a Windows
Service18 project, which willPages configure yourControls ServiceBase-derived type correctly when installed onto the target Chapter - ASP.NET Web and Web machine. add an installer for the CarService, open the design-time service editor (by double-clicking the Chapter 19 To - ASP.NET Web Applications CarService.cs file from the Solutions Explorer), and click the Add Installer link that now appears on the bottom of the Properties window (Figure 12-17).
Chapter 20 - XML Web Services Index
List of Figures List of Tables
Figure 12-17: Including an installer for the custom Windows Service C# and the .NET Platform, Second Edition
Andrew This selection willbyadd a newTroelsen component that derives from the ISBN:1590590554 System.Configuration.Install.Installer base © 2003 (1200ways pages)to configure your installer (both programmatically and declaratively), class. While thereApress are numerous the default settings This are comprehensive all you need to text install startsyour withCarWinService.exe a brief overview of the on a given machine. Now, compile C# language and then quickly moves to key technical and your project. architectural issues for .NET developers.
Installing the CarService Table of Contents
Toand install on a given machine (local or remote) requires two steps: C# the CarService.exe .NET Platform, Second Edition 1. Move the compiled service assembly (and any necessary external assemblies) to the remote Introduction (obviously). Part Onemachine - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
2. Run the Installutil.exe command line tool, specifying your service as an argument.
Part Two - The Programming Language Assuming stepC#one is complete, open a command
window, navigate to the location of the
Chapter 3 - C# Language Fundamentals CarWinService.exe assembly, and issue the following command: Chapter 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime Installutil carwinservice.exe
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter Once this 8 Windows - Advanced Service C# Type has Construction been properly Techniques installed, you are now able to start and configure it using the Part Services Three applet, - Programming located under with .NET the Assemblies Administrative
Tools folder of your system's Control Panel. Once you
have located your CarService 12-18), click the Start link to load and run the binary. Chapter 9 - Understanding .NET(Figure Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List ofFigure Figures12-18: The Windows Services Applet List of Tables
Once the service is started, you are able to run your client application as before. Now that you have seen how to host your remote objects using a custom Windows Service, let's see how to host remote types using IIS. SOURCE CODE
The CarWinService project is located under the Chapter 12 subdirectory.
Hosting Remote Objects Using IIS Hosting a remote assembly under the care of IIS is even simpler than building a Windows Service, given that IIS is already preprogrammed to allow incoming HTTP requests via port 80. Now, given the fact that IIS is a Web server, it should stand to reason that IIS is only able to host remote objects using the HttpChannel type (unlike a Windows Service that can also leverage the TcpChannel type). Assuming this is not perceived as a limitation, follow the steps below to leverage the remoting support of IIS: 1. On your hard drive, create a new folder to hold your CarGeneralAsm.dll. Within this folder, create a
1. subdirectory named \Bin. Now, copy the CarGeneralAsm.dll to this subdirectory (for example: C# and the .NET Platform, Second Edition C:\IISHostCarService\Bin). Do be aware that you are also able to install your general assembly into bythe Andrew Troelsen the GAC of web-server machine as an alternative toISBN:1590590554 placing a copy under the \Bin folder. Apress © 2003 (1200 pages)
2. Open the Internet Informationtext Services the host machine This comprehensive starts applet with a on brief overview of the (located under the Administrative C#under language then quickly moves to key technical and Tools folder yourand system's Control Panel). architectural issues for .NET developers.
3. Right-click the "Default Web Site" node and select "New | Virtual Directory". a virtual directory that maps to the root folder you just created (C:\IISCarService). The Table4.of Create Contents remaining default Second settingsEdition presented by the New Virtual Directory Wizard are fine. C# and the .NET Platform, Introduction
5. Finally, create a new configuration file named "web.config" (and only web.config) to control how this virtual directory should register the remote type (see the following). Make sure this file is saved under Chapter 1 - The Philosophy of .NET the root folder (in this example, C:\IISCarService). Part One - Introducing C# and the .NET Platform
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
- C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections Part Three - Programming with .NET Assemblies Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 3
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Now that your CarGeneralAsm.dll has been configured to be reachable via HTTP requests under IIS, you can update your client-side *config file as follows (using the name of your IIS host, of course):
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Index Chapter 20 - XML Web Services
Cool! At this point, you are able to run your client application as before.
C# andRemoting the .NET Platform, Second Edition Asynchronous by Andrew Troelsen
ISBN:1590590554
Next, let's examine how ©to2003 invoke of a remote type asynchronously. In Chapter 7 you were first Apress (1200members pages) introduced to the This topiccomprehensive of asynchronous method invocations, given the support provided by the text starts with a brief overview of the System.MulticastDelagete type. As you would expect, if a client assembly C# language and then quickly moves to key technical and wishes to call a remote object architectural for .NET developers. asynchronously, the first step issues is to define a custom delegate to represent the remote method in question. At this point, the caller can make use of any of the techniques seen in Chapter 7 to invoke and receive the method return value. Table of Contents
Byand waythe of .NET a simple illustration, C# Platform, Secondcreate Editiona new console application (AsyncWKOCarProviderClient) and set a reference to the first iteration of the CarGeneralAsm.dll assembly. Now, update the Main() method to look Introduction like One this:- Introducing C# and the .NET Platform Part Chapter 1
- The Philosophy of .NET
Chapter class2 AsyncCarClient - Building C# Applications Part { Two - The C# Programming Language
delegate for the GetAllAutos() method. Chapter // 3 -The C# Language Fundamentals delegate ArrayList Chapter internal 4 - Object-Oriented Programming with GetAllAutosDelegate(); C# void and Main(string[] Chapter static 5 - Exceptions Object Lifetime args) Chapter { 6
- Interfaces and Collections
Chapter 7
Console.WriteLine("Client started! Hit enter to end"); - Callback Interfaces, Delegates, and Events
RemotingConfiguration.Configure ("AsyncWKOCarProviderClient.exe.config"); Part Three - Programming with .NET Assemblies // Make the car provider. Chapter 9 - Understanding .NET Assemblies CarProvider cp = new CarProvider(); Chapter 10 - Processes, AppDomains, Contexts, and Threads // Make the delegate. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming GetAllAutosDelegate getCarsDel = Part Four - Leveraging the .NET Libraries new GetAllAutosDelegate(cp.GetAllAutos); Chapter 12 - Object Serialization and the .NET Remoting Layer // Call GetAllAutos() asynchronously. Chapter 13 - Building a Better Window Windows Forms) IAsyncResult ar =(Introducing getCarsDel.BeginInvoke(null, null); Chapter 14 - A // Better Painting Framework Simulate client (GDI+) side activity. Chapter 15 - Programming with Windows Forms Controls while(!ar.IsCompleted) Chapter 16 - The Namespace { System.IO Console.WriteLine("Client working..."); } Chapter 17 - Data with ADO.NET // Access All done! Get return value from delegate. Part Five - WebArrayList Applications and XML Web allJBCs = Services getCarsDel.EndInvoke(ar); Chapter 18 - ASP.NET // Use Web all Pages cars and in WebArrayList. Controls foreach(JamesBondCar j in allJBCs) Chapter 19 - ASP.NET Web Applications UseCar(j); Chapter 20 - XML Web Services Console.ReadLine(); Index } List of Figures } of Tables List Chapter 8
- Advanced C# Type Construction Techniques
Notice how the client application first declares a delegate that matches the signature of the GetAllAutos() method of the remote CarProvider type. When the delegate is created, you pass in the name of the method to call (GetAllAutos), as always. Next, you trigger the BeginInvoke() method, cache the resulting IAsyncResult interface, and simulate some work on the client side (recall that the IAsyncResult.IsCompleted property allows you to monitor if the associated method has completed processing). Finally, once the client's work has completed, you obtain the ArrayList returned from the CarProvider.GetAllAutos() method by invoking the EndInvoke() member, and pass each JamesBondCar into a static helper function named UseCar(): public static void UseCar(JamesBondCar j) { Console.WriteLine("Can car fly? {0}", j.isFlightWorthy); Console.WriteLine("Can car swim? {0}", j.isSeaWorthy);
} C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
2003 (1200 pages)type is the fact that the logic used to invoke remote methods Again, the beautyApress of the ©.NET delegate asynchronously isThis identical to the process of local invocations. comprehensive text starts withmethod a brief overview of the
SOURCE CODE
C# language and then quickly moves to key technical and architectural issues for .NET developers.project is located under the Chapter 12 The AsyncWKOCarProviderClient
subdirectory.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and[OneWayAttribute] the .NET Platform, Second Edition The Role ofC#the Type by Andrew Troelsen
ISBN:1590590554
To wrap things up, let's © consider a pages) .NET attribute that allows the remote client to automatically invoke a Apress 2003 (1200 method asynchronously, without requiring the use delegates. Imagine that your CarProvider has This comprehensive text starts withofa formal brief overview of the a new method named AddCar(), which takes a JamesBondCar input parameter and returns nothing. The C# language and then quickly moves to key technical and issues .NET developers. key point is that itarchitectural returns nothing. Asfor you might assume given the name of the System.Runtime.Remoting.Messaging.OneWayAttribute class, the .NET Remoting layer passes the call to the remote one-way method but does not bother to set up the infrastructure used to return a given value Table of Contents (hence, the name one-way). Here is the update: C# and the .NET Platform, Second Edition Introduction
// Home of the [OneWay] attribute. using System.Runtime.Remoting.Messaging; Chapter 1 - The Philosophy of .NET namespace CarGeneralAsm Chapter 2 Building C# Applications { Part Twopublic - The C# class Programming Language : MarshalByRefObject CarProvider Chapter { 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# private ArrayList theJBCars = new ArrayList(); Chapter ... 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces // Theand client Collections can 'fire and forget' when calling this method. [OneWay] Chapter 7 - Callback Interfaces, Delegates, and Events publicC#void newJBC) Chapter 8 - Advanced Type AddCar(JamesBondCar Construction Techniques { theJBCars.Add(newJBC);} Part Three - Programming with .NET Assemblies Chapter } 9 - Understanding .NET Assemblies } Chapter 10 - Processes, AppDomains, Contexts, and Threads Part One - Introducing C# and the .NET Platform
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Callers would invoke this method directly as always:
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
// Make the car provider. CarProvider cp = new CarProvider(); Chapter 15 - Programming with Windows Forms Controls // Add a new car. Chapter 16 - The System.IO Namespace cp.AddCar(new JamesBondCar("Zippy", 200, false, false)); Chapter 14 - A Better Painting Framework (GDI+)
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 client's - ASP.NET Web Pagesthe andcall Web From the point of view, toControls AddCar() is completely asynchronous, as the CLR will ensure Chapter 19 - ASP.NET Web Applications that a background thread is used to remotely trigger the method. Given that AddCar() has been decorated Chapter with the20[OneWay] - XML Web attribute, Servicesthe client is unable to obtain any return value from the call. Because AddCar()
returns void, this is not an issue. In addition to this restriction, also be aware that if you have a [OneWay] Index method that defines output or reference parameters (via the "out" or "ref" keyword), the caller will not be List of Figures able obtain the callee's modification(s). Furthermore, if the [OneWay] method happens to throw an List of to Tables exception (of any type), the caller is completely oblivious to this fact. In a nutshell, remote objects can mark select methods as [OneWay] to allow the caller to employ a fire-and-forget mentality.
C# and the .NET Platform, Second Edition Final Thoughts... by Andrew Troelsen
ISBN:1590590554
That wraps up our investigation of the .NET Remoting layer. I'd bet that you still have many questions Apress © 2003 (1200 pages) bouncing aroundThis at this point (which, sadly, I just don't have the physical comprehensive text starts with a brief overview of thespace to cover in this text). For example: C# language and then quickly moves to key technical and architectural issues for .NET developers.
How can I prevent the client-side assembly from referencing general assemblies containing CIL to protect proprietary code? Table of Contents
How message queuing (MSMQ) in a .NET application? C# and thecan .NETI incorporate Platform, Second Edition Introduction
How can I leverage component services (aka COM+ services) in a .NET application?
Part One - Introducing C# and the .NET Platform
Chapter 1 can - The Philosophy .NET How I augment (orofreplace) the default .NET Remoting layer? Chapter 2 - Building C# Applications
What about issues? Part Two - The C# security Programming Language Chapter 3
- C# Language Fundamentals
If you are interested in learning more about the .NET Remoting layer (and related topics such as MSMQ a - Object-Oriented Programming with C# la .NET), check out Distributed .NET Programming in C# (Barnaby, Apress 2002). If you are interested in Chapter 5 - Exceptions andofObject Lifetime learning the ins-and-outs building secure .NET applications (local, remote, or otherwise) pick up a copy Chapter 6 Interfaces and Collections of.NET Security (Bock et al., Apress 2002). And as a friendly reminder, if you need to dive deep into the Chapter - Callback Interfaces, Delegates, andcheck Eventsout Advanced .NET Remoting (Rammer, Apress topic of7bypassing the default remoting layer, Chapter 2002). 8 - Advanced C# Type Construction Techniques Chapter 4
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
In this chapter, you examined how pages) to configure distinct .NET assemblies to share types between Apress © 2003 (1200 application boundaries. As you have seen, a remote may be of configured as an MBV or MBR type. This comprehensive text starts with aobject brief overview the This choice ultimately controls how a remote type is realized in the client's application domain (a copy or C# language and then quickly moves to key technical and architectural for .NET transparent proxy). Given this issues distinction, the developers. chapter opened by examining the MBV-centric topic of object serialization. Table If youofhave Contents configured a type to function as an MBR entity, you are suddenly faced with a number of
related choices (WKO vs.Second CAO, Edition single call vs. singleton, and so forth), each of which was addressed C# and the .NET Platform, during this chapter. As well, you also examined the process of tracking the lifetime of a remote object via Introduction the One use -ofIntroducing leases andC# lease Finally, Part and sponsorship. the .NET Platform
you revisited the role of the .NET delegate type in order
to understand to asynchronously invoke a remote method (which, as luck would have it, is identical to Chapter 1 - Thehow Philosophy of .NET the process of asynchronously invoking a local type). Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Chapter C# 13: Building a Better Window (Introducing ISBN:1590590554 by Andrew Troelsen © 2003 (1200 pages) WindowsApress Forms) This comprehensive text starts with a brief overview of the C# language and thenchapters, quickly moves to key have technical and handle on the C# programming If you have read through the previous you should a solid architectural issues for .NET developers. language as well as the foundation of the .NET architecture. While you could take your newfound knowledge and begin building the next generation of console applications (boring! ) you are more likely to be interested in building an attractive graphical user interface (GUI) to allow the outside world to interact Table of Contents with your system. C# and the .NET Platform, Second Edition
Introduction This chapter introduces you to the System.Windows.Forms namespace. Here, you learn how to build a Part Onestylized - Introducing C# and(e.g., the .NET Platform highly main window a Form-derived
class). In the process, you learn about a number of
Chapter 1 - The types, Philosophy of .NET window-related including MenuItem, ToolBar, StatusBar, and Application. This chapter also Chapter 2 Building C# Applications introduces how to capture and respond to user input (i.e., handling mouse and keyboard events) within the Part Two of - The C# environment. Programming Along Language context a GUI the
way, you will construct a final example that illustrates the
Chapter construction 3 - C# of MDI Language applications Fundamentals a la Windows Forms. Chapter 4
- Object-Oriented Programming with C#
Object Lifetime A Tale -ofExceptions Threeand GUI Namespaces
Chapter 5 Chapter 6
- Interfaces and Collections The .NET of version 1.1) provides three GUI toolkits, known as "Windows Forms," "Web Chapter 7 -platform Callback(as Interfaces, Delegates, and Events
Forms,"8 and "Mobile Forms." System.Windows.Forms namespaces contain a number of types that Chapter - Advanced C# TypeThe Construction Techniques allow you -toProgramming build traditional applications, Part Three withdesktop .NET Assemblies
as well as Windows-based applications that target handled computing devices (such as the Pocket PC). As you would expect, Windows Forms hides the raw Chapter 9 - Understanding .NET Assemblies windowing primitives from view, allowing you to focus on Chapter 10 - Processes, AppDomains, Contexts, and Threadsthe functionality of your application using the familiar11 .NET typeReflection, system. Late Binding, and Attribute-Based Programming Chapter - Type Part Four - Leveraging the .NET Libraries
Web Forms, on the other hand, is a GUI toolkit used during ASP.NET development. The bulk of the Web Form types are contained in the System.Web.UI.WebControls namespace. Using these types, you are Chapter - Building a Better Windowfront (Introducing Windows Forms) able to 13 build browser-independent ends based on various industry standards (HTML, HTTP, and so Chapter 14 - will A Better Framework forth). You get toPainting know the ASP.NET(GDI+) Web controls in Chapter 18. Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 15 - Programming with Windows Forms Controls
Finally,16 .NET version 1.1 ships with a new GUI-centric namespace, System.Web.UI.MobileControls, which Chapter - The System.IO Namespace allow you buildAccess UIs that target mobile devices (such as cellular phones). Not surprisingly, the Chapter 17 to - Data with ADO.NET programming of Mobile applications Part Five - Web model Applications and control XML Web Services
mimics the functionality found within ASP.NET.
Chapter 18 - ASP.NET Web Pages and Web Controls
Note Coverage of mobile .NET technologies (including Pocket PC programming) is outside the scope of this text. If you are interested, check out Mobile .NET (Ferguson, Apress 2001).
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Index It is worth pointing out that while Windows Forms, Web Forms, and Mobile Forms technologies define a List number of Figures of similarly named types (e.g., Button, CheckBox, etc.) with similar members (Text, BackColor,
etc.), they do not share a common implementation and cannot be treated identically. Nevertheless, as you List of Tables become comfortable with the Windows Forms namespace, you should find the process of learning the details of other .NET GUI toolkits far more palatable.
and System.Windows.Forms the .NET Platform, Second Edition Namespace Overview ofC#the by Andrew Troelsen
ISBN:1590590554
Like any namespace, System.Windows.Forms is composed of a number of classes, structures, delegates, Apress © 2003 (1200 pages) interfaces, and enumerations. Over the next couple chapters, youofdrill This comprehensive text starts with aofbrief overview theinto the specifics of a good number of these C# types. While it is redundant to list every member of the language and then quickly moves to key technical and Windows Forms family (as they architectural issuesTable for .NET developers. are all documented in online Help) 13-1 lists some (but by no means all) of the core classes found within System.Windows.Forms. Table of 13-1: Contents Table A Subset of Types Within the System.Windows.Forms Namespace C# and the .NET Platform, Second Edition
Windows Forms Class Introduction
Meaning in Life
Part One - Introducing C# and the .NET Platform
Application
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
This class represents the guts of a Windows Forms application. Using the members of Application, you are able to process windows messages, start and terminate a Windows Forms application, and so forth.
Chapter 3
- C# Language Fundamentals ButtonBase, Button, CheckBox, These Chapter 4 - Object-Oriented Programming with C# classes (in addition to many others) represent
ComboBox, DataGrid,and GroupBox, Chapter 5 - Exceptions Object Lifetime ListBox, LinkLabel, PictureBox Chapter 6 - Interfaces and Collections Chapter Form 7 Chapter 8
types that correspond to various GUI widgets. You examine many of these items in detail in Chapter 15.
- Callback Interfaces, Delegates, and Events This type represents a main window, dialog box, or MDI - Advanced C# Type Construction Techniques child window of a Windows Forms application.
Part Three - Programming with .NET Assemblies
ColorDialog, OpenFileDialog, As you might expect, Windows Forms defines a - Understanding .NET Assemblies SaveFileDialog, FontDialog, number of canned dialog boxes. If these don't fit the Chapter 10 - Processes, AppDomains, Contexts, and Threads PrintPreviewDialog, bill, you are free to build your own custom dialogs. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming FolderBrowserDialog Chapter 9
Part Four - Leveraging the .NET Libraries
Menu,12MainMenu, MenuItem, and the .NET Remoting These types are used to build top most and contextChapter - Object Serialization Layer ContextMenu sensitive (pop-up) menu systems. Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Clipboard, Help, Timer, Screen,
Various utility types used to facilitate interactive GUIs.
Chapter 15 -Cursors Programming with Windows Forms Controls ToolTip, Chapter 16 - The System.IO Namespace
StatusBar, Splitter, ToolBar, ScrollBar Chapter 17 - Data Access with ADO.NET Part Five - Web Applications
Various types used to adorn a Form with common child controls. and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the the .NET Platform, Second Edition Interacting C# with Windows Forms Types by Andrew Troelsen
ISBN:1590590554
When you build aApress Windows Forms application, you may choose to write all the relevant code by hand © 2003 (1200 pages) (using Notepad perhaps) and send *.csa files the C#ofcompiler using the /target:winexe This comprehensivethe textresulting starts with briefinto overview the flag. Taking time C# to build some Windows Forms applications by hand is not only a great learning language and then quickly moves to key technical and architectural for .NETthe developers. experience, but also helps youissues understand code generated by various GUI wizards. Another option is to build Windows Forms projects using the Visual Studio .NET IDE. To be sure, the IDE Table doesofsupply Contents a number of great wizards, starter templates, and configuration tools that make working with
Windows extremely simple. The problem with wizards, of course, is that if you do not understand C# and the Forms .NET Platform, Second Edition what the generated code is doing on your behalf, you cannot gain a true mastery of the underlying Introduction technology. Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Given this fact, you begin by creating your initial Windows Forms examples in the raw (complete with - Building C# Applications menus, status bars, and toolbars). Over the course of the chapter however, I'll illustrate the use of various Part Two - The C# Programming Language wizards supplied by the Visual Studio .NET. Hopefully, this will also drive the point home that when you do Chapter 3 - C# Language Fundamentals leverage VS .NET to build your Windows Forms applications, you are not creating source code that will tie Chapter 4 - Object-Oriented Programming with C# you to a particular IDE. Chapter 2
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Prepping the Project Workspace - Callback Interfaces, Delegates, and Events
Chapter 7 Chapter 8
- Advanced C# Type Construction Techniques To begin understanding Windows Forms programming, let's build a simple main window by hand. The first order of business is to create a new empty C# project workspace named "MyRawWindow" using the VS Chapter 9 -Next, Understanding .NET .NET IDE. insert a new C#Assemblies class definition (resist the temptation to insert a new Windows Form Chapter 10 Processes, AppDomains, and Threads class! ) from the "Project | Add New Contexts, Item..." menu option. Name this class MainWindow. Part Three - Programming with .NET Assemblies
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
When you build a main by hand, Part Four - Leveraging thewindow .NET Libraries
you need to use the Form and Application types (at minimum),
both of 12 which are contained in the assembly. A Windows Forms application Chapter - Object Serialization andSystem.Windows.Forms.dll the .NET Remoting Layer also needs reference System.dll, that some types Forms) in the Windows Forms assembly make use of Chapter 13 - to Building a Better Window given (Introducing Windows types in14the System.dll assembly. Add references to these assemblies now (Figure 13-1). Chapter - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 13-1: The minimal set of assembly references
Building a Main Window (By Hand) In the world of Windows Forms, the Form class is used to represent any window in your application. This includes a topmost main window in an SDI (Single Document Interface) application, modeless and modal dialogs, as well as the parent and child windows of an MDI (Multiple Document Interface) application. When you are interested in creating a new main window, you have two mandatory steps: Derive a new custom class from System.Windows.Forms.Form. Configure the application's Main() method to call Application.Run(), passing an instance of your new
Form-derived type as an argument.
C# and the .NET Platform, Second Edition
ISBN:1590590554 Andrew Troelsen With these steps by in mind, you are able to update your initial class definition as follows:
Apress © 2003 (1200 pages)
using System;This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and using System.Windows.Forms; architectural issues for .NET developers. namespace MyRawWindow { Table of public Contents class MainWindow : Form { C# and the .NET Platform, Second Edition public MainWindow(){ } Introduction // Run this application and identify the main window. Part One - Introducing C# and the .NET Platform public static int Main(string[] args) Chapter 1 - The Philosophy of .NET { Chapter 2 - Building C# Applications Application.Run(new MainWindow()); Part Two - The C# Programming Language return 0; Chapter 3 - C# Language Fundamentals } Chapter } 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime } Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Here, I 8have defined with Main() method theTechniques scope of the class that represents the main window. If you Chapter - Advanced C# Type Construction prefer, you may wish to create a second class Part Three - Programming with .NET Assemblies (I named mine, TheApp) which is responsible for the task of launching main window: Chapter 9 -the Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
namespace MyRawWindow Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming { Four - Leveraging the .NET Libraries Part class MainWindow Form Chapterpublic 12 - Object Serialization and the : .NET Remoting Layer Chapter{13 - Building a Better Window (Introducing Windows Forms)
MainWindow(){} Chapter 14 -public A Better Painting Framework (GDI+) Chapter}15 - Programming with Windows Forms Controls
public class TheApp { Chapter 17 - Data Access with ADO.NET public static int Main(string[] args) Part Five - Web Applications and XML Web Services { Chapter 18 - ASP.NET Web Pages and Web Controls Application.Run(new MainWindow()); Chapter 19 - ASP.NET Web Applications return 0; Chapter 20 - XML Web Services } Index } List } of Figures Chapter 16 - The System.IO Namespace
List of Tables
In either case, Figure 13-2 shows a test run.
Figure 13-2: A simple main window a la Windows Forms If you notice how your MyRawWindow application has been launched, you should notice an annoying
command window looming in the background. This is because you have not yet configured the build C# and the .NET Platform, Second Edition settings to generate a Windows *.exe application. To supply the /t:winexe flag from within the IDE, open ISBN:1590590554 by Andrew Troelsen the Project Properties window (just right-click the project icon from the Solution Explorer) and expand the Apress © 2003 (1200 pages) "Common Properties | General" node. Finally, configure the "Output Type" property as "Windows This13-3). comprehensive starts with brief overview of the window will be gone and your Application" (Figure When youtext recompile, thea annoying command C# language and then quickly moves to key technical and application will run as a true-blue Windows app. architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Figure 13-3: Specifying /t—winexe within VS .NET
Chapter 9
- Understanding .NET Assemblies
Chapter 10 -point Processes, AppDomains, Contexts, and Threads So, at this we have a minimizable, maximizable, resizable, and closable main window (with a default Chapter 11 Type Reflection, Late Binding, and Attribute-Based system-supplied icon to boot!). To be sure, it is a great boon Programming to the Win32 programmers of the world to Part Fourthe - Leveraging the .NETconfigure Libraries a forego need to manually
WndProc function, establish a WinMain() entry point, and twiddle
Chapter Serialization and the .NET Remoting Layer the bits12 of -a Object WNDCLASSEX structure. Granted, your MainWindow does not do too much at this point, Chapter 13 Building a Better Window (Introducing Windows Forms) however, you'll enhance its functionality throughout the chapter. Chapter 14 - A Better Painting Framework (GDI+)
SOURCE The MyRawWindow application Chapter 15 - Programming with Windows Forms Controlscan be found under the Chapter 13 subdirectory. CODE
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Building a VS .NET Windows Forms Project Workspace by Andrew Troelsen
ISBN:1590590554
The benefit of building Forms ApressWindows © 2003 (1200 pages) applications using Visual Studio .NET is that the integrated tools can take care of a number of mundane details by delegating This comprehensive textcoding starts with a brief overview ofthem the to a number of wizards, configuration windows, and so forth. To illustrate how to make use of such assistance, close your current C# language and then quickly moves to key technical and for .NET developers. workspace. Now,architectural select a newissues C# Windows Application project type (see Figure 13-4).
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Figure 13-4: The Windows Forms project workspace
Part Three - Programming with .NET Assemblies
Chapter 9
Understanding .NET Assemblies When you-click OK, you will find that you are automatically given a new class derived from
Chapter 10 - Processes, AppDomains, Threads Main() method] and have references set to each System.Windows.Forms.Form [with Contexts, a properlyand configured Chapter 11 Type Reflection, Late Binding, and Attribute-Based Programming required assembly (as well as some additional assemblies that you may or may not make use of). Part Four - Leveraging the .NET Libraries
You will12also see that you are given a design-time template Chapter - Object Serialization and the .NET Remoting Layer that can be used to assemble the user interface Form (Figure 13-5).(Introducing UnderstandWindows that as you update this design-time template, you are Chapter 13of - your Building a Better Window Forms) indirectly code to the Framework associated (GDI+) Form-derived class (named Form1 by default). Chapter 14 adding - A Better Painting Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 13-5: The Form Designer Using the Solution Explorer window, you are able to alternate between this design-time template and the underlying C# code. To view the code that represents your current design, simply right-click the *.cs file and select "View Code". You can also open the code window by double-clicking anywhere on the design time Form; however, this has the (possibly undesirable) effect of writing an event handler for the Form's Load event (more on event processing later in this chapter). Once you open the code window, you will see a class that looks very much like the following (XML-based code comments removed for clarity):
namespace VSWinApp C# and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen public class Form1 : System.Windows.Forms.Form Apress © 2003 (1200 pages) { This comprehensive text starts with a brief overview ofcomponents the private System.ComponentModel.Container = null; C# language and then quickly moves to key technical and public Form1() architectural issues for .NET developers. { InitializeComponent(); } protected override void Dispose( bool disposing ) { Table of Contents if( disposing ) C# and the .NET Platform, Second Edition { Introduction if (components != null) Part One - Introducing C# and the .NET Platform { Chapter 1 - The Philosophy of .NET components.Dispose(); Chapter 2 - Building C# Applications } Part Two - The C# Programming Language } Chapter 3 - C# Language Fundamentals base.Dispose(disposing); Chapter 4 - Object-Oriented Programming with C# } Chapter 5 - Exceptions and Object #region WindowsLifetime Form Designer generated code Chapter 6 - Interfaces andvoid Collections private InitializeComponent() Chapter 7 - Callback Interfaces, Delegates, and Events { Chapter 8 - Advancedthis.components C# Type Construction = Techniques new System.ComponentModel.Container(); Part Three - Programming this.Size with .NET = Assemblies new System.Drawing.Size(300,300); this.Text = "Form1"; Chapter 9 - Understanding .NET Assemblies } Chapter 10 - Processes, AppDomains, Contexts, and Threads #endregion Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming [STAThread] Part Four - Leveraging the .NET Libraries static void Main() Chapter 12 - Object Serialization and the .NET Remoting Layer { Chapter 13 - Building a Better Window (Introducing Windows Forms) Application.Run(new Form1()); Chapter 14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls } Chapter 16 - The System.IO Namespace } Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter ASP.NET Web Pages Web Controls As you 18 can- see, this class listingand is essentially the same code as the previous raw Windows Forms Chapter 19 Your - ASP.NET Web Applications example. type still derives from System.Windows.Forms.Form, and the Main() method still calls Chapter 20 - XML Web Services Application.Run(). The major change is a new method named InitializeComponent(), which is wrapped by Index the #region and #endregion preprocessor directives (as described in Chapter 2). List of Figures
The Role of InitializeComponent() and Dispose()
List of Tables
The InitializeComponent() method is updated automatically by the Form Designer to reflect the modifications you make to the Form and its controls using the Visual Studio .NET IDE. For example, if you were to use the Properties window to modify the Form's Text and BackColor properties (Figure 13-6), you would find that InitializeComponent() has been modified accordingly:
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Figure- 13-6: The Properties window provides design time editing support. Object-Oriented Programming with C#
Chapter 4 Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
#region Windows Form Designer generated code - Callback Interfaces, Delegates, and Events private void InitializeComponent() Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); Chapter 9 - Understanding .NET Assemblies this.BackColor = System.Drawing.Color.Lime; Chapter this.ClientSize 10 - Processes, AppDomains, and Threads = newContexts, System.Drawing.Size(292, 273); Chapter this.Text 11 - Type Reflection, Late Binding, and Attribute-Based Programming = "My Rad Form"; Part } Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer #endregion Chapter 7
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
The Form-derived class calls within the scope of the default constructor: Chapter 15 - Programming with InitializeComponent() Windows Forms Controls Chapter 16 - The System.IO Namespace
public Chapter 17 Form1() - Data Access with ADO.NET { Five - Web Applications and XML Web Services Part for Windows Designer support Chapter // 18 -Required ASP.NET Web Pages and WebForm Controls Chapter InitializeComponent(); 19 - ASP.NET Web Applications
} Chapter 20 - XML Web Services Index List of Figures
Do be very aware that this helper method is simply a well-known member that VS .NET understands. If you moved all the code within this method into the Form's constructor, your application would run identically. Unlike other windowing toolkits, the wizard-generated code does not tie you to a particular IDE (VS .NET or otherwise).
List of Tables
The final point of interest is the overridden Dispose() method. This method is called automatically when your Form is about to be destroyed, and is a safe place to free any allocated resources.
C# and the .NET Platform, Second Edition Class The System.Windows.Forms.Application by Andrew Troelsen
ISBN:1590590554
The Application class defines members Apress © 2003 (1200 pages) that allow you to control various low-level behaviors of a Windows Forms application. For example, the Application class defines a set of of the events that allow you to respond to This comprehensive text starts with a brief overview events such as application shutdown and idle processing. For the most C# language and then quickly moves to key technical andpart, you do not need to directly architectural .NET to developers. interact with this type (beyondissues callingfor Run() show your main window); however, let's check out some of its behavior. To begin, ponder the following core methods (all of which are static) listed in Table 13-2. Table of 13-2: Contents Table Methods of the Application Type C# and the .NET Platform, Second Edition
Method of the Introduction Application Class Part One - Introducing C# and the Chapter 1
Meaning in Life .NET Platform
- The Philosophy of .NET
AddMessageFilter()
Chapter 2
These methods allow your application to intercept messages for
- Building C# Applications any necessary preprocessing. When you add a message filter, RemoveMessageFilter()
Part Two - The C# Programming Language you must
Chapter 3 Chapter 4
specify a class that implements the IMessageFilter
- C# Language Fundamentals interface (as you do shortly). - Object-Oriented Programming with C#
DoEvents() Provides the ability for an application to process messages Chapter 5 - Exceptions and Object Lifetime
currently in the message queue, during a lengthy operation (such as a looping construct). Think of DoEvents() as a quick and dirty Chapter 7 - Callback Interfaces, Delegates, and Events way to simulate multithreaded behaviors. Chapter 6
- Interfaces and Collections
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NETTerminates Assemblies the Exit()
Chapter 9
application.
- Understanding .NET Assemblies
ExitThread()
Exits the message loop on the current thread and closes all windows owned by the current thread.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part OLERequired() Four - Leveraging the .NET Libraries Initializes
the OLE libraries. Consider this the .NET equivalent of
OleInitialize(). Chapter 12 - Object Serialization andmanually the .NET calling Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Run()
Begins running a standard application message loop on the current thread.
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Chapter The Application 17 - Dataclass Access also with defines ADO.NET a number of static properties, many of which are read-only. As you Part examine Five - the Webfollowing Applications table,and realize XML Web that each Services property represents
some "application-level" trait such as
company version and soControls forth. In fact, given what you already know about .NET attributes Chapter 18 name, - ASP.NET Webnumber, Pages and Web (see Chapter 11), many ofApplications these properties should look vaguely familiar (Table 13-3). Chapter 19 - ASP.NET Web Chapter 20 - XML Web Services
Table 13-3: Core Properties of the Application Type Index List of Figures List of Tables
Property of C# Application Meaning Life and the .NET Platform, Secondin Edition Class ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages)
CommonAppDataRegistry
Retrieves the registry key for the application data that is
CompanyName
Retrieves the company name associated with the current application
This comprehensive text starts with a brief overview of the shared among all users C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents CurrentCulture
Gets or sets the locale information for the current thread
C# and the .NET Platform, Second Edition
CurrentInputLanguage
Gets or sets the current input language for the current thread
Introduction
Part One - Introducing C# and the .NET Platform
Chapter ProductName 1 - The Philosophy of .NET Chapter 2
Retrieves the product name associated with this application
- Building C# Applications
Part Two - The C# Programming Language
ProductVersion
Chapter 3
Retrieves the product version associated with this application
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# StartupPath Chapter 5 - Exceptions and Object LifetimeRetrieves the path for the executable file that started the
application
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Notice 8that- some properties, such as CompanyName Chapter Advanced C# Type Construction Techniquesand ProductName, provide a handy way to retrieve assembly-level metadata.with As .NET you recall from Chapter Part Three - Programming Assemblies
11, an assembly may be described using a number of attributes. Thus, if you specify a value for the AssemblyCompany attribute, you may obtain this Chapter 9 - Understanding .NET Assemblies information using Application.CompanyName without the making direct use of the types defined within Chapter 10 - Processes, AppDomains, Contexts, and Threads System.Reflection. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Fourthe - Leveraging the .NETdefines Libraries Finally, Application class the
events shown in Table 13-4.
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building Window (Introducing Table 13-4: EventsaofBetter the Application Type Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Application in Life Chapter 15 - ProgrammingMeaning with Windows Forms Controls Event
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access Occurs with ADO.NET ApplicationExit when the application is just about to shut down. Part Five - Web Applications and XML Web Services
Idle 18 - ASP.NET Web Occurs theControls application's message loop has finished processing and is Chapter Pages when and Web about to enter an idle state (meaning there are no messages to process at Chapter 19 - ASP.NET Web Applications the current time).
Chapter 20 - XML Web Services Index ThreadExit List of Figures List of Tables
Occurs when a thread in the application is about to terminate. If the main thread for an application is about to be shut down, this event will be raised before the ApplicationExit event.
Fun with the Application Class To illustrate some of the functionality of the Application class (as well as preview Windows Forms event handling), let's enhance our current raw MainWindow to perform the following tasks: Display some basic information about this application on startup. Respond to the ApplicationExit event. Perform some preprocessing of the WM_LBUTTONDOWN message. To begin, assume that you have extended your manifest using a number of attributes that mark the name of this fine application and the company that created it. Thus, insert a new file named assemblyinfo.cs which contains the following assembly-level attributes:
C# and the .NET Platform, Edition // Some attributes regarding thisSecond assembly. by Andrew Troelsen [assembly:AssemblyCompany("Intertech, Inc.")]ISBN:1590590554 Apress © 2003 (1200 pages) Better Window")] [assembly:AssemblyProduct("A This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NETcan developers. The constructor of our Form-derived class obtain this information using properties of the Application,
which are displayed using the Show() method of the MessageBox type: Table of Contents
using System; using System.Windows.Forms;
C# and the .NET Platform, Second Edition Introduction
Part One - Introducing C# and the .NET Platform
namespace AppClassExample - The Philosophy of .NET { Chapter 2 - Building C# Applications public class MainForm : Form Part Two - The C# Programming Language { Chapter ... 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# public MainForm() Chapter 5 - Exceptions and Object { GetStats(); }Lifetime Chapter 6 - Interfaces andvoid Collections private GetStats() Chapter 7 - Callback Interfaces, Delegates, and Events { Chapter 8 - Advanced// C# Read Type Construction some metadata Techniques from the manifest. Part Three - Programming string with .NET info Assemblies = string.Format("Company: {0}\n", Chapter 9 - Understanding .NETApplication.CompanyName); Assemblies info += string.Format("App Chapter 10 - Processes, AppDomains, Contexts, and Threads Name: {0}\n", Application.ProductName); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming +=Libraries string.Format("I live here: {0}", Part Four - Leveraging info the .NET Application.StartupPath); Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building aMessageBox.Show(info); Better Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls } Chapter 1
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Fiveyou - Web and you XMLsee WebaServices When run Applications this application, message
box that displays various bits of information (Figure 13-
Chapter 18 - ASP.NET Web Pages and Web Controls 7). Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 13-7: Reading attributes via the Application type
Responding to the ApplicationExit Event Next, let's configure this Form to respond to the ApplicationExit event. When you wish to respond to events from within a Windows Forms application, you will be happy to find that the same event logic detailed in Chapter 7 is used to handle GUI-based events. Therefore, if you wish to intercept the ApplicationExit event, you simply register an event handler using the += operator: public class MainForm : Form { ... public MainForm()
{ ...C# and the .NET Platform, Second Edition ISBN:1590590554 Andrew Troelsen // by Intercept the ApplicationExit event. Apress © 2003 (1200 pages) Application.ApplicationExit += new EventHandler(Form_OnExit); This comprehensive text starts with a brief overview of the } language and then quickly moves to key technical and // EventC#handler. architectural issues for .NET developers. private void Form_OnExit(object sender, EventArgs evArgs) { MessageBox.Show("See ya!", "This app is dead..."); Table of Contents } C# and the .NET Platform, Second Edition } Introduction
Part One - Introducing C# and the .NET Platform
Chapter Thesignature Philosophy .NET Notice 1that- the ofofthe ApplicationExit event handler must conform to a delegate of type Chapter 2 Building C# Applications System.EventHandler: Part Two - The C# Programming Language
Chapter 3
C# Language Fundamentals // Many -GUI-based events make use of this delegate (EventHandler)
Chapter 4 - Object-Oriented Programming with C# // which requires two parameters: Chapter 5 delegate - Exceptions void and Object Lifetime public EventHandler(object sender, EventArgs e); Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
As you 8will- see, the EventHandler delegate Techniques is the most common type used to handle events under Chapter Advanced C# Type Construction Windows Forms, however, alternatives do exist Part Three - Programming with .NET Assemblies for other events. The first parameter of the EventHandler delegate type System.Object, which represents the object sending the event. The EventArgs Chapter 9 is- of Understanding .NET Assemblies parameter (or a descendent thereof) containsand relevant information for the current event. Chapter 10 - Processes, AppDomains, Contexts, Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
While the EventArgs parameter will always work in conjunction with the EventHandler delegate, it also functions as the base class to more specific event argument types. For example, if you have an event Chapter 12 - Object Serialization and the .NET Remoting Layer handler that responds to a mouse event, the MouseEventArgs parameter will contain mouse related Chapter - Building a y) Better Window (Introducing Windowsevent Forms) details 13 such as the (x, position of the cursor. Keyboard handlers make use of the KeyEventArgs Chapter - A Better Painting Framework (GDI+) type. In14 any case, if you run the application, you will be able to respond to the termination of this Chapter 15 - Programming with Windows Forms Controls application. Part Four - Leveraging the .NET Libraries
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Preprocessing Messages with the Application Class
Part Five - Web Applications and XML Web Services
Chapter 18step - ASP.NET Pages Web Controls The final of this Web example is and to perform some preprocessing logic of the WM_LBUTTONDOWN Chapter 19 -As ASP.NET Web Applications message. you may know, this standard Windows message is sent when the left mouse button has Chapter 20 - XML Web Services been clicked within the client area of a given Form (or any GUI widget that is equipped to respond to this Index event). Now, be very aware that you will find a much simpler way to intercept standard mouse events a bit List later of in Figures this chapter. The point of this step is simply to illustrate how to perform custom preprocessing logic
before a given event is fully dispatched to its handler. List of Tables When you wish to filter messages in the .NET framework, your first task is to create a new class that implements the IMessageFilter interface. This is extremely simple, given that IMessageFilter defines only one method, PreFilterMessage(). Return "true" to filter the message and prevent it from being dispatched or "false" to allow the message to continue on its way. Within the scope of your implementation, you may examine the incoming Message.Msg field to extract the numerical value of the Windows message (in this case, WM_LBUTTONDOWN, which is the value 513). For example: using Microsoft.Win32; // Contains Win32 specific types. ... // Create a message filter. public class MyMessageFilter : IMessageFilter {
public bool PreFilterMessage(ref Message m) C# and the .NET Platform, Second Edition { Andrew Troelsen // by Intercept the left mouse button ISBN:1590590554 down message. Apress © 2003 (1200 pages) if (m.Msg == 513) // WM_LBUTTONDOWN = 513. { This comprehensive text starts with a brief overview of the C#MessageBox.Show("WM_LBUTTONDOWN language and then quickly moves to key technical is: and " + m.Msg); architectural issues for .NET developers. return true; } return false; // All other messages are ignored... Table of Contents } C# and the .NET Platform, Second Edition } Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1 -have The created Philosophy .NETthat will be filtering the incoming messages, you must register a new Once you theofclass Chapter 2 Building C# Applications instance of this type using the static AddMessageFilter() method. Here is the update to your existing Part Two - The C# Programming Language MainForm class:
Chapter 3
- C# Language Fundamentals
Chapter 4 class - Object-Oriented Programming public MainForm : Form with C# Chapter 5 Exceptions and Object Lifetime { Chapter private 6 - Interfaces and Collections MyMessageFilter msgFilter = new MyMessageFilter(); Chapter ... 7 - Callback Interfaces, Delegates, and Events Chapter public 8 - Advanced C# Type Construction Techniques MainForm() Part Three { - Programming with .NET Assemblies
Chapter 9
- Understanding ... .NET Assemblies
// Add AppDomains, message filter. Chapter 10 - Processes, Contexts, and Threads Application.AddMessageFilter(msgFilter); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four} - Leveraging the .NET Libraries
handler and the .NET Remoting Layer Chapter // 12 -Event Object Serialization void Form_OnExit(object sender, EventArgs evArgs) Chapter private 13 - Building a Better Window (Introducing Windows Forms) Chapter { 14 - A Better Painting Framework (GDI+)
MessageBox.Show("See ya!", "This app is dead..."); // Remove message filter. Chapter 16 - The System.IO Namespace Application.RemoveMessageFilter(msgFilter); Chapter 17 - Data Access with ADO.NET } Part Five - Web Applications and XML Web Services } Chapter 15 - Programming with Windows Forms Controls
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Index When you run this application, you see a message that informs you of the numerical value of the Win32 List WM_LBUTTONDOWN of Figures message when you click the left mouse button anywhere in the application. List of Tables
As you can tell, filtering messages is not a task you need to perform all that often (if ever). Nevertheless, it is nice to know that Windows Forms allows you to drop down to this level of detail if you so choose. SOURCE CODE
The AppClassExample project can be found under the Chapter 13 subdirectory.
C# and .NET Platform, Second Edition The Anatomy of the a Form by Andrew Troelsen
ISBN:1590590554
Now that you understand the role the Application type, our next task is to examine the functionality of the Apress © 2003 (1200of pages) Form class itself.This As you have seen, when you with create a new windowof(or comprehensive text starts a brief overview thedialog box) you need to define a new class deriving from System.Windows.Forms.Form. This class gains C# language and then quickly moves to key technical and a great deal of functionality from architectural issues for .NET the types in its inheritance chain. Figure 13-8developers. illustrates the big picture.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Figure 13-8: The derivation of Assemblies a custom Form
Chapter 9
- Understanding .NET Assemblies Before 10 we-get to the real meat of theContexts, Form's inheritance Chapter Processes, AppDomains, and Threadschain, understand that like any type in the .NET
universe, derives from System.Object (whichProgramming should be no surprise to you at this point). As Chapter 11 Form - Typeultimately Reflection, Late Binding, and Attribute-Based youFour recall from Chapter MarshalByRefObject Part - Leveraging the 12, .NET Libraries
defines the behavior to remote this type by reference, rather than by value. Thus, if you remotely interact with a Form across the wire, you are manipulating a Chapter 12 - Object Serialization and the .NET Remoting Layer reference to the Form on the remote machine (not a local copy of the Form on the client machine). Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14each - A Better Painting Framework (GDI+) Detailing and every member of each class in the Form's inheritance chain would require a small Chapter - Programming WindowstoForms Controls book in15 itself. However, it with is important understand the core behavior supplied by each base class. I Chapter - The assume16that youSystem.IO will spendNamespace time examining the full details behind each class at your leisure. Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The Component Class by Andrew Troelsen
ISBN:1590590554
The first base class of immediate Apress © 2003 (1200interest pages) is Component. The Component type provides a canned implementation of the IComponent interface defines a property named Site, This comprehensiveinterface. text startsThis withpredefined a brief overview of the which returns (surprise, surprise) an ISite interface. Furthermore, IComponent inherits a single event from C# language and then quickly moves to key technical and architectural issues for .NET developers. the IDisposable interface named Disposed: public interface IComponent : IDisposable { C# and the .NET Platform, Second Edition // The Site property. Introduction public ISite Site { get; set; } Part One - Introducing C# and the .NET Platform // The Disposed event. Chapterpublic 1 - Theevent Philosophy of .NET EventHandler Disposed; Chapter 2 Building C# Applications }
Table of Contents
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals The ISite defines aProgramming number of methods Chapter 4 interface - Object-Oriented with C# that allow a Control to interact with the hosting container: Chapter 5
- Exceptions and Object Lifetime
Chapter 6 interface - Interfaces and Collections public ISite : IServiceProvider Chapter { 7 - Callback Interfaces, Delegates, and Events
ISite interface. Chapter// 8 Properties - Advanced C# of Typethe Construction Techniques public IComponent Component { Part Three - Programming with .NET Assemblies
get; } public IContainer Container { get; } Chapter 9 - Understanding .NET Assemblies public bool DesignMode { get; Chapter 10 - Processes, AppDomains, Contexts, and}Threads { get; } Chapterpublic 11 - Type string Reflection,Name Late Binding, andset; Attribute-Based Programming } Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
By and large, the properties defined by the ISite interface are only of interest to you if you are attempting to build a widget that can be manipulated at design time (such as a custom Windows Forms control).
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter In addition 16 -toThe theSystem.IO Site property, Namespace Component also provides an implementation of the Dispose() method (as
seen earlier in this chapter). that the Dispose() method is called when a component is no longer Chapter 17 - Data Access with Recall ADO.NET required. When a Form hasand been closed, the Dispose() Part Five - Web Applications XML Web Services for all widgets contained Chapter 18 - ASP.NET Webwithin Pagesthat and form. Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
method is called automatically for the Form and
and the .NET Platform, Second Edition The ControlC#Class by Andrew Troelsen
ISBN:1590590554
The next base class of interest is System.Windows.Forms.Control, which establishes the common behaviors Apress © 2003 (1200 pages) required by any GUI-centric type. The core members of System.Windows.Forms.Control allow you to configure This comprehensive text starts with a brief overview of the the size and position of a control, extract the underlying HWND (i.e., a numerical handle for a given window), as C# language and then quickly moves to key technical and architectural .NET Table developers. well as capture keyboard andissues mouseforinput. 13-5 defines some of the properties to be aware of. Table 13-5: Core Properties of the Control Type
Table of Contents
Property C#Control and the .NET Platform, Second EditionMeaning in Life Introduction
Top, Left, Bottom, Right, Bounds, ClientRectangle, Height, Chapter 1 - The Philosophy of .NET Width
Each of these properties specifies various attributes about the current dimensions of the Control-derived object.
Part One - Introducing C# and the .NET Platform
Bounds returns a Rectangle that specifies the size of the control. ClientRectangle returns a Rectangle that corresponds to the size - The C# Programming Language of the client area of the control.
Chapter 2 Part Two
Chapter 3
- Building C# Applications
- C# Language Fundamentals
Chapter 4 -Disposed, Object-Oriented Programming with properties C# Created, Enabled, These each return a Boolean that specifies the state of Chapter Focused, 5 - Visible Exceptions and Object Lifetime the current Control. Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Handle
Returns a numerical value (integer) that represents the HWND of this Control.
ModifierKeys This static Part Three - Programming with .NET Assemblies
property checks the current state of the modifier keys (shift, control, and alt) and returns the state in a Keys type. Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
MouseButtons
This static property checks the current state of the mouse buttons
Chapter 11 - Type Reflection, Late Binding, andright, Attribute-Based (left, and middle Programming mouse buttons) and returns this state in a Part Four - Leveraging the .NET LibrariesMouseButtons
type.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Parent Returns a Control that represents the parent of the current Chapter 13 - Building a Better Window (Introducing Windowsobject Forms) Chapter 14 - A Better Painting FrameworkControl. (GDI+) Chapter 15 - Programming with WindowsThese Forms properties Controls are used to configure the tab order of the TabIndex, TabStop Chapter 16 - The System.IO Namespace Control. Chapter 17 - Data Access with ADO.NET
Text
The current text associated with this Control.
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Webalso Applications The Control base class defines a number of methods that allow you to interact with any Control-derived Chapter 20 XML Web Services type. A partial list of some of the more common members appears in Table 13-6. Index List of Figures Table 13-6: Select Members of the Control Type List of Tables
Control Method in Life C# and theMeaning .NET Platform, Second Edition GetStyle() SetStyle() Hide()
ISBN:1590590554 by Andrew Troelsen These methods are used to manipulate the style flags of the current Control Apress © 2003 (1200 pages)
using the ControlStyles enumeration.
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and indirectly set the state of the Visible property. architecturalThese issuesmethods for .NET developers.
Show() Invalidate() Table of Contents
Forces the Control to redraw itself by forcing a paint message into the message queue. C# and the .NET Platform, Second Edition This method is overloaded to allow you to specify a specific Rectangle to Introduction than the entire client area. Part One - Introducing C# andrefresh, the .NETrather Platform Chapter 1
- The Philosophy of .NET OnXXXX() The Control class defines numerous methods which can be overridden by a - Building C# Applications subclass to respond to various events (e.g., OnMouseMove(), Part Two - The C# Programming Language OnKeyDown(), OnResize(), and so forth). Chapter 2 Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 7
- Callback Interfaces, Delegates, and Events
As you see later in this chapter, when you wish to intercept a GUI-based event, you have two approaches. One approach is to simply override one of Chapter 5 - Exceptions and Object Lifetime the existing event handlers. Another is to add a custom event handler to a Chapter 6 - Interfaces and Collections given delegate. Refresh() Forces the Control to invalidate and immediately repaint itself and any Chapter 8 - Advanced C# Type Construction Techniques children. Part Three - Programming with .NET Assemblies Chapter 9 - Understanding .NET Assemblies SetBounds(), Each of these methods is used to establish the dimensions of the ControlChapter 10 Processes, AppDomains, SetLocation(), derived Contexts, object. and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming SetClientArea() Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Setting a Form's Styles
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with methods Windows of Forms Controlstype: GetStyle() and SetStyle(), both of which interact with Let's examine two interesting the Control Chapter 16 The System.IO Namespace the ControlStyles enumeration. Win32 programmers are no doubt familiar with the WNDCLASSEX structure, Chapter - Dataof Access with ADO.NET and the17 dozens oddball styles that can be used to fill the various fields. While Windows Forms hides this Part Five - Web and are XMLable Webto Services Windows "goo"Applications from view, you modify the
default styles of your Form if need be. To illustrate, check
Chapter - ASP.NET Web Pages and Web Controls out the18 related ControlStyles enumeration: Chapter 19 - ASP.NET Web Applications Chapter 20 enum - XML Web Services public ControlStyles Index { List of Figures AllPaintingInWmPaint, CacheText, List of Tables DoubleBuffer, ContainerControl,
EnableNotifyMessage, FixedHeight, FixedWidth, Opaque, ResizeRedraw, Selectable, StandardClick, StandardDoubleClick, SupportsTransparentBackColor, UserMouse, UserPaint }
The values of the ControlStyle enumeration may OR-ed together if you wish to specify multiple styles. And, as you would expect, a Form has a default style set (I assume you will check out online Help for full details of each value). Assume you have a Form containing a single Button type. In the Click event handler of this Button, you can check if the Form supports a given style using GetStyle():
// Shows false! C# and the .NET Platform, Second Edition private void btnGetStyles_Click(object sender, System.EventArgs e) ISBN:1590590554 by Andrew Troelsen { Apress © 2003 (1200 pages) MessageBox.Show(GetStyle(ControlStyles.ResizeRedraw).ToString(), comprehensive text starts with a brief overview of the "DoThis you have ResizeRedraw?"); C# language and then quickly moves to key technical and } architectural issues for .NET developers. To set the bit of a given style (by specifying true or false) you could write:
Table of Contents
C# and the .NET Platform, Second Edition
public StyleForm() Introduction { One - Introducing C# and the .NET Platform Part Chapter ... 1 - The Philosophy of .NET
SetStyle(ControlStyles.ResizeRedraw, true); - Building C# Applications } Part Two - The C# Programming Language Chapter 2 Chapter 3
- C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with want C# to add to a given Form. By default this style is not active and The ResizeRedraw is one value you typically Chapter 5 Exceptions and Object Lifetime thus, a Form will not automatically redraw its client area when resized. This means, if you have intercepted a Chapter 6 - (which Interfaces Paint event youand willCollections do a bit later) and resize the Form, your drawing logic is not refreshed! If you wish to Chapter 7 Callback Interfaces, ensure that the Paint event firesDelegates, wheneverand the Events user resizes the Form, be sure to specify the ResizeRedraw style Chapter 8 - Advanced C# Type Construction Techniques using SetStyle(). Part Three - Programming with .NET Assemblies
Another9 (equally valid) alternative to ensure correct repainting is to intercept the Form's Resize event and call Chapter - Understanding .NET Assemblies Invalidate() Chapter 10 - directly: Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
private void StyleForm_Resize(object Part Four - Leveraging the .NET Libraries
sender, System.EventArgs e)
{ Chapter 12 - Object Serialization and the .NET Remoting Layer Invalidate(); This(Introducing forces aWindows repaint (more details later...) Chapter 13 - Building a Better// Window Forms) } Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 you - Data Access with ADO.NET the Resize() event when you have additional work to do beyond triggering Typically, would want to intercept Part Fivesession. - Web Applications andsetting XML Web a paint If you do not, the Services ControlStyles.ResizeRedraw
will do the trick.
Chapter 18 - ASP.NET Web Pages and Web Controls
Now, to19illustrate the Web effect of setting Form styles, assume you have handled the Form's Paint event and coded Chapter - ASP.NET Applications a block20 of -GDI+ logic that draws a dashed black line around the client area rectangle (GDI+ is Chapter XML rendering Web Services detailed in the next chapter, so don't sweat the details): Index List of Figures
//ofGDI+ List Tablesrequires setting a reference to System.Drawing.dll! using System.Drawing; // Needed for Color, Brush, and Font types. ... private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { // A custom dash... Pen customDashPen = new Pen(Color.Black, 10); float[] myDashes = {5.0f, 2.0f, 1.0f, 3.0f}; customDashPen.DashPattern = myDashes; e.Graphics.DrawRectangle(customDashPen, ClientRectangle); }
If the ResizeRedraw bit is set to "false," you find the ugliness shown in Figure 13-9 as you resize the Form.
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table Figure of Contents 13-9: ControlStyles.ResizeRedraw = false C# and the .NET Platform, Second Edition
If you set it to "true" you have correct rendering (Figure 13-10). Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Figure 13-10: ControlStyles.ResizeRedraw = true
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies SOURCE The FormStylesContexts, project isand under the Chapter 13 subdirectory. Chapter 10 - Processes, AppDomains, Threads
CODE Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Control Events by Andrew Troelsen
ISBN:1590590554
The Control classApress also defines a number © 2003 (1200 pages) of events that can logically be grouped into two major categories: Mouse events and keyboard events 13-7). This comprehensive (Table text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers. Table 13-7: Events of the Control Type
Control Event Table of Contents
Meaning in Life
Click, DoubleClick, MouseEnter, MouseLeave, MouseDown, MouseUp, MouseMove, MouseHover, Introduction MouseWheel
The Control class defines numerous events triggered in response to mouse input.
KeyPress, KeyUp, KeyDown Chapter 1 - The Philosophy of .NET
The Control class also defines numerous events triggered in response to keyboard input.
C# and the .NET Platform, Second Edition
Part One - Introducing C# and the .NET Platform
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
- Exceptions and ObjectClass Lifetime Fun with the Control
Chapter 5 Chapter 6
- Interfaces and Collections To be sure, the Control class does define and additional Chapter 7 - Callback Interfaces, Delegates, Eventsproperties, methods, and events beyond the subset you
have just to illustrate some of these core members, let's build a new Form type (also Chapter 8 examined. - AdvancedHowever, C# Type Construction Techniques called MainForm) that provides theAssemblies following functionality: Part Three - Programming with .NET Chapter 9
- Understanding .NET Assemblies
Set the initial size of the Form to some arbitrary dimensions.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Late Binding, and Attribute-Based Programming Override the Reflection, Dispose() method. Part Four - Leveraging the .NET Libraries
Respond to theSerialization MouseMove and eventsLayer (using two approaches). Chapter 12 - Object and theMouseUp .NET Remoting Chapter 13 - Building a Better Window (Introducing Windows Forms)
Capture and process keyboard input.
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 assume - Programming with Formsderived Controls To begin, you have a Windows new C# class from Form. First, update the default constructor to set Chapter - The System.IO Namespace the top,16 left, bottom, and right coordinates of the Form using various properties of the Control class. To Chapter confirm17 these - Data changes, Access with makeADO.NET use of the Bounds property, and display the string version of the current Part dimensions. Five - Web Do Applications be aware that and Bounds XML Web returns Services a Rectangle
type that is defined in the System.Drawing
namespace. Therefore bePages sure and to set an Controls assembly reference (to System.Drawing.dll) if you are building this Chapter 18 - ASP.NET Web Web Form by (VisualWeb Studio .NET Windows Forms projects do so automatically): Chapter 19hand - ASP.NET Applications Chapter 20 - XML Web Services Index // Need this for Rectangle definition.
using System.Drawing; List of Figures ... List of Tables public class MainForm : Form { public static int Main(string[] args) { Application.Run(new MainForm()); return 0; } public MainForm() { Top = 100; Left = 75; Height = 100; Width = 500; MessageBox.Show(Bounds.ToString(), "Current rect");
} }
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
When you run this application, you are able to confirm the overview coordinates of your Form via the Bounds This comprehensive text starts with a brief of the C# language and then quickly moves to key technical and property. architectural issues for .NET developers.
Now, let's retrofit your class to override the inherited Dispose() method (this is done automatically when using VS .NET). As you recall from earlier in this chapter, the Application object defines an event named Table of ContentsIf you configure your Form to intercept this event, you are effectively informed of the ApplicationExit. C# and the .NET Platform, Second destruction of the application. AsEdition a (much) simpler alternative, you can achieve the same effect by simply Introduction overriding the Dispose() method. Do note that you should call your base class' Dispose() method before Part One - Introducing C# and the .NET Platform exiting: Chapter 1
- The Philosophy of .NET
Chapter 2 - Building C# Applications protected override void Dispose( bool disposing ) Part { Two - The C# Programming Language
ChapterMessageBox.Show("Disposing 3 - C# Language Fundamentals this Form"); Chapterif( 4 -disposing Object-Oriented ) Programming with C# Chapter{5
- Exceptions and Object Lifetime
Chapter 6
(components != null) -if Interfaces and Collections
Chapter 7
-{Callback Interfaces, Delegates, and Events
Chapter 8
components.Dispose(); - Advanced C# Type Construction Techniques
} Part Three - Programming with .NET Assemblies Chapter 9
-}Understanding .NET Assemblies
disposing Chapter 10 -base.Dispose( Processes, AppDomains, Contexts,); and Threads }
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Responding to Mouse Events: Take One
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Next, you to intercept theWindows MouseUp event. The goal is to display the (x,y) position at which the Chapter 15 need - Programming with Forms Controls
MouseUp event occurred. When you wish to respond to events from within a Windows Forms application, you have two general approaches. The first approach should be familiar to you at this point in the game: Chapter 17 - Data Access with ADO.NET Use delegates. The second approach is to override the appropriate base class method. Let's examine each Part Five - Web Applications and XML Web Services technique, beginning with standard delegation. Here is the updated MainForm: Chapter 16 - The System.IO Namespace
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
public class MainForm : Form { Index public static int Main(string[] args) List of Figures { List of Tables Application.Run(new MainForm()); return 0; } public MainForm() { ... // Listen for the MouseUp event... this.MouseUp += new MouseEventHandler(OnMouseUp); } // Method called in response to the MouseUp event. public void OnMouseUp(object sender, MouseEventArgs e) { this.Text = string.Format("Current Pos: ({0}, {1})", e.X, e.Y); } ... } Chapter 20 - XML Web Services
C# and the .NET Platform, Second Edition
Now, recall that GUI-based delegates take an EventArgs (or derivative thereof) as the second parameter. ISBN:1590590554 by Andrew Troelsen When you process mouse events, the second parameter is of type MouseEventArgs. This type (defined in Apress © 2003 (1200 pages) the System.Windows.Forms namespace) defines a number of interesting properties that may be used to This comprehensive text starts with a brief overview of the gather various statistics regarding the state of the mouse, as seen in Table 13-8. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 13-8: Properties of the MouseEventArgs Type MouseEventArgs Table of Contents
Meaning in Life Property C# and the .NET Platform, Second Edition Introduction
Button
Gets which mouse button was pressed, as defined by the MouseButtons enumeration
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Clicks2 Chapter
Gets the number of times the mouse button was pressed and - Building C# Applications
released Part Two - The C# Programming Language Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# has rotated
Chapter 5
- Exceptions and Object Lifetime
X Chapter 6
Gets the x-coordinate of a mouse click - Interfaces and Collections
Chapter 7 Y
- Callback Interfaces, Delegates, Events Gets theand y-coordinate of a mouse click - Advanced C# Type Construction Techniques
Delta
Chapter 8
Gets a signed count of the number of detents the mouse wheel
Part - Programming with .NET Assemblies TheThree implementation of the OnMouseUp() method
simply extracts the (x, y) position of the cursor and
Chapter - Understanding Assemblies displays9 this information in .NET the Form's caption via the inherited Text property. Chapter 10 - Processes, AppDomains, Contexts, and Threads
To make more interesting, could also captureProgramming a MouseMove event, and display the same (x, Chapter 11 things - Typeeven Reflection, Late Binding,we and Attribute-Based y) position data in thethe caption the Form. Part Four - Leveraging .NET of Libraries
In this way, the current location of the cursor is tracked whenever
the mouse moved within Chapter 12 - cursor Object is Serialization andthe theclient .NET area: Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
public MainForm : Form (GDI+) Chapter 14 class - A Better Painting Framework { Chapter 15 - Programming with Windows Forms Controls ... 16 - The System.IO Namespace Chapter Chapter public 17 - Data MainForm() Access with ADO.NET Part Five{- Web Applications and XML Web Services
... // Track mouse movement and MouseUp event. Chapter 19 - ASP.NET Web Applications this.MouseUp += new MouseEventHandler(OnMouseUp); Chapter 20 - XML Web Services this.MouseMove += new MouseEventHandler(OnMouseMove); Index } List of Figures public void OnMouseUp(object sender, MouseEventArgs e) List of Tables { // Now we will just show a message when clicked. MessageBox.Show("Stop clicking me!"); } public void OnMouseMove(object sender, MouseEventArgs e) { this.Text = string.Format("Current Pos: ({0}, {1})", e.X, e.Y); } } Chapter 18 - ASP.NET Web Pages and Web Controls
Determining Which Mouse Button Was Clicked One thing to be aware of is that the MouseUp (or MouseDown) event is sent whenever any mouse button is clicked. If you wish to determine exactly which button was clicked (left, right, or middle) you need to examine the Button property of the MouseEventArgs class. The value of Button is constrained by the
MouseButtons enumeration. For example:
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
public void OnMouseUp(object sender, MouseEventArgs e) Apress © 2003 (1200 pages) { This comprehensive text starts with a brief overview of the // WhichC#mouse button was clicked? language and then quickly moves to key technical and if(e.Button == MouseButtons.Left) architectural issues for .NET developers. MessageBox.Show("Left click!"); if(e.Button == MouseButtons.Right) MessageBox.Show("Right click!"); Table of Contents if (e.Button == MouseButtons.Middle) C# and the .NET Platform, Second Edition MessageBox.Show("Middle click!"); Introduction } Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Responding to Mouse Events: Take Two
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals The previous mouse event logic followed with the standard .NET delegate pattern. The other approach to Chapter 4 - Object-Oriented Programming C#
capture5 events in a Control-derived type is to override the correct base class method, which in this case Chapter - Exceptions and Object Lifetime would be and OnMouseMove(). The Control type defines a number of protected virtual Chapter 6 OnMouseUp() - Interfaces and Collections methods will be Interfaces, called automatically the corresponding event is triggered. If you were to update Chapter 7 that - Callback Delegates, when and Events
your Form-using this technique, you have no need to manually specify a custom event handler (or write the Advanced C# Type Construction Techniques necessary event handling logic): Part Three - Programming with .NET Assemblies Chapter 8 Chapter 9
- Understanding .NET Assemblies
public MainForm : Form Chapter 10 class - Processes, AppDomains, Contexts, and Threads { Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four... - Leveraging the .NET Libraries
public MainForm() { Chapter 13 - Building a Better Window (Introducing Windows Forms) ... Chapter 14 - A Better Painting Framework (GDI+) // No need to do this when overriding! Chapter 15 - Programming with Windows Forms Controls // this.MouseUp += new MouseEventHandler(OnMouseUp); Chapter 16 - The System.IO Namespace // this.MouseMove+= new MouseEventHandler(OnMouseMove); Chapter } 17 - Data Access with ADO.NET Part Five -protected Web Applications and XMLvoid Web Services override OnMouseUp(/*object sender,*/ MouseEventArgs e) Chapter { 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications // Which mouse button was clicked? Chapter 20 - XML Web Services == MouseButtons.Left) if(e.Button Index MessageBox.Show("Left click!"); List of Figures if(e.Button == MouseButtons.Right) MessageBox.Show("Right click!"); List of Tables if(e.Button == MouseButtons.Middle) MessageBox.Show("Middle click!"); base.OnMouseUp(e); } protected override void OnMouseMove(/*object sender,*/ MouseEventArgs e) { this.Text = string.Format("Current Pos: ({0}, {1})", e.X, e.Y); } } Chapter 12 - Object Serialization and the .NET Remoting Layer
Notice how the signature of each method takes a single parameter of type MouseEventArg, rather than two parameters that conform to the MouseEventHandler delegate. If you run the program again, you see no change whatsoever (which is good). Recall that these virtual methods defined by your base types are simply the default event handlers that will be called if you do not explicitly handle a given event. Typically you only need to override an "OnXXXX()" method if you have additional work to perform before calling your parent's implementation. The preferred
approach (and the one used by Visual Studio .NET) is to handle the event directly as you did in the first the .NET Platform, Second Edition mouse example, C# andand make use of the .NET event syntax. Given this, I will refrain from overriding base class ISBN:1590590554 by Andrew Troelsen GUI event handlers during the remainder of this text. Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C#to andKeyboard the .NET Platform, Second Edition Responding Events by Andrew Troelsen
ISBN:1590590554
Processing keyboard input is almost identical to responding to mouse activity. The following code captures Apress © 2003 (1200 pages) the KeyUp event This and comprehensive displays the textual namewith of the character thatofwas text starts a brief overview the pressed in a message box. Here, you capture this event using the delegation technique (there is a method C# language and then quickly moves to key technical and named OnKeyUp() that can be overridden as an architectural alternative): issues for .NET developers. public class MainForm : Form { C# and the .NET Platform, Second Edition ... Introduction public MainForm() Part One - Introducing C# and the .NET Platform { Chapter 1 - The Philosophy of .NET ... Chapter 2 - Building C# Applications // Listen to KeyUp Event. Part Two - The C# Programming this.KeyUp +=Language new KeyEventHandler(OnKeyUp); Chapter } 3 - C# Language Fundamentals Chapter public 4 - Object-Oriented Programming withsender, C# void OnKeyUp(object KeyEventArgs e) Chapter { 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces MessageBox.Show(e.KeyCode.ToString(), and Collections "Key Pressed!"); Chapter } 7 - Callback Interfaces, Delegates, and Events } Chapter 8 - Advanced C# Type Construction Techniques
Table of Contents
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
As you can see, the KeyEventArgs type maintains an enumeration named KeyCode that holds the ID of the key press. In addition, the KeyEventArgs type, defines the useful properties listed in Table 13-9.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Table 13-9: Properties of the KeyEventArgs Type
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter KeyEventArgs 13 - Building a BetterMeaning Window (Introducing in Life Windows Forms)
Property Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Alt
Gets a value indicating whether the Alt key was pressed
Chapter 16 - The System.IO Namespace
Chapter Control 17 - Data Access with Gets ADO.NET a value indicating whether the Ctrl key was pressed Part Five - Web Applications and XML Web Services
Handled
Gets or sets a value indicating whether the event was handled
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter KeyCode 19 - ASP.NET Web Applications Gets the keyboard code for a System.Windows.Forms.Control.KeyDown
or System.Windows.Forms.Control.KeyUp event Chapter 20 - XML Web Services Index
KeyData
List of Figures List of Tables
Gets the key data for a System.Windows.Forms.Control.KeyDown or System.Windows.Forms.Control.KeyUp event
Modifiers
Indicates which modifier keys (Ctrl, Shift, and/or Alt) were pressed
Shift
Gets a value indicating whether the Shift key was pressed
Figure 13-11 shows a possible key press.
Figure 13-11: Intercepting key presses
SOURCE CODE
C# and .NET Platform, Second Edition under the Chapter 13 subdirectory. The the ControlBehaviors project is included ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the Revisited .NET Platform, Second Edition The ControlC#Class by Andrew Troelsen
ISBN:1590590554
The Control classApress defines further to configure background and foreground colors, background © 2003 (1200behaviors pages) images, font characteristics, drag-and-drop functionality and supportoffor This comprehensive text starts with a brief overview thepop-up context menus. This class provides dockingC# andlanguage anchoring behaviors for the derived types (which and then quickly moves to key technical andyou examine in Chapter 15). issues developers. Perhaps the mostarchitectural important duty of for the .NET Control class is to establish a mechanism to render images, text, and various geometric patterns onto the client area via a registered Paint event handler. To begin, observe these additional properties of the Control class, as seen in Table 13-10. Table of Contents C# and the .NETAdditional Platform, Second Edition Table 13-10: Control Properties Introduction
Control Property in Part One - Introducing C# and theMeaning .NET Platform
Life
Chapter 1
- The Philosophy of .NET AllowDrop If AllowDrop is set to true then this control allows drag-and-drop - Building C# Applications operations and events to be used.
Chapter 2
Part Two - The C# Programming Language
Anchor The anchor property determines which edges of the control are Chapter 3 - C# Language Fundamentals Chapter 4
anchoredwith to the - Object-Oriented Programming C#container's edges.
Chapter 5 - Exceptions and Object Lifetime BackColor, These properties configure how the client area should be Chapter 6 Interfaces and Collections BackgroundImage, Font, displayed. Chapter 7 - Callback ForeColor, Cursor Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
ContextMenu
Specifies which context menu (e.g., pop-up menu) will be shown when the user right-clicks the control.
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter and Threads Dock 10 - Processes, AppDomains, The Contexts, dock property controls which edge of the container this control Chapter 11 - Type Reflection, Latedocks Binding, to. and For Attribute-Based example, whenProgramming docked to the top of the container, the Part Four - Leveraging the .NET Libraries control
is displayed flush at the top of the container, extending the
length theRemoting container. Chapter 12 - Object Serialization and the of .NET Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Opacity
Determines the opacity of the control, in percentages (0.0 is completely transparent, 1.0 is completely opaque).
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Region This property configures a Region object that specifies the Chapter 16 - The System.IO Namespace outline/silhouette/boundary of the control. Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Services RightToLeft ThisWeb is used for international
applications where the language is
Chapter 18 - ASP.NET Web Pages written and Web Controls from right to left. Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
The Control class also defines a number of additional methods and events used to configure how the Index Control should respond to drag-and-drop operations and respond to painting operations (Table 13-11). List of Figures List of Tables
Table 13-11: Additional Control Methods
Control Meaning in Life C# and the .NET Platform, Second Edition Method/Event by Andrew Troelsen DoDragDrop()
ISBN:1590590554
Apress © 2003 (1200 pages)
These methods are used to monitor drag-and-drop operations for a
This comprehensive text starts with a brief overview of the Control descendent. OnDragDrop() C# language given and then quickly moves to key technical and architectural issues for .NET developers.
OnDragEnter()
OnDragLeave() Table of Contents OnDragOver() C# and the .NET Platform, Second Edition
ResetFont()
These methods reset various UI attributes of a child control to the corresponding value of the parent. ResetCursor() Part One - Introducing C# and the .NET Platform Introduction
Chapter 1 - The Philosophy of .NET ResetForeColor() Chapter 2
- Building C# Applications
ResetBackColor()
Part Two - The C# Programming Language
OnPaint() Inheriting classes should override this method to handle the Paint Chapter 3 - C# Language Fundamentals Chapter 4
event. - Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime DragEnter These events are sent in response to drag-and-drop operations.
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
DragLeave
DragDrop Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies DragOver Chapter 9
Paint
- Understanding .NET Assemblies
This event is sent whenever the Control has become "dirty" and needs to be repainted.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
More Fun with the Control Class
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
To illustrate some of these additional Control members, the following class sets the background color of the Form object to "Tomato" (you just have to love the names of these colors), the opacity to 50 percent Chapter 16 - The System.IO Namespace (to generate a semi-transparent main window), and configures the mouse cursor to display an hourglass Chapter 17 - Data Access with ADO.NET icon. More important, let's handle the Paint event in order to render a text string into the Form's client area. Part Five - Web Applications and XML Web Services Here is the update: Chapter 15 - Programming with Windows Forms Controls
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
using System; using System.Windows.Forms; Index using System.Drawing; // Needed for Color, Brush, and Font types. Chapter 20 - XML Web Services List of Figures
List of Tables public class MainForm : Form
{ ... public MainForm() { // Set some properties that we have inherited from Control. BackColor = Color.Tomato; Opacity = 0.5d; this.Cursor = Cursors.WaitCursor; // Handle the Paint event. this.Paint += new PaintEventHandler(MainForm_Paint); } private void MainForm_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.DrawString("What a head trip...",
new Font("Times New Roman", 20), C#new and SolidBrush(Color.Black), the .NET Platform, Second Edition 40, 10); ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages)
} }
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural .NET If you run this application you issues will seeforthat thedevelopers. Form is indeed transparent!
Painting Basics
Table of Contents
C# and the .NET Platform, Second Edition
The most important aspect of this application is the handling of the Paint event. Notice that the delegate defines a method that takes a parameter of type PaintEventArgs. This type defines two properties to help Part One - Introducing C# and the .NET Platform you configure the current paint session for the Control as seen in Table 13-12. Introduction Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Table 13-12: Additional Control Properties
Part Two - The C# Programming Language
Chapter PaintEventArgs 3 - C# Language Property Fundamentals Meaning in Life Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
ClipRectangle
Gets the rectangle in which to paint
Chapter 6 - Interfaces and Collections Graphics Chapter 7
Gets the Graphics object used during a paint session
- Callback Interfaces, Delegates, and Events
Chapter The critical 8 - property AdvancedofC# PaintEventArgs Type Construction is Graphics, Techniques which is called to retrieve a Graphics object to use Part during Three the- painting Programming session. with You .NET examine Assemblies this class
(and GDI+ in general) in greater detail in Chapter 14.
For now, understand that theAssemblies Graphics class defines a number of members that allow you to render Chapter 9 do - Understanding .NET text, geometric shapesAppDomains, and images onto a Control-derived Chapter 10 - Processes, Contexts, and Threads type. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Finally, in this example you also configured the Cursor property to display an hour-glass symbol whenever the mouse cursor is within the bounding rectangle of this Control. The Cursors type can be assigned to Chapter 12 - Object Serialization and the .NET Remoting Layer any member of the Cursors enumeration (e.g., Arrow, Cross, UpArrow, Help, and so forth): Part Four - Leveraging the .NET Libraries
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
public MainForm() { Chapter 16 - The System.IO Namespace ... Chapter 17 - Data Access with ADO.NET this.Cursor = Cursors.WaitCursor; Part Five - Web Applications and XML Web Services }
Chapter 15 - Programming with Windows Forms Controls
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services IndexSOURCE List ofCODE Figures List of Tables
The MoreControlBehaviors project is included under the Chapter 13 subdirectory.
C# and the .NET Platform, The ScrollableControl Class Second Edition by Andrew Troelsen
ISBN:1590590554
ScrollableControlApress is used to define a small number of members that allow your widget to support vertical © 2003 (1200 pages) and horizontal scrollbars. The most of overview the ScrollableControl type would have to be the This comprehensive intriguing text startsmembers with a brief of the AutoScroll property and the related AutoScrollMinSize property. For example, assume you wish to ensure C# language and then quickly moves to key technical and architectural issues for horizontal .NET developers. that if the end user resizes your Form, and vertical scrollbars are automatically inserted if the size of the client area is less than or equal to 300×300 pixels. Programmatically, your task is simple: Table of Contents
// Note that you need to reference the System.Drawing namespace // to gain access to the Size type. Introduction this.AutoScroll = true; Part One - Introducing C# and the .NET Platform this.AutoScrollMinSize= new System.Drawing.Size (300, 300); C# and the .NET Platform, Second Edition
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part - The C# Programming Language TheTwo ScrollableControl class takes care of
the rest. For example, if you had a Form that contained a
Chapter number3 of-child C# Language objects (buttons, Fundamentals labels, or whatnot), you would find that the scrolling logic ensures the
entire Form real estate is viewable. For the current Chapter 4 - Object-Oriented Programming with C# example, simply render a large block of text onto a Label object (see Figure 13-12). Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Figure Form GUI Chapter 14 - 13-12: A BetterScroll Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
At runtime, the Form will automatically display vertical and horizontal scrollbars when any part of the Label
Chapter 17 - Data with ADO.NET is not visible. TheAccess ScrollableControl class does define a number of additional members beyond AutoScroll Part - Web Applications Web Services andFive AutoScrollMinSize, butand not XML many. Also be aware that
when you wish to take greater control over the
Chapter 18process, - ASP.NET and Web Controls scrolling youWeb arePages able to create and manipulate individual ScrollBar types (such as HScrollBar Chapter 19 - ASP.NET Web Applications and VScrollBar). I'll leave it to you to check out the remaining members using online Help. Chapter 20 - XML Web Services IndexSOURCE List ofCODE Figures List of Tables
The ScrollForm project is included under the Chapter 13 subdirectory.
C# and theClass .NET Platform, Second Edition ContainerControl by Andrew Troelsen
ISBN:1590590554
ContainerControlApress defines support manage the focus of a given GUI item. In practice, the behavior © 2003 (1200to pages) defined by System.Windows.Forms.ContainerControl is much moreofuseful This comprehensive text starts with a brief overview the when you are building a Form that contains a number of child controls, and wish to allow the user to use C# language and then quickly moves to key technical and the Tab key to alternate focus. issues for .NET developers. obtain the currently selected control, force Using a small setarchitectural of members, you can programmatically another to receive focus, and so forth. Table 13-13 gives a rundown of some of the more interesting members. Table of Contents C# and the .NETMembers Platform, of Second Edition Table 13-13: the ContainerControl Type Introduction
ContainerControl in Part One - Introducing C# and theMeaning .NET Platform
Life
Member Chapter 1 - The Philosophy of .NET Chapter 2 - Building C# Applications ActiveControl ParentForm These properties allow you to obtain and set the active control, as Part Two - The C# Programming Language well as retrieve
Chapter 3
a reference to the Form that is hosting the item.
- C# Language Fundamentals
ProcessTabKey() This method you to programmatically activate the Tab key to Chapter 4 - Object-Oriented Programming withallows C# Chapter 5
set focus to the next available control. - Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
On a related note, recall that all descendents of System.Windows.Forms.Control inherit the TabStop and - Callback Interfaces, Delegates, and Events TabIndex properties. As you might be able to guess, these items are used to set the tab order of controls Chapter 8 - Advanced C# Type Construction Techniques maintained by a parent container, and are used in conjunction with the members supplied by the Part Three - Programming with .NET Assemblies ContainerControl class. You revisit the issue of tab order during the discussion of programming controls Chapter 9 - Understanding .NET Assemblies (Chapter 15). Chapter 7
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The Form Class by Andrew Troelsen
ISBN:1590590554
This brings us to Apress the Form class itself, which is typically the direct base class for your custom Form types. In © 2003 (1200 pages) addition to the large set of members inherited Control, ScrollableControl, and ContainerControl This comprehensive text startsfrom with the a brief overview of the classes, the FormC# type adds even greater functionality. Let's start with the core properties (Table 13-14). language and then quickly moves to key technical and architectural issues for .NET developers.
Table 13-14: Properties of the Form Type Form Table of Contents
Meaning in Life Property C# and the .NET Platform, Second Edition Introduction
AcceptButton
Gets or sets the button on the Form that is clicked when the user presses the Enter key.
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET ActiveMDIChild of these properties is used within the context of an MDI application. Chapter 2 - Building C#Each Applications Part Two - The C# Programming Language IsMDIChild
Chapter 3
- C# Language Fundamentals
IsMDIContainer
Chapter 4
- Object-Oriented Programming with C# AutoScale or setsLifetime a value indicating whether the Form will adjust its size to fit the Chapter 5 - Exceptions Gets and Object Chapter 6
of the font used on the form and scale its controls. - Interfaces height and Collections
Chapter 7 - Callback Interfaces, Delegates, and style Events BorderStyle Gets or sets the border of the Form. Used in conjunction with the Chapter 8 - Advanced C# Type Construction Techniques FormBorderStyle enumeration. Part Three - Programming with .NET Assemblies
CancelButton Gets.NET or sets the button control that will be clicked when the user presses the Chapter 9 - Understanding Assemblies key. Chapter 10 - Processes, Esc AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based ControlBox Gets or sets a value indicating whetherProgramming the Form has a control box. Part Four - Leveraging the .NET Libraries
Menu12 - Object Serialization Gets or sets menuLayer for the Form. Chapter and the the (merged) .NET Remoting MergedMenu Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
MaximizeBox
Used to determine if this Form will enable the maximize and minimize boxes.
Chapter 15 - Programming with Windows Forms Controls
MinimizedBox
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET ShowInTaskbar Should this Form be seen on the Windows taskbar? Part Five - Web Applications and XML Web Services
StartPosition
Gets or sets the starting position of the Form at run time, as specified by the FormStartPosition enumeration.
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services WindowState Configures how the Form is to be displayed on startup. Used in conjunction with Index the FormWindowState enumeration. List of Figures List of Tables
The truth of the matter is that the Form class does not define a great deal of additional methods. The bulk of a Form's functionality comes from the base classes you have already examined. However, Table 13-15 gives a partial list of some additional methods to be aware of. Table 13-15: Key Methods of the Form Type
Method of the Form Meaning LifeEdition C# and the .NET Platform,in Second Type by Andrew Troelsen Activate() Close()
ISBN:1590590554
Apress © 2003 (1200 pages)
Activate a given Form and give it focus.
This comprehensive text starts with a brief overview of the C# language andCloses then quickly moves to key technical and a Form. architectural issues for .NET developers.
CenterToScreen()
Places the Form on the dead center of the screen.
LayoutMDI()
Arranges each child Form (as specified by the LayoutMDI enumeration) within the parent Form.
Table of Contents
C# and the .NET Platform, Second Edition Introduction OnResize()
May be overridden to respond to Resize events.
Part One - Introducing C# and the .NET Platform
ShowDialog()
Displays a Form as a Modal dialog. More on dialog box programming at a later time.
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Finally, the Form class does define a number of Events (Table 13-16).
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Table 13-16: Select Events of the Form Type
Form6 Event in Life Chapter - InterfacesMeaning and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Activate
Sent when a Form is brought to the front of the active application.
Part Three -Closing Programming with .NET Assemblies Closed, These events are used to
Chapter 9
determine when the Form is about to close, or has
- Understanding closed. .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
MDIChildActive
Sent when a child window is activated.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Fun with the Form Class
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
At this point, you should feel quite comfortable with the functionality provided by the Form class and each of its parent classes. Here is a main window (MainForm) that makes use of various members in the inheritance Chapter 16 - The System.IO Namespace chain: Chapter 15 - Programming with Windows Forms Controls Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
public class MainForm: Form { Chapter 19 - ASP.NET Web Applications ... Chapter 20 - XML Web Services public MainForm () Index { List of Figures // Configure the initial look and feel of this form. List of Tables BackColor = Color.LemonChiffon; // Background color. Text = "My Fantastic Form"; // Form's caption. Size = new Size(200, 200); // 200 * 200. CenterToScreen(); // Center Form to the screen. // Handle events. this.Resize += new EventHandler(this.Form1_Resize); this.Paint += new PaintEventHandler(this.Form1_Paint); } private void MainForm_Resize(object sender, System.EventArgs e) { Invalidate(); } // Reference System.Drawing to render this string. private void MainForm_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Chapter 18 - ASP.NET Web Pages and Web Controls
g.DrawString("Windows Forms is for building GUIs!", C# and the .NET SecondNew Edition new Platform, Font("Times Roman", 20), ISBN:1590590554 by Andrew Troelsen new SolidBrush(Color.Black), Apress © 2003 (1200 pages) this.DisplayRectangle); // Display in client rect. This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
} }
Here, a Form object that begins life centered on the screen has been created. In addition, the Resize event has been handled. Simply call Invalidate() to force the client area to be refreshed. In this way, the text string C# and the .NET Platform, Second Edition rendered on the client area always fits within the bounding rectangle Form's client area (note the use of the Introduction DisplayRectangle property).
Table of Contents
Part One - Introducing C# and the .NET Platform
Chapter SOURCE 1 - The Philosophy The SimpleFormApp of .NET can be found under the Chapter 13 subdirectory.
CODE Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and Platform, Form Second Edition The Life-Cycle ofthea .NET Windows Type by Andrew Troelsen
ISBN:1590590554
If you have programmed interfaces Apress © user 2003 (1200 pages) using GUI toolkits such as Java Swing, MFC or the raw Win32 API, you are aware that Window types have number ofaevents which fire its lifetime. The same holds true This comprehensive texta starts with brief overview of during the for System.Windows.Forms.Form-derived types. Table 13-17 documents lifetime-centric Form level events. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 13-17: Form Life Time Events Form Table of Contents
Meaning in Life Lifetime C# and the .NET Platform, Second Edition Event Introduction Part One - Introducing C# and the .NET Platform
Activated
Occurs whenever the Form is activated, meaning the Form has been given the current focus on the desktop.
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Closing Occurs when a Form Part Two - The C# Programming Language
is about to be closed completely. As you will see, this method allows you to prompt the user with the obligatory "Are you sure you Chapter 3 - C# Language Fundamentals wish to close this form" message. Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions This and Object Closed occursLifetime when the Form is truly closing down and is about to be disposed. Chapter 6 - Interfaces and Collections
Deactivate Occurs whenever Form is deactivated, meaning the Form has lost current Chapter 7 - Callback Interfaces, Delegates,the and Events Chapter 8
focus on the desktop.
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Load Occurs afterAssemblies the Form has
Chapter 9
been allocated into memory, but is not yet visible on
- Understanding .NET Assemblies the screen.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Dispose
As you have already seen, the Dispose() method is called automatically to allow the type to perform any clean up.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Of course, the true life of a Form begins when the Application.Run() method triggers the type's constructor. Once the object has been allocated on the heap, the first event that fires is Load. Within Load, you are free to Chapter 14 - A Better Painting Framework (GDI+) configure the look and feel of Form (to augment the work preformed by the InitializeComponent() method), Chapter 15 - Programming with Windows Forms Controls prepare any contained child controls (such as ListBoxes, TreeViews, and whatnot), or simply allocate Chapter 16 -used The System.IO resources during the Namespace Form's operation (database connections, handles to remote objects, or whatnot). Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 17 - Data Access with ADO.NET Part Once Five the- Web LoadApplications event has fired, and XML the next Webevent Services is Activate.
As mentioned, this event fires when the Form
receives as theWeb active window on the desktop. The logical counterpart to the Activate event is (of Chapter 18focus - ASP.NET Pages and Web Controls course)19Deactivate, fires when the Form loses focus as the active window. As you can guess, the Chapter - ASP.NETwhich Web Applications Activate20and Deactivate events can fire numerous times over the life of a given Form type. Chapter - XML Web Services Index
When the user has chosen to close the Form in question, two close-centric events fire: Closing and Closed. The Closing event is fired first, and is an ideal place to prompt the end user with the much hated "Are you List of Tables sure you wish to close this application?" dialog box. As you are aware, this type of confirmation is quite helpful when you wish to ask the user if s/he wishes to save the current application-centric data. The Closing event works in conjunction with System.ComponentModel.CancelEventHandler delegate, which maps to methods that take a System.ComponentModel.CancelEventArgs type as its second argument (the first, as always is a System.Object). If you set the CancelEventArgs.Cancel property to "true," you prevent the Form from being destroyed and instruct it to return to normal operation. For example: List of Figures
// Assume you have handled the Closing event in the Form. private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { DialogResult dr = MessageBox.Show("Do you REALLY want to close this app?", "Closing event!", MessageBoxButtons.YesNo); if(dr == DialogResult.No) e.Cancel = true; else
e.Cancel = false; }
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Here, we display This a message box thattext contains Nooverview buttons, of and comprehensive starts Yes with and a brief thecapture which button was clicked via C# language thenon quickly moves key technical the returned DialogResult typeand (more this type andtodialog boxes inand general in Chapter 15). If the user architectural issues for .NET developers. property to true, thereby preventing the Form from clicks the No button, we set the CancelEventArgs.Cancel shutting down. Table of Contents Assuming the user does want to close the Form completely, the next event of the Form's life cycle is Closed. C# and you the .NET Platform, Second Edition Here, are able to clean up any acquired resources, write to log files, or what have you. Last but not least, Introduction the Dispose() method will be called to allow the Form to clean up any contained widgets. Part One - Introducing C# and the .NET Platform
Chapter 1
Philosophy of .NET A Form- The Lifetime Example
Chapter 2
- Building C# Applications
Part Two - The Programming Language To solidify theC# sequence of events that take
place during a Form's lifetime, assume you have a new
Chapter 3 - that C# Language Fundamentals application handles the Load, Activated, Deactivate, Closing, and Close events: Chapter 4 - Object-Oriented Programming with C# Chapter 5 MainForm() - Exceptions and Object Lifetime public Chapter 6 - Interfaces and Collections { Chapter InitializeComponent(); 7 - Callback Interfaces, Delegates, and Events Chapter this.Closing 8 - Advanced C# += Typenew Construction Techniques Part Three - Programming with .NET Assemblies System.ComponentModel.CancelEventHandler(this.MainForm_Closing);
Chapter this.Load 9 - Understanding += new .NETSystem.EventHandler(this.MainForm_Load); Assemblies
+= new System.EventHandler(this.MainForm_Closed); Chapter this.Closed 10 - Processes, AppDomains, Contexts, and Threads System.EventHandler(this.MainForm_Activated); Chapter this.Activated 11 - Type Reflection, += Latenew Binding, and Attribute-Based Programming new System.EventHandler(this.MainForm_Deactivate); Part Fourthis.Deactivate - Leveraging the .NET+= Libraries } Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
In each registered event handler, we are going to update a private System.String member variable (named lifeTimeInfo) with a simple message that displays the name of the event that has just been intercepted:
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
private void MainForm_Load(object sender, System.EventArgs e) { lifeTimeInfo += "Load event\n"; } Chapter 18 - ASP.NET Web Pages and Web Controls private void MainForm_Activated(object sender, System.EventArgs e) Chapter 19 - ASP.NET Web Applications { lifeTimeInfo += "Activate event\n"; } Chapter 20 - XML Web Services private void MainForm_Closing(object sender, Index System.ComponentModel.CancelEventArgs e) List { of Figures List of Tables ... lifeTimeInfo += "Closing event\n"; } private void MainForm_Deactivate(object sender, System.EventArgs e) { lifeTimeInfo += "Deactivate event\n"; } private void MainForm_Closed(object sender, System.EventArgs e) { lifeTimeInfo += "Closed event\n"; } Part Five - Web Applications and XML Web Services
Finally, in Dispose(), display your string using a MessageBox type: protected override void Dispose(bool disposing) { MessageBox.Show(lifeTimeInfo, "Life time events"); ... }
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
Now, run your application and(1200 shiftpages) the Form into and out of focus a few times (to trigger the Activate and Apress © 2003 Deactivate events). Once you shut down the Form, you will see a message box looking something like Figure This comprehensive text starts with a brief overview of the 13-13. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - 13-13: Interfaces andevents Collections Figure Form Chapter 7 - Callback Interfaces, Delegates, and Events
SOURCE FormLifeTime project can be found under the Chapter 13 subdirectory. Chapter 8 - AdvancedThe C# Type Construction Techniques CODE- Programming with .NET Assemblies Part Three Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Handing Form Level Events aSecond la VSEdition .NET by Andrew Troelsen
ISBN:1590590554
Although you areApress always© free handle 2003 to (1200 pages)Form-level events by authoring the necessary logic by hand, it is worth pointing outThis thatcomprehensive VS .NET offers design-time as well. Ifofyou text starts withsupport a brief overview the examine the IDE's Property Window, you will C# notice a small lightning bolt icon. Once selected, you will find the set of events for language and then quickly moves to key technical and architectural issues .NET developers. whatever GUI widget you select fromforthe drop-down list box mounted on the top of the Window. Simply locate the name of the event you wish to handle and type in the name to be used as an event handler (or simply double-click the event to generate a default name). Table of Contents
Forand example, 13-14 illustrates how you could handle the Load event for a given Form. C# the .NETFigure Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure 13-14: Form events
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
If you were to Serialization look at the code behind Form,Layer you would find that the InitializeComponent() Chapter 12 - now Object and the .NETyour Remoting method13has been updated handle(Introducing the given event, and aForms) empty event handler has been generated Chapter - Building a BettertoWindow Windows automatically. As youPainting might guess, this same technique can be used to autogenerate events for any GUI Chapter 14 - A Better Framework (GDI+) widget (as you will see over the course of this text).
Chapter 15 - Programming with Windows Forms Controls Chapter 16 The - Thedefault System.IO Note nameNamespace used to generate an event handler is formed as ClassName_EventName Chapter 17 therefore, - Data Access ADO.NET it is with always a good idea to name your GUI types appropriately before autogenerating Part Five - Web Applications and XML Web Services events (unless you like manually renaming
auto-generated code).
Chapter 18 - ASP.NET Web Pages and Web Controls
Note GUI Web widget has a default event, which simply refers to the event that will be handled if you Chapter 19 Every - ASP.NET Applications the item at design time. For example, a Form's default event is Load, and if you Chapter 20 double-click - XML Web Services Index
double-click anywhere on a Form type, the IDE will automatically write code to handle this event.
List of Figures List of Tables
C# and with the .NET Platform, Second Edition Building Menus Windows Forms by Andrew Troelsen
ISBN:1590590554
Now that you understand the composition Apress © 2003 (1200 pages) and lifecycle of the Form class, the next task is to learn how to establish a menuThis system to provide degree comprehensive some text starts withofauser briefinteraction. overview ofThe the System.Windows.Forms namespace provides a number of types that facilitate the building of main C# language and then quickly moves to key technical and menus (e.g., menus mounted at architectural for .NET developers. the top of a Form), as well as issues context-sensitive pop-up menus (e.g., "right-click" menus). To begin, let's examine what it would take to build a topmost menu that allows the user to exit the application using a standard "File | Exit" menu command. Table of Contents
The first be aware of is System.Windows.Forms.Menu, which functions as the base class for all C# and theclass .NETto Platform, Second Edition other menu-related classes (MainMenu, MenuItem, and ContextMenu). Be aware that Introduction System.Windows.Forms.Menu an abstract Part One - Introducing C# and theis.NET Platformclass,
and therefore you cannot create a direct instance of
this type. you createofinstances of one (or more) of the derived types. The Menu class defines basic Chapter 1 Rather, - The Philosophy .NET menu-centric behaviors such as providing access to an individual menu item, cloning menus, merging Chapter 2 - Building C# Applications menus MDI so forth. Part Two (for - The C#applications), Programming and Language
Figure 13-15 shows the relationship between these core types.
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Figure Menu-centric types of Windows Forms Chapter 9 - 13-15: Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 the - Type Reflection, Late Binding, and Attribute-Based Programming Note that Menu class defines a nested class named MenuItemCollection, which is inherited by the Part Four - Leveraging the .NET Libraries MainMenu, MenuItem, and ContextMenu
subclasses. As you would expect, this collection holds onto a set
Chapter 12 menu - Object Serialization the .NET Remoting Layer of related items, which isand accessed using the Menu.MenuItems property (more details in a moment). Chapter 13 Building a Better Window (Introducing Windows The Menu base class defines the core members shown inForms) Table 13-18. Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming Forms Controls Table 13-18: Members ofwith theWindows Menu Type Chapter 16 - The System.IO Namespace
Menu Member
Meaning in Life
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XMLprovides Web Services Handle This property access
to the underlying Win32 HMENU handle that
Chapter 18 - ASP.NET represents Web Pages and Controls this Web Menu. Chapter 19 - ASP.NET Web Applications
IsParent
This property specifies whether this menu contains any items or is the topmost item.
Chapter 20 - XML Web Services Index ListMdiListItem of Figures List of Tables
This property returns the MenuItem that contains the list of MDI child windows.
MenuItems
Another property. Returns an instance of the nested Menu.MenuItemCollection type, which represents the submenus owned by the Menu derived class.
GetMainMenu()
Returns the MainMenu item that contains this menu.
MergeMenu()
Merges another menu's items with this one's as specified by their mergeType and mergeOrder properties. Used to merge an MDI container's menu with that of its active MDI child.
CloneMenu()
Sets this menu to be an identical (deep) copy of another menu.
Menu$MenuItemCollection Type Perhaps the most immediately important member of the Menu class is the MenuItems property, which returns an instance of the nested Menu$MenuItemCollection type (recall that the the ;'$' notation is just a
convention to represent a nested type, and has nothing at all to do with C# or .NET code). Recall that C# and the .NET Platform, Second Edition nested classes can be helpful when you wish to establish a logical relationship between related types. ISBN:1590590554 by Andrew Troelsen type represents the set of Here, the Menu$MenuItemCollection all submenus owned by a Menu-derived Apress © 2003 (1200 pages) object. This comprehensive text starts with a brief overview of the C#created language then quickly moves to key technical and menu, you would add MenuItems For example, if you a and MainMenu to represent the topmost "File" architectural issues for .NET developers. (for example, Open, Save, Close, Save As) into the collection. As you would expect, Menu$MenuItemCollection defines members to add and remove MenuItem types, obtain the current count of MenuItems, as well as access a particular member in the collection. Table 13-19 lists some (but not all) Table of Contents of the core members. C# and the .NET Platform, Second Edition Introduction
Table 13-19: The Nested MenuItemCollection Type
Part One - Introducing C# and the .NET Platform
Menu$MenuItemCollection Chapter 1 - The Philosophy of .NET
Meaning in Life
Member Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Count
Chapter 3
- C# Language Fundamentals
Returns the number of MenuItems in the collection.
Add()4 Chapter
Inserts (or removes) a new MenuItem into the collection. - Object-Oriented Programming with C# (Add adds/ remove removes. Add does not remove.) Be Chapter 5 Exceptions and Object Lifetime AddRange() aware that the Add() method has been overloaded
Chapter 6
- Interfaces and Collections
Chapter 7
numerous times to allow you to specify shortcut keys, - Callback Interfaces, Delegates, and Events
Chapter 8
delegates, and whatnot. - Advanced C# Type Construction Techniques
Remove()
Part Three - Programming with .NET Assemblies AddRange()
Chapter 9
is helpful in that it allows you to add an array of
MenuItems in a single call. - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Clear()
Removes all items from the collection.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Contains() Part Four - Leveraging the .NET Libraries
Used to determine if a given MenuItem is inside the
collection. Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Building Your Menu System by Andrew Troelsen
ISBN:1590590554
Now that you understand the functionality Apress © 2003 (1200 pages) of the abstract Menu class (and the nested MenuItemCollection type), you can build your simple File text menu. Thewith process by creating This comprehensive starts a briefbegins overview of the a MainMenu object. The MainMenu class represents the collection of topmost menu items (e.g., C# language and then quickly moves to key technical andFile, Edit, View, Tools, Help, and architectural issues for .NET so forth) which appear on a Form type. Thus:developers. public class MainForm : Form { C# and the .NET Platform, Second Edition // The Form's main menu. Introduction private MainMenu mainMenu = new MainMenu(); Part One - Introducing C# and the .NET Platform ... Chapter 1 - The Philosophy of .NET }
Table of Contents
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter Once you 3 -have C# Language created aFundamentals MainMenu object, use the Menu$MenuItemCollection.Add() method to insert the
topmost (the "File" menu). Menu$MenuItemCollection.Add() returns a MenuItem object that Chapter 4 item - Object-Oriented Programming with C# represents newly inserted FileLifetime menu. Chapter 5 - the Exceptions and Object Chapter 6
- Interfaces and Collections
To insert the subitems (e.g., Exit), you insert MenuItem types into the Menu$MenuItemCollection - Callback Interfaces, Delegates, and Events maintained by the File MenuItem. Finally (and most important), when you are finished populating the Chapter 8 - Advanced C# Type Construction Techniques MainMenu type, attach it to the owning Form using the inherited Menu property. If you fail to do so, your Part Three - Programming with .NET Assemblies menu system will not be visible! Here are the relevant code updates: Chapter 7
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
public class MainForm : Form { Part Four - Leveraging the .NET Libraries // The Form's main menu. Chapter 12 - Object Serialization and the .NET Remoting Layer private MainMenu mainMenu = new MainMenu(); Chapter 13 - Building a Better Window (Introducing Windows Forms) public MainForm() Chapter { 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming Windows Forms Controls // Createwith the 'File' Menu and add it to the MenuItemCollection. Chapter 16 - The System.IO Namespace MenuItem miFile = mainMenu.MenuItems.Add("&File"); Chapter 17 - Data with ADO.NET // Access Now make the Exit MenuItem and add it to the File MenuItem. Part Five - Web// Applications and XML Web Servicestakes: This version of Add() Chapter 18 - ASP.NET Web Pages and Web Controls // 1) A new MenuItem. Chapter 19 - ASP.NET // 2)Web A new Applications delegate (EventHandler). //Web 3) Services An optional shortcut key. Chapter 20 - XML miFile.MenuItems.Add(new MenuItem("E&xit", Index new EventHandler(this.FileExit_Clicked), List of Figures Shortcut.CtrlX)); List of Tables // Attach main menu to the Form object. this.Menu = mainMenu; } ... } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Notice that if you embed an ampersand within the string name of a menu item, this marks which letter should be underlined to designate the Alt key access combination. Thus, when you specify "&File," you allow the user to activate the File menu by selecting "Alt+F." When you added the Exit submenu item, you specified an optional shortcut flag. The System.Windows.Forms.Shortcut enumeration is fully detailed in online Help. As you might guess, this enumeration provides fields that specify traditional shortcut keys (Ctrl+C, Ctrl+V, F1, F2, Ins) as well as more exotic combinations.
Here then, is the current code for the simple menu application. Just for kicks, notice how you are able to and the .NET Platform, Second Edition set the BackColorC# property of the Form using the MainMenu.GetForm() method: by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
// The Simple Menu Application. This comprehensive text starts with a brief overview of the public class C# MainForm : Form language and then quickly moves to key technical and { architectural issues for .NET developers. // The Form's main menu. private MainMenu mainMenu = new MainMenu(); Run the application. Table of // Contents public staticSecond void Edition Main(string[] args) C# and the .NET Platform, { Introduction Application.Run(new MainForm()); Part One - Introducing C# and the .NET Platform } Chapter 1 - The Philosophy of .NET form. Chapter// 2 Construct - Building C# the Applications public MainForm() Part Two - The C# Programming Language { Chapter 3 - C# Language Fundamentals // Configure the initial look and feel of this form. Chapter 4 - Object-Oriented Programming with C# Text = "Simple Menu"; Chapter 5 - Exceptions and Object Lifetime CenterToScreen(); Chapter 6 - Interfaces and Collections // Create the 'File | Exit' Menu. Chapter 7 - Callback Interfaces, Delegates, and Events MenuItem miFile = mainMenu.MenuItems.Add("&File"); Chapter 8 - Advanced C# Type Construction Techniques miFile.MenuItems.Add(new MenuItem("&Exit", Part Three - Programming with .NET Assemblies new EventHandler(this.FileExit_Clicked), Chapter 9 - Understanding .NET AssembliesShortcut.CtrlX)); Chapter 10 - Processes, AppDomains, Contexts, and Threads // Attach main menu to the Form object. Chapter 11 - Type Reflection,= Late Binding, and Attribute-Based Programming this.Menu mainMenu; Part Four - Leveraging the .NET Libraries // MainMenu.GetForm() returns a reference to the owning Form. Chapter 12 - Object and the .NET Remoting Layer // ToSerialization illustrate... Chapter 13 - Building mainMenu.GetForm().BackColor a Better Window (Introducing Windows = Color.Black; Forms) } Chapter 14 - A Better Painting Framework (GDI+) | Exit with Menu item Forms handler Chapter// 15 File - Programming Windows Controls private void FileExit_Clicked(object sender, EventArgs e) Chapter 16 - The System.IO Namespace { Chapter 17 - Data Access with ADO.NET this.Close(); // Services Just close the application... Part Five - Web Applications and XML Web } Chapter 18 - ASP.NET Web Pages and Web Controls } Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index
Adding Another Topmost Menu Item
List of Figures List of Tables
Now, what if you wish to add another topmost menu named "Help" that contains a single subitem named "About" (Figure 13-16)?
Figure 13-16: A more elaborate main menu The code models the "File | Exit" menu logic almost exactly: Begin by adding a new MenuItem ("Help") to the MainMenu object. From here, add a new subitem ("About"):
public class C# MainForm : Form and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen private Apress MainMenu mainMenu = new MainMenu(); © 2003 (1200 pages) ... This comprehensive text starts with a brief overview of the public MainForm() C# language and then quickly moves to key technical and { architectural issues for .NET developers. // Create the 'File | Exit' Menu. MenuItem miFile = mainMenu.MenuItems.Add("&File"); Table of Contents miFile.MenuItems.Add(new MenuItem("E&xit", newSecond EventHandler(this.FileExit_Clicked), C# and the .NET Platform, Edition Shortcut.CtrlX)); Introduction // NowC#create a 'Help | About' menu. Part One - Introducing and the .NET Platform MenuItem Chapter 1 - The Philosophy miHelp of .NET = mainMenu.MenuItems.Add("Help"); miHelp.MenuItems.Add(new MenuItem("&About", Chapter 2 - Building C# Applications new EventHandler(this.HelpAbout_Clicked), Part Two - The C# Programming Language Shortcut.CtrlA)); Chapter 3 - C# Language Fundamentals ... Chapter 4 - Object-Oriented Programming with C# } Chapter 5 - Exceptions and Object Lifetime // Help | About Menu handler Chapter 6 - Interfaces and Collections private void HelpAbout_Clicked(object sender, EventArgs e) Chapter 7 - Callback Interfaces, Delegates, and Events { Chapter 8 - Advanced C# Type Construction Techniques MessageBox.Show("The amazing menu app..."); Part Three - Programming with .NET Assemblies } Chapter 9 - Understanding .NET Assemblies } Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
SOURCE The SimpleMenu is located Chapter 12 - Object Serialization and the application .NET Remoting Layer under the Chapter 13 subdirectory. CODE Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Creating a C# Pop-Up Menu by Andrew Troelsen
ISBN:1590590554
Let's now examine the process of building a context-sensitive pop-up (i.e., right-click) menu. The Apress © 2003 (1200 pages) ContextMenu class represents the pop-up menu itself. Likeoverview the process of building a MainMenu, your goal This comprehensive text starts with a brief of the is to add individual MenuItems to the MenuItemCollection to represent the C# language and then quickly moves to key technical and possible selectable subitems. architectural issues .NETmenu developers. The following class makes use of a for pop-up to allow the user to configure the font size of a string rendered to the client area: Table of Contents
namespace MainForm { Introduction // Helper enum for font size. Part One - Introducing C# and the .NET Platform internal enum TheFontSize Chapter { 1 - The Philosophy of .NET Chapter 2 - Building C# Applications FontSizeHuge = 30, Part Two - The C# Programming Language FontSizeNormal = 20, Chapter 3 - C# Language Fundamentals FontSizeTiny = 8 Chapter } 4 - Object-Oriented Programming with C# C# and the .NET Platform, Second Edition
Chapter 5
- Exceptions and Object Lifetime
Chapter public 6 - Interfaces class andMainForm Collections : Form Chapter { 7
- Callback Interfaces, Delegates, and Events
Chapter 8
// Current of font. - Advanced C# Typesize Construction Techniques
private with TheFontSize currFontSize Part Three - Programming .NET Assemblies Chapter 9
= TheFontSize.FontSizeNormal; - Understanding .NET Assemblies
// The AppDomains, Form's popup menu. Chapter 10 - Processes, Contexts, and Threads private ContextMenu popUpMenu = new ContextMenu(); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming publicthestatic void Part Four - Leveraging .NET Libraries
Main(string[] args) { Application.Run(new MainForm()); } Chapter 12 - Object Serialization and the .NET Remoting Layer private void MainForm_Resize(object sender, System.EventArgs e) Chapter 13 - Building a Better Window (Introducing Windows Forms) { Invalidate(); } Chapter 14 - A Better Painting Framework (GDI+) public MainForm() Chapter 15 - Programming with Windows Forms Controls { Chapter 16 - The System.IO Namespace // Now add the subitems & attach context menu. Chapter 17 - Data Access with ADO.NET popUpMenu.MenuItems.Add("Huge", Part Five - Web Applications and Web Services newXML EventHandler(PopUp_Clicked)); Chapter 18 - ASP.NET popUpMenu.MenuItems.Add("Normal", Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications new EventHandler(PopUp_Clicked)); Chapter 20 - XML WebpopUpMenu.MenuItems.Add("Tiny", Services Index new EventHandler(PopUp_Clicked)); List of Figures this.ContextMenu = popUpMenu; // Handle events. List of Tables this.Resize += new System.EventHandler(this.MainForm_Resize); this.Paint += new PaintEventHandler(this.MainForm_Paint); } // PopUp_Clicked | X Menu item handler private void PopUp_Clicked(object sender, EventArgs e) { // Figure out the string name of the selected item. MenuItem miClicked = null; if (sender is MenuItem) miClicked = (MenuItem)sender; else return; string item = miClicked.Text; if(item == "Huge") currFontSize = TheFontSize.FontSizeHuge;
if(item == "Normal") C# and thecurrFontSize .NET Platform, Second Edition = TheFontSize.FontSizeNormal; ISBN:1590590554 by Andrew Troelsen if(item == "Tiny") Apress © 2003 (1200 pages) currFontSize = TheFontSize.FontSizeTiny; ThisInvalidate(); comprehensive text starts with a brief overview of the } C# language and then quickly moves to key technical and architectural issues for .NET developers.
private void MainForm_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Table of Contents g.DrawString("Please click on me...", C# and the .NET Platform, Second Edition new Font("Times New Roman", (float)currFontSize), Introduction new SolidBrush(Color.Black), Part One - Introducing C# and the .NET Platform this.DisplayRectangle); Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications } Part Two - The C# Programming Language } Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter Notice 5that- as Exceptions you add and the subitems Object Lifetime to the ContextMenu, you have assigned the same event handler to
each MenuItem type. When a given item is clicked, the flow of logic brings us to the PopUp_Clicked() Chapter 6 - Interfaces and Collections method. the "sender" argument, youand areEvents able to determine the textual name of the MenuItem and Chapter 7 Using - Callback Interfaces, Delegates, take an8appropriate of action (whichTechniques works just fine, assuming you are not interested in localizing Chapter - Advancedcourse C# Type Construction the Three application). Part - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
Also notice that once you have created a ContextMenu, you associate it to the Form using the Control.ContextMenu property. Be aware that any control can be assigned a context menu. For example, Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming you could create a Button object on a dialog box that responds to a particular context menu. In this way, Part Four - Leveraging the .NET Libraries the menu would only be displayed if the mouse button were clicked while within the bounding rectangle of Chapter 12 - Object Serialization and the .NET Remoting Layer the button. Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Adorning Your Menu System by Andrew Troelsen
ISBN:1590590554
The MenuItem class also defines number of members that allow you to check, enable, and hide a given Apress © 2003 (1200apages) menu item. TableThis 13-20 gives a rundown of some properties of MenuItem. comprehensive text starts withof a the briefinteresting overview of the C# language and then quickly moves to key technical and architectural for .NET developers. Table 13-20: More Details ofissues the MenuItem Type
MenuItem Member Table of Contents
Meaning in Life
C# and the .NET Platform, Second Edition
Checked
Introduction
Gets or sets a value indicating whether a check mark appears beside the text of the menu item
Part One - Introducing C# and the .NET Platform
DefaultItem Getsofor.NET sets a value indicating whether the menu item is the default Chapter 1 - The Philosophy Chapter 2
Enabled
- Building C# Applications
Gets or sets a value indicating whether the menu item is enabled
Part Two - The C# Programming Language
Index 3 Chapter
Gets or sets the menu item's position in its parent menu - C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
MergeOrder
Chapter 6
Gets or sets the relative position of the menu item when its menu is merged with another
- Interfaces and Collections MergeType Gets or sets a valueand that indicates the behavior of this menu item when its Chapter 7 - Callback Interfaces, Delegates, Events Chapter 8
menu merged withTechniques another - Advanced C# TypeisConstruction
Part Three - Programming with OwnerDraw Gets or.NET setsAssemblies a value indicating
whether code that you provide draws the
Chapter 9
- Understanding .NET Assemblies menu item or Windows draws the menu item Chapter 10 - Processes, AppDomains, Contexts, and Threads
RadioCheck Gets Late or sets a value indicates whether the menu item, if checked, Chapter 11 - Type Reflection, Binding, andthat Attribute-Based Programming displays a radio-button Part Four - Leveraging the .NET Libraries
mark instead of a check mark
Chapter 12 - Object Serialization and the Remoting Layer Shortcut Gets or sets the .NET shortcut key associated with the menu item Chapter 13 - Building a Better Window (Introducing Windows Forms)
ShowShortcut
Gets or sets a value that indicates whether the shortcut key that is associated with the menu item is displayed next to the menu item caption
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter Text 16 - The System.IO GetsNamespace or sets the text of the menu item Chapter 17 - Data Access with ADO.NET Part Five - Web Applications andMenuItem XML Web Services To illustrate further use of the type, let's
extend the previous pop-up menu to display a check
Chapter mark next 18 -toASP.NET the currently Web Pages selected andmenu Web Controls item. Setting a check mark on a given menu item is not at all
difficult19 (just set the Checked property to true). However, tracking which menu item should be checked Chapter - ASP.NET Web Applications does require some additional Chapter 20 - XML Web Services logic. One possible approach is to define distinct MenuItem objects that map to each possible submenu item and an additional MenuItem that represents the currently selected item: Index List of Figures
public class MainForm : Form List of Tables { ... // Used private private private private
to keep track of the current checked item. MenuItem currentCheckedItem; // Marks the item checked. MenuItem checkedHuge; MenuItem checkedNormal; MenuItem checkedTiny;
... }
The next step is to associate each of these MenuItems to the correct submenu. Thus, you would update the constructor as follows: // Construct the form.
public MainForm() C# and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen ... Apress © 2003 (1200 pages) // Set each MenuItem to the correct submenu. This comprehensive text starts with a brief overview of the checkedHuge = this.ContextMenu.MenuItems[0]; C# language and then quickly moves to key technical and checkedNormal = this.ContextMenu.MenuItems[1]; architectural issues for .NET developers. checkedTiny = this.ContextMenu.MenuItems[2]; // Now check the 'Normal' menu item. currentCheckedItem = checkedNormal; Table of Contents currentCheckedItem.Checked = true; C# and the .NET Platform, Second Edition } Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2 - Building C#aApplications At this point, you have way to programmatically identify each subitem, as well as the currently checked Part - The C#been Programming Language itemTwo (which has initially set to checkedNormal).
The last step is to update the PopUp_Clicked() event
Chapter C# Language Fundamentals handler3 to-check the correct MenuItem in response to the user selection (see Figure 13-17 for a test run): Chapter 4 - Object-Oriented Programming with C# Chapter 5 -void Exceptions and Object Lifetime private PopUp_Clicked(object sender, EventArgs e) Chapter 6 Interfaces and Collections { Chapter // 7 -Uncheck Callback Interfaces, Delegates, checked and Events item. the currently Chapter currentCheckedItem.Checked 8 - Advanced C# Type Construction Techniques = false; Part ...Three - Programming with .NET Assemblies
Chapter // 9 -Based Understanding on selection, .NET Assemblies establish the current checked menu item.
== "Huge") Chapter if(item 10 - Processes, AppDomains, Contexts, and Threads Chapter { 11 - Type Reflection, Late Binding, and Attribute-Based Programming
currFontSize = TheFontSize.FontSizeHuge; Part Four - Leveraging the .NET Libraries currentCheckedItem = checkedHuge; Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter } 13 - Building a Better Window (Introducing Windows Forms)
==Painting "Normal") Chapter if(item 14 - A Better Framework (GDI+) {
Chapter 15 - Programming with Windows Forms Controls
currFontSize = TheFontSize. FontSizeNormal; currentCheckedItem = checkedNormal;
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
} if(item == "Tiny") Chapter 18 - ASP.NET Web Pages and Web Controls { Chapter 19 - ASP.NET Web Applications currFontSize = TheFontSize. FontSizeTiny; Chapter 20 - XML Web Services currentCheckedItem = checkedTiny; Index } List of Figures // Now check it. List of Tables currentCheckedItem.Checked = true; Invalidate(); } Part Five - Web Applications and XML Web Services
Figure 13-17: Check-marking a menu item
SOURCE CODE
C# and .NET Platform, Edition The the PopUpMenu projectSecond is contained under the Chapter 13 subdirectory. ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Edition Building a Menu Using VisualSecond Studio .NET by Andrew Troelsen
ISBN:1590590554
Indeed, knowledge is power. the other hand, now that you understand how you can write raw C# code Apress © 2003On (1200 pages) to create and configure a menu system, examine howoverview Visual Studio This comprehensive text let's starts with a brief of the.NET can offer some design-time assistance. To begin, assume that you have created a new C# Windows C# language and then quickly moves to key technical and Application project workspace. architectural issues for .NET developers.
Using the Toolbox window, double-click the MainMenu icon. Once you do, you see a new icon appear at the icon tray of the design-time template. Furthermore, you see a design-time representation of your menu Table attached of Contents to the top of your Form. To add new menu items, simply double-click a slot and type away! Consider 13-18. Second Edition C# and theFigure .NET Platform, Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Figure 13-18: The integrated menu editor of VS .NET
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 handling - Programming Forms As far as events with for aWindows given item (as Controls well as configuring a number of other properties), select the Chapter 16 The System.IO Namespace MenuItem you wish to configure using the VS .NET Properties window (Figure 13-19). Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 13-19: Handing menu-centric events using VS .NET Once you enter the name of our event handler, the Visual Studio .NET IDE automatically generates stub code for the event handler: private void mnuFileExit_Clicked (object sender, System.EventArgs e) { // Respond to File | Exit selection...
} C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
© 2003 your (1200 menus pages) at design time, the IDE is updating the InitializeComponent() Be aware, that asApress you modify helper function, as well as adding member variables represent This comprehensive text starts with a to brief overviewthe of types the you are manipulating at design C# language then moves to familiar. key technical and time. If you examine the code,and things (I quickly hope) look very
architectural issues for .NET developers.
Note VS .NET also supports design-time configuration of pop-up menus. Simply drag a ContextMenu item onto your Form and edit the selections using the menu editor. Once this has been done, Table of Contents assign this object to the ContextMenu property of the widget you wish to leverage this pop-up. C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andStatus the .NET Platform, Understanding Bars Second Edition by Andrew Troelsen
ISBN:1590590554
In addition to a menu system, manypages) Forms also maintain a status bar. Status bars may be divided into any Apress © 2003 (1200 number of "panes." Panes hold some textual graphical) information such as menu help strings, or This comprehensive text starts(or with a brief overview of the other application-specific information. The StatusBar type derives directly C# language and then quickly moves to key technical and from architectural issues .NET developers. System.Windows.Forms.Control. In for addition to the inherited members, StatusBar defines the core properties shown in Table 13-21. Table of 13-21: Contents Table Select StatusBar Properties C# and the .NET Platform, Second Edition
StatusBar Introduction
Meaning in Life Property Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET BackgroundImage Gets or sets the image rendered on the background of the StatusBar - Building C# Applications control
Chapter 2
Part Two - The C# Programming Language
Font 3 Chapter
Gets or sets the font the StatusBar control will use to display information - C# Language Fundamentals
Chapter 4 - Object-OrientedGets Programming with C# ForeColor or sets the foreground color of the control Chapter 5 - Exceptions and Object Lifetime
Panels Returns a nested StatusBarPanelCollection type that contains each Chapter 6 - Interfaces and Collections Chapter 7
Panel maintained the StatusBar (much like the menu pattern) - Callback Interfaces, Delegates, andby Events
Chapter 8 - Advanced C# Type Techniques ShowPanels GetsConstruction or sets a value indicating whether panels should be shown Part Three - Programming with .NET Assemblies
SizingGrip GetsAssemblies or sets a value indicating whether a sizing grip will be rendered on Chapter 9 - Understanding .NET the corner of the StatusBar control
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Once you create a StatusBar, your next task is to add any number of panels (represented by the
Chapter 12 - Object Serialization and the StatusBar$StatusBarPanelCollection. .NET Remoting Layer StatusBarPanel class) into the nested Be aware that the constructor Chapter 13 Building a Better Window (Introducing Windows of StatusBarPanel automatically configures the new panelForms) with a default look and feel (therefore, if you Chapter 14 -with A Better Painting Frameworkyour (GDI+) are happy this initial configuration, programming task is made even simpler). Table 13-22 lists of Chapter 15members - Programming with Windows Forms the core of the StatusBarPanel type.Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Table 13-22: Properties of the StatusBarPanel Type Part Five - Web Applications and XML Web Services
StatusBarPanel Property
Meaning in Life
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web ServicesDetermines the alignment of text in the pane. Alignment Index List of Figures ListAutoSize of Tables
The default value is HorizontalAlignment.Left. Determines if this pane should automatically resize (and how). Default value is StatusBarPanelAutoSize.None.
BorderStyle
Configures border style. Default value is StatusBarPanelBorderStyle.Sunken.
Icon
Is there an icon in the pane? A null reference is the default (e.g., no icon).
MinWidth
Default is 10.
Style
What does this pane contain? Default is StatusBarPanelStyle.Text, but there may be other types as specified by the StatusBarPanelStyle enumeration.
Text
Caption of pane. The default is an empty string.
ToolTipText
Any tool-tip? An empty string is the default.
Width
is 100. Second Edition C# and theDefault .NET Platform, by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive Building a Status Bar text starts with a brief overview of the C# language and then quickly moves to key technical and
issues for .NET developers. To illustrate, let'sarchitectural construct a StatusBar object that is divided into two panes. The first pane is used to show helpful prompts describing the functionality of each menu selection. The second pane displays the current system time. And let's place a small icon on the far left side of the first pane (just to keep things Table of Contents interesting). Check out Figure 13-20. C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - 13-20: Interfaces and Collections Figure A custom status bar Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Assume have updated the.NET SimpleMenu application Part Threeyou - Programming with Assemblies
created earlier in this chapter, to support this status bar. Like any Control-derived type, the StatusBar needs to be added to the Form's Controls Chapter 9 - Understanding .NET Assemblies collection (more details on this collection in Chapter 15). As you might guess, this collection contains an Chapter 10 - Processes, AppDomains, Contexts, and Threads entry for any GUI widget mounted on the client area, including StatusBars types. Here is the status bar Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming logic: Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
public MainForm : Form Chapter 13 class - Building a Better Window (Introducing Windows Forms) {
Chapter 14 - A Better Painting Framework (GDI+)
// Member data for the status bar, and each pane. private StatusBar statusBar = new StatusBar(); Chapter 16 - The System.IO Namespace private StatusBarPanel sbPnlPrompt = new StatusBarPanel(); Chapter 17 - Data Access with ADO.NET private StatusBarPanel sbPnlTime = new StatusBarPanel(); Part Five - Web Applications and XML Web Services public MainForm () Chapter 18 - ASP.NET Web Pages and Web Controls { Chapter 19 - ASP.NET ... Web Applications Chapter 20 - XML Web Services BuildStatBar(); // Helper function. Index } Chapter 15 - Programming with Windows Forms Controls
List of Figures List of Tables private void BuildStatBar()
{ // Configure the status bar. statusBar.ShowPanels = true; statusBar.Size = new System.Drawing.Size(212, 20); statusBar.Location = new System.Drawing.Point(0, 216); // AddRange() allows you to add a set of panes at once. statusBar.Panels.AddRange(new StatusBarPanel[] { sbPnlPrompt, sbPnlTime}); // Configure prompt panel. sbPnlPrompt.BorderStyle = StatusBarPanelBorderStyle.None; sbPnlPrompt.AutoSize = StatusBarPanelAutoSize.Spring; sbPnlPrompt.Width = 62; sbPnlPrompt.Text = "Ready"; // Configure time pane. sbPnlTime.AutoSize = StatusBarPanelAutoSize.Spring;
sbPnlTime.Width = 120; and .NET Platform, Second Edition // C# Add antheicon. ISBN:1590590554 by Andrew Troelsen try Apress © 2003 (1200 pages) { This// comprehensive startsbe with of the This icontext must ina brief theoverview same app directory. C# language and then quickly moves to key technical andembed // Chapter 14 will illustrate how to architectural issues for .NET developers. // resources into your assembly! Icon i = new Icon("status.ico"); sbPnlPrompt.Icon = i; Table of Contents } C# and the .NET Platform, Second Edition catch(Exception e) Introduction { Part One - Introducing C# and the .NET Platform MessageBox.Show(e.Message); Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications // Now add this new status bar to the Form's Controls collection. Part Two - The C# Programming Language this.Controls.Add(statusBar); Chapter } 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# } Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques Working with the Timer Type
Part Three - Programming with .NET Assemblies
Chapter Understanding .NET Assemblies Recall 9that- the second pane should display the current time. The first step to take to achieve this design Chapter - Processes, AppDomains, Contexts, Threads goal is 10 to add a Timer member variable to theand Form. If you have a Visual Basic background, you should Chapter 11 - this Typeobject Reflection, and Attribute-Based Programming understand quite Late well.Binding, Win32/C++ programmers also understand the notion of timers given the Part Four - Leveraging the .NET Libraries WM_TIMER message. Regardless of your
background, a Windows Forms Timer object is simply a type
Chapter 12 some - Object Serialization andby thethe .NET Remoting Layer that calls method (specified Tick event) at a given interval (specified by the Interval property). Chapter Table 13-23 13 - Building lists some a Better core Window members. (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Table 13-23: The Timer Type Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Timer Member
Meaning in Life
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter Enabled 18 - ASP.NET This Web property Pages and enables Web or Controls disables the Timer's ability to fire the Tick event. You
may also use Start() and Stop() to achieve the same effect. Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Interval
Index
Sets the number of milliseconds between ticks.
ListStart() of Figures
Like the Enabled property, these methods control the
List of Tables
Stop()
firing of the Tick event.
OnTick()
This member may be overridden in a custom class deriving from Timer.
Tick
The Tick event adds a new event handler to the underlying MulticastDelegate.
Thus, you can update our class as follows: public class MainForm : Form { ... private Timer timer1 = new Timer(); public MainForm () { // Configure the timer. timer1.Interval = 1000;
timer1.Enabled = true; C# and the .NET Second Edition timer1.Tick += Platform, new EventHandler(timer1_Tick); ISBN:1590590554 by Andrew Troelsen ... Apress © 2003 (1200 pages) } comprehensive starts with a brief overview of the // This This method will betext called (roughly) every second. C# language and then quickly moves to key technical and private void timer1_Tick(object sender, EventArgs e) architectural issues for .NET developers. { DateTime t = DateTime.Now; string s = t.ToLongTimeString(); Table of Contents // Change text of pane to current time. C# and the .NET Platform, Second Edition sbPnlTime.Text = s; Introduction } Part One - Introducing C# and the .NET Platform } Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter C# Timer Language Fundamentals Notice 3that- the event handler makes use of the DateTime type. Here, you simply find the current Chapter - Object-Oriented Programming system4time using the Now property, and with use itC# to set the Text property of the correct StatusBarPanel Chapter object. 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
- Callback Interfaces, Delegates, and Events Displaying Menu Selection Prompts
Chapter 7 Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with Finally, you must configure the.NET firstAssemblies pane to hold
menu help strings. As you know, most applications send
Chapter a small9bit-ofUnderstanding text information .NET to Assemblies the first pane of a status bar whenever the end user selects a menu item
(e.g., "This the application"). Chapter 10 - terminates Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Assume the menu system for this application is identical to the Simple Menu application. This time, however, you need to respond to the Select event of each subitem. When the user selects "File | Exit" or Chapter 12 - Object Serialization and the .NET Remoting Layer "Help | About" you tell the first StatusBarPanel object to display a given text message. Note, you also Chapter 13 - Building a Better Window (Introducing Windows Forms) handle the MenuComplete event (described in the bold code comment below). Here is the update: Part Four - Leveraging the .NET Libraries
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
public class MainForm: Form { Chapter 17 - Data Access with ADO.NET ... Part Five - Web Applications and XML Web Services public MainForm () Chapter 18 - ASP.NET Web Pages and Web Controls { Chapter 19 - ASP.NET Web Applications ... Chapter 20 - XML //Web TheServices MenuComplete event is sent when the user clicks off Index // the menu. We want to capture this event in order to List of Figures // set the text of the first pane to "Ready". If we did not, List of Tables // the StatusBarPanel text would always be based on the last menu // selected! this.MenuComplete += new EventHandler(StatusForm_MenuDone); BuildMenuSystem(); } private void FileExit_Selected(object sender, EventArgs e) { sbPnlPrompt.Text = "Terminates this app"; } private void HelpAbout_Selected(object sender, EventArgs e) { sbPnlPrompt.Text = "Displays app info"; } private void StatusForm_MenuDone(object sender, EventArgs e) { sbPnlPrompt.Text = "Ready"; // See big comment in ctor... } // Helper functions. private void BuildMenuSystem() { Chapter 16 - The System.IO Namespace
// First make the main menu. C# and the .NET MainMenu(); Platform, Second Edition mainMenu = new ISBN:1590590554 by Andrew Troelsen // Create the 'File' Menu. Apress © 2003 (1200 pages) MenuItem miFile = mainMenu.MenuItems.Add("&File"); This comprehensive text starts with a brief overview of the miFile.MenuItems.Add(new MenuItem("E&xit", C# language and then quickly moves to key technical and new EventHandler(this.FileExit_Clicked), architectural issues for .NET developers. Shortcut.CtrlX)); // Handle the Select event for the Exit menu item. miFile.MenuItems[0].Select += new EventHandler(FileExit_Selected); Table of Contents // Now create a 'Help | About' menu. C# and the .NET Platform, Second Edition MenuItem miHelp = mainMenu.MenuItems.Add("Help"); Introduction miHelp.MenuItems.Add(new MenuItem("&About", Part One - Introducing C# and the .NET Platform new EventHandler(this.HelpAbout_Clicked), Chapter 1 - The Philosophy of .NET Shortcut.CtrlA)); Chapter 2 - Building C# Applications // Handle the Select event for the About menu item. Part Two - The C# Programming Language miHelp.MenuItems[0].Select += Chapter 3 - C# Language Fundamentals new EventHandler(HelpAbout_Selected); Chapter 4 - Object-Oriented Programming C# Form object. // Attach main menu with to the Chapter 5 - Exceptions and Object Lifetime this.Menu = mainMenu; Chapter } 6 - Interfaces and Collections Chapter ... 7 - Callback Interfaces, Delegates, and Events Chapter } 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies Excellent! you may AppDomains, guess, the Visual Studio IDE also provides some design-time assistance to facilitate Chapter 10 -As Processes, Contexts, and Threads
the building of status bar objects. In just a bit, you examine how to build a toolbar using tools provided by the IDE. Once you understand this process, you should have no problems designing status bars using the Part Four - Leveraging the .NET Libraries design-time tools. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building aThe Better Window (Introducing SOURCE StatusBarApp project isWindows includedForms) under the Chapter 13 subdirectory. Chapter 14 - A Better Painting Framework (GDI+) CODE Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andBar the .NET Platform, Second Edition Building a Tool by Andrew Troelsen
ISBN:1590590554
The final Form level GUI© item to examine Apress 2003 (1200 pages) in this chapter is the ToolBar type. As you know, tool bars typically provide an alternate means to activate a given Thus, if the user would rather click a Save button, This comprehensive text starts menu with a item. brief overview of the this has the sameC# effect as selecting "File | Save." In the Windows Forms language and then quickly moves to key technical and namespace, a handful of types are architectural issues for .NET developers. defined to allow you to build such a beast. Let's start with the ToolBar class itself. Note the core properties as seen in Table 13-24. Table of 13-24: Contents Table Properties of the ToolBar Type C# and the .NET Platform, Second Edition
ToolBar Introduction
Meaning in Life Property Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET BorderStyle The kind of border around this control, as specified by the BorderStyle - Building C# enumeration. Applications
Chapter 2
Part Two - The C# Programming Language
Buttons The collection of buttons belonging to the toolbar (e.g., Chapter 3 - C# Language Fundamentals Chapter 4
ToolBar$ToolBarButtonCollection). - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime ButtonSize Determines the size of a button in the ToolBar. Chapter 6 - Interfaces and Collections
ImageList Returns Delegates, the ImageList Chapter 7 - Callback Interfaces, and control Events that maintains the images for this ToolBar. Chapter 8 - Advanced C# Type Construction Techniques ImageSize The method to return the size of the images within the toolbar's image list. Part Three - Programming with .NET Assemblies
ShowToolTips Indicates whether or not the ToolBar will show tool tips for each button. Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Wrappable ToolBar buttons can optionally "wrap" to the next line when the ToolBar Chapter 11 - Type Reflection, Late Binding, and to Attribute-Based Programming becomes too narrow include all buttons on the same line. Part Four - Leveraging the .NET Libraries
Chapter - Object Serialization and the When a12Form maintains a ToolBar (or .NET two), Remoting the goal isLayer to create some number of individual ToolBarButton Chapter 13 Building a Better Window (Introducing Windows Forms) objects and add them to the ToolBar$ToolBarButtonCollection type. Each button may contain text, images, Chapter or both.14To- keep A Better things Painting simple, Framework let's build (GDI+) a toolbar containing two buttons displaying text prompts only. Table
13-25 presents some important members of the ToolBarButton. Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Table 13-25: Properties of the ToolBarButton Type Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
ToolBarButton Property
Meaning in Life
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
DropDownMenu ToolBarButtons can optionally specify a pop-up menu that is shown Chapter 20 - XML Web Services Index List of Figures List of Tables
whenever the drop-down button is pressed. This property lets you control just which menu is shown. Note that this is only shown if the Style property is set to DropDownButton.
ImageIndex
Returns the index of the image that this ToolBarButton is using. The index comes from the parent ToolBar's ImageList.
Style
Returns the style of the ToolBar button. This will form the ToolBarButtonStyle enumeration.
Text
The caption that will be displayed in this ToolBar button.
ToolTipText
If the parent ToolBar has the ShowToolTips property turned on, then this property describes the text that will be displayed for this button.
Visible
Indicates whether the button is visible or not. If the button is not visible, it will not be shown and will be unable to receive user input.
Your custom toolbar will contain two buttons, echoing the behavior supplied by the Save and Exit menu items. Here is the code update:
public class MainForm: Form C# and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen // State data for the toolbar and two buttons. Apress © 2003 (1200 pages) private ToolBarButton tbSaveButton = new ToolBarButton(); comprehensive text starts with a brief overview of the private This ToolBarButton tbExitButton = new ToolBarButton(); C# language and then quickly moves to key technical and private architectural ToolBar toolBar = new ToolBar(); issues for .NET developers. public MainForm() { ... Table of Contents C# and the .NETBuildToolBar(); Platform, Second Edition // Helper function. } Introduction void BuildToolBar() Part Oneprivate - Introducing C# and the .NET Platform { Chapter 1 - The Philosophy of .NET // Configure each button. Chapter 2 - Building C# Applications tbSaveButton.Text = "Save"; Part Two - The C# Programming Language tbSaveButton.ToolTipText = "Save"; Chapter 3 - C# Language Fundamentals tbExitButton.Text = "Exit"; Chapter 4 - Object-Oriented Programming with C# tbExitButton.ToolTipText = "Exit"; Chapter 5 - Exceptions and Object Lifetime // Configure ToolBar and add buttons. Chapter 6 - Interfaces and Collections toolBar.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; Chapter 7 - Callback Interfaces, Delegates, and Events toolBar.ShowToolTips = true; Chapter 8 - Advanced C# Type Construction TechniquesToolBarButton[] toolBar.Buttons.AddRange(new Part Three - Programming with .NET Assemblies { tbSaveButton, tbExitButton} ); Chapter 9 - Understanding .NET Assemblies+= new toolBar.ButtonClick Chapter 10 - Processes, AppDomains, Contexts, and Threads ToolBarButtonClickEventHandler(ToolBar_Clicked)); Chapter 11 - Type andthe Attribute-Based // Reflection, Add the Late newBinding, bar to ControlsProgramming collection. Part Four - Leveraging the .NET Libraries this.Controls.Add(toolBar); Chapter } 12 - Object Serialization and the .NET Remoting Layer handler. Chapter // 13 -Button Building aclick Better Window (Introducing Windows Forms) private void ToolBar_Clicked(object sender, ToolBarButtonClickEventArgs e) Chapter 14 - A Better Painting Framework (GDI+) { Chapter 15 - Programming with Windows Forms Controls MessageBox.Show(e.Button.ToolTipText); Chapter 16 - The System.IO Namespace } Chapter 17 - Data Access with ADO.NET ...Five - Web Applications and XML Web Services Part } Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 -run XML Web Services things will look quite bland (after all, how many toolbars display only text)? You When you the application, Index will add some images in just a moment, but first let's analyze some code. The BuildToolBar() helper function List of Figures begins by configuring some basic properties for each ToolBarButton. Next, add them to the ToolBar List of Tables collection using the AddRange() method (rather than calling Add() multiple times). To handle the Click
events for a given button, you must handle the ButtonClick event. toolBar.ButtonClick += new ToolBarButtonClickEventHandler(ToolBar_Clicked);
The ToolBarButtonClickEventHandler delegate can only call methods taking a second parameter of type ToolBarButtonClickEventArgs. This type may be examined to determine which button sent the event, using the Button property: private void ToolBar_Clicked(object sender, ToolBarButtonClickEventArgs e) { // Just show the corresponding tool bar text. MessageBox.Show(e.Button.ToolTipText); }
C# and the .NET Platform, Second Edition by Andrew Troelsen Adding Images to Your Toolbar Buttons Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview your of the Real Toolbar buttons contain images. When you wish to configure buttons to do so, the first step is to C# language and then quickly moves to key technical and have the Form create an ImageList type. This class represents a set of images that are consumed by some architectural issues for .NET developers. other type (like a ToolBar). If you have ever created a toolbar using Visual Basic 6.0, you should feel right at home with this aspect of Windows Forms. Let's update your existing ToolBarForm to make use of two icons for display purposes, in addition to simple text strings. Here is the relevant update: Table of Contents C# and the .NET Platform, Second Edition
public class MainForm: Form Introduction { One - Introducing C# and the .NET Platform Part theof images used by the toolbar. Chapter // 1 -Contains The Philosophy .NET ImageList toolBarIcons = new ImageList(); Chapter private 2 - Building C# Applications Part Two... - The C# Programming Language
void BuildToolBar() Chapter private 3 - C# Language Fundamentals { - Object-Oriented Programming with C# // Configure save button. Chapter 5 - Exceptions and Object Lifetime tbSaveButton.ImageIndex = 0; Chapter 6 - Interfaces and Collections tbSaveButton.ToolTipText = "Save"; Chapter 7 - Callback Interfaces, Delegates, and Events // Configure exit button. Chapter 8 - Advanced C# Type Construction Techniques tbExitButton.ImageIndex = 1; Part Three - Programming with .NET Assemblies tbExitButton.ToolTipText = "Exit"; Chapter 9 - Understanding Assemblies // Create .NET ToolBar and add buttons. Chapter 10 - Processes, AppDomains, Contexts, and Threads toolBar.ImageList = toolBarIcons; Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming ... Part Four - Leveraging the .NET Libraries // Load images (again, the icons need to be in the app dir). Chapter 12 - Object Serialization and the .NET Remoting toolBarIcons.ImageSize = new Layer System.Drawing.Size(32, 32); Chapter 13 - Building a Better Window (Introducing Windows Forms) toolBarIcons.Images.Add(new Icon("filesave.ico")); Chapter 14 - A toolBarIcons.Images.Add(new Better Painting Framework (GDI+) Icon("fileexit.ico")); toolBarIcons.ColorDepth = ColorDepth.Depth16Bit; Chapter 15 - Programming with Windows Forms Controls toolBarIcons.TransparentColor = System.Drawing.Color.Transparent; Chapter 16 - The System.IO Namespace ...Access with ADO.NET Chapter 17 - Data Part Five}- Web Applications and XML Web Services } Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 4
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Notice the following points:
Index
List ofYou Figures must tell each ToolBarButton which image to use, via the ImageIndex property. List of Tables
You add new images to the ImageList class using the Images.Add() method. The ToolBar itself must be told which ImageList it is associated with using the ImageList property. If you now run the application (Figure 13-21), you will see a much more pleasing end result (if you wish these buttons to look more standard, simply adjust the size to 16 × 16):
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents
Figure 13-21: A custom toolEdition bar C# and the .NET Platform, Second Introduction Part One - IntroducingThe C# and the .NET Platform SOURCE SimpleToolBar project
is included under the Chapter 13 subdirectory.
Chapter 1 - The Philosophy of .NET CODE Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the at .NET Platform,Time Second Edition Building ToolBars Design by Andrew Troelsen
ISBN:1590590554
As you would guess, VS©.NET has pages) design-time support for constructing toolbar entities. The first step is to Apress 2003 (1200 drag a ToolBar from the Toolbox window onto your design-time template. This comprehensive text starts with a brief overview of the Design-time configuration of the ToolBar is accomplished using the Properties Window. For example, if you wish to add buttons to the C# language and then quickly moves to key technical and architectural for property. .NET developers. ToolBar type, double-click theissues Buttons This opens a dialog that allows you to add, remove, and configure the individual ToolBarButton items (Figure 13-22). Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - 13-22: Type Reflection, Figure ToolbarsLate a la Binding, VS .NETand Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Adding an ImageList at Design Time
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Notice 15 how- this same dialog allowsForms you toControls assign an iconic image to each button using the Chapter Programming withalso Windows ImageIndex property. However, this property is useless until you add an ImageList type to your current Chapter 16 - The System.IO Namespace project.17 To- add ImageList member to a Form at design time, return to the Toolbox window and doubleChapter Dataan Access with ADO.NET clickFive the-icon. this point, and you XML can use Properties Part Web At Applications Webthe Services
window to add the individual images using the Images property. Once you have added each image file to the ImageList, inform the ToolBar which Chapter 18 - ASP.NET Web Pages and Web Controls ImageList it is to make use of using the Properties window (Figure 13-23). Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 13-23: Assigning an ImageList via VS .NET At this point, return to the ToolBar button editor and map a given image in the ImageList to each button (Figure 13-24).
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
C# Language Fundamentals Figure- 13-24: Assigning images to ToolBar buttons
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime Cool! Now you understand how to make use of the Visual Studio .NET IDE to configure a ToolBar Chapter 6 - that Interfaces and Collections
type, I assume you will continueDelegates, to exploreand similar design-time configurations. For example, using (more or Chapter 7 - Callback Interfaces, Events less) the same process, you can design a fully functional status bar with minimal coding on your part. - Advanced C# Type Construction Techniques
Chapter 8
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Building anC#MDI Application by Andrew Troelsen
ISBN:1590590554
To wrap up your initial at (1200 Windows Apresslook © 2003 pages)Forms, I'll close this chapter by examining how to configure a Form to function This as a comprehensive parent to any number of child (i.e., an text starts with awindows brief overview of MDI the container). MDI applications allow the user to C# have multiple windows open at a single time, with each language and then quickly moves to key technical and window representing a given forof .NET developers. "document" of thearchitectural application.issues By way an example, VS .NET is an MDI application in that you are able to have multiple documents open from within an instance of the application. Table When of you Contents are building MDI applications using Windows Forms, your first task is to (of course) create a
brand-new Windows Application. The initial Form of the application typically hosts a menuing system that C# and the .NET Platform, Second Edition allows the user to create new documents (such as File | New) as well as arrange existing open windows Introduction (cascade, vertical tile,C# and horizontal Part One - Introducing and the .NET tile). Platform Chapter 1
- The Philosophy of .NET
The child windows are interesting in that you typically have a prototypical Form that functions as a basis for - Building C# Applications each child window. Given that Forms are class types, any private data defined in the child Form will be Part Two - The C# Programming Language unique to a given instance. For example, if you were to create an MDI word processing application, you Chapter 3 - C# Language Fundamentals might create a child Form that maintained a collection of Strings to represent a given line of text. If the user Chapter 4 - Object-Oriented Programming with C# created five new child windows, each Form would maintain its own copy of the underlying collection and Chapter 5 treated - Exceptions and Object Lifetime could be individually. Chapter 2
Chapter 6
- Interfaces and Collections Additionally, MDI applications you toand "merge menus." As mentioned previously, parent windows Chapter 7 - Callback Interfaces,allow Delegates, Events
typically8 have a menu C# system allows the user to spawn and organize additional child windows. Chapter - Advanced Type that Construction Techniques However, if the childwith window maintains Part Three -what Programming .NET also Assemblies
a menuing system? If the user maximizes a particular child window, you need to merge the child's menu system within the parent Form to allow the user to Chapter 9 - Understanding .NET Assemblies activate items from each menu system. The Windows Forms namespace defines a number of properties, Chapter 10 - Processes, AppDomains, Contexts, and Threads methods, and events that allow you to programmatically merge menu systems. In addition, there is a Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming "default merge" system, which works in a good number of cases. I leave it as a task for the interested Part Four - Leveraging the .NET Libraries reader to investigate this aspect of MDI applications. Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Building the Parent Form
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
To illustrate the basics of building an MDI application, begin by creating a brand-new Windows Application named MDIApp. Almost all of the MDI infrastructure can be assigned to your initial Form using various Chapter 17 - Data Access with ADO.NET design-time tools. To begin, locate the IsMdiContainer property in the Property window and set it to True. If Part Five - Web Applications and XML Web Services you look at the design-time Form, you see that the client area has been modified to visually represent a Chapter 18 - ASP.NET Web Pages and Web Controls container of child windows. Chapter 16 - The System.IO Namespace
Chapter 19 - ASP.NET Web Applications
Chapter 20place - XMLa Web Next up, new Services MainMenu widget on your main Form. This menu specifies three topmost MenuItems Index named "File," "Window," and "Arrange Windows." The File menu contains two subitems named "New" List andof"Exit." Figures The Window does not contain any subitems, as you will programmatically add new items as the
user List of creates Tables additional child windows. Finally, the Arrange Window menu defines three subitems named "Cascade," "Vertical," and "Horizontal." Figure 13-25 offers a high-level design-time view.
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3 - 13-25: C# Language Fundamentals Figure The parent window's menu system Chapter 4 - Object-Oriented Programming with C#
Given that already and doveObject into the muck of coding raw menu logic during this chapter, simply use the Chapter 5 -you Exceptions Lifetime IDE to generate event and handlers for each submenu. You'll implement the File | New handler in the next Chapter 6 - Interfaces Collections section—however, is the code behindand theEvents remaining menu selections (remember, the Window menu Chapter 7 - Callbackhere Interfaces, Delegates, does not have any sub-items just yet): - Advanced C# Type Construction Techniques
Chapter 8
Part Three - Programming with .NET Assemblies
// Handle close event arrange all child windows. Chapter 9 - Understanding .NETand Assemblies private mnuFileExit_Click(object sender, System.EventArgs e) Chapter 10 -void Processes, AppDomains, Contexts, and Threads { this.Close(); } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming private void mnuArrangeCascade_Click(object Part Four - Leveraging the .NET Libraries
sender, System.EventArgs e) { LayoutMdi(MdiLayout.Cascade); } Chapter 12 - Object Serialization and the .NET Remoting Layer private void mnuArrangeVert_Click(object sender, System.EventArgs e) Chapter 13 - Building a Better Window (Introducing Windows Forms) { LayoutMdi(MdiLayout.TileVertical); } Chapter 14 - A Better Painting Framework (GDI+) private void mnuArrangeHorizontal_Click(object sender, System.EventArgs e) Chapter 15 - Programming with Windows Forms Controls { LayoutMdi(MdiLayout.TileHorizontal); } Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part - Web and XML TheFive main pointApplications of interest here is theWeb useServices of the LayoutMdi()
method and the corresponding MdiLayout
Chapter 18 - ASP.NET Webbehind Pages each and Web Controls enumeration. The code menu select handler should be quite clear. When the user selects a Chapter given arrangement, 19 - ASP.NET you Webtell Applications the parent Form to automatically reposition any and all child windows. Chapter 20 - XML Web Services
Before you move on to the child Form, you need to add one design-time property to the topmost Window menu item. The MdiList property may be set to true for a given topmost menu, to inform the hosting Form List of Figures to automatically list the name of each child window as a possible menu selection. Enable this behavior for List of Tables the topmost Windows menu item. By default, this list is the value of the child's Text property followed by a numerical suffix (i.e., Form1, Form2, Form3, and so on). Index
Building the Child Form Now that you have the shell of an MDI container Form, you need to create an additional Form that functions as the prototype for a given child window. Begin by inserting a new Form type into your current project (using the Project | Add Windows Form... menu selection) named KidPrototypeForm, and handle the Click event. In the generated event handler, randomly set the background color of the client area. In addition, print out the "stringified" value of the new Color object into the child's caption bar. The following logic should do the trick: private void KidPrototypeForm_Click(object sender, System.EventArgs e) { // Get three random numbers
int r, g, b; C# and the .NET Platform, Second Edition Random ran = new Random(); ISBN:1590590554 by Andrew Troelsen r = ran.Next(0, 255); Apress © 2003 (1200 pages) g = ran.Next(0, 255); This comprehensive b = ran.Next(0, 255); text starts with a brief overview of the C# language then quickly moves to key and Color currColor =and Color.FromArgb(r, g,technical b); architectural issues for .NET developers. this.BackColor = currColor; this.Text = currColor.ToString(); }
Table of Contents C# and the .NET Platform, Second Edition Introduction
Spawning Child Windows
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET Your final of business is to flesh out the details behind the parent Form's "File New" event handler. Chapter 2 order - Building C# Applications
NowTwo that- The you C# have defined a child Form, Part Programming Language
the logic is simple: Create and show a new instance of the ChildForm type. Furthermore, you need to set the value of the child Form's MdiParent property to point to Chapter 3 - C# Language Fundamentals the containing Form (in this case, your main window). Note that the child Form may also access the Chapter 4 - Object-Oriented Programming with C# MdiParent property directly whenever it needs to manipulate (or communicate with) its parent window. Chapter 5 - Exceptions and Object Lifetime Here is the update: Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
private void mnuFileNew_Click(object sender, System.EventArgs e) Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies // Make a new child window. Chapter 9 - Understanding .NET Assemblies KidPrototypeForm newChild = new KidPrototypeForm(); Chapter 10 - Processes, AppDomains, Contexts, and Threads // Set the Parent Form of the Child window. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming newChild.MdiParent = this; Part Four - Leveraging the .NET Libraries // Display the new form. Chapter newChild.Show(); 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Now, to16take thisSystem.IO application out for a test drive, begin by creating a set of new child windows and click on Chapter - The Namespace each one establish a unique background color (see Figure 13-26). Chapter 17 to - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 13-26: Spawning child windows As you can see, if you access the Arrange Window menu items, you can instruct the parent Form to vertically tile, horizontally tile, or cascade the child Forms.
SOURCE CODE
C# and .NET Platform, Second Edition The the SimpleMdiApp project can be found under the Chapter 13 subdirectory. ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
This chapter introduced fine artpages) of building a user interface with the types contained in the Apress ©the 2003 (1200 System.Windows.Forms namespace. It began examining the basic steps you must take to build a This comprehensive text starts by with a brief overview of the custom Form. This entailed a discussion of the Application object, and its various members. As you have C# language and then quickly moves to key technical and architectural issues for developers.from a rather long chain of base types. seen, the Form type gains a majority of .NET its functionality During the course of this chapter, you learned how to build topmost menus (and pop-up menus) and how Table to respond of Contents to a number of menu events. You also came to understand how to further enhance your Form
objects using and statusEdition bars. Finally, this chapter illustrated how to construct MDI applications C# and the .NETtoolbars Platform, Second using Windows Forms. Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Chapter C# 14: A Better Painting Framework (GDI+) ISBN:1590590554 by Andrew Troelsen
Overview
Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and Theprevious chapter architectural introduced issues youfor to .NET the fine developers. art of building a traditional main window using various
types contained within the System.Windows.Forms namespace. Now that you can assemble a Form to represent the shell of your GUI-based applications, the next task is to understand the details of rendering Table of Contents graphical data (including stylized text and image data) onto the Form's client area. C# and the .NET Platform, Second Edition
We begin by taking a high-level view of the numerous drawing-related namespaces, and examine the Introduction process respondingC#toand (andthe initiating) paint sessions. Part One -of Introducing .NET Platform
You will also discover various ways of obtaining (and configuring) a Graphics object. Once you understand the general layout of the GDI+ landscape, the Chapter 1 - The Philosophy of .NET remainder of this chapter covers how to manipulate colors, fonts, geometric shapes, and graphical Chapter 2 - Building C# Applications images. This entails understanding related types such as Brush, Pen, Color, Point, and Rectangle (among Part Two - The C# Programming Language others). This chapter also explores a number of GDI+-centric programming techniques such as Chapter 3 - C# Language Fundamentals nonrectangular hit testing and GUI drag-and-drop logic. Chapter 4
- Object-Oriented Programming with C#
Chapter 5 - Exceptions Object Lifetime The chapter concludesand by exploring the new .NET resource format. While technically not part of GDI+ Chapter 6 Interfaces and Collections proper, it does involve the manipulation of graphical data (which in my opinion is "GDI+-enough" to be Chapter 7 -here). Callback Interfaces, Delegates, and Events presented Here, you learn how to embed your application's external resources directly into a .NET Chapter assembly 8 to - Advanced ship a more C# portable Type Construction binary image. Techniques During the process, you explore the System.Resources Part namespace Three - Programming and learn how with to .NET perform Assemblies read/write
operations on the underlying *.resx and *.resources files
by hand, well as pull resources from an assembly at runtime using the Chapter 9 as - Understanding .NET Assemblies System.Resources.ResourceManager type. and Threads Chapter 10 - Processes, AppDomains, Contexts, Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Note If you are a Web programmer by trade, you may think that GDI+ is of no use to you. However, as you will see later in this text during our examination of ASP.NET, GDI+ is not limited to traditional Chapter 12 - Object Serialization and the .NET Remoting Layer desktop applications and is extremely relevant for Web applications. Part Four - Leveraging the .NET Libraries
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Survey of the GDI+ Namespaces by Andrew Troelsen
ISBN:1590590554
The .NET Framework a number Apressprovides © 2003 (1200 pages) of namespaces devoted to two-dimensional graphical rendering. In addition to the This basiccomprehensive functionality you to find in a graphics textwould starts expect with a brief overview of the package (color, font, pen, brush, and image manipulation), you also find types that enable geometric antialiasing, palette C# language and then quickly moves to key technical transformations, and architectural issues for .NET developers. blending, and document printing support. Collectively speaking, these namespaces make up the .NET facility we call GDI+, which is a vast improvement over the traditional Win32 Graphical Device Interface (GDI) API. Table 14-1 gives a high-level view of each major player. Table of Contents C# and the .NET Platform, Second Edition Table 14-1: The Core GDI+ Namespaces Introduction
GDI+Namespace Meaning in Part One - Introducing C# and the .NET Platform
Life
Chapter 1
- The Philosophy of .NET System.Drawing This is the key GDI+ namespace, which defines numerous types - Building C# Applications for basic rendering (fonts, pens, basic brushes, etc.) as well as Part Two - The C# Programming Language the almighty Graphics type. Chapter 2 Chapter 3
- C# Language Fundamentals System.Drawing.Drawing2D This namespace Chapter 4 - Object-Oriented Programming with C# provides types used for more advanced twoChapter 5
graphics functionality (e.g., gradient brushes, pen- Exceptions and Object dimensional Lifetime
Chapter 6
- Interfaces and Collections
caps, geometric transforms, etc.).
Chapter 7 - Callback Interfaces, Delegates, and Events System.Drawing.Imaging This namespace defines types that allow you to directly Chapter 8 - Advanced C# Type Construction Techniques manipulate graphical images (e.g., change the palette, extract Part Three - Programming with .NETimage Assemblies metadata,
Chapter 9
manipulate metafiles, and so forth).
- Understanding .NET Assemblies
System.Drawing.Printing
This namespace defines types that allow you to render images to the printed page, interact with the printer itself, and format the Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming overall appearance of a given print job. Chapter 10 - Processes, AppDomains, Contexts, and Threads Part Four - Leveraging the .NET Libraries
System.Drawing.Text This small) namespace allows you to manipulate Chapter 12 - Object Serialization and the (rather .NET Remoting Layer collections of fonts. For example, Chapter 13 - Building a Better Window (Introducing Windows Forms) as you see in this chapter, the InstalledFontCollection type allows you to dynamically discover Chapter 14 - A Better Painting Framework (GDI+) the setForms of installed fonts on the target machine. Chapter 15 - Programming with Windows Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Configuring a GDI+ Project Workspace
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
When you to make of GDI+, you must set a reference to the System.Drawing.dll assembly. This Chapter 19 -wish ASP.NET Webuse Applications single binary contains definitions of the types for each of the core GDI+ namespaces. Be aware that if you Chapter 20 - XML Web Services select a new Windows Application Project Workspace using VS .NET, this reference is set on your behalf Index
automatically. Other project types, however, may require you to set this assembly reference explicitly. In any case, once you have set this reference, just make use of the C# "using" keyword and you are ready to List of Tables render: List of Figures
// Don't forget to reference System.Drawing.dll! using System.Drawing;
To begin the GDI+ journey, let's examine the functionality defined by the System.Drawing namespace.
and System.Drawing the .NET Platform, Second Edition Overview ofC#the Namespace by Andrew Troelsen
ISBN:1590590554
A vast majority ofApress the types used when © 2003 (1200 pages)programming GDI+ applications are found within the System.Drawing This namespace. As you would expect, classes comprehensive text starts with athere brief are overview of that the represent images, brushes, pens, and fonts. Furthermore, System.Drawing defines a number of related types such as Color, Point, C# language and then quickly moves to key technical and architectural issues for(but .NETnot developers. and Rectangle. Table 14-2 lists some all) of the core types. Table 14-2: Core Types of the System.Drawing Namespace
Table of Contents
Meaning in Life C#System.Drawing and the .NET Platform, Second Edition Type Introduction Part One - Introducing C# and the .NET Platform
Bitmap
Encapsulates a given image file (*.bmp or otherwise) and defines a number of methods to manipulate the underlying graphical data.
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Brush BrushLanguage objects are Part Two - The C# Programming
used to fill the interiors of graphical shapes such as rectangles, ellipses, and polygons. These types represent a number of Chapter 3 - C# Language Fundamentals Brushes brush variations, with Brush functioning as the abstract base class to the Chapter 4 - Object-Oriented Programming with C# SolidBrush remaining types. Additional Brush types are defined in the Chapter 5 - Exceptions and Object Lifetime SystemBrushes System.Drawing.Drawing2D namespace. Chapter 6 - Interfaces and Collections TextureBrush Chapter 7 - Callback Interfaces, Delegates, and Events Chapter Color8
- Advanced C# Type Construction Techniques As you have already seen in the previous chapter, the Color structure
Part Three - Programming with .NETaAssemblies defines number of
SystemColors
static fields that can be used to configure the color
Chapter 9
- Understanding of .NET Assemblies fonts, brushes, and pens. The ColorTranslator type allows you to build ColorTranslator Chapter 10 - Processes, AppDomains, Contexts, and from Threads a new .NET Color type other color representations (Win32, the Chapter 11 - Type Reflection, Late Binding, type, and Attribute-Based Programming OLE_COLOR HTML color constants, etc.). Part Four - Leveraging the .NET Libraries
Font
The Font type encapsulates the characteristics of a given font (i.e., type name, bold, italic, point size, and so forth). FontFamily provides an FontFamily Chapter 13 - Building a Better Window (Introducing Windows Forms) abstraction for a group of fonts having a similar generic design but with Chapter 14 - A Better Painting Framework (GDI+) certain variations in styles. Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 15 - Programming with Windows Forms Controls
Graphics core class represents a valid drawing surface, as well as a number Chapter 16 - The System.IOThis Namespace of methods Chapter 17 - Data Access with ADO.NET to render text, images, and geometric patterns. Consider this Part Five - Web Applicationstype and the XML.NET Webequivalent Services
of a Win32 HDC.
Chapter 18 - ASP.NET Web Pages and Web Controls
Icon
These classes represent custom icons, as well as the set of standard
Chapter 19 - ASP.NET Web Applications system supplied icons. SystemIcons Chapter 20 - XML Web Services Index Image ListImageAnimator of Figures List of Tables
Pen Pens
Image is an abstract base class that provides functionality for the Bitmap, Icon, and Cursor types. ImageAnimator provides a way to iterate over a number of Image-derived types at some specified interval. Pens are objects used to draw lines and curves. The Pens type defines a number of static properties that return a new Pen of a given color.
SystemPens Point PointF Rectangle RectangleF Size SizeF StringFormat
These structures represent an (x,y) coordinate mapping to an underlying integer or float (respectively). These structures represent a rectangular dimension (again mapping to an underlying integer or float). These structures represent a given height/width (again mapping to an underlying integer or float). This type is used to encapsulate various features of textual layout (i.e., alignment, line spacing, etc.).
Region
Describes the interior of a geometric C# and the .NET Platform, Second Edition image composed of rectangles and paths. by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Many of these core types make substantial usewith of aanumber of related enumerations, most of which are This comprehensive text starts brief overview of the also defined within the System.Drawing namespace. As you can guess, C# language and then quickly moves to key technical and many of these enumerations are forbrushes .NET developers. used to configurearchitectural the look andissues feel of and pens. For example, ponder the types listed in Table 143. Table of 14-3: Contents Table Enumerations in the System.Drawing Namespace C# and the .NET Platform, Second Edition
System.Drawing Introduction Enumeration Part One - Introducing C# and the
Meaning in Life .NET Platform
Chapter 1 - The Philosophy of .NET Specifies how to align content on a drawing surface (center, left, ContentAlignment Chapter 2 - Building C# Applications right, and so forth) Part Two - The C# Programming Language
FontStyle Specifies style information applied to text (bold, italic, etc.) Chapter 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming withthe C#unit of measure for the given item (much like the GraphicsUnit Specifies Chapter 5 - Exceptions and Object Lifetime Win32 mapping mode constants) Chapter 6
- Interfaces and Collections
KnownColor Specifies friendly names for the known system colors - Callback Interfaces, Delegates, and Events Chapter 8 - Advanced C# Type Construction StringAlignment SpecifiesTechniques the alignment of a text string relative to its layout Part Three - Programming with .NET Assemblies rectangle Chapter 7
Chapter 9
- Understanding .NET Assemblies
StringFormatFlags
Specifies the display and layout information for text strings (e.g., NoWrap, LineLimit, and so on)
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries StringTrimming Specifies
how to trim characters from a string that does not
Chapter 12 - Object Serialization and the completely .NET Remoting fit into aLayer layout shape Chapter 13 - Building a Better Window (Introducing Windows Forms)
StringUnit
Specifies the units of measure for a text string
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - Thehave System.IO Namespace If you currently a background using graphic toolkits found in other frame-works (such as Java or Chapter 17 -should Data Access withatADO.NET MFC) you feel right home with the functionality provided by the .NET System.Drawing Part Five - WebNext Applications and XML Web Services namespace. up, let's examine the set of basic
Chapter programming. 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
utility types that are commonly used in GDI+
and the .NET Platform, Second Edition Examining C# the System.Drawing Utility Types by Andrew Troelsen
ISBN:1590590554
Many of the drawing methods defined by the System.Drawing.Graphics class require you to specify the Apress © 2003 (1200 pages) position or area inThis which you wish to render a given item. example, the DrawString() method requires comprehensive text starts with a briefFor overview of the you to specify theC# location to render the text string on the Control-derived language and then quickly moves to key technical and type. Given that DrawString() has .NET developers. been overloadedarchitectural a number ofissues times,for this positional parameter may be specified using an (x,y) coordinate or the dimensions of a "box" to draw within. Other GDI+ type methods may require you to specify the width and height of a given item, or the internal bounds of a geometric image. Table of Contents
Toand specify suchPlatform, information, the Edition System.Drawing namespace defines the Point, Rectangle, Region, and C# the .NET Second Size types. Obviously, a Point represents some (x,y) coordinate. Rectangle types capture a pair of points Introduction representing the upper and right bounds of Part One - Introducing C#left and thelower .NET Platform
a rectangular region. Size types are similar to
Rectangles, however theseofstructures represent a given dimension using a given length and width. Chapter 1 - The Philosophy .NET Regions a way represent and manipulate nonrectangular drawing surfaces. Chapter 2 provide - Building C# to Applications Part Two - The C# Programming Language
The member variables used by the Point, Rectangle, and Size types are internally represented as an - C# Language Fundamentals integer data type. If you need a finer level of granularity, you are free to make use of the corresponding Chapter 4 - Object-Oriented Programming with C# PointF, RectangleF, and SizeF types, which (as you might guess) map to an underlying float. Regardless Chapter 5 - Exceptions and Object Lifetime of the underlying data representation, each type has an identical set of members, including a number of Chapter 6 Interfaces and Collections overloaded operators. A quick run-through follows. Chapter 3
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques Point(F) Type
Part Three - Programming with .NET Assemblies
Chapter 9 utility - Understanding .NET be Assemblies The first type you should aware of is System.Drawing.Point(F). As you recall, you created a Chapter 10 Processes, AppDomains, and Threads custom Point type earlier in this text,Contexts, which in many ways was a slimmed-down version of the official GDI+ Chapter 11 Type Reflection, Late Binding, and Attribute-Based Programming Point type. A breakdown of each member is shown in Table 14-4. Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and Point(F) the .NET Types Remoting Layer Table 14-4: Key Members of the Chapter 13 - Building a Better Window (Introducing Windows Forms)
Point and PointF Member
Meaning in Life
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace + Allows you to manipulate the underlying (x,y) point using common Chapter 17 - Data Access with ADO.NET overloaded operators.
-
Part Five - Web Applications and XML Web Services
= = 18 - ASP.NET Web Pages and Web Controls Chapter != Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
X
Index
These properties allow you to get and set the underlying (x,y) values.
Y
List of Figures ListCeiling() of Tables
This static method convents a PointF type into a Point by rounding off the underlying floats into integers.
IsEmpty
This property returns true if x and y are both set to zero.
Offset()
This method translates a given Point type by a given amount.
Although this type is most commonly used when working with GDI+ and user interface applications, do be aware that you may make use of any utility type from any application. To illustrate, here is a console application that makes use of the System.Drawing.Point type (be sure to set a reference to System.Drawing.dll). using System; using System.Drawing; namespace UtilTypes {
public class UtilTester C# and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen public static int Main(string[] args) Apress © 2003 (1200 pages) { This// comprehensive textoffset starts with brief overview of the Create and a apoint. C# language and then quickly moves to technical and Point pt = new Point(100, key 72); architectural issues for .NET developers. Console.WriteLine(pt); pt.Offset(20, 20); Console.WriteLine(pt); Table of Contents // Overloaded Point operators. C# and the .NET Platform, Second Edition Point pt2 = pt; Introduction if(pt == pt2) Part One - Introducing C# and the .NET Platform WriteLine("Points are the same"); Chapter 1 - The Philosophy of .NET else Chapter 2 - Building C# Applications WriteLine("Different points"); Part Two - The C# Programming Language // Change pt2's X value. Chapter 3 - C# Language Fundamentals pt2.X = 4000; Chapter 4 - Object-Oriented Programming withX C# // Now show each value: Chapter 5 - Exceptions and Object Lifetime Console.WriteLine("First point: {0} ", pt); Chapter 6 - InterfacesConsole.WriteLine("Second and Collections point: {0} ", pt2); Chapter 7 - Callback Interfaces, Delegates, and Events return 0; Chapter 8 - Advanced } C# Type Construction Techniques Part Three } - Programming with .NET Assemblies } Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Rectangle(F) Type
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Rectangles, Points, are useful in any(GDI+) application (GUI-based or otherwise). Some core members to be Chapter 14 - Alike Better Painting Framework aware of listed in Table 14-5. Chapter 15are - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Table 14-5: Key Access Members the Rectangle(F) Types Chapter 17 - Data withof ADO.NET Part Five - Web Applications and XML Web Services
Rectangle and
Meaning in Life
Chapter 18 - ASP.NET Web Pages and Web Controls RectangleF Member Chapter 19 - ASP.NET Web Applications
= = 20 - XML Web Services Allows you to test if two rectangles have identical values (or not). Chapter Index != List of Figures
Inflate()
List of Tables
Intersect() Union() Top
These static methods allow you to expand a rectangle, as well as create new rectangles that are a result of an intersection or union operation. These properties set the dimensions of a new Rectangle type.
Left Bottom Right Height
Configures the height and width of a given Rectangle.
Width Contains()
This method can be used to determine if a given Point (or Rectangle) is within the bounds of the current Rectangle. Great for hit testing a point within a rectangle.
X
These properties returnEdition the x or y coordinate of the Rectangle's C# and the .NET Platform, Second
Y
upper left corner. by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
One of the more This useful comprehensive methods of the textRectangle starts withtype a brief is Contains(). overview ofThis the method allows you to determine languageisand then quickly moves to key technicalRectangle and if a given Point orC# Rectangle within the current bounds of another object. Later in this chapter, architectural issues for .NET developers. you see how to make use of this method to reform hit testing of GDI+ images. Until then, here is a simple example: Table of Contents
public int Second Main(string[] args) C# and the static .NET Platform, Edition {
Introduction
... // Point is initially outside of rectangle's bounds. Chapter 1 - The Philosophy of .NET Rectangle r1 = new Rectangle(0, 0, 100, 100); Chapter 2 - Building C# Applications Point pt3 = new Point(101, 101); Part Two - The C# Programming Language if(r1.Contains(pt3)) Chapter 3 - C# Language Fundamentals Console.WriteLine("Point is within the rect!"); Chapter 4 - Object-Oriented Programming with C# else Chapter 5 - Exceptions and Object Lifetime Console.WriteLine("Point is not within the rect!"); Chapter // 6 -Now Interfaces and Collections place point in rectangle's area. Chapter pt3.X 7 - Callback Interfaces, Delegates, and Events = 50; Chapter pt3.Y 8 - Advanced = 30;C# Type Construction Techniques Part Three - Programming with .NET Assemblies if(r1.Contains(pt3)) Chapter 9 - Understanding .NET Assemblies Console.WriteLine("Point is within the rect!"); Chapter else 10 - Processes, AppDomains, Contexts, and Threads Console.WriteLine("Point is not within the rect!"); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming 0; the .NET Libraries Part Fourreturn - Leveraging } Chapter 12 - Object Serialization and the .NET Remoting Layer Part One - Introducing C# and the .NET Platform
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Size(F) and Region Types
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
The Size SizeF types areADO.NET quite simple to manipulate, and require little comment. These types each Chapter 17 and - Data Access with define Width properties handful Part FiveHeight - Web and Applications and XML and WebaServices
of overloaded operators (Table 14-6).
Chapter 18 - ASP.NET Web Pages and Web Controls
Table 14-6: Key Members of the Size(F) Types Chapter 19 - ASP.NET Web Applications Chapter - XML Web Services Size20and SizeF
Meaning in Life
Index Member List of Figures List+ of Tables
Operators to manipulate Size types.
== != Height Width
These properties are used to manipulate the current dimension of a Size type.
The Region Class Finally we have the Region class. This type represents the interior of a geometric shape. Given this last statement, it should make sense that the constructors of the Region class require you to send an instance of some existing geometric pattern. For example, assume you have created a (100 ×100) pixel rectangle. If you wish to gain access to the rectangle's interior region, you could write the following:
// Get the interior this rectangle. C# and theof .NET Platform, Second Edition Rectangle r =by new Rectangle(0, 0, 100, 100); Andrew Troelsen Region rgn = Apress new Region(r); © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Once you do have the interior dimensions of a given shape, you may manipulate it using the core members shown in Table 14-7. Table of Contents C# Table and the 14-7: .NET Members Platform,ofSecond the Region EditionClass Introduction
Region Member
Meaning in Life
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2 - Building C# Applications Complement() Updates this Region to the portion of the specified graphics object that does Part Two - The C# Programming Language not intersect with this
Region.
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Exclude()
Chapter 5
Updates this Region to the portion of its interior that does not intersect with the specified graphics object.
- Exceptions and Object Lifetime GetBounds() a RectangleF that represents a rectangular region that bounds this Chapter 6 - Interfaces Returns and Collections Chapter 7
Region. Delegates, and Events - Callback Interfaces,
Chapter 8
- Advanced C# Type Construction Techniques Intersect() Overloaded. Updates this Region to the intersection of itself with the specified graphics object.
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies IsEmpty() whetherContexts, this Region an empty interior on the specified drawing Chapter 10 - Processes,Tests AppDomains, andhas Threads
surface (orBinding, sets theand current Region empty). Chapter 11 - Type Reflection, Late Attribute-Based Programming MakeEmpty() Part Four - Leveraging the .NET Libraries
IsInfinite()
Tests whether this Region has an infinite interior on the specified drawing surface (or sets the current Region infinite).
Chapter 12 - Object Serialization and the .NET Remoting Layer
MakeInfinite() Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)by the specified Matrix. Transform() Transforms this Region Chapter 15 - Programming with Windows Forms Controls
Translate() Offsets the coordinates of this Region by the specified amount. Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Union() Updates this Region to the union of itself and the specified graphics object. Part Five - Web Applications and XML Web Services
Xor() 18 - ASP.NET Web Updates to the union minus the intersection of itself with the Chapter Pagesthis andRegion Web Controls specified graphics object. Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
I'm sure you get the general idea behind these coordinate primitives. You will have a chance to work with each of them during the course of this chapter (and any time you program against GDI+). Now then, on to List of Figures some more interesting material! Index
List of Tables
SOURCE CODE
The UtilTypes project is included under the Chapter 14 subdirectory.
the .NET Platform, Second Edition Regarding C# theand Disposal of System.Drawing Types by Andrew Troelsen
ISBN:1590590554
Before diving intoApress specific GDI+ topics, © 2003 (1200 pages)it is important to point out that a number of types within the System.Drawing.dll assembly implement the IDisposable Asthe you recall from Chapter 5, this This comprehensive text starts with a brief interface. overview of interface defines C# a single method named Dispose(), which may be called language and then quickly moves to key technical and by the object user to release any architectural .NET developers. internally managed resourcesissues of thefor type. When you make use of GDI+, your best bet is to explicitly call Dispose() on any type you have explicitly Table created of Contents via the C# "new" keyword (when you are finished interacting with it) to ensure that the type cleans
upand anythe internally allocated memory as soon as possible. On the other hand, when operating on a GDI+ C# .NET Platform, Second Edition type passed as a member parameter or received via a method invocation, you should not call Dispose(), Introduction because partC# of and the system still require Part One - another Introducing the .NETmay Platform Chapter 1
the type. To illustrate:
- The Philosophy of .NET
Chapter private 2 -void Building mainForm_Paint(object C# Applications sender, PaintEventArgs e) Part { Two - The C# Programming Language
Graphics object from param (don't dispose!). Chapter// 3 Get - C# a Language Fundamentals g = e.Graphics; ChapterGraphics 4 - Object-Oriented Programming with C# a SolidBrush (you new-ed it, dispose when done) Chapter// 5 Make - Exceptions and Object Lifetime new SolidBrush(...); ChapterSolidBrush 6 - Interfacesbr and=Collections Chapterbr.Dispose(); 7 - Callback Interfaces, Delegates, and Events
}
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies Recall, however, that if you fail (or forget) to call Dispose() on an IDisposable compatible type, the
Chapter 10collector - Processes, AppDomains, Contexts, Threads garbage will eventually clean up the and allocated memory. The only downfall to this lazy approach is Chapter 11 Type Reflection, Late Binding, and Attribute-Based the fact that you do not know exactly when the .NET garbageProgramming collector will kick in. If your application Part Four - to Leveraging theon .NET Librarieswith happens be installed a machine
large amounts of memory, the lazy approach may be just fine.
Chapter 12 as - Object Serialization the .NETsure Remoting However, you can never be and completely about Layer the hardware of the hosting machine, it is best to Chapter 13 Building a Better Window (Introducing Windows Forms) dispose of all GDI+ objects you create ASAP. Chapter 14 - A Better Painting Framework (GDI+)
Note simplicity, I with will abide by the lazyControls approach in this chapter and will not directly call Dispose() Chapter 15 For - Programming Windows Forms theSystem.IO types created in this chapter's example applications. Chapter 16 on - The Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andPaint the .NET Platform, Second Edition Understanding Sessions by Andrew Troelsen
ISBN:1590590554
As you have seenApress in the©previous the Control class defines a virtual method named OnPaint(). When 2003 (1200chapter, pages) a Form (or any descendent of Control) wishes render graphical you may override this method This comprehensive text starts to with a brief overviewinformation, of the and extract a Graphics object from the incoming PaintEventArgs parameter: C# language and then quickly moves to key technical and architectural issues for .NET developers.
public class MainForm : Form { Table of Contents public MainForm() C# and the .NET Platform, Second Edition { Introduction CenterToScreen(); Part One - Introducing C# and the .NET Platform this.Text = "Basic Paint Form"; Chapter } 1 - The Philosophy of .NET Chapter public 2 - Building C# Applications static void Main(string[] args) Part Two{- The C# Programming Language Chapter 3 - C# Language Fundamentals Application.Run(new MainForm()); Chapter } 4 - Object-Oriented Programming with C# Chapter protected 5 - Exceptions and Object void Lifetime override OnPaint(PaintEventArgs e) Chapter { 6 - Interfaces and Collections Graphics g = Delegates, e.Graphics; Chapter 7 - Callback Interfaces, and Events g.DrawString("Hello GDI+", new Font("Times New Roman", 20), Chapter 8 - Advanced C# Type Construction Techniques new SolidBrush(Color.Black), 0, 0); Part Three - Programming with .NET Assemblies // If overriding OnPaint(), be sure to call base class implementation. Chapter 9 - Understanding .NET Assemblies base.OnPaint(e); Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter } 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Four - Leveraging the .NET Libraries Part Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Recall that when responding to GUI-based events, you actually have two options at your disposal. In the
Chapter 14code - A Better Painting the Framework (GDI+) previous you overrode OnPaint() method directly. The other approach is to directly handle the raw Chapter 15 Programming with Windows Forms Controls Paint event using the associated PainEventHandler delegate: Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
public class MainForm : Form { Chapter public 18 - ASP.NET Web Pages and Web Controls MainForm() Chapter { 19 - ASP.NET Web Applications Chapter 20 - XML //Web TheServices VS .NET Property Window would rig this Index // up in InitializeComponent() List of Figures this.Paint += new List of Tables System.Windows.Forms.PaintEventHandler(MainForm_Paint); } // Note the signature of the event handler... public void MainForm_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; ... } ... } Part Five - Web Applications and XML Web Services
Regardless of how you respond to the Paint event, be aware that whenever a window becomes "dirty" a paint message is placed into the application's message queue. As you are most likely aware, a window is "dirty" whenever it is resized, covered by another window (partially or completely) or is minimized and then restored. Eventually, the flow of logic is routed to the method that handles repainting the window. In these cases, the
.NET Framework ensures that when your Form needs to be redrawn, the Paint handler is called automatically. C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
InvalidatingApress Your Client Area © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
During the flow ofC# your GDI+ application, you may need to explicitly inform a window that it needs to redraw language and then quickly moves to key technical and itself (in other words, you need to place a paint message into the queue programmatically). For example, you architectural issues for .NET developers. may have a program that allows the user to select from a number of bitmap images using a custom dialog. Once the dialog is dismissed, you need to draw the newly selected image onto the client area. Obviously, if you waited for the window to become "naturally dirty," the user would not see the change take place until it Table of Contents was resized or covered another window. When you need to force a window to repaint itself C# and the .NET Platform,by Second Edition programmatically, call Invalidate(). For example: Introduction Part One - Introducing C# and the .NET Platform
Chapter public 1 class - The Philosophy MainForm: of .NET Form
{ Chapter 2
- Building C# Applications
...Two - The C# Programming Language Part void MainForm_Paint(object sender, PaintEventArgs e) Chapter private 3 - C# Language Fundamentals Chapter { 4
- Object-Oriented Programming with C#
Chapter 5
Graphics = e.Graphics; - Exceptions andgObject Lifetime
// Assume logic to render a bitmap... - Interfaces and Collections } Chapter 7 - Callback Interfaces, Delegates, and Events private void GetNewBitmap() Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies // Show dialog and get new image... Chapter 9 - Understanding .NET Assemblies // Repaint the client area. Chapter 10 - Processes, AppDomains, Contexts, and Threads Invalidate(); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Part Four - Leveraging the .NET Libraries } Chapter 6
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter Do be aware 14 - A that Better thePainting Invalidate() Framework method (GDI+) has been overloaded a number of times to allow you to specify a
specific15 rectangular regionwith to repaint, the entire client area (which is the default). If you only wish to Chapter - Programming Windowsrather Formsthan Controls update16 the- extreme upper left rectangle of the client area, you could write: Chapter The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part - Web Applications and XML Web Services // Five Repaint a given rectangular area
of the Form.
Chapter private 18 -void ASP.NET UpdateUpperArea() Web Pages and Web Controls
{ Chapter 19 - ASP.NET Web Applications Chapter Rectangle 20 - XML WebmyRect Services = new Rectangle(0, 0, 75, 150);
Invalidate(myRect); } List of Figures Index
List of Tables
Obtaining a Graphics Type Outside a Paint Handler On a related note, you may find yourself in the position of needing to render some image outside the scope of a standard Paint event handler. For example, assume you wish to draw a small circle at the (x,y) position where the mouse has been clicked. The first step (of course) is to locate a valid Graphics object, which can be obtained using the static Graphics.FromHwnd() method. Notice that you are passing your current Handle as the sole parameter (recall that the Handle property is inherited from the Control class): private void MainForm_MouseDown(object sender, MouseEventArgs e) { // Grab a Graphics object via Hwnd. Graphics g = Graphics.FromHwnd(this.Handle); // Now draw a 10*10 circle at mouse click. g.DrawEllipse(new Pen(Color.Green), e.X, e.Y, 10, 10);
} C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
Apress © (1200 pages)an OnPaint() event handler, it is very important to understand that if the While this logic renders a 2003 circle outside form is invalidated (and thus redrawn), each of with the circles erased! This should make sense, given that this This comprehensive text starts a brief are overview of the C# language quickly key technical and rendering only happens withinand the then context of amoves mousetoclick. architectural issues for .NET developers.
A better approach is to have the MouseUp logic add a new point to an internal collection (such as an ArrayList) of Point objects, followed by a call to Invalidate(). At this point, the OnPaint() method can simply iterate over Table of Contents the collection and draw each item: C# and the .NET Platform, Second Edition Introduction public class MainForm : System.Windows.Forms.Form Part One - Introducing C# and the .NET Platform
{
Chapter // 1 -Used The Philosophy .NET the points. to holdof all Chapter private 2 - Building C# Applications ArrayList myPts = new ArrayList(); Part Two... - The C# Programming Language
Chapter private 3 - C# Language Fundamentals void MainForm_MouseDown(object sender, MouseEventArgs e) Chapter { 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions // Add and to Object points Lifetime collection.
Chapter 6
myPts.Add(new Point(e.X, e.Y)); - Interfaces and Collections
Invalidate(); - Callback Interfaces, Delegates, and Events } Chapter 8 - Advanced C# Type Construction Techniques private void with MainForm_Paint(object sender, PaintEventArgs e) Part Three - Programming .NET Assemblies { Chapter 9 - Understanding .NET Assemblies Graphics g = e.Graphics; Chapter 10 - Processes, AppDomains, Contexts, and Threads g.DrawString("Hello GDI+", new Font("Times New Roman", 20), Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming new SolidBrush(Color.Black), 0, 0); Part Four - Leveraging the .NET Libraries // Draw all points in ArrayList. Chapter 12 - Object Serialization and the .NET Remoting Layer foreach(Point p in myPts) Chapter 13 - Building a Better Window (Introducing Windows Forms) g.DrawEllipse(new Pen(Color.Green), p.X, p.Y, 10, 10); Chapter 14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls } Chapter 7
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Obtaining a Graphics Type from Windows Forms Controls
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
As you have seen, the Graphics.FromHwnd() method provides a handy way to obtain a Graphics object for a Form outside a registered paint handler. However, this same method can also be used to extract a Graphics Index type from any System.Windows.Forms.Control-derived type. For example, assume you have two Button types List FiguresForm. The first button (named btnRenderToOtherButton) has the following Click event handler: on of a single Chapter 20 - XML Web Services
List of Tables
private void btnRenderToOtherButton_Click(object sender, System.EventArgs e) { // Get graphics object for Button on Form. Graphics buttonGraphics = Graphics.FromHwnd(btnRenderedButton.Handle); // Make an interesting brush. // (must 'use' System.Drawing.Drawing2D namespace to get HatchBrush!) HatchBrush b = new HatchBrush(HatchStyle.Cross, Color.Purple, Color.Gold); // Render brush patter on the left side of button. buttonGraphics.FillRectangle(b, 0, 0, 50, btnRenderedButton.Height); }
When you click this button, the appearance of the other button (named btnRenderedButton) is updated with a
custom rectangular region established using a System.Drawing.Drawing2D.HatchBrush type (more on brush and the .NET Platform, Second Edition types later in this C# chapter). Figure 14-1 shows a test run of this initial GDI+ application. by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies Figure 14-1: A simple GDI+ application
Chapter 9
- Understanding .NET Assemblies Do be aware, however,AppDomains, that if you click the newly Chapter 10 - Processes, Contexts, and rendered Threads button, the graphical data will vanish (as the widget
is repainted to its Reflection, default look and feel). Ifand youAttribute-Based wish to build a Programming stylized widget that always renders itself in a Chapter 11 - Type Late Binding, unique you may wishLibraries to build a Part Fourmanner, - Leveraging the .NET
custom Windows Forms control (see Chapter 15).
Chapter 12 - Object Serialization and the .NET Remoting Layer
SOURCE CODE
The BasicPaintForm project is included under the Chapter 14 subdirectory.
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, Class Second Edition Understanding Graphics by Andrew Troelsen
ISBN:1590590554
Now that you have seen©various ways to obtain a Graphics object, you need to understand exactly how to Apress 2003 (1200 pages) manipulate it. TheThis System.Drawing.Graphics youroverview gatewayoftothe GDI+ rendering functionality. This comprehensive text startsobject with aisbrief class represents C# a valid device context (e.g., HDC) coupled with a slew language and then quickly moves to key technical andof methods that allow you to architectural issues for developers. render text, images (icons, bitmaps, and.NET so on), as well as numerous geometric patterns. Table 14-8 gives a partial list of intriguing members. Table of 14-8: Contents Table Members of the Graphics Class C# and the .NET Platform, Second Edition
Graphics Introduction
Meaning in Life Methods Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET FromHdc() These static methods provide a way to obtain a valid Graphics object - Building C# Applications from a given image (e.g., icon, bitmap, etc.) or GUI widget. FromHwnd()
Chapter 2
Part Two - The C# Programming Language
FromImage() Chapter 3 - C# Language Fundamentals Chapter 4
Programming with C# Clear() - Object-Oriented Fills a Graphics object with a specified color, erasing the current drawing - Exceptions andsurface Object Lifetime in the process.
Chapter 5 Chapter 6
- Interfaces and Collections DrawArc() TheseDelegates, methods and are used to render a given image or geometric pattern. Chapter 7 - Callback Interfaces, Events Chapter DrawBezier() 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies DrawBeziers()
Chapter 9
- Understanding .NET Assemblies
DrawCurve()
Chapter 10 - Processes, AppDomains, Contexts, and Threads
DrawEllipse() Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries DrawIcon()
Chapter 12 - Object Serialization and the .NET Remoting Layer DrawLine() Chapter 13 - Building a Better Window (Introducing Windows Forms)
DrawLines()
Chapter 14 - A Better Painting Framework (GDI+)
DrawPie() Chapter 15 - Programming with Windows Forms Controls Chapter DrawPath() 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET DrawRectangle() Part Five - Web Applications and XML Web Services
DrawRectangles()
Chapter 18 - ASP.NET Web Pages and Web Controls
DrawString() Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services FillEllipse() These methods are used to fill the interior of a given geometric shape. Index
FillPath()
List of Figures ListFillPie() of Tables
FillPolygon() FillRectangle() MeasureString()
Returns a Size structure that represents the bounds of a given block of text.
As well as providing a number of rendering methods, the Graphics class defines additional members that control the details of the current rendering operation. In more concrete terms, the Graphics type allows you to configure the state of the Graphics object using the property set in Table 14-9. Table 14-9: Stateful Properties of the Graphics Class
Graphics Property Clip
Meaning in LifeSecond Edition C# and the .NET Platform, by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
These properties allow you to set the clipping options used with the
ClipBounds
This comprehensive text starts with a brief overview of the current Graphics object. C# language and then quickly moves to key technical and architectural issues for .NET developers.
VisibleClipBounds IsClipEmpty
Table of Contents IsVisibleClipEmpty C# and the .NET Platform, Second Edition
Transform
Introduction
Allows you to transform "world coordinates" (more details later).
Part One - Introducing C# and the properties .NET Platform PageUnit These allow
you to configure the point of origin for your
Chapter 1
- The Philosophy of .NET operations, as well as configure the unit of measurement. rendering PageScale Chapter 2 - Building C# Applications
DpiX Part Two - The C# Programming Language DpiY 3 Chapter
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
SmoothingMode
These properties allow you to configure the smoothness of geometric objects and text. These are set with corresponding enumerations defined PixelOffsetMode Chapter 6 - Interfaces andinCollections the System.Drawing and System.Drawing.Drawing2D namespaces. TextRenderingHint Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques CompositingMode The CompositingMode property determines whether drawing overwrites the background or is blended with the background. The value is set with CompositingQuality Chapter 9 - Understandingthe .NET Assemblies CompositingMode enumeration defined in the corresponding Chapter 10 - Processes, AppDomains, Contexts, and Threads System.Drawing.Drawing2D namespace. The CompositingQuality Chapter 11 - Type Reflection, Late Binding, andthe Attribute-Based property specifies complexity ofProgramming the blending process. Part Three - Programming with .NET Assemblies
Part Four - Leveraging the .NET Libraries
InterpolationMode Specifies dataRemoting is interpolated Chapter 12 - Object Serialization and how the .NET Layer between endpoints, using a related enumeration.
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter Programming with Windows Forms Controls During 15 the-course of this chapter you will check out how to configure a number of these stateful properties. Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NETSystems Platform, Second Edition The GDI+ Coordinate by Andrew Troelsen
ISBN:1590590554
Next up, you need a bit of background regarding the underlying coordinate system. GDI+ defines three Apress © 2003 (1200 pages) distinct coordinate systems (Table 14-10), which area used by the runtime This comprehensive text starts with brief overview of the to determine the location and size of the element to be rendered. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 14-10: The GDI+ Coordinate Systems GDI+ Table of Contents
Meaning in Life Coordinate C# and the .NET Platform, Second Edition System Introduction Part One - Introducing C# and the .NET Platform
World World coordinates represent an abstraction of the size of a given GDI+ type, - The Philosophy of .NET Coordinates irrespective of the unit of measurement.
Chapter 1 Chapter 2
- Building C# Applications
For example, if you draw a rectangle using the dimensions of (0, 0, 100, 100), you have specified a rectangle 100 × 100 "things" in size.
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
As you may guess,with the C# default thing is a pixel, but this can be configured to - Object-Oriented Programming
Chapter 5
unit of measure (inch, centimeter, etc.). - Exceptions be andanother Object Lifetime
Chapter Page 6
- Interfaces and Collections Page coordinates represent an offset applied to the original world
Chapter 7 - Callback Interfaces, Delegates, Events Coordinates coordinates. This isand helpful in that you are not the one in charge of manually Chapter 8 - Advanced C# Type Construction Techniques applying offsets in your code (should you need them). Part Three - Programming with .NET Assemblies
For example, if you have a Form that needs to maintain a 100 × 100 pixel border, you can specify a (100 ×100) page coordinate to allow all rending to Chapter 10 - Processes, AppDomains, and In Threads begin at pointContexts, (100 × 100). your code base however, you are able to Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming specify simple world coordinates (thereby avoiding the need to manually Part Four - Leveraging the .NET Libraries calculate the offset). Chapter 9
- Understanding .NET Assemblies
Chapter 12 - Object Serialization and the .NET Remoting Layer
Device DeviceWindow coordinates represent the result of applying page coordinates to the Chapter 13 - Building a Better (Introducing Windows Forms) Coordinates
original world coordinates. This coordinate system is used to determine exactly where the GDI+ type will be rendered on the Control-derived type.
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
When you are programming with GDI+, you tend to think in terms of "world coordinates." Simply put, this coordinate system is the baseline used to determine the size and location of a GDI+ type:
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
// Render a rectangle by specifying world coordinates. myGraphicsObject.DrawRectangle(10, 10, 100, 100);
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures
List of Tables Under the hood of GDI+, your world coordinates are automatically mapped in terms of page coordinates,
and are then mapped into device coordinates. In many cases, you will never directly make use of page or device coordinates unless you wish to apply some sort of graphical transformation. Given that the previous line of code did not specify any transformational page coordinate logic, the world, page, and device coordinates are identical. If you do wish to apply various transformations before rendering your GDI+ logic, you will make use of various members of the Graphics type (such as the TranslateTransform() method) to specify various "page coordinates" to your existing world coordinate system before the rendering operation. The result is the set of device coordinates that will be used to render the GDI+ type to the target device: // Specify page coordinate offsets (10 * 10). myGraphicsObject.TranslateTransform(10, 10); // Render a rectangle by specifying world coordinates. // However! Given the previous offset, // this rectangle is really drawn at (20 ,20)
// and is 110 * 110 pixels in size. C# and the .NET Platform, Second myGraphicsObject.DrawRectangle(10, 10, Edition 100, 100); by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
In this case, the rectangle is actually text rendered left pointofofthe (20, 20) and a lower right point of This comprehensive starts with with aa upper brief overview C# language and then quickly moves to key technical and (110, 110). architectural issues for .NET developers.
The Default Unit of Measure Table of Contents
As suggested in the last example, the default unit of measure is pixel-based and places the origin in the upper left corner with the x-axis increasing to the right and the y-axis increasing downward (Figure 14-2).
C# and the .NET Platform, Second Edition Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - 14-2: Type Reflection, Late Binding, and Attribute-Based Programming Figure The default coordinate system of GDI+ Part Four - Leveraging the .NET Libraries
Chapter 12you - Object and .NET Remoting Layer Again, if renderSerialization a Rectangle asthe follows: Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 -void A Better Painting Framework (GDI+) sender, PaintEventArgs e) private MainForm_Paint(object Chapter 15 - Programming with Windows Forms Controls { Chapter // 16 -Set The System.IO up worldNamespace coordinates using the default unit of measure. Chapter Graphics 17 - Data Access g = with e.Graphics; ADO.NET Part Fiveg.DrawRectangle(new - Web Applications and XMLPen(Color.Red, Web Services
5), 10, 10, 100, 100);
} Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
you would see a square rendered 10 pixels down and in from the top left client edge of the Form, which spans 90 pixels in both directions (Figure 14-3). Given that you have not applied any page transformations, List of Figures the world, page, and device coordinate values are identical. Index
List of Tables
Figure 14-3: Rendering via pixel units In most cases, the default measurement system will most likely be your unit of choice. However, like most things in the .NET Framework, you are able to configure the GDI+ mapping mode to your liking.
the .NET Platform, Edition Specifying C# anand Alternative UnitSecond of Measure by Andrew Troelsen
ISBN:1590590554
If you do not wishApress to render images using a pixel-based unit of measure, you are able to change this © 2003 (1200 pages) default setting byThis setting the PageUnit property of the Graphics object to alter the units used by the page comprehensive text starts with a brief overview of the coordinate system. The PageUnit property can be assigned any member C# language and then quickly moves to key technical and of the GraphicsUnit enumeration (Table 14-11). architectural issues for .NET developers. Table 14-11: The GraphicsUnit Enumeration
Table of Contents
Value C#GraphicsUnit and the .NET Platform, SecondDescription Edition Introduction
Display
Specifies 1/75 inch as the unit of measure
Part One - Introducing C# and the .NET Platform
Document Specifies the document unit (1/300 inch) as the unit of measure Chapter 1 - The Philosophy of .NET Chapter 2
Inch
- Building C# Applications
Specifies the inch as the unit of measure
Part Two - The C# Programming Language
Millimeter Specifies the millimeter as the unit of measure Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Point 6 Chapter
Specifies a printer's point (1/72 inch) as the unit of measure - Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Pixel
Specifies a device pixel as the unit of measure
For example, if you update your previous rendering code as follows:
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies private MainForm_Paint(object Chapter 10 -void Processes, AppDomains, Contexts, andsender, Threads PaintEventArgs e)
{
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Draw a rectangle in inches...not pixels. Graphics g = e.Graphics; Chapter 12 - Object Serialization and the .NET Remoting Layer g.PageUnit = GraphicsUnit.Inch; Chapter 13 - Building a Better Window (Introducing Windows Forms) g.DrawRectangle(new Pen(Color.Red, 5), 0, 0, 100, 100); Chapter 14 - A Better Painting Framework (GDI+) } Part Four - Leveraging the .NET Libraries
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter Data Access with rectangle ADO.NET (Figure 14-4). you find17a -radically different Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 14-4: Rendering via inch units The reason that 95% (or so) of the Form's client area is now filled in is due to the fact that you have configured a Pen with a five inch nib! The rectangle itself is 100 × 100 inches in size! In fact, the small gray box you see located in the lower right corner is the upper left interior of the rectangle! As you would guess, if you specify alternative values to the Graphics.PageUnit property, you would find the rectangle rendered in various units of measurement.
Specifying C# anand Alternative Point of Origin the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
Recall that when you make use of the default coordinate and measurement system, point (0, 0) is at the Apress © 2003 (1200 pages) extreme upper left of the client area. Again, this is typically what you desire. However, what if you wish to comprehensive text starts with a brief overview of the alter the location This where rendering begins? For example, let's assume that your application always needs C# language and then quickly moves to key technical and to reserve a 100-pixel boundary around the Form's client area (for whatever reason). You need to ensure architectural issues for .NET developers. that all GDI+ operations take place somewhere within this internal region. One approach you could take is to offset all your rendering code manually. This, of course, is a huge bother, in that you would need to constantly apply some offset value to each and every rendering C# and the .NET Platform, Second Edition operation. It would be far better (and simpler) if you could set a property that says, in effect, "Although I Introduction might say render a rectangle with a point of origin at (0, 0), make sure you begin at point (100, 100)." This Part One - Introducing C# and the .NET Platform would simplify your life a great deal, as you can continue to specify your plotting points without Chapter 1 - The Philosophy of .NET modification.
Table of Contents
Chapter 2
- Building C# Applications
Part Two - you The can C# Programming Language In GDI+, adjust the point of origin
by setting the transformation value using the
Chapter 3 - C# Language Fundamentals TranslateTransform() method of the Graphics class, which allows you to specify a page coordinate system Chapter that will4be- applied Object-Oriented to your original Programming world coordinate with C# specifications. For example: Chapter 5
- Exceptions and Object Lifetime
Chapter 6 -void Interfaces and Collections private MainForm_Paint(object sender, PaintEventArgs e) Chapter 7 Callback Interfaces, Delegates, and Events { Chapter Graphics 8 - Advanced g C# = e.Graphics; Type Construction Techniques Part Three //- Programming Set page coordinate with .NET Assemblies to (100,
100).
Chapter g.TranslateTransform(100, 9 - Understanding .NET Assemblies 100);
origin is still (0,and 0,Threads 100, 100), Chapter // 10 -World Processes, AppDomains, Contexts, device is Attribute-Based now (100, 100, 200, 200). Chapter // 11 -however Type Reflection, Late origin Binding, and Programming Pen(Color.Red, Part Fourg.DrawRectangle(new - Leveraging the .NET Libraries
5), 0, 0, 100, 100);
} Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Here, we have set our world coordinate values (0, 0, 100, 100). However, the page coordinate values have specified an offset of (100, 100). Given this, the device coordinates map to (100, 100, 200, 200). Thus, Chapter 16the - The Namespace looks as if you are rendering a rectangle on the upper left of the although callSystem.IO to DrawRectangle() Chapter 17 Data Access with Form, the following renderingADO.NET has taken place (Figure 14-5). Chapter 15 - Programming with Windows Forms Controls
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 14-5: The result of applying page offsets To help you experiment with some of the ways to alter the default GDI+ mapping system, the companion code contains a sample application named CoorSystem. Using two topmost menu items, you are able to alter the point of origin as well as the unit of measurement (Figure 14-6).
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Figure 14-6: Altering coordinate and measurement modes
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# Now that have a better understanding Chapter 5 you - Exceptions and Object Lifetime of the underlying transformations used to determine where to
render 6a given GDI+ type a target device, the next order of business is to examine details of color Chapter - Interfaces andonto Collections manipulation. Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
SOURCE CODE
The CoorSystem project is included under the Chapter 14 subdirectory.
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# an and Active the .NET Platform, Establishing Color Second Edition by Andrew Troelsen
ISBN:1590590554
Many of the rendering defined Apressmethods © 2003 (1200 pages) by the Graphics class require you to specify the color that should be used during the drawing process. Thestarts System.Drawing.Color structure This comprehensive text with a brief overview of the represents an alpha-red-greenblue (ARGB) color constant. Most of the Color type's functionality comes C# language and then quickly moves to key technical and by way of a number of static architectural issuesa for developers. read-only properties, which return new.NET (correctly configured), Color type: // One of many predefined colors... Color c = Color.PapayaWhip;
Table of Contents
C# and the .NET Platform, Second Edition Introduction
Part Oneare - Introducing .NET a Platform There other waysC# youand canthe create Color type.
Regardless of the method you use, you are then able
Chapter 1 relevant - The Philosophy of .NET to extract information using any of the members listed in Table 14-12 (in addition to the set of Chapter 2 Building C# Applications static read-only properties). Part Two - The C# Programming Language
Chapter 3 - C# Languageof Fundamentals Table 14-12: Members the Color Type Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Color Member
Meaning in Life
Chapter 6 - Interfaces and Collections FromArgb() Returns a new Color object based on numerical red, green, and blue Chapter 7 - Callback Interfaces, values.Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
FromKnownColor()
Returns a new Color object based on a member of the KnownColor enumeration.
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter FromName() 10 - Processes, AppDomains, Returns a new Contexts, Color and object Threads based on a string name (e.g., "Red"). Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
A, R, G, B
These properties return the value assigned to the alpha, red, green, and blue aspect of a Color object.
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
IsNamedColor() These members can be Windows applied toForms) a Color object to determine if the Chapter 13 - Building a Better Window (Introducing current ARGB values Chapter Framework (GDI+)have a predefined name (e.g., "Red") and if so, Name14 - A Better Painting it via the Name property. Chapter 15 - Programmingretrieve with Windows Forms Controls
Chapter 16 - The System.IO Namespace GetBrightness() GDI+ Color types have an associated Hue-Saturation-Brightness (HSB) Chapter 17 - Data Access with ADO.NET value. These methods retrieve the specifics.
GetHue()
Part Five - Web Applications and XML Web Services
GetSaturation() Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET WebReturns Applications ToArgb() the ARGB value of the Color type, or the KnownColor Chapter 20 - XML Web Services enumeration value based on a valid Color object.
ToKnownColor()
Index
List of Figures List of Tables
Examining the ColorDialog Class On a related note, the System.Windows.Forms namespace provides a predefined dialog box class (ColorDialog) that can be used to prompt the end user for his or her color selection (Figure 14-7).
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Figure 14-7: The stock .NET color dialog
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Working dialog is simple: using a Part Two - with The this C# Programming Language
valid instance of the ColorDialog type, call ShowDialog() to display the dialog modally. Once the user has closed the dialog, you can extract the corresponding Color Chapter 3 - C# Language Fundamentals object using the ColorDialog.Color property. Chapter 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
For example, assume you wish to allow the user to configure the background color of the Form's client - Interfaces and Collections area using the ColorDialog. To keep things simple, let's assume that when the user clicks anywhere on Chapter 7 - Callback Interfaces, Delegates, and Events the client area, you show the ColorDialog object and act accordingly. Here is the code: Chapter 6 Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
public class ColorDlgForm : System.Windows.Forms.Form - Understanding .NET Assemblies { Chapter 10 - Processes, AppDomains, Contexts, and Threads // The ColorDialog. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming private ColorDialog colorDlg; Part Four - Leveraging the .NET Libraries public ColorDlgForm() Chapter { 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better (Introducing Windows Forms) colorDlg = Window new ColorDialog(); Chapter 14 - A Text Better Painting Framework = "Click on me(GDI+) to change the color"; Chapter 15 - Programming with Windows Forms Controls this.MouseUp += Chapter 16 - The System.IO Namespace new MouseEventHandler(this.ColorDlgForm_MouseUp); Chapter } 17 - Data Access with ADO.NET Part ...Five - Web Applications and XML Web Services void sender, MouseEventArgs e) Chapter private 18 - ASP.NET WebColorDlgForm_MouseUp(object Pages and Web Controls { Chapter 19 - ASP.NET Web Applications ifWeb (colorDlg.ShowDialog() != DialogResult.Cancel) Chapter 20 - XML Services { Index currColor = colorDlg.Color; List of Figures this.BackColor = currColor; List of Tables // Show current color. string strARGB = colorDlg.Color.ToString(); MessageBox.Show(strARGB, "Color is:"); } } } Chapter 9
Although there has not yet been a formal discussion of how to manipulate dialog boxes, the previous code should not raise too many eyebrows. Notice that you are able to determine which button has been clicked (OK or Cancel) by testing the return value of ShowDialog() against the DialogResult enumeration. You will see additional stock dialog boxes used in this chapter. Later, in Chapter 15, you learn how to build custom dialogs to gather (and validate) user input. SOURCE CODE
The ColorDlg application is included under the Chapter 14 subdirectory.
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Manipulating Fonts by Andrew Troelsen
ISBN:1590590554
Next, let's examine the specifics of pages) the Font class (and related types). The System.Drawing.Font type Apress © 2003 (1200 represents a given font installed on While the Font class defines a number of This comprehensivethe textuser's startsmachine. with a brief overview of the overloaded constructors, here are some common options: C# language and then quickly moves to key technical and architectural issues for .NET developers.
// Create a Font of a given type name and size. Font f = new Font("Times New Roman", 12); Table of Contents // Create a Font with a given name, size, and style set. C# and the .NET Platform, Second Edition Font f2 = new Font("WingDings", 50, FontStyle.Bold | FontStyle.Underline); Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1 has - The Philosophy .NET Here, f2 been created of using a set of FontStyle flags. The members of this enumeration allow you to Chapter 2 Building C# Applications configure a number of properties of the Font object such as bold or italic (if you require more than one Part Two - The C# Programming FontStyle, simply OR each itemLanguage together).
Chapter 3
Table 14-13 lists your choices.
- C# Language Fundamentals
Chapter Table 14-13: 4 - Object-Oriented The FontStyle Programming Enumeration with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter Bold 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
FontStyle Enumeration Member
Italic
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies Regular
Meaning in Life Bold text Italic text Normal text
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Strikeout
Text with a line through the middle
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries Underline
Underlined text
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter Once you 13 -have Building configured a Betterthe Window look and (Introducing feel of your Windows Font object, Forms)the next obvious task is to pass it as a
parameter Graphics.DrawString() method. Although DrawString() has also been overloaded a Chapter 14 -to A the Better Painting Framework (GDI+) number15of-times, each variation typically requires the same basic information: a string to draw, the font to Chapter Programming with Windows Forms Controls draw it 16 in, -a The brush used for Namespace rendering, and a location to place it. For example: Chapter System.IO Chapter 17 - Data Access with ADO.NET Part // Five One- Web version: Applications voidand DrawString(String, XML Web Services
Font, Brush, Point);
g.DrawString("My string", Font("Pop", 25), Chapter 18 - ASP.NET Web Pages and new Web Controls new SolidBrush(Color.Black), new Point(0,0)); Chapter 19 - ASP.NET Web Applications // Another void DrawString(String, Font, Brush, float, float); Chapter 20 - XMLversion: Web Services g.DrawString("Another string", new Font("Times New Roman", 16), Index List of Figures
new SolidBrush(Color.Red), 40, 40);
List of Tables
In each of these examples, you have made use of a SolidBrush type (of a particular color). It is possible to configure a number of brush types. For the time being, a solid brush fits the bill; you see more exotic brush types a bit later in this chapter. Once you have created a valid Font type, you are able to extract its current settings using a number of properties (e.g., Bold, Italic, Unit, Height, Size, FontFamily, and so forth).
Working with Font Families The System.Drawing namespace also defines the FontFamily type, which abstracts a group of typefaces having a similar basic design but having certain style variations (such as point size). A family of fonts, like Verdana, can include several fonts that differ in style and size. For example, 12-point Verdana bold and 24point Verdana italic are different fonts within the Verdana font family. The constructor of the FontFamily type takes a string representing the name of the font family you are attempting to capture. Once you create the generic family, you are then able to create a more specific Font object (in the following code, assume "g" is an object of type Graphics):
C# and the .NET Platform, Second Edition // Make a family of fonts. ISBN:1590590554 by Andrew = Troelsen FontFamily myFamily new FontFamily("Verdana"); Apress © 2003 (1200 pages) // Pass family into ctor of Font. comprehensive text starts12); with a brief overview of the Font myFont =This new Font(myFamily, C# language and then quickly moves to key technical and g.DrawString("Hello?", myFont, Brushes.Blue, 10, 10); architectural issues for .NET developers.
Of greater interest is the ability to gather statistics regarding a given family of fonts. For example, let's say you were building a text-processing application and wish to determine the average width of a character in a C# and the .NET Platform, Second Edition particular FontFamily. What if you wish to know the ascending and descending values for a given Introduction character? To answer such questions, the FontFamily type defines the key members shown in Table 14-14. Part One - Introducing C# and the .NET Platform Note that each requires you to specify the font style using the FontStyle enumeration.
Table of Contents
Chapter 1
- The Philosophy of .NET
Chapter 2 - Building C# Applications Table 14-14: Members of the FontFamily Type Part Two - The C# Programming Language
FontFamily Meaning in Life Chapter 3 - C# Language Fundamentals Member Chapter 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime GetCellAscent() Returns the ascender metric for the members in this family
Chapter 6
- Interfaces and Collections GetCellDescent() Returns the descender metric for members in this family Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques GetLineSpacing() Returns the distance between two consecutive lines of text for this Part Three - Programming with .NET Assemblies FontFamily with the specified
Chapter 9
FontStyle
- Understanding .NET Assemblies
GetName() Returns the name of FontFamily in the specified language Chapter 10 - Processes, AppDomains, Contexts, andthis Threads Chapter 11 - Type Reflection,Indicates Late Binding, and Attribute-Based Programming IsStyleAvailable() whether the specified FontStyle is available Part Four - Leveraging the .NET Libraries
Chapter 12 - Object and the .NET Remoting Layer To illustrate, here isSerialization a Paint handler that prints a number of characteristics of the Verdana font family: Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
private void MainForm_Paint(object sender, PaintEventArgs e)
Chapter 15 - Programming with Windows Forms Controls { Chapter Graphics 16 - The System.IO Namespace g = e.Graphics; Chapter FontFamily 17 - Data Access with ADO.NET myFamily = new FontFamily("Verdana"); Part FiveFont - WebmyFont Applications and XML Web Services = new Font(myFamily,
12);
Chapter int 18 - ASP.NET y = 0;Web Pages and Web Controls Chapter int 19 - ASP.NET Web Applications fontHeight = myFont.Height; // Get pixel height of font. Chapter // 20 -Show XML Web units Services of measurement for FontFamily members. Index
this.Text = "Measurements are in GraphicsUnit." + myFont.Unit.ToString();
g.DrawString("The Verdana family.", myFont, Brushes.Blue, 10, y); List of Figures y += 20; List of Tables // Print our family ties... g.DrawString("Ascent for bold Verdana: " + myFamily.GetCellAscent(FontStyle.Bold), myFont, Brushes.Black, 10, y + fontHeight); y += 20; g.DrawString("Descent for bold Verdana: " + myFamily.GetCellDescent(FontStyle.Bold), myFont, Brushes.Black, 10, y + fontHeight); y += 20; g.DrawString("Line spacing for bold Verdana: " + myFamily.GetLineSpacing(FontStyle.Bold), myFont, Brushes.Black, 10, y + fontHeight); y += 20; g.DrawString("Height for bold Verdana: " + myFamily.GetEmHeight(FontStyle.Bold),
myFont, Brushes.Black, 10, y + fontHeight); y += 20;C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
}
ISBN:1590590554
This comprehensive text starts with a brief overview of the C#the language Figure 14-8 shows result. and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# Figure Gathering statistics of the Verdana font family Chapter 5 - 14-8: Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Note that these members of the FontFamily type return values using GraphicsUnit.Point (not Pixel) as the - Callback Interfaces, Delegates, and Events unit of measure, which corresponds to 1/72 inch. You are free to transform these values to other units of Chapter 8 - Advanced C# Type Construction Techniques measure as you see fit. Chapter 7
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Understanding Font Metrics
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
If you have not worked with Fonts using this level of detail before, here are a few words regarding character measurements. The dimensions of a given Font are all based on the baseline value, which is the imaginary Chapter 12 - Object Serialization and the .NET Remoting Layer line on which each character "sits." Some characters (such as "j," "y," or "g") have a portion that drops Chapter 13 -baseline. Building a Better Window Forms) below this This is called the(Introducing descendingWindows value. The ascending value represents the amount a Chapter 14 - A Better Framework (GDI+) given character risesPainting above the baseline. The leading value represents the difference between the height Chapter 15 - Programming Forms Controls and ascent, where height with is theWindows total distance between the leading and descending values. Part Four - Leveraging the .NET Libraries
Chapter 16 - The System.IO Namespace
To keep items fixed in your mind, ponder Figure 14-9 (the baseline is identified by the thicker line Chapter 17all - these Data Access with ADO.NET toward bottom). Part Fivethe - Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 14-9: Font metrics SOURCE CODE
The FontFamily application is included under the Chapter 14 subdirectory.
C# and Application the .NET Platform, Second Edition Building a Font by Andrew Troelsen
ISBN:1590590554
Now, let's build aApress more complex application that allows the user to manipulate a Font object maintained by © 2003 (1200 pages) a main Form. TheThis application will allow the user to select current comprehensive text starts with a briefthe overview offont the face from a predefined set using the "Configure | Font Face" menu selection. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Let's also allow the user to indirectly control the size of the Font object using a Windows Forms Timer object. If the user activates the Timer using the "Configure | Swell?" menu item, the size of the Font object Table increases of Contents at a regular interval (to a maximum upper limit). In this way, the text appears to swell and thus provides simple animation of "breathing" text. C# and thea.NET Platform, Second Edition Introduction
Finally, add a final menu item under the Configure menu named "List All Fonts," which will be used to list all fonts installed on the end-user's machine. Figure 14-10 shows the menu UI logic (the File menu simply Chapter 1 - The Philosophy of .NET allows the user to exit the application). Part One - Introducing C# and the .NET Platform
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - 14-10: Programming with Windows Forms Controls Figure Menu layout of the FontApp project Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
To begin implementing ourand application, the Part Five - Web Applications XML Webupdate Services
main Form with a Timer member variable (named timer), a string to represent the current font face (named fontFace), and an integer (named swellValue) to Chapter 18 - ASP.NET Web Pages and Web Controls represent the amount to adjust the font size. In addition to configuring the basic look and feel of the Form, Chapter 19 - ASP.NET Web Applications configure your timer to emit a Tick event every 100 milliseconds: Chapter 20 - XML Web Services Index
public class FontForm : System.Windows.Forms.Form { List of Tables private Timer timer; private int swellValue; private string fontFace = " WingDings"; // The default font face. public FontForm() { // The menu system has been designed using the IDE... InitializeComponent(); timer = new Timer(); Text = "Font App"; Width = 425; Height = 150; BackColor = Color.Honeydew; CenterToScreen(); // Configure the Timer. timer.Enabled = true; timer.Interval = 100; List of Figures
timer.Tick += new EventHandler(FontForm_OnTimer); C# and the .NET Platform, Second Edition
}
by Andrew Troelsen Apress © 2003 (1200 pages)
}
ISBN:1590590554
This comprehensive text starts with a brief overview of the language and then to key technical and In the Tick event C# handler, increase the quickly value ofmoves the swellValue data member, and refresh your client area architectural issuesthat for .NET developers.integer will be added to the current font size to via the Invalidate() method. Recall the swellValue provide a simple animation (assume swellValue has a maximum upper limit of 50). To help reduce the flicker that can occur when redrawing the entire client area, you only refresh the minimum dirty rectangular Table of Contents region: C# and the .NET Platform, Second Edition Introduction
private void FontForm_OnTimer(object sender, EventArgs e) { Chapter 1 - The Philosophy of .NET // Increase current swellValue by 5. Chapter 2 - Building C# Applications swellValue += 5; Part Two - The C# Programming Language // If this value is greater than or equal to 50, reset to zero. Chapter 3 - C# Language Fundamentals if(swellValue >= 50) Chapter 4 - Object-Oriented with C# swellValueProgramming = 0; Chapter // 5 -Just Exceptions and Object Lifetime invalidate the 'minimal dirty rectangle to help reduce flicker. Chapter Invalidate(new 6 - Interfaces and Collections Rectangle(0, 0, ClientRectangle.Width, 100)); Chapter 7 - Callback Interfaces, Delegates, and Events } Part One - Introducing C# and the .NET Platform
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Now that upper 100 pixels your client area are refreshed with each tick of the Timer, you better have Chapter 9 the - Understanding .NETofAssemblies something render! InAppDomains, the Form's Paint handler, create a Font object based on the user-defined font face Chapter 10 -to Processes, Contexts, and Threads (as selected fromReflection, the appropriate menu item) and current swellValue (as dictated by the timer). Once you Chapter 11 - Type Late Binding, and Attribute-Based Programming have your Font objectthe fully configured, Part Four - Leveraging .NET Libraries render
a message into the center of the dirty rectangle:
Chapter 12 - Object Serialization and the .NET Remoting Layer
private FontForm_Paint(object PaintEventArgs e) Chapter 13 -void Building a Better Window (Introducingsender, Windows Forms) { Chapter 14 - A Better Painting Framework (GDI+) g = e.Graphics; Chapter Graphics 15 - Programming with Windows Forms Controls // The font size can be between 12 and 62, // based on the current swellValue. Chapter 17 - Data Access with ADO.NET Font theFont = new Font(fontFace, 12 + swellValue); Part Five - Web Applications and XML Web Services string message = "Hello GDI+"; Chapter 18 - ASP.NET Web Pages and Web Controls // Display message in the center of the rect. Chapter 19 - ASP.NET Web Applications float windowCenter = this.DisplayRectangle.Width/2; Chapter 20 - XML Web Services SizeF stringSize = g.MeasureString(message, theFont); Index float startPos = windowCenter - (stringSize.Width/2); List of Figures g.DrawString(message, theFont, new SolidBrush(Color.Blue), startPos, 10); List } of Tables Chapter 16 - The System.IO Namespace
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# and the .NET Platform, Second Edition
}
by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
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. Doing gives you a chance to explore another namespace of GDI+, System.Drawing.Text. This Table of so Contents namespace contains a (small) C# and the .NET Platform, 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. Introduction Part One - Introducing C# and the .NET Platform
Table 14-15: The Text Type Chapter 1 - The Philosophy of .NET Chapter 2 - Building C# Applications System.Drawing.Text Meaning in Life Part Two - The C# Programming Language Type
Chapter 3
- C# Language Fundamentals InstalledFontCollection Represents Chapter 4 - Object-Oriented Programming with the C# set of all fonts installed on the target system. Chapter 5
- Exceptions and Object Lifetime PrivateFontCollection Encapsulates a collection of specific Font types.
Chapter 6
- Interfaces and Collections LineSpacing This enumeration Chapter 7 - Callback Interfaces, Delegates, and Eventsspecifies the spacing between lines of text in a Chapter 8
text string Techniques that spans more than a single line. - Advanced C# Type Construction
Part Three - Programming with .NETAnother Assemblies TextRenderingHint enumeration
that allows you to specify the quality of the
Chapter 9
- Understanding .NET Assemblies current text rendering operation. For example, the Text value Chapter 10 - Processes, AppDomains, Contexts,aand represents fastThreads (but low quality) rendering. AntiAliased marks Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming better quality but a slower rendering cycle. Part Four - Leveraging the .NET Libraries
Chapter 12 -user Object Serialization and the |.NET Remoting When the selects the "Configure List All Fonts" Layer menu item, the corresponding Clicked handler Chapter 13 Building a Better Window (Introducing Forms) creates an instance of the InstalledFontCollectionWindows class. This class maintains an array named FontFamily, Chapter which represents 14 - A Better thePainting set of all Framework fonts on the (GDI+) target machine, and may be obtained using the
InstalledFontCollection.Families property. Using the FontFamily.Name property, you are able to extract the Chapter 15 - Programming with Windows Forms Controls font face New Namespace Roman, Arial, etc.) for each font. Chapter 16(e.g., - TheTimes System.IO Chapter 17 - Data Access with 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 Controls name of each string, and adds the new font face to the private installedFonts data member: Part Five - Web Applications and XML Web Services
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
public class FontForm : System.Windows.Forms.Form { List of Figures // 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(); } ... } Index
The final task is to render the installedFonts string to the client area, directly below the screen real estate C# and the .NET Platform, Second Edition that is used for your swelling text: by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
private void FontForm_Paint(object sender, PaintEventArgs e) This comprehensive text starts with a brief overview of the { C# language and then quickly moves to key technical and Graphicsarchitectural g = e.Graphics; issues for .NET developers. Font theFont = new Font(fontFace, 12 + swellValue); string message = "Hello GDI+"; Display message in the center of the window! Table of // Contents float = this.DisplayRectangle.Width/2; C# and the .NET windowCenter Platform, Second Edition SizeF stringSize = e.Graphics.MeasureString(message, theFont); Introduction float startPos = windowCenter Part One - Introducing C# and the .NET Platform - (stringSize.Width/2); theFont, new SolidBrush(Color.Blue), startPos, 10); Chapter g.DrawString(message, 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, Part Two - The C# Programming Language ClientRectangle.Width, ClientRectangle.Height); Chapter 3 - C# Language Fundamentals // Paint this area of the Form black. Chapter 4 - Object-Oriented Programming with C# g.FillRectangle(new SolidBrush(Color.Black), myRect); Chapter 5 - Exceptions and Object Lifetime g.DrawString(installedFonts, new Font("Arial", 12), Chapter 6 - Interfaces and Collections new SolidBrush(Color.White), myRect); Chapter 7 - Callback Interfaces, Delegates, and Events } Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter Understanding .NET Assemblies Recall 9that- the size of the "dirty rectangle" has been mapped to the upper 100 pixels of the client rectangle. Chapter Because 10 your - Processes, Tick handler AppDomains, only invalidates Contexts, 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 Programming of the client area). Chapter - Type Reflection, Late and Attribute-Based Part Four - Leveraging the .NET Libraries
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 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
private FontForm_Resize(object sender, System.EventArgs e) Chapter 15 -void Programming with Windows Forms Controls {
Chapter 16 - The System.IO Namespace
Rectangle myRect = new Rectangle(0, 100, ClientRectangle.Width, ClientRectangle.Height); Part Five - Web Applications and XML Web Services Invalidate(myRect); Chapter 18 - ASP.NET Web Pages and Web Controls } Chapter 17 - Data Access with ADO.NET
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Index With that, Figure 14-11 shows the result. List of Figures List of Tables
Figure 14-11: The FontApp application in action SOURCE CODE
The FontApp application is included under the Chapter 14 subdirectory.
C# andClass the .NET Platform, Second Edition The FontDialog by Andrew Troelsen
ISBN:1590590554
As you might assume, a default Apressthere © 2003is(1200 pages) font dialog box (FontDialog), as seen in Figure 14-12. This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5 - 14-12: Exceptions Object Figure Theand stock .NETLifetime Font dialog Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Like the ColorDialog type examined earlier in this chapter, when you wish to work with the FontDialog, Chapter 8 - Advanced C# Type Construction Techniques simply call the ShowDialog() method. Using the Font property, you may extract the characteristics of the Part Three - Programming with .NET Assemblies current selection for use in the application. To illustrate, here is a new Form that mimics the logic of the Chapter 9 - Understanding .NET Assemblies previous ColorDlgForm (i.e., click the form to launch the File dialog and render GDI+ logic onto the form's Chapter 10 - Processes, AppDomains, Contexts, and Threads client area). Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
public class FontDlgForm : System.Windows.Forms.Form { Chapter 13 - Building a Better Window (Introducing Windows Forms) private FontDialog fontDlg; Chapter 14 - A Better Painting Framework (GDI+) private Font currFont; Chapter private 15 - Programming with Windows Forms Controls void FontDlgForm_Paint(object sender, PaintEventArgs e) Chapter { 16 - The System.IO Namespace Chapter 17 - Data Access with Graphics g ADO.NET = e.Graphics; Part Five - Webg.DrawString("Testing...", Applications and XML Web Services currFont, Chapter 18 - ASP.NET new Web Pages and Web Controls SolidBrush(Color.Black), 0, 0); Chapter } 19 - ASP.NET Web Applications Chapter public 20 - XML Web FontDlgForm() Services Index { List of Figures 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 - Object Serialization and the .NET Remoting Layer
C# and the .NET Platform, Second Edition
SOURCE CODE
ISBN:1590590554 by Andrew Troelsen The FontDlgForm application is included under the Chapter 14 subdirectory. Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Survey of the System.Drawing.Drawing2D Namespace by Andrew Troelsen
ISBN:1590590554
Now that you have manipulated Font types, the next task is to examine how to manipulate Pen and Brush Apress © 2003 (1200 pages) objects to renderThis geometric patterns. While youwith could do so makingofuse comprehensive text starts a brief overview theof nothing more than the types found in the System.Drawing namespace, you should be aware that many C# language and then quickly moves to key technical and of the more "sexy" pen and architectural issuesthe for HatchBrush .NET developers. brush configurations (for example, type used at the beginning of this chapter) require types defined within the System.Drawing.Drawing2D namespace. Table This of additional Contents GDI+ namespace (which is substantially smaller than System.Drawing) provides a number
of and classes that allow youSecond to modify the line cap (triangle, diamond, etc.) used for a given pen, build C# the .NET Platform, Edition textured brushes, as well as work with vector graphic manipulations. Some core types to be aware of, Introduction grouped related functionality, are shown in Table Part One - by Introducing C# and the .NET Platform Chapter 1
14-16.
- The Philosophy of .NET
Table 14-16: The Classes of System.Drawing.Drawing2D Chapter 2 - Building C# Applications Part Two - The C# Programming Language
System.Drawing.Drawing2D
Meaning in Life
Chapter 3 - C# Language Fundamentals Class Chapter 4
- Object-Oriented Programming with C# AdjustableArrowCap Pen caps are used to paint the beginning and end points of Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections CustomLineCap
a given line. These types represent an adjustable arrow-
Chapter 7
shaped and user-defined cap. - Callback Interfaces, Delegates, and Events
Chapter Blend8
- Advanced C# Type Construction Techniques Used to define a blend pattern (and colors) used in
Part Three - Programming with .NET Assemblies conjunction with
ColorBlend
Chapter 9
a LinearGradientBrush.
- Understanding .NET Assemblies
Chapter GraphicsPath 10 - Processes, AppDomains, Contexts, A GraphicsPath and Threadsobject represents a series of connected
and curves. This class allows you to insert just about Chapter 11 - Type Reflection, Late Binding,lines and Attribute-Based Programming GraphicsPathIterator Part Four - Leveraging the .NET Libraries
PathData
any type of geometrical pattern (arcs, rectangles, lines,
strings, polygons, Chapter 12 - Object Serialization and the .NET Remoting Layeretc.) into the path. PathData holds the graphicalWindows data thatForms) makes up a path. Chapter 13 - Building a Better Window (Introducing Chapter 14 - A Better Painting Framework (GDI+) HatchBrush Exotic brush types. Chapter 15 - Programming with Windows Forms Controls
LinearGradientBrush
Chapter 16 - The System.IO Namespace
PathGradientBrush Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Also be18 aware that the System.Drawing.Drawing2D namespace defines another set of enumerations that Chapter - ASP.NET Web Pages and Web Controls are used these core types. Table 14-17 gives a quick rundown. Chapter 19 in- conjunction ASP.NET Webwith Applications Chapter 20 - XML Web Services
Table 14-17: The Enumerations of System.Drawing.Drawing2D
Index
List of Figures List of Tables
System.Drawing.Drawing2D Meaning C# and the .NET Platform, Second Edition in Life Enumeration by Andrew Troelsen ISBN:1590590554 DashStyle FillMode
Apress © 2003 (1200 pages)
Specifies the style of dashed lines drawn with a
This comprehensive text starts with a brief overview of the Pen C# language and then quickly moves to key technical and architectural issues for .NET developers.
Specifies how the interior of a closed path is filled
HatchStyle
Specifies the different patterns available for HatchBrush objects
Table of Contents C# and the .NET Platform, Second Edition
LinearGradientMode
Specifies the direction to apply a linear gradient
Introduction
Part One - Introducing C# and the .NET Platform LineCap
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
Part Two - The C# Programming Language
Chapter PenType 3 - C# Language Fundamentals
Specifies the type of fill a Pen uses to fill lines
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
QualityMode
SmoothingMode Chapter 6 - Interfaces and Collections
Specifies the overall quality used to render a graphic image
RenderingHint Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
- Understanding .NET Assemblies Quality Establishing the Rendering
Chapter 9
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter Notice 11 that- some Type Reflection, of the enumerations Late Binding, defined and Attribute-Based in the System.Drawing.Drawing2D Programming namespace (such as Part QualityMode Four - Leveraging and SmoothingMode) the .NET Libraries allow
you to configure the overall quality of the current rendering
operation. obtain a Graphics object, it has aLayer default rendering mode, which is a middle-of-theChapter 12 -When Objectyou Serialization and the .NET Remoting road combination of aspeed overall quality. Let's examine one way to tweak a Graphics object to Chapter 13 - Building Betterand Window (Introducing Windows Forms) override default values.Framework (GDI+) Chapter 14these - A Better Painting Chapter 15 - Programming with Windows Forms Controls
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 System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Table 14-18: Various SmoothingMode Values
Chapter 18 - ASP.NET Web Pages and Web Controls
SmoothingMode Meaning in Life Chapter 19 - ASP.NET Web Applications Value Chapter 20 - XML Web Services Index
AntiAlias
List of Figures 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# and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen Graphics g = e.Graphics; Apress © 2003 (1200 pages) // Set quality of GDI+ object rendering. This comprehensive text starts with a brief overview of the g.SmoothingMode = SmoothingMode.AntiAlias; C# language and then quickly moves to key technical and ... architectural issues for .NET developers. } Table of Contents
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 Introduction TextRenderingHint property using the related System.Drawing.Text.TextRenderingHint enumeration: C# and the .NET Platform, Second Edition
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
public enum System.Drawing.Text.TextRenderingHint - Building C# Applications { Part Two - The C# Programming Language AntiAlias, AntiAliasGridFit, Chapter 3 - C# Language Fundamentals ClearTypeGridFit, SingleBitPerPixel, Chapter 4 - Object-Oriented Programming with C# SingleBitPerPixelGridFit, SystemDefault Chapter 5 - Exceptions and Object Lifetime } Chapter 2
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Working with Pens
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
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 Attribute-Based Programming valid Pen type to any number of render methods defined by the Graphics class. In general, the Part Four - Leveraging the .NET Libraries DrawXXXX() methods are used to render some set of lines to a graphics surface, and are typically used Chapter 12objects. - ObjectThe Serialization thealso .NETdefines Remoting Layer of FillXXXX() methods that render an image with Pen Graphicsand class a number Chapter 13 Building a Better Window (Introducing Windows Forms) using some sort of Brush-derived type (more on those in just a minute). Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 14 - A Better Painting Framework (GDI+)
Although have seen many drawing Forms members earlier in the chapter, here they are again (Table 14-19) Chapter 15 you - Programming with Windows Controls in a bit 16 more detail (be aware that each of these methods have been overloaded a number of times). Chapter - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Table Members ofWeb the Services Graphics Part Five14-19: - WebDrawing Applications and XML
Class
Chapter 18 - ASP.NET and Web Controls Drawing MethodWeb of PagesMeaning in Life Chapter 19 - ASP.NET Graphics Type Web Applications Chapter 20 - XML Web Services
DrawArc() Index List of Figures 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# and the .NET Draws the outline of a polygon Platform, Second Edition defined by an array of Point types. ISBN:1590590554 by Andrew Troelsen DrawRectangle() Renders a box, or a whole bunch of boxes, based on top-leftApress © 2003 (1200 pages) bottom-right coordinates. This can be specified using Rectangle DrawRectangles() This comprehensive starts or with a briefpoint overview of the types,text integers, floating numbers.
C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 of width of the pen nib (you can also construct a new Pen based on an existing Brush object...more Table Contents later). Most of aPlatform, Pen's functionality comes by way of its supported properties. Table 14-20 gives a partial C# and the .NET Second Edition list. Introduction Part One - Introducing C# and the .NET Platform
Table 14-20: Pen Properties - The Philosophy of .NET
Chapter 1
Chapter - Building C#Meaning Applications Pen 2Property in Life Part Two - The C# Programming Language
Brush3 Chapter
Determines the Brush used by this Pen. - C# Language Fundamentals
Chapter Color4
- Object-Oriented Programming with C# used by this Pen. Determines the Color type - Exceptions and Object Lifetime
Chapter 5
CompoundArray or sets an array of custom dashes and spaces. Chapter 6 - Interfaces Gets and Collections Chapter 7 - Callback Interfaces, Delegates, andcap Events CustomStartCap Gets or sets a custom style to use at the beginning or end of lines drawn Chapter 8 - Advanced C# Techniques withType this Construction Pen. Cap styles are simply the term used to describe how the initial
CustomEndCap
Part Three - Programming Assemblies andwith final.NET stroke of the Pen
should look and feel. These properties allow you
Chapter 9
- Understanding .NETcustom Assemblies to build caps for your Pen types. Chapter 10 - Processes, AppDomains, Contexts, and Threads
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 Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter DashOffset 12 - Object Serialization Gets or sets and the the distance .NET Remoting from the Layer start of a line to the beginning of a dash Chapter 13 - Building a pattern. Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
DashPattern
Gets or sets an array of custom dashes and spaces. The dashes are made up of line segments.
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
DashStyle Gets sets the style used for dashed lines drawn with this Pen. Chapter 17 - Data Access withorADO.NET Part Five - Web Applications and XML Web Services
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 Controls Chapter 19 - ASP.NET Web Applications
PenType Gets the style of lines drawn with this Pen. Chapter 20 - XML Web Services Index 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 Figures 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); and thepen .NETfrom Platform, Edition // Get aC#stock the Second Pens type. ISBN:1590590554 by Andrew Troelsen Pen pen2 = Pens.Firebrick; Apress © 2003 (1200 pages) // Render some shapes with the pens. This comprehensive text starts with a brief100); overview of the g.DrawEllipse(bluePen, 10, 10, 100, C# language and then quickly moves to key g.DrawLine(pen2, 10, 130, 110, 130); technical and architectural issues for .NET developers. g.DrawPie(Pens.Black, 150, 10, 120, 150, 90, 80); // Draw a purple dashed polygon as well... Pen pen3 = new Pen(Color.Purple, 5); Table of Contents pen3.DashStyle = DashStyle.DashDotDot; C# and the .NET Platform, Second Edition g.DrawPolygon(pen3, new Point[]{new Point(30, 140), Introduction new Point(265, 200), new Point(100, 225), Part One - Introducing C# and the .NET Platform 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... Part Two - The C# Programming Language Rectangle r = new Rectangle(150, 10, 130, 60); Chapter g.DrawRectangle(Pens.Blue, 3 - C# Language Fundamentals r); Chapter g.DrawString("Hello 4 - Object-Oriented Programming with C# out there...How are ya?", Chapter 5 - Exceptions and Object Lifetime new Font("Arial", 12), Brushes.Black, r); Chapter 6 - Interfaces and Collections } Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Notice 9that- the Pen that is used to render your polygon makes use of the DashStyle enumeration (defined Chapter Understanding .NET Assemblies in System.Drawing.Drawing2D). ThisContexts, is the .NET of the raw Win32 pen style flags (e.g., Chapter 10 - Processes, AppDomains, and equivalent Threads PS_SOLID).Table 14-21 lists your choices.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Table 14-21: Dash Styles
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing DashStyle Meaning in Life Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Value Chapter 15 - Programming with Windows Forms Controls
Custom
Specifies a user-defined custom dash style
Chapter 16 - The System.IO Namespace
Chapter ADO.NET Dash 17 - Data Access with Specifies a line comprised of dashes Part Five - Web Applications and XML Web Services
DashDot
Specifies a line comprised of an alternating pattern of dash-dot-dash-dot
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Specifies Applications DashDotDot a line comprised of an alternating pattern of dash-dot-dot-dashChapter 20 - XML Web Services dot-dot Index
Dot
List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies Figure 14-13: Working with Pen types
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 -custom Type Reflection, Late Binding, andaround Attribute-Based Programming // Draw dash pattern all the boarder of the form. Part - Leveraging the = .NET Libraries PenFour customDashPen new Pen(Color.BlueViolet,
5);
Chapter 12 -myDashes Object Serialization and the2.0f, .NET Remoting float[] = { 5.0f, 1.0f, Layer 3.0f} ; Chapter 13 Building a Better Window (Introducing Windows Forms) customDashPen.DashPattern = myDashes; Chapter g.DrawRectangle(customDashPen, 14 - A Better Painting Framework (GDI+) ClientRectangle); Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
SOURCE The PenApp project is included under the Chapter 14 subdirectory. CODE Part Five - Web Applications and XML Web Services Chapter 17 - Data Access with ADO.NET
Chapter 18 - ASP.NET Web Pages and Web Controls
Working with Pen Caps
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
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 Figures 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. Index
Table 14-22: LineCap Values
LineCap Values Meaning in Second Life Edition C# and the .NET Platform, ArrowAnchor
ISBN:1590590554 by Andrew Troelsen Specifies an arrow-shaped cap Apress © 2003 (1200 pages)
DiamondAnchorThis comprehensive Specifies textastarts diamond with anchor a brief overview cap of the C# language and then quickly moves to key technical and Specifies a flatdevelopers. line cap architectural issues for .NET
Flat Round
Specifies a round line cap
Table of Contents RoundAnchor
Specifies a round anchor cap
C# and the .NET Platform, Second Edition
Square
Introduction
Specifies a square line cap
Part One - Introducing C# and the .NET Platform SquareAnchor Specifies no line
Chapter 1
cap
- The Philosophy of .NET
Triangle - Building C# Applications Specifies a triangular line cap
Chapter 2
Part Two - The C# Programming Language
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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and .NET Platform, Second Edition int yOffSet = the 10; by Andrew Troelsen // Get all members of the LineCap enum. ISBN:1590590554 Apress © 2003 (1200 pages) Array obj = Enum.GetValues(typeof(LineCap)); This comprehensive starts with a brief overview of the // Draw a line with a text LineCap member. C# language and then quickly moves to key technical and for(int x = 0; x < obj.Length; x++) architectural issues for .NET developers. { // Get next cap and configure pen. LineCap temp = (LineCap)obj.GetValue(x); Table of Contents thePen.StartCap = temp; C# and the .NET Platform, Second Edition thePen.EndCap = temp; Introduction // Print name of LineCap enum. Part One - Introducing C# and the .NET Platform 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. Part Two - The C# Programming Language g.DrawLine(thePen, 100, yOffSet, Width - 50, yOffSet); Chapter 3 - C# Language += Fundamentals yOffSet 40; Chapter } 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime } Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
SOURCE The PenCapApp project is included under the Chapter 14 subdirectory. Chapter 9 - Understanding .NET Assemblies CODE Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Working with Solid Brushes
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
So much drawinga lines. Brush-derived are used to fill the space between the lines, with a Chapter 13 for - Building BetterGDI+ Window (Introducingtypes Windows Forms) given color, pattern, or image. Recall that the Brush class is an abstract type, and cannot be directly Chapter 14 - A Better Painting Framework (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 System.IO Namespace the System.Drawing namespace also defines two types that return a configured brush using a number of Chapter 17 - Data Access with ADO.NET static properties: Brushes and SystemBrushes. Using a properly configured brush, you are able to call any Part Five - Web Applications and XML Web Services number of methods [such as DrawString()], as well as the following set of FillXXXX() methods (Table 14Chapter 18 - ASP.NET Web Pages and Web Controls 23). Chapter 15 - Programming with Windows Forms Controls
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Table 14-23: Fill Methods of the Graphics Type
Index
Method of Graphics ListFill of Figures
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# and the .NET Platform, Second Edition are able to build some brush of interest (for example, a brush that paints a bitmap image) and render by with Andrew TroelsenPen. To illustrate, here is aISBN:1590590554 geometric patterns configured small sample program that makes use of Apress © 2003 (1200 [the pages) the SolidBrush and Brushes types output of this program (Figure 14-15) should look familiar...] This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure 14-15: Working with Brush types
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
If you can't this application is little more than the original Pens application, making use of the Chapter 15 - tell, Programming with Windows Forms Controls FillXXXX() and SolidBrush types, rather than pens and the related DrawXXXX() methods. Here is Chapter 16 -methods The System.IO Namespace the implementation of the paint handler: Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
private MainForm_Paint(object Chapter 18 -void ASP.NET Web Pages and Web Controlssender, PaintEventArgs e) { Chapter 19 - ASP.NET Web Applications g Services = e.Graphics; Chapter Graphics 20 - XML Web // Make a blue SolidBrush. SolidBrush blueBrush = new SolidBrush(Color.Blue); List of Figures // 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); } Index
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
SOURCE CODE
ISBN:1590590554
SolidBrushApp projectwith is included under the Chapter 14 subdirectory. ThisThe comprehensive text starts a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Working with Hatch Style Brushes Table of Contents
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 Introduction HatchStyle enumeration. Here are some (but not all) of the hatch values (Table 14-24). C# and the .NET Platform, Second Edition
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Table 14-24: Values of the HatchStyle Enumeration
Part Two - The C# Enumeration Programming Language HatchStyle Meaning
in Life
Chapter Value 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter Cross6 Chapter 7
- Interfaces and Collections Creates a brush consisting of horizontal and vertical crossing - Callback Interfaces, Delegates, linesand Events
Chapter 8
- Advanced C# Type Construction Techniques
BackwardDiagonal
DiagonalCross
Creates a brush consisting of backward diagonal lines
Creates a brush consisting of diagonal crossing lines
Part Three - Programming with .NET Assemblies
Chapter ForwardDiagonal 9 - Understanding .NET Assemblies Creates a brush consisting of forward diagonal lines Chapter 10 - Processes, AppDomains, Contexts, and Threads
Hollow
Configures a "hollow" brush that doesn't paint anything
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Horizontal Four - Leveraging the .NET LibrariesCreates
a brush consisting of horizontal lines
Chapter 12 - Object Serialization and the .NET Remoting Layer
Pattern
Creates a Brush with a pattern consisting of a custom bitmap
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Solid 14 - A Better Painting Framework Creates Chapter (GDI+)a solid colored brush (as an alternative to using the type directly) Chapter 15 - Programming with WindowsSolidBrush Forms Controls Chapter 16 - The System.IO Namespace
Vertical
Chapter 17 - Data Access with ADO.NET
A brush consisting of vertical lines
Part Five - Web Applications and XML Web Services
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 Controls use during fill operation. To illustrate, let's rework the logic seen previously from the PenCapApp Chapter 19 The - ASP.NET Applications example. output Web renders a filled oval for the first ten hatch values (Figure 14-16). Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 14-16: The hatch styles
Here is the code C# behind and the theForm: .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
© 2003 (1200 pages) private void Apress MainForm_Paint(object sender, PaintEventArgs e) This comprehensive text starts with a brief overview of the { and then quickly moves to key technical and GraphicsC#glanguage = e.Graphics; architectural issues for .NET developers. int yOffSet = 10; // Get all members of the HatchStyle enum. Array obj = Enum.GetValues(typeof(HatchStyle)); Table of Contents // Draw an oval with first 10 HatchStyle values. C# and the .NET Platform, Second Edition for(int x = 0; x < 10; x++) Introduction { Part One - Introducing C# and the .NET Platform // Configure Brush. Chapter 1 - The Philosophy of .NET HatchStyle temp = (HatchStyle)obj.GetValue(x); Chapter 2 - Building C# Applications HatchBrush theBrush = new HatchBrush(temp, Part Two - The C# Programming Language Color.White, Color.Black Chapter 3 - C# Language // Print Fundamentals name of HatchStyle enum. Chapter 4 - Object-Oriented Programming with C# g.DrawString(temp.ToString(), new Font("Times New Roman", 10), Chapter 5 - Exceptions and Object Lifetime new SolidBrush(Color.Black), 0, yOffSet); Chapter 6 - Interfaces andaCollections // Fill rectangle with the correct brush. Chapter 7 - Callback g. FillEllipse(theBrush, Interfaces, Delegates, and Events 150, yOffSet, 200, 25); yOffSet += 40; Chapter 8 - Advanced C# Type Construction Techniques } - Programming with .NET Assemblies Part Three } Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
SOURCE CODE
The BrushStyles application is included under the Chapter 14 subdirectory.
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Working with Textured Brushes
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with 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 Controls 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. TheApplications image itself is typically found stored in some local file (*.bmp, *.gif, *.jpg) or Chapter 20 XML Web Services embedded into a .NET assembly. Part Five - Web Applications and XML Web Services
Index
Let's build a sample application that makes use of the TextureBrush type. One brush is used to paint the List of Figures 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# and the .NET Platform, Second Edition
ISBN:1590590554 Andrew The code is very by simple. ToTroelsen begin, your Form-derived class maintains two abstract Brush types, which are Apress © 2003 (1200 assigned to a new TextureBrush in pages) the constructor. Notice that the constructor of the TextureBrush type requires a type derived This comprehensive from Image: text starts with a brief overview of the
C# language and then quickly moves to key technical and architectural issues for .NET developers.
public class MainForm : System.Windows.Forms.Form { Note! These *.bmp files must be in the same folder Table of // Contents // as the application (or specify hard coded paths). C# and the .NET Platform, Second Edition // We'll fix this limitation later in this chapter. Introduction Part One - Introducing C# and the .NET Platform
// Data for the image brush. - The Philosophy of .NET private Brush texturedTextBrush; Chapter 2 - Building C# Applications private Brush texturedBGroundBrush; Part Two - The C# Programming Language public MainForm() Chapter 3 - C# Language Fundamentals { Chapter 4 - Object-Oriented Programming with C# ... Chapter 5 - Exceptions Object for Lifetime // Loadand image background brush. Chapter 6 - Interfaces and Collections Image bGroundBrushImage = new Bitmap("Clouds.bmp"); Chapter 7 - Callback Interfaces, Delegates, and Events texturedBGroundBrush = new TextureBrush(bGroundBrushImage); Chapter 8 - Advanced Type image Construction // NowC#load for Techniques text brush. Part Three - Programming with .NET Assemblies Image textBrushImage = new Bitmap("Soap Bubbles.bmp"); Chapter 9 - Understanding .NET Assemblies texturedTextBrush = new TextureBrush(textBrushImage); Chapter } 10 - Processes, AppDomains, Contexts, and Threads ... 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter } Four - Leveraging the .NET Libraries Part Chapter 1
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Now that you have two TextureBrush types to render with, the paint handler should be a no-brainer:
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
private MainForm_Paint(object sender, PaintEventArgs e) Chapter 16 -void The System.IO Namespace {
Chapter 17 - Data Access with ADO.NET
Graphics g = e.Graphics; Rectangle r = ClientRectangle; Chapter 18 - ASP.NET Web Pages and Web Controls // Paint the clouds on the client area. Chapter 19 - ASP.NET Web Applications g.FillRectangle(texturedBGroundBrush, r); Chapter 20 - XML Web Services // Some big bold text with a textured brush. Index g.DrawString("Bitmaps as brushes! Way cool...", List of Figures new Font("Arial", 60, List of Tables FontStyle.Bold | FontStyle.Italic), texturedTextBrush, r); } Part Five - Web Applications and XML Web Services
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# and the .NET Platform, Second Edition two colors together in a gradient pattern. Working with this type is just as simple as working with the other ISBN:1590590554 Andrew Troelsen brush types. The by only point of interest is that when building a LinearGradientBrush, you need to specify the Apress © 2003 (1200 pages) direction of the blend, using a value from the LinearGradientMode enumeration (Table 14-25). This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and Table 14-25: LinearGradientMode Enumeration architectural issues for .NET developers.
LinearGradientMode Value Table BackwardDiagonal of Contents C# and the .NET Platform, Second Edition
ForwardDiagonal
Introduction
Meaning in Life Specifies a gradient from upper right to lower left Specifies a gradient from upper left to lower right
Part Horizontal One - Introducing C# and the .NET Platform Specifies
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
Part Two - The C# Programming Language
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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Figure GradientNamespace brushes at work Chapter 16 - 14-18: The System.IO Chapter 17 - Data Access with ADO.NET
Now the code, which I assume requires little comment at this point:
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
private MainForm_Paint(object sender, PaintEventArgs e) Chapter 19 -void ASP.NET Web Applications { Chapter 20 - XML Web Services Graphics g = e.Graphics; Rectangle r = new Rectangle(10, 10, 100, 100); List of Figures // 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); Index
yOffSet += 80; C# and the .NET Platform, Second Edition
}
by Andrew Troelsen Apress © 2003 (1200 pages)
}
SOURCE CODE
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers. The GradientBrush application is included under the Chapter 14 subdirectory.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Rendering C# Images by Andrew Troelsen
ISBN:1590590554
At this point you have examined how to manipulate three of the four major GDI+ types (fonts, pens, and Apress © 2003 (1200 pages) brushes). The final type you examine in this chapter the Image class, and related subtypes. The abstract This comprehensive text starts with aisbrief overview of the System.Drawing.Image type defines a number of methods and properties C# language and then quickly moves to key technical and that hold various bits of architectural issues for .NET information regarding the underlying pixel setdevelopers. 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. Table of Contents C# and the .NETMembers Platform, of Second EditionType Table 14-26: the Image Introduction
Image Member C# andMeaning in Life Part One - Introducing the .NET Platform Name1 Chapter
- The Philosophy of .NET
Chapter 2 - Building C# Applications FromFile() This static method creates an Image from the specified file. Part Two - The C# Programming Language
FromHbitmap() This static method creates a Bitmap from a Windows handle. Chapter 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# FromStream() This static method creates an Image from the specified data stream. Chapter 5 - Exceptions and Object Lifetime
Height6 Chapter
These properties return information regarding the dimensions of this - Interfaces and Collections
Chapter Width7
Image. - Callback Interfaces, Delegates, and Events
Chapter Size 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
PhysicalDimensions
Chapter 9
- Understanding .NET Assemblies
HorizontalResolution Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter VerticalResolution 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Palette
This property returns a ColorPalette data type that represents the underlying palette used for this Image.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
GetBounds() a Rectangle Chapter 14 - A Better PaintingReturns Framework (GDI+) that represents the current size of this Image. Chapter 15 - Programming with Windows Forms Controls
Save()
Saves the data held in an Image-derived type to file.
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five - Web andclass XML Web Services Given that the Applications abstract Image cannot be directly
created, you typically make a direct instance of the
Chapter - ASP.NET Web Pages and you Webhave Controls Bitmap18 type. For example, assume some Form-derived class that renders three bitmaps into the Chapter client area. 19 - To ASP.NET begin,Web you Applications may create 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 Services Index List of Figures public class 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# and the .NET Platform, Second Edition
Rendering these items from within the context of a paint handler is easy as could be, given that the ISBN:1590590554 by Andrew Troelsen Graphics class has a member named (appropriately enough) DrawImage(). This method has been Apress © 2003 (1200 pages) overloaded numerous times to provide various ways to place the image onto the drawing surface. For This comprehensive text starts with and a brief overview of enumerations. the example, you may specify optional ImageAttributes GraphicsUnit For your purposes, all C# language and then quickly moves to key technical and you need to do isarchitectural specify the location at which to render each image (which may be defined using Point, issues for .NET developers. Rectangles, integers, or floats): Table of Contents protected void OnPaint (object sender, System.Windows.Forms.PaintEventArgs e) C# { and the .NET Platform, Second Edition
Graphics g = e.Graphics; Introduction Render all three images. Part One// - Introducing C# and the .NET Platform 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 Part Twog.DrawImage(bMapImageC, - The C# Programming Language10,
210, 90, 90);
} Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
The result can be seen in Figure 14-19.
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition g.DrawImage(myPNG, 150, 200); by Andrew Troelsen g.DrawImage(myTIF, 300, 200);
ISBN:1590590554
Apress © 2003 (1200 pages)
SOURCE CODE
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers. The Images application is included under the Chapter 14 subdirectory.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Edition Dragging, Hit Testing, and theSecond PictureBox Control by Andrew Troelsen
ISBN:1590590554
While you are free to render images directly onto a Control-derived type (such as a Form), you will Apress © 2003Bitmap (1200 pages) find that you gainThis far greater control youoverview instead choose comprehensive and text functionality starts with a if brief 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 moves to key technical so. andFirst, because the PictureBox type architectural issues for .NET derives from Control, you inherit a great dealdevelopers. 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 Table of Contents boilerplate code. C# and the .NET Platform, Second Edition
To illustrate the usefulness of the PictureBox type, let's create an application that illustrates the ability to Introduction capture MouseDown, and MouseMove Part One -MouseUp, Introducing C# and the .NET Platform
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 - Object-Oriented Programming with C# (seen shortly). As you may know, the process of testing for mouse Click events within the context of a Chapter 5 the - Exceptions Object region of screen is and termed "hitLifetime testing." Part Two - The C# Programming Language
Chapter 6
- Interfaces and Collections When it7 comes to theInterfaces, functionality provided byEvents the PictureBox type, there is little to say, as all of the Chapter - Callback Delegates, and
necessary comes from the Control base class. Given that you have already explored a Chapter 8 -functionality Advanced C# Type Construction Techniques number the members with for these you can Part Threeof- Programming .NET types, Assemblies
quickly turn your attention to the process of assigning an
image to PictureBox member variable: Chapter 9 the - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
public MainForm : Binding, System.Windows.Forms.Form Chapter 11 class - Type Reflection, Late and Attribute-Based Programming { Four - Leveraging the .NET Libraries Part an image smileyLayer face. Chapter // 12 -This Objectholds Serialization and the of .NETaRemoting PictureBox happyBox; Chapter private 13 - Building a Better Window (Introducing Windows Forms) MainForm() Chapter public 14 - A Better Painting Framework (GDI+) Chapter { 15 - Programming with Windows Forms Controls
// Configure the PictureBox. happyBox = new PictureBox(); Chapter 17 - Data Access with ADO.NET happyBox.SizeMode = PictureBoxSizeMode.StretchImage; Part Five - Web Applications and XML Web Services happyBox.Location = new System.Drawing.Point(64, 32); Chapter 18 - ASP.NET Web Pages and Web Controls happyBox.Size = new System.Drawing.Size(50, 50); Chapter 19 - ASP.NET Web Applications happyBox.Cursor = Cursors.Hand; Chapter 20 - XML Web Services happyBox.Image = new Bitmap("happy.bmp"); Index // Now add to the Form's Controls collection. List of Figures Controls.Add(happyBox); List of Tables } ... } Chapter 16 - The System.IO Namespace
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 Second in Life C# and the .NET Platform, Edition Member Name by Andrew Troelsen AutoSize CenterImage
ISBN:1590590554
Apress © 2003 (1200 pages)
The PictureBox is sized equal to the size of the image that it
This comprehensive text starts with a brief overview of the contains. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents
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 the .NET Platform, Second Edition
Normal Introduction
The image is located in the upper left corner of the PictureBox. If is smaller than the image, it will be clipped.
thePlatform PictureBox Part One - Introducing C# and the .NET 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 Part Two - for Thethe C# MouseMove, ProgrammingMouseUp, Language
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
- Object-Oriented Programming with C# // Add the following events. Chapter 5 handlers - Exceptions for and Object Lifetime
happyBox.MouseDown new MouseEventHandler(happyBox_MouseDown); Chapter 6 - Interfaces and += Collections happyBox.MouseUp += newDelegates, MouseEventHandler(happyBox_MouseUp); Chapter 7 - Callback Interfaces, and Events happyBox.MouseMove += new MouseEventHandler(happyBox_MouseMove); Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
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 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
// Mouse event handler to initiate dragging the pictureBox around. private void happyBox_MouseDown(object sender, MouseEventArgs e) Chapter 13 - Building a Better Window (Introducing Windows Forms) { Chapter 14 - A Better Painting Framework (GDI+) isDragging = true; Chapter 15 - Programming with Windows Forms Controls // Save the (x, y) of the mouse down click, Chapter // 16 -because The System.IO Namespace we need it as an offset when dragging the image. Chapter oldX 17 - Data Access with ADO.NET = e.X; Part FiveoldY - Web=Applications and XML Web Services e.Y; Chapter 18 ASP.NET Web Pages and Web Controls } Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
The MouseMove handler simply relocates the position of the PictureBox (using the Top and Left Index properties) List of Figuresby 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# and the .NET Platform, Second Edition however, that this application has one extra point of logic. If the MouseUp event occurs when the ISBN:1590590554 by Andrew Troelsen PictureBox is contained within a GDI+ Rectangle object, you can assume the user has won the game Apress © 2003 (1200 pages) (albeit a rather lame game...). That said, here is the remainder of the Form's logic: This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and // When the mouse goesissues up,for they done dragging. architectural .NET are developers.
// See if they dropped the image in the rectangle... private void happyBox_MouseUp(object sender, MouseEventArgs e) Table { of Contents isDragging = Second false;Edition C# and the .NET Platform, // Is the mouse within the area of the drop rect? Introduction Part Oneif(dropRect.Contains(happyBox.Bounds)) - Introducing C# and the .NET Platform MessageBox.Show("You win!", "What an amazing test of skill..."); Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications Part Two - The C# Programming Language
// Assume we have aFundamentals private Rectangle configured as follows: Chapter 3 - C# Language // Rectangle dropRect = new Rectangle(100, 100, 150, 150); - Object-Oriented Programming with C# private void MainForm_Paint(object sender, PaintEventArgs e) Chapter 5 - Exceptions and Object Lifetime { Chapter 6 - Interfaces and Collections // Draw the drop box. Chapter 7 - Callback Interfaces, Delegates, and Events Graphics g = e.Graphics; Chapter 8 - Advanced C# Type Construction Techniques g.FillRectangle(Brushes.AntiqueWhite, dropRect); Part Three - Programming with .NET Assemblies // Display instructions. Chapter g.DrawString("Drag 9 - Understanding .NET Assemblies the happy guy in here...", Chapter 10 - Processes, AppDomains, Contexts, and Threads new Font("Times New Roman", 25), Brushes.Red, dropRect); Chapter 11 Type Reflection, Late Binding, and Attribute-Based Programming } Chapter 4
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
As a reminder, it is worth pointing out(Introducing that the Rectangle defines the Contains() method that has been Chapter 13 - Building a Better Window Windowstype Forms) overloaded test forPainting contained Rectangle, Point, or two integer values. This member can be quite helpful Chapter 14 - to A Better Framework (GDI+) when calculating if a mouse has occurred within a given rectangular region (as seen in the MouseUp Chapter 15 - Programming withclick Windows Forms Controls event handler). you run the application, you are presented with what appears in Figure 14-20. Chapter 16 - The When System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Figure 14-21: You have nerves of steel... Table of Contents
SOURCE TheSecond DraggingImages application is included under the Chapter 14 subdirectory. C# and the .NET Platform, Edition CODE
Introduction
Part One - Introducing C# and the .NET Platform
More Hit - The Testing Philosophy Details of .NET
Chapter 1 Chapter 2
- Building C# Applications
Validating a hit test against a Control-derived Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# Images application, and add some additional functionality. Chapter 5
- Exceptions and Object Lifetime
Chapter 6 is- to Interfaces andwhen Collections The goal determine the user clicks a given image (which as you recall was not rendered within Chapter 7 Callback Interfaces, and Events a PictureBox control). Once youDelegates, discover which image was clicked, adjust the Text property of the Form, Chapter 8 - Advanced C#with Type Construction Techniques and highlight the image a 5-pixel outline. Part Three - Programming with .NET Assemblies
The first is to intercept.NET the MouseDown Chapter 9 step - Understanding Assemblies event for the Form itself. When the event occurs, you need to programmatically figure out if the incoming (x,and y) coordinate Chapter 10 - Processes, AppDomains, Contexts, Threads is somewhere within the bounds of the Rectangles used Reflection, to represent theBinding, dimension each Image. Programming If the user does click a given image, you set a Chapter 11 - Type Late and of Attribute-Based private member variable (isImageClicked) Part FourBoolean - Leveraging the .NET Libraries
to true, and indicate which image was selected via another member variable (of type integer): Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
public MainForm : System.Windows.Forms.Form Chapter 14 class - A Better Painting Framework (GDI+) { Chapter 15 - Programming with Windows Forms Controls ... // Did they click an image? Chapter 17 - Data Access with ADO.NET private bool isImageClicked = false; Part Five - Web Applications and XML Web Services private int imageClicked; Chapter 18 - ASP.NET Web Pages and Web Controls protected void OnMouseDown (object sender, MouseEventArgs e) Chapter 19 - ASP.NET Web Applications { Chapter 20 - XML Web Services // Get (x, y) of mouse click. Index Point mousePt = new Point(e.X, e.Y); List of Figures // 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 System.IO Namespace
this.Text = "You clicked image C"; } C# and the .NET Platform, Second Edition ISBN:1590590554 by Andrew// Troelsen else Not in any shape, set defaults. Apress © 2003 (1200 pages) { ThisisImageClicked comprehensive text starts with a brief overview of the = false; C# language and then quickly moves this.Text = "Images"; to key technical and architectural issues for .NET developers. } // Redraw the client area. Invalidate(); Table of Contents } C# and the .NET Platform, Second Edition ... Introduction } Part One - Introducing C# and the .NET Platform
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 Part Theclick C# Programming Language userTwo did -not one of your three 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 - Object-Oriented Programming with C# updated handler: Chapter 5
- Exceptions and Object Lifetime
Chapter 6 -void Interfaces and Collections private MainForm_Paint(object sender, PaintEventArgs e) Chapter 7 Callback Interfaces, Delegates, and Events { Chapter Graphics 8 - Advanced Type Construction Techniques g C# = e.Graphics; Part Three .NET images. Assemblies //- Programming Render allwith three
Chapter ... 9 - Understanding .NET Assemblies
outline (if clicked...) Chapter // 10 -Draw Processes, AppDomains, Contexts, and Threads true) Chapter if(isImageClicked 11 - Type Reflection, Late == Binding, and Attribute-Based Programming Part Four{ - Leveraging the .NET Libraries
Pen Serialization outline =and new Chapter 12 - Object the Pen(Color.Red, .NET Remoting Layer 5); switch(imageClicked) Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A { Better Painting Framework (GDI+)
case 0: g.DrawRectangle(outline, rectA); Chapter 16 - The System.IO Namespace break; Chapter 17 - Data Access with ADO.NET case 1: Part Five - Web Applications and XML Web Services g.DrawRectangle(outline, rectB); Chapter 18 - ASP.NET Web Pages and Web Controls break; Chapter 19 - ASP.NET Web Applications case 2: Chapter 20 - XML Web Services g.DrawRectangle(outline, rectC); Index break; List of Figures default: List of Tables break; } } } Chapter 15 - Programming with Windows Forms Controls
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Chapter 3
- C# Language Fundamentals
Figure 14-22: Hit-testing polygons Part Two - The C# Programming Language This geometric image was rendered on the Form using the FillPath() method of the Graphics type. This - Object-Oriented Programming with C# method takes an instance of a GraphicsPath object, which was mentioned earlier during your examination Chapter 5 - Exceptions and Object Lifetime of the System.Drawing.Drawing2D namespace. The GraphicsPath object encapsulates a series of Chapter 6 - lines, Interfaces andand Collections connected curves, (interestingly enough) strings. Adding new items to a GraphicsPath instance Chapter 7 - using Callback Interfaces, Delegates, and Events (Table 14-28). is achieved a number of related "add" methods Chapter 4
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies Table 14-28: Add-Centric Methods of the GraphicsPath
Chapter 9
Class
- Understanding .NET Assemblies
GraphicsPath "Add" Method
Meaning in Life
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries AddArc() Appends
an elliptical arc to the current figure
Chapter 12 - Object Serialization and the .NET Remoting Layer
AddBezier() Adds a cubic Bezier curve Chapter 13 - Building a Better Window (Introducing Windows Forms)(or set of Bezier curves) to the current figure
AddBeziers() Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
AddClosedCurve()
Adds a closed curve to the current figure
Chapter 16 - The System.IO Namespace
AddCurve() Chapter 17 - Data Access with ADO.NETAdds a curve to the current figure Part Five - Web Applications and XML Web Services
AddEllipse()
Adds an ellipse to the current figure
Chapter 18 - ASP.NET Web Pages and Web Controls
AddLine() Chapter 19 - ASP.NET Web Applications Appends a line segment to the current figure Chapter 20 - XML Web Services AddLines() Index
AddPath()
List of Figures 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()
{ and thean .NET Platform, Second Edition // C# Create interesting region. ISBN:1590590554 by Andrew Troelsen myPath.StartFigure(); Apress © 2003 (1200 pages) myPath.AddLine(new Point(150, 10), new Point(120, 150)); This comprehensive text200, starts with overview of the myPath.AddArc(200, 100,a brief 100, 0, 90); C# language and then quickly moves to key technical and Point point1 = new Point(250, 250); architectural issues for .NET developers. Point point2 = new Point(350, 275); Point point3 = new Point(350, 325); Point point4 = new Point(250, 350); Table of Contents Point[] points = { point1, point2, point3, point4} ; C# and the .NET Platform, Second Edition myPath.AddCurve(points); Introduction myPath.CloseFigure(); Part One - Introducing C# and the .NET Platform ... Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications } Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter Object-Oriented Programming with C# When you call StartFigure(), you are able to insert a Notice 4the-calls to StartFigure() and CloseFigure(). Chapter new item 5 into - Exceptions the current andpath Object youLifetime are building. 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 - Interfaces and Collections case of7the- myPath loop is closed by connecting a line from the endpoint to the starting Chapter Callback instance), Interfaces,the Delegates, and Events point. 8 Chapter
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
There are more members for System.Drawing.Drawing2D.GraphicsPath, but let's keep focused on the hit- Understanding .NET Assemblies testing logic. The next step would be to update your existing MouseDown event handler to test for the Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming be discovered using the IsVisible() member: Chapter 9
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
protected void OnMouseDown (object sender, MouseEventArgs e) { Chapter 14 - A Better Painting Framework (GDI+) // Get (x, y) of mouse click. Chapter 15 - Programming with Windows Forms Controls Point mousePt = new Point(e.X, e.Y); Chapter ... 16 - The System.IO Namespace Chapter else 17 - Data Access with ADO.NET if(myPath.IsVisible(mousePt)) Part Five{- Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Controls isImageClicked = Web true; Chapter 19 - ASP.NET Web Applications imageClicked = 3; Chapter 20 - XML Web Services this.Text = "You clicked the strange shape..."; Index } ... List of Figures } of Tables List Chapter 13 - Building a Better Window (Introducing Windows Forms)
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# and ... the .NET Platform, Second Edition ISBN:1590590554 by Andrew Troelsen case 3: Apress © 2003 (1200 pages) g.DrawPath(outline, myPath); This comprehensive break; text starts with a brief overview of the C# language and then quickly moves to key technical and default: architectural issues for .NET developers.
break;
} }
Table of Contents
}
C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET Images project is included under the Chapter 14 subdirectory. SOURCE The (updated) Chapter 2 Building C# Applications CODE Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, Second Edition Understanding .NET Resource Format by Andrew Troelsen
ISBN:1590590554
Up to this point, each application that made use of external resources (such as bitmaps) assumed that Apress © 2003 (1200 pages) they were locatedThis in acomprehensive separate stand-alone filewith within the application For example, the Images text starts a brief overview of directory. the application rendered three bitmap images, which as you recall were loaded directly from file: C# language and then quickly moves to key technical and architectural issues for .NET developers.
// Fill the images with bitmaps. bMapImageA = new Bitmap("imageA.bmp"); Table of Contents bMapImageB = new Bitmap("imageB.bmp"); C# and the .NET Platform, Second Edition bMapImageC = new Bitmap("imageC.bmp"); Introduction
Part One - Introducing C# and the .NET Platform
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). Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services Figure 14-23: An application with three external
resources
Chapter 18 - ASP.NET Web Pages and Web Controls
If any of19these files are deleted, renamed, or relocated outside the application directory, the program fails Chapter - ASP.NET Web Applications to execute a tryServices just for verification's sake). Now, as you recall from Chapter 9, an assembly is a Chapter 20 -(give XML itWeb
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 Figures self-contained. In a nut-shell, bundling external resources into a .NET assembly involves the following List of Tables steps: Index
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# and the .NET Platform, Second Edition System.Resources Namespace by Andrew Troelsen
ISBN:1590590554
The key to understanding the (1200 .NETpages) resource format is to know the types defined within the System.Resources Apress © 2003 namespace. ThisThis set comprehensive of types provides the programmatic to of manipulate both *.resx (XML-based) and text starts with a briefmeans overview the *.resources (binary) files. Table 14-29 provides a rundown of the core types. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 14-29: Members of the System.Resources Namespace System.Resources Table of Contents
Meaning in Life Type C# and the .NET Platform, Second Edition Introduction
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. Part One - Introducing C# and the .NET Platform
Part Two - The C# Programming Language
ResourceReader These classes provide an implementation of the IResourceReader and Chapter 3 - C# Language Fundamentals IResourceWriter interfaces. Using the ResourceReader and Chapter 4 - Object-Oriented Programming with C# ResourceWriter Chapter 5
ResourceWriter types, you are able to read from and write to binary - Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
*.resources files.
Chapter 7 - Callback Interfaces, Delegates, and Events ResXResourceReader These classes also provide an implementation of the IResourceReader Chapter 8 - Advanced C# Typeand Construction Techniques IResourceWriter interfaces. Using the ResXResourceReader and
ResXResourceWriter
Part Three - Programming withResXResourceWriter .NET Assemblies
Chapter 9
types, you are able to read from, and write to, XML
- Understanding .NET *.resx Assemblies files. This file may be turned into a binary equivalent (the
*.resources file) using the resgen.exe utility. Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
ResourceManager
Provides easy access to culture-specific resources (BLOBs and string resources) at runtime.
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Programmatically Creating an *.resx File
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
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, Part Five - Web Applications and XML Web Services add binary and string-based resources, and commit them to storage. To illustrate, assume you have a simple Chapter 18 - you ASP.NET and Web Controls application have Web built Pages a la notepad and csc.exe, whose job in life is to build an *.resx file containing an Chapter 19the - ASP.NET Webimage Applications entry for happy.bmp seen earlier in this chapter, and a single string resource. The GUI is as simple Chapter 20 - (Figure XML Web Services as possible 14-24). Chapter 17 - Data Access with ADO.NET
Index List of Figures 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# and the .NET Platform, Second Edition { ISBN:1590590554 // Make by anAndrew resxTroelsen writer & specify the file to write to. Apress © 2003 (1200 pages) ResXResourceWriter w = comprehensive text starts with a brief overview of the newThis ResXResourceWriter("ResXForm.resx"); C# language quickly moves to key technical and // Add happy dudeand & then string. architectural issues for .NET developers. Image i = new Bitmap("happy.bmp"); w.AddResource("happyDude", i); w.AddResource("welcomeString", "Hello new resource format!"); Table of Contents // Commit it. C# and the .NET Platform, Second Edition w.Generate(); Introduction w.Close(); Part One - Introducing C# and the .NET Platform } Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part - The C# Programming Language TheTwo member of interest is ResXResourceWriter.AddResource().
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 Object-Oriented Programming C#version takes two parameters: the name of a given resource in have done your test string). Notice thatwith each Chapter the *.resx 5 file - Exceptions and the data and itself. ObjectThe Lifetime Generate() method commits the information to file. Chapter 6
- Interfaces and Collections
Understand that you are not the one in charge of writing the raw XML that describes your resources. Rather, - Callback Interfaces, Delegates, and Events the logic within the ResXResourceWriter class is responsible for building the XML description of the inserted Chapter 8 - Advanced C# Type Construction Techniques items. To prove the point, compile and run your application, load the new *.resx file using VS .NET, and peek Part Three - Programming with .NET Assemblies inside the contents (Figure 14-25). Chapter 7
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Figure Viewing *.resx file a la VS .NET Chapter 17 - 14-25: Data Access withthe ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
If you switch to the XML view, you should be able to identify happyDude and welcomeString by name. The
Chapter 19 - ASP.NET WebtoApplications XML syntax that is used represent your name/value pairs follows [note the (partial) binary representation of Chapter 20 XML Web Services the happy dude bitmap...]: Index List of Figures
< 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# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
protected void btnReadResxFile_Click (object sender, System.EventArgs e) Apress © 2003 (1200 pages) { This comprehensive text starts with a brief overview of the // Make C# anlanguage resx reader. and then quickly moves to key technical and ResXResourceReader r = architectural issues for new .NET ResXResourceReader("ResXForm.resx"); developers. // Grab the IDictionaryEnumerator interface and show everything. IDictionaryEnumerator en = r.GetEnumerator(); (en.MoveNext()) Table of while Contents { C# and the .NET Platform, Second Edition MessageBox.Show("Value:" + en.Value.ToString(), Introduction "Key: " + en.Key.ToString()); Part One - Introducing C# and the .NET Platform } Chapter 1 - The Philosophy of .NET Chapter r.Close(); 2 - Building C# Applications } Two - The C# Programming Language Part Chapter 3
- C# Language Fundamentals
Chapter 4
Object-Oriented Programming with C# When you-click the button, you see a pair of message boxes pop up, as the ResXResourceReader type loops
Chapter - Exceptions Object Lifetime through5 the XML file forand each named value. Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Building the *.resources File Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Now that you understand how to build and manipulate an *.resx file, you can make use of the resgen.exe utility
Chapter 9 - the Understanding .NET Assemblies to produce binary equivalent. Again, VS .NET will do so automatically, but just for the love of learning, here Chapter 10 Processes, AppDomains, Contexts, and Threads is the raw command: Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
resgen resxform.resx resxform.resources
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter Of course, 15 -you Programming must openwith a command Windows Forms promptControls in the directory containing the *.resx file before running
resgen.exe. Once you do, however, you are able to open the new *.resources file and check out the binary Chapter 16 - The System.IO Namespace format 17 (Figure 14-26). Chapter - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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 and the .NET Platform, Second Edition in the assembly'sC# metadata. by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition
Figure 14-27: The embedded resources
Introduction
Part One can - Introducing C# and the Platform As you see, the manifest has.NET recorded the
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. Part Two - The C# Programming Language
SOURCE The Fundamentals ResXWriterReader.cs file is included under the Chapter 14 subdirectory. Chapter 3 - C# Language CODE Chapter 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Working with ResourceWriters by Andrew Troelsen
ISBN:1590590554
The previous example the ResXResourceReader and ResXResourceWriter types to Apressmade © 2003use (1200ofpages) generate an XMLThis file that contains name/value pairsa for each application comprehensive text starts with brief overview of the resource. The resulting *.resx file was then run through the resgen.exe utility. Finally the *.resources file was bound into the owning C# language and then quickly moves to key technical and architectural for .NET assembly using the /resourceissues flag. The truth developers. 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). Table If youofdo Contents not require an *.resx file, you can make use of the ResourceWriter type to directly create a binary
*.resources file.Platform, To illustrate, assume C# and the .NET 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 Introduction typeOne to directly generate the myResources.resources Part - Introducing C# and the .NET Platform Chapter 1
file:
- The Philosophy of .NET
Chapter class2 ResourceGenerator - Building C# Applications Part { Two - The C# Programming Language
void Main(string[] args) Chapter static 3 - C# Language Fundamentals Chapter { 4
- Object-Oriented Programming with C#
Chapter 5
// Makeand a Object new *.resources file. - Exceptions Lifetime
Chapter 6
ResourceWriter rw; - Interfaces and Collections
Chapter 7
rw = Interfaces, new ResourceWriter("myResources.resources"); - Callback Delegates, and Events
// Add 1 image and 1 string. rw.AddResource("happyDude", new Bitmap("happy.bmp")); Part Three - Programming with .NET Assemblies rw.AddResource("welcomeString", "Welcome to .NET resources."); Chapter 9 - Understanding .NET Assemblies rw.Generate(); Chapter 10 - Processes, AppDomains, Contexts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Chapter 8
- Advanced C# Type Construction Techniques
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building Better (Introducing Windowsthe Forms) At this point, compilea and runWindow the application to generate *.resource file. Now, we can bind the Chapter 14 -binary A Better Painting Framework (GDI+)as before: contained data to the owning assembly Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace csc /resource:myresources.resources *.cs Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
If you wish read theWeb rawPages name/value from the binary *.resources file, you are free to make use of Chapter 18 -to ASP.NET and Webdata Controls the ResourceReader class. This is almost identical to working with the ResXResourceWriter type. Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Working with ResourceManagers by Andrew Troelsen
ISBN:1590590554
Rather than working with© the class directly, you will most likely use the Apress 2003ResourceReader (1200 pages) ResourceManager type. The reason is simple: It is easier work with! Using the ResourceManager, you This comprehensive text starts with a briefto overview of the are able to extract binary and textual data from an assembly for use in your application. C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 Table assembly of Contents and dump them into a PictureBox and Label object using the GetObject() and GetString() members. Be very awareSecond however, that the double quoted strings you send into these methods are case C# and the .NET Platform, Edition sensitive. Here is the code: Introduction Part One - Introducing C# and the .NET Platform
Chapter - The Philosophy of .NET class1 MyResourceReader Chapter { 2
- Building C# Applications
Part Twopublic - The C# static Programming voidLanguage ReadMyResources()
Chapter { 3
- C# Language Fundamentals
Chapter 4
// Open the resources - Object-Oriented Programming withfile. C#
Chapter 5
ResourceManager rm = new ResourceManager("myResources", - Exceptions and Object Lifetime
Chapter 6
Assembly.GetExecutingAssembly()); - Interfaces and Collections
Chapter 7
// Load imageDelegates, resource. - Callback Interfaces, and Events
PictureBox p = new PictureBox(); Bitmap b = (Bitmap)rm.GetObject("happyDude"); Part Three - Programming with .NET Assemblies p.Image = (Image)b; Chapter 9 - Understanding .NET Assemblies p.Height = b.Height; Chapter 10 - Processes, AppDomains, Contexts, and Threads p.Width = b.Width; Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming p.Location = new Point(10, 10); Part Four - Leveraging the .NET Libraries // Load string resource. Chapter 12 - Object Serialization and the .NET Remoting Layer Label label1 = new Label(); Chapter 13 - Building a Better Window =(Introducing Windows 10); Forms) label1.Location new Point(50, Chapter 14 - A label1.Font Better Painting Framework (GDI+) = new Font(label1.Font.FontFamily, 12, FontStyle.Bold); Chapter 15 - Programming with Windows Forms Controls label1.AutoSize = true; Chapter 16 - The System.IO Namespace label1.Text = rm.GetString("welcomeString"); Chapter 17 - Data // Access Buildwith a ADO.NET Form to show the resources. Part Five - WebForm Applications and XML Web Services f = new Form(); Chapter 18 - ASP.NET f.Height Web Pages = 100; and Web Controls f.Width 370; Chapter 19 - ASP.NET Web=Applications f.Text = "These resources are embedded in the assembly!"; Chapter 20 - XML Web Services // Add controls and show Form. Index f.Controls.Add(p); List of Figures List of Tables f.Controls.Add(label1); f.ShowDialog(); } } Chapter 8
- Advanced C# Type Construction 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the Figure 14-28: Reading (and using) embedded resources C# language and then quickly moves to key technical and architectural issues for .NET developers.
SOURCE CODE
The ResourceTest project is included under the Chapter 14 subdirectory.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Automatic Resource Configuration a la Visual Studio .NET by Andrew Troelsen
ISBN:1590590554
To wrap things up, let's © look howpages) the Visual Studio .NET IDE gets you up and running with the correct Apress 2003at(1200 resource file configuration automatically. Whenwith you acreate a new Windows This comprehensive text starts brief overview of the Forms project workspace using Visual Studio .NET, the IDE automatically defines an *.resx file for each C# language and then quickly moves to key technical andForm in your application. architectural for .NET developers. Furthermore, when you insertissues new resources to a given Form, the name/value pairs contained in the *.resx 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). Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - 14-29: Type Reflection, Late Binding, andfor Attribute-Based Figure The underlying *.resx file MainForm.csProgramming Part Four - Leveraging the .NET Libraries
Chapter Once you 12 -select Object this Serialization file, checkand out the the .NET Properties Remoting window. LayerYou will see that the build action for this file has
been configured as "Embedded Resource" (Figure 14-30).Forms) Chapter 13 - Building a Better Window (Introducing Windows Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Figure 14-31: GUI of the ResLoader application
Part Two - The C# Programming Language
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 - Object-Oriented Programming with C#InitializeComponent() method: ResourceManager type within the scope of your Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
private void InitializeComponent() - Callback Interfaces, Delegates, and Events { Chapter // 8 -Note Advanced Type to Construction youC#need specifyTechniques the name of the Form that Part Three Assemblies //- Programming maintains with the .NET embedded resources. Chapter System.Resources.ResourceManager 9 - Understanding .NET Assemblies resources = Chapter 10 - Processes, AppDomains, Contexts, and Threads new System.Resources.ResourceManager (typeof(MainForm)); Chapter ... 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part FourpictureBox1.Image - Leveraging the .NET Libraries = Chapter 12 - Object Serialization and the .NET Remoting Layer (System.Drawing.Image) resources.GetObject ("pictureBox1.Image"); Chapter } 13 - Building a Better Window (Introducing Windows Forms) Chapter 7
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
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 System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
// Be18sure to specify Chapter - ASP.NET Web Pages'using and WebSystem.Resources' Controls private btnLoadRes_Click(object sender, System.EventArgs e) Chapter 19 -void ASP.NET Web Applications {
Chapter 20 - XML Web Services
// Make a ResourceManager ResourceManager resources = new ResourceManager (typeof(MainForm)); List of Figures // 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(); } Index
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition
Figure 14-32: Loading resources with the ResourceManager type
Introduction
Part One - Introducing C# and the .NET Platform
SOURCE The ResLoader project is included under the Chapter 14 subdirectory. Chapter 1 - The Philosophy of .NET CODE Chapter 2 - Building C# Applications Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# revisit GDI+ later in this text when you examine ASP.NET (as odd as that may seem). Until then, the next Chapter - Exceptions Lifetime chapter5 addresses the and use Object of Windows Forms widgets. Chapter 3
Chapter 6
- Interfaces and Collections Note are interested exploring and GDI+ further (including printing support), be sure to check out Chapter 7 If- you Callback Interfaces,inDelegates, Events
Programming C# and VBTechniques .NET (Symmonds, Apress 2002). Chapter 8 GDI+ - Advanced C# Typein Construction Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
GDI+ is the nameApress given ©to2003 a number of related .NET namespaces, each of which is used to render graphic (1200 pages) images to a Control-derived type. The chapter by examining thethe core types defined within the This comprehensive text starts began with a brief overview of System.Drawing C# namespace (including a number of useful utility types), language and then quickly moves to key technical and and examined various manners to architectural issues for .NET developers. intercept paint events. The bulk of this chapter was spent examining how to work with core GDI+ object types such as colors, Table fonts, ofgraphics Contents images, pens, and brushes in conjunction with the almighty Graphics type. Along the way,
you examined GDI+-centric details such as hit-testing, and how to drag and drop images. C# and the .NETsome Platform, Second Edition Introduction
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 Part Two - The C# Programming Language 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. Part One - Introducing C# and the .NET Platform
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Chapter C# 15: Programming with ISBN:1590590554 Windows Forms by Andrew Troelsen ControlsApress © 2003 (1200 pages)
Overview
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
This chapter is concerned with providing a roadmap of the suite of GUI widgets defined in the Table System.Windows.Forms of Contents namespace. You have already had a chance to work with some Form-level
control types such as MainMenu, MenuItem, StatusBar, and ToolBar (see Chapter 13); however, in this C# and the .NET Platform, Second Edition chapter, you will be examining various types that tend to exist within the boundaries of a Form's client area Introduction (e.g., Buttons, TextBoxes, Panels, andPlatform the like). Part One - Introducing C# and the .NET 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 Part Two - The C# Programming Language 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
- Object-Oriented Programming with C#
Chapter 5 - examine Exceptions and Object Next, you'll a new facility Lifetime offered by the .NET Windows Forms architecture: Form inheritance. As Chapter you will6see, - Interfaces it is now possible and Collections to establish "is-a" relationships between related Forms (which should make
the MFC of the world insanely and happy). Finally, we wrap things up with an examination of the Chapter 7 developers - Callback Interfaces, Delegates, Events process8 of-building custom Windows FormsTechniques controls (which should make the ATL developers of the world Chapter Advanced C# Type Construction insanely Part Threehappy). - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, Forms Second Edition Understanding Windows Control Hierarchy by Andrew Troelsen
ISBN:1590590554
The System.Windows.Forms Apress © 2003 namespace (1200 pages) contains a number of types that represent common GUI widgets that allow you to respond to user input in starts a Windows application. Because .NET is a system of This comprehensive text with a Forms brief overview of the types built on standard OO principles, these controls are arranged in a hierarchy of related types. Figure C# language and then quickly moves to key technical and architectural developers. 15-1 illustrates the big pictureissues (note for that.NET System.Windows.Forms.Control is the common base class for all Windows Forms widgets.) Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Figure The Windows Forms control hierarchy Chapter 9 - 15-1: Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter - TypeinReflection, Late Binding, and Attribute-Based Programming As you 11 learned Chapter 13, the System.Windows.Forms.Control type is the base class that provides a Part Four -and Leveraging Libraries for minimal completethe set.NET of behaviors
all descending widgets. This includes the ability to process
Chapter Object Serialization and the .NET Remoting Layer mouse12 and- keyboard events, establish the physical dimensions of the widget using various properties Chapter 13 Building a Better Window (Introducing Windows Forms) (Height, Width, Left, Right, Location, and so on), manipulate background and foreground colors, establish Chapter the active 14 -font, A Better and so Painting forth. Also, Framework the Control (GDI+)base type also defines members that control a widget's
anchoring docking behaviors (as seen later in this chapter). Chapter 15 -and Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
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 Part Five - Web Applications and XML Web Services less) on a given type's unique members. Chapter 17 - Data Access with ADO.NET
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the Platform, Second Edition Adding Controls to.NET Forms (IDE-Free) by Andrew Troelsen
ISBN:1590590554
Regardless of which type of control you choose to place on a Form, you will follow a similar set of steps. Apress © 2003 (1200 pages) First of all, you must define member variables the GUI maintained by the Form. This comprehensive text starts that withrepresent a brief overview 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 moves to key technical and issues for the .NETexposed developers. the look and feel architectural of 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 Table of at Contents visible runtime! To illustrate this process in the raw, consider the MyForm class: C# and the .NET Platform, Second Edition Introduction
// 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 { Part Two// - The C# Programming Define a widgetLanguage data member. Chapter private 3 - C# Language Fundamentals TextBox firstNameBox = new TextBox(); Chapter public 4 - Object-Oriented MyForm()Programming with C# Chapter { 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces this.Text and Collections = "Controls in the raw"; // Configure the widget. Chapter 7 - Callback Interfaces, Delegates, and Events firstNameBox.Text = "Chucky"; Chapter 8 - Advanced C# Type Construction Techniques firstNameBox.Size = new Size(150, 50); Part Three - Programming with .NET Assemblies firstNameBox.Location Chapter 9 - Understanding .NET Assemblies = new Point(10, 10); // Add AppDomains, new widget to the Chapter 10 - Processes, Contexts, andForm's Threads Controls collection. this.Controls.Add(firstNameBox); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } - Leveraging the .NET Libraries Part Four ... Chapter 12 - Object Serialization and the .NET Remoting Layer } Part One - Introducing C# and the .NET Platform
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
The Control$ControlCollection Type
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with 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 Controls defined by the Control class (recall that a nested type can be denoted using the "$" token, e.g., Chapter 19 - ASP.NET Web Applications Control$ControlCollection). The Control$ControlCollection type maintains an entry for each widget placed Chapter 20 - XML Web Services on the Form. You can obtain a reference to this collection anytime you wish to "walk the list" of child Index widgets: Part Five - Web Applications and XML Web Services
List of Figures 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 in Life C# and the .NET Platform, Second Edition Member ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages)
Add() AddRange() Clear()
Used to insert a new Control-derived type (or array of
This comprehensive text starts with a brief overview of the types) in the collection C# language and then quickly moves to key technical and architectural issues for .NET developers.
Removes all entries in the collection
Count
Table of Contents C#GetChildIndex() and the .NET Platform, Second Edition Introduction SetChildIndex() Part One - Introducing C# and the .NET Platform
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
Part Two - The C# Programming Language
RemoveAt()
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetimeof this very important collection, assume you have now configured To illustrate programmatic manipulation Chapter and added 6 - aInterfaces new Button andwidget Collections to the Form's collection (Figure 15-2). Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Figure 15-2: The Form's UI
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Also assume you have written an event handler for the Button's Click event. In the implementation of this Chapter method, 20you - XML loopWeb overServices each item in the Controls collection and print out some relevant information
regarding the contained members: Index List of Figures 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# and the .NET Platform, Second Edition
{
ISBN:1590590554 by Andrew Troelsen Control.ControlCollection coll = this.Controls; Apress © 2003 (1200 pages) string ctrs = ""; This comprehensive textcoll) starts with a brief overview of the foreach(Control c in C# language and then quickly moves to key technical and { architectural issues for .NET developers. if(c != null) ctrs += string.Format("Index: {0}, Text: {1}\n", coll.GetChildIndex(c, false), c.Text); Table of Contents } C# and the .NET Platform, Second Edition MessageBox.Show(ctrs, "Index and Text values for each control"); Introduction } Part One - Introducing C# and the .NET Platform ... Chapter 1 - The Philosophy of .NET }
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter Object-Oriented Programming with you C# to obtain the numerical index of a given widget in the Notice 4how- the call to GetChildIndex() allows Chapter collection 5 (the - Exceptions second Boolean and Object parameter Lifetime 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 Interfaces and Collections with the7 information in Figure 15-3.and Events Chapter - Callback shown Interfaces, Delegates, Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - 15-3: A Better Painting Framework (GDI+) Figure Interacting with a Form's Controls collection Chapter 15 - Programming with Windows Forms Controls
Given that types maintain a nested Control.ControlsCollection Chapter 16 -System.Windows.Forms.Control-derived The System.IO Namespace type, it 17 stands to reason that ADO.NET you can dynamically add, hide, disable, or remove items using this collection Chapter - Data Access with at any in Applications a Form's lifetime (which can prove quite Part Fivepoint - Web and XML Web Services
helpful if you need to dynamically generate new
controls18on- the fly or Web restrict which should be displayed based on user preferences/ permissions). Chapter ASP.NET Pages andcontrols Web Controls Chapter 19 - ASP.NET Web Applications
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 Index to a GroupBox, TextBox types to a Panel, and so forth). We will see examples of this technique over the List of Figures course of this chapter. Chapter 20 - XML Web Services
List of Tables
SOURCE CODE
The ControlsByHand project is included under the Chapter 15 subdirectory.
C# and the Platform, Edition Adding Controls to.NET Forms (viaSecond VS .NET) by Andrew Troelsen
ISBN:1590590554
Although you areApress always© free write Windows Forms code "in the raw," you will probably choose to use 2003 to (1200 pages) the Visual Studio This .NET IDE instead. When you drop widget from the Toolbox onto the form designer, the comprehensive text starts with aabrief overview of the IDE responds by C# automatically adding the correct member variable to the language and then quickly moves to key technical and Form-derived class on your architectural issueswant for .NET developers. behalf. Of course, you will typically to change the 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 Table Contents codeofchanges are added to the InitializeComponent() member function. C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies Figure Design time property configuration Chapter 10 - 15-4: Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part the .NET Libraries Be Four aware- Leveraging that this window allows you to
configure not only the property set of a given GUI item, but the set
Chapter 12 as - Object Serialization and the the .NET"lightning Remotingbolt" Layer of events well (available by clicking icon). Simply select the widget from the dropChapter 13 Building a Better Window (Introducing Windows Forms) down list and type in the name of the method to be called for the events you are interested in responding Chapter 14 -15-5). A Better Painting Framework (GDI+) to (Figure Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition this.firstNameBox.TextChanged += new ISBN:1590590554 by Andrew Troelsen System.EventHandler(this.firstNameBox_TextChanged); Apress © 2003 (1200 pages) this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); This comprehensive starts with a brief overview of the this.ClientSize = new text System.Drawing.Size(292, 273); C# language and then quickly moves to key technical and this.Controls.AddRange(new System.Windows.Forms.Control[] architectural issues for .NET developers. { this.firstNameBox}); ... }
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Note that here you use VS .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 Part Two - The C# Programming Language particular event):
Chapter 3
- C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C# protected void firstNameBox_TextChanged (object sender, System.EventArgs e) Chapter 5 Exceptions and Object Lifetime { Chapter // 6 -Do Interfaces and Collections whatever you need to do... Chapter 7 Callback Interfaces, Delegates, and Events } Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
As you 9can- see, the VS .NET IDE simply saves you some typing. The remainder of this chapter focuses on Chapter Understanding .NET Assemblies a number behaviors AppDomains, offered by numerous Chapter 10 -ofProcesses, Contexts,GUI and widgets Threads by examining the "raw" code behind the scenes. If you decide to use the VS .NET IDE, be and sureAttribute-Based to examine theProgramming code generated inside the Chapter 11 - Type Reflection, Late Binding, InitializeComponent() method to gain a Part Four - Leveraging the .NET Libraries
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 - Object Serialization and the .NET Remoting Layer attention to the specifics of various Windows Forms widgets. Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# Control and the .NET Platform, Second Edition The TextBox by Andrew Troelsen
ISBN:1590590554
The TextBox control is the first(1200 itempages) under investigation. This GUI widget holds some blurb of text or possibly Apress © 2003 multiple lines of text. TextBox controls can alsowith be configured as read-only This comprehensive text starts a brief overview of the and may support scroll bars. The immediate base class of TextBox is TextBoxBase, which provides many C# language and then quickly moves to key technical andcommon behaviors for the TextBox issues for15-2 .NETdescribes developers. and RichTextBoxarchitectural descendents. Table some of the core properties provided by the TextBoxBase type. Table of 15-2: Contents Table Members of the TextBoxBase Type C# and the .NET Platform, Second Edition
TextBoxBase Introduction
Meaning in Life Property Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET AcceptsTab Indicates if pressing the Tab key in a multiline TextBox control tabs within the - Building C# Applications control itself, rather than moving the focus to the next control in the tab order.
Chapter 2
Part Two - The C# Programming Language
AutoSize Determines if the size of the control automatically adjusts when the assigned Chapter 3 - C# Language Fundamentals Chapter 4
font is changed.with C# - Object-Oriented Programming
Chapter 5 - Exceptions andGet Object Lifetime BackColor or set the background/foreground color of the control. Chapter 6 - Interfaces and Collections
ForeColor
Chapter 7
- Callback Interfaces, Delegates, and Events
HideSelection GetsConstruction or sets a value indicating whether the selected text in the TextBox Chapter 8 - Advanced C# Type Techniques control remains highlighted when the control loses focus. Part Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
MaxLength
Configures the maximum number of characters that can be entered into the TextBox control.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Modified GetsLibraries or sets a value Part Four - Leveraging the .NET
that indicates that the TextBox control has been
modified by the user since the control was created or its contents were last Chapter 12 - Object Serialization and the .NET Remoting Layer set. Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Multiline Specifies if this TextBox can contain multiple lines of text. Chapter 15 - Programming with Windows Forms Controls
ReadOnly this TextBox as read-only. Chapter 16 - The System.IO Marks Namespace Chapter 17 - Data Access with ADO.NET SelectedText Contain the currently selected text (or some number of characters) in the Part Five - Web Applicationscontrol. and XML Web Services gets SelectionStart
SelectionLength
or sets the starting point of text selected in the
Chapter 18 - ASP.NET Web Pages and Web Controls text box. SelectionStart Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services WordWrap Indicates whether a multiline TextBox control automatically wraps words to Index the beginning of the next line when necessary. List of Figures 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 Life Second Edition C# andMeaning the .NET Platform, by Andrew Troelsen Apress © 2003 (1200 pages)
Gets or sets a value indicating whether pressing Enter in a multiline TextBox
This comprehensive text starts with a brief overview of the control creates a new line of text in the control or activates the default Button C# language and then quickly moves to key technical and for the Formfor .NET developers. architectural issues
CharacterCasing Table of Contents
ISBN:1590590554
Gets or sets whether the TextBox control modifies the case of characters as they are typed
C#PasswordChar and the .NET Platform, Gets Second or sets Edition the character used to mask characters in a single-line TextBox Introduction
control used to enter passwords
Part One - Introducing C# and the .NET Platform
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 HorizontalAlignment Part Two - The C# Programming Language
enumeration
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
- Exceptions and Object Lifetime Fun with TextBoxes
Chapter 5 Chapter 6
- Interfaces and Collections To illustrate some ofInterfaces, the more exotic aspects the TextBox, let's build a multiline text area that has been Chapter 7 - Callback Delegates, and of Events
configured accept Return and Tab keystrokes and supports a vertical scroll bar. Here is the configuration Chapter 8 - to Advanced C# Type Construction Techniques code (assume you have already defined a Form-level Part Three - Programming with .NET Assemblies Chapter 9
member variable of type TextBox named multiLineBox):
- Understanding .NET Assemblies
Chapter // Your 10 -first Processes, TextBox. AppDomains, Contexts, and Threads
multiLineBox.Location = Binding, new System.Drawing.Point (152, 8); Chapter 11 - Type Reflection, Late and Attribute-Based Programming multiLineBox.Text "Type some Part Four - Leveraging the = .NET Libraries
stuff here (and hit the return and tab keys...)";
multiLineBox.Multiline = true; Chapter 12 - Object Serialization and the .NET Remoting Layer multiLineBox.AcceptsReturn = true; Windows Forms) Chapter 13 - Building a Better Window (Introducing multiLineBox.ScrollBars = ScrollBars.Vertical; Chapter 14 - A Better Painting Framework (GDI+) multiLineBox.TabIndex = 0; Forms Controls Chapter 15 - Programming with Windows multiLineBox.AcceptsTab = true;
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
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 Controls following Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
public enum System.Windows.Forms.ScrollBars { List of Figures Both, Horizontal, None, Vertical List } of Tables Index
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# and the .NET Platform, Second Edition keystrokes typed in the passwordBox TextBox widget, as shown here: by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
protected void btnPasswordDecoderRing_Click (object sender, System.EventArgs e) This comprehensive text starts with a brief overview of the { C# language and then quickly moves to key technical and MessageBox.Show(passwordBox.Text, architectural issues for .NET developers. "Your password is:"); } Table of Contents
Here the.NET relevant codeSecond that configures C# andisthe Platform, Edition these new TextBox types: Introduction Part C# andwidget. the .NET Platform // One The- Introducing 'Caps Only!'
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 = Language new System.Drawing.Point Part Two - The C# Programming
(14, 176); capsOnlyBox.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper; Chapter 3 - C# Language Fundamentals capsOnlyBox.Size = new System.Drawing.Size (120, 20); Chapter 4 - Object-Oriented Programming with C# // The password TextBox Chapter 5 - Exceptions and Object Lifetime passwordBox.Location = new System.Drawing.Point (160, 176); Chapter 6 - Interfaces and Collections passwordBox.PasswordChar = '$'; Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
The final GUI can be seen in Figure 15-6.
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Figure 15-6: The many faces of the TextBox type
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications As mentioned, TextBoxBase has an additional derived type named RichTextBox. This class is a type that Chapter 20 XML Web Services supports the display and manipulation of (highly) formatted text. For example, using this type you can Index configure support for multiple font selections, bulleted text, and so forth. I assume interested readers will List of Figures consult online help for further details. List of Tables
SOURCE CODE
The TextBoxes application is included under the Chapter 15 subdirectory.
and the .NET Platform, Second Edition The MightyC# Button Type by Andrew Troelsen
ISBN:1590590554
Of all user interface widgets, Button Apress © 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 is to provide This comprehensive text starts with a brief overview 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 moves to key technical and architectural issues for .NET developers. type named ButtonBase, which provides a number of 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. Table of Contents C# and the .NET Platform, Second Edition Table 15-4: ButtonBase Properties Introduction
ButtonBase Meaning in Platform Life Part One - Introducing C# and the .NET 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 Part Two - The C# Programming Language the FlatStyle enumeration.
Chapter 3
- C# Language Fundamentals
Image4 Chapter
Configures which (optional) - Object-Oriented Programming with C# image is displayed somewhere within the bounds
Chapter 5
a Object ButtonBase-derived type. Recall that the Control class also defines a - Exceptions of and Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
BackgroundImage property, which is used to render an image over the entire surface area of a widget.
Chapter 8 - Advanced C# Type ImageAlign Sets theConstruction alignment ofTechniques the image on the Button control, using the Part Three - Programming with .NET Assemblies ContentAlignment enumeration.
Chapter 9
- Understanding .NET Assemblies
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 - Processes, AppDomains, Contexts, and Threads
ImageList Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries IsDefault Specifies whether
the Button control is the default Button (i.e., receives focus in
Chapter 12 - Object Serialization the .NET Remoting Layer responseand to pressing of the Enter key). Chapter 13 - Building a Better Window (Introducing Windows Forms)
TextAlign Gets or sets the alignment Chapter 14 - A Better Painting Framework (GDI+) of the text on the Button control, using the ContentAlignment enumeration.
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Chapter 17 - class Data Access with ADO.NET The Button itself defines almost no additional functionality beyond that inherited by the ButtonBase Part Five - Web Applications and XMLofWeb base class, with the key exception the Services DialogResult
property. As you will see later in this chapter, a dialog
Chapter 18 - use ASP.NET Pages to and Web a Controls box makes of thisWeb property return value representing which Button was clicked (e.g., OK, Cancel, Chapter ASP.NET Applications and so 19 on)- when the Web dialog box is terminated. Chapter 20 - XML Web Services Index
Configuring the Content Position
List of Figures
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# and the .NET Platform, Second Edition
Fun with Buttons by Andrew Troelsen
ISBN:1590590554
Apress © 2003 (1200 pages)
To illustrate working with this most primitive of user input widgets, the following application uses the FlatStyle, comprehensive text starts a brief overview of the the underlying code is in the Click event ImageAlign, and This TextAlign properties. The mostwith interesting aspect of C# language and then quickly moves to key technical and handler for the btnStandard type (which would be the Button in the middle of the Form). The implementation architectural issues for .NET developers. 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. Table of Contents
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 Introduction is the relevant code: C# and the .NET Platform, Second Edition
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
public class ButtonForm: System.Windows.Forms.Form - Building C# Applications { Part Two - The C# Programming Language // You have four Buttons on this Form. Chapter 3 - C# Language Fundamentals private System.Windows.Forms.Button btnImage; Chapter 4 - Object-Oriented Programming with C# private System.Windows.Forms.Button btnStandard; Chapter private 5 - Exceptions and Object Lifetime System.Windows.Forms.Button btnPopup; Chapter private 6 - Interfaces and Collections System.Windows.Forms.Button btnFlat; Chapter // 7 -Hold Callback Interfaces, Delegates, and Events the current alignment value. Chapter ContentAlignment 8 - Advanced C# Type currAlignment Construction Techniques = ContentAlignment.MiddleCenter; Part Three - Programming with=.NET int currEnumPos 0; Assemblies Chapter ... 9 - Understanding .NET Assemblies Chapter protected 10 - Processes, void AppDomains, btnStandard_Click Contexts, and Threads (object sender, System.EventArgs e) Chapter { 11 - Type Reflection, Late Binding, and Attribute-Based Programming // Gettheall values of the ContentAlignment enum. Part Four - Leveraging .NETpossible Libraries Array values and = Enum.GetValues(currAlignment.GetType()); Chapter 12 - Object Serialization the .NET Remoting Layer // Bump theWindow current position in the enum. Chapter 13 - Building a Better (Introducing Windows Forms) // & check for wraparound. Chapter 14 - A Better Painting Framework (GDI+) currEnumPos++; Chapter 15 - Programming with Windows Forms Controls if(currEnumPos >= values.Length) Chapter 16 - The System.IO Namespace currEnumPos = 0; Chapter 17 - Data Access with ADO.NET // Change the current enum value. Part Five - Web Applications and XML Web Services currAlignment = Chapter 18 - ASP.NET Web Pages and Web Controls (ContentAlignment)ContentAlignment.Parse(currAlignment.GetType(), Chapter 19 - ASP.NET Web Applications values.GetValue(currEnumPos).ToString()); Chapter 20 - XML Web Services // Paint enum name on Button. Index btnStandard.Text = currAlignment.ToString(); List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Figure 15-7: The many faces of the Button type
Chapter SOURCE 8 - AdvancedThe C# Type Buttons Construction application Techniques is included under the Chapter 15 directory. Part Three CODE- Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Working with CheckBoxes by Andrew Troelsen
ISBN:1590590554
The other two ButtonBase-derived types of interest are CheckBox (which can support up to three possible Apress © 2003 (1200 pages) states) and RadioButton (which can or not selected). Like the Button, these types also This comprehensive be texteither startsselected with a brief overview of the receive most of their functionality from the Control base class. However, C# language and then quickly moves to key technical and each class defines some architectural issues forthe .NET developers. additional functionality. First, consider core properties of the CheckBox widget described in Table 15-5. Table 15-5: CheckBox Properties
Table of Contents
Meaning Life C#CheckBox and the .NET Platform, Second in Edition Property Introduction Part One - Introducing C# and the .NET Platform
Appearance
Configures the appearance of a CheckBox control, using the Appearance enumeration.
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
AutoCheck Gets or sets a value Part Two - The C# Programming Language
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 - Object-Oriented with C# CheckAlign Gets orProgramming sets the horizontal and vertical alignment of a CheckBox on a Chapter 5 - Exceptions and Object Lifetime CheckBox control, using the ContentAlignment enumeration (see the Button Chapter 6
- Interfacestype andfor Collections a full description).
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 9
- Understanding .NET Assemblies
Checked Returns a Boolean value representing the state of the CheckBox (checked or Chapter 8 - Advanced C# Type Construction Techniques unchecked). If the ThreeState property is set to true, the Checked property Part Three - Programming with .NET Assemblies returns true for either checked or indeterminately checked values. Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based rather than a Programming Boolean value. This is very helpful Part Four - Leveraging when the .NET working Libraries with
tristate CheckBoxes.
Chapter 12 - Object Serialization and the .NET Remoting Layer
ThreeState
Configures whether the CheckBox supports three states of selection (as specified by the CheckState enumeration), rather than two.
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform,and Second Edition Working with RadioButtons GroupBoxes by Andrew Troelsen
ISBN:1590590554
The RadioButtonApress type really little comment, given that it is (more or less) just a slightly redesigned © 2003requires (1200 pages) CheckBox. In fact, the members of a RadioButton almost identical to those of the CheckBox type. The This comprehensive text starts withare a brief overview of the only notable difference is the CheckedChanged event, which is fired when C# language and then quickly moves to key technical and the Checked value changes. architectural issues .NET developers. Also, the RadioButton type 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 Table whole. of Contents For example, if you have a set of four RadioButton types representing the color choice of a given
automobile, youPlatform, may wish to ensure that only one of the four types can be checked at a time. Rather than C# and the .NET Second Edition writing code programmatically to do so, use the GroupBox control. Like the RadioButton, there is little to Introduction sayOne about the GroupBox control, givenPlatform that it receives Part - Introducing C# and the .NET 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
Part Two - The C# Programming Language
To illustrate working with Fundamentals the CheckBox, RadioButton, and GroupBox types, let's create a new Windows Chapter 3 - C# Language Forms 4Application named CarConfig, which Chapter - Object-Oriented Programming withwill 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 Object Lifetime summary displayed and in a Collections Label type once the Confirm Order button has been clicked. Figure 15-8 shows Chapter 6 is - Interfaces the user Chapter 7 interface. - Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications XML ServicesForm Figure 15-8: The initialand UI of theWeb CarConfig
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
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 Services Index
List of Figures
// 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# and .NETRadioButtons Platform, Second Edition // Green, Red, and the Pink configured in a similar vein. ISBN:1590590554 by Andrew Troelsen ... © 2003 (1200 // Now build Apress the group of pages) radio items. This comprehensive text starts with a brief overview of the groupBox1.Location = new System.Drawing.Point (16, 56); C# language and then quickly moves to key technical and groupBox1.Text = "Exterior Color"; architectural issues for .NET developers. groupBox1.Size = new System.Drawing.Size (264, 88); groupBox1.Leave += new System.EventHandler (groupBox1_Leave); groupBox1.Enter += new System.EventHandler (groupBox1_Enter); Table of Contents groupBox1.Controls.Add (this.radioPink); C# and the .NET Platform, Second Edition groupBox1.Controls.Add (this.radioYellow); Introduction groupBox1.Controls.Add (this.radioRed); Part One - Introducing C# and the .NET Platform groupBox1.Controls.Add (this.radioGreen); Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
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 - Object-Oriented Programming C# the caption text of the GroupBox as shown here: However, illustrate, the event handlers with update Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - Interfaces and the Collections // Figure out when focus is in your group. Chapter 7 Callback Interfaces, Delegates, and Events sender, System.EventArgs e) protected void groupBox1_Leave (object Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies groupBox1.Text = "Exterior Color:
Chapter } 9
Thanks for visiting the group...";
- Understanding .NET Assemblies
protected void groupBox1_Enter (object sender, System.EventArgs e) Chapter 10 - Processes, AppDomains, Contexts, and Threads { Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming groupBox1.Text "Exterior Part Four - Leveraging the = .NET Libraries
Color: You are in the group...";
} Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (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 System.IO Namespace the Click event handler of the order Button, as shown here: Chapter 15 - Programming with Windows Forms Controls Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
protected void btnOrder_Click (object sender, System.EventArgs e) { Chapter 19 - ASP.NET Web Applications // Build a string to display information. Chapter 20 - XML Web Services string orderInfo = ""; Index if(checkFloorMats.Checked) List of Figures 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 Controls
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.
the .NET Platform, Second Edition Examining C# theandCheckedListBox Control by Andrew Troelsen
ISBN:1590590554
Now that you have explored basic Button-centric widgets, let's move on to the set of list selectionApress © 2003the (1200 pages) centric types, specifically, CheckedListBox, ListBox, ComboBox. This comprehensive text starts with aand brief overview ofThe the CheckedListBox widget allows you to group together related CheckBox options in a scrollable list control. C# language and then quickly moves to key technical and Assume you have added such architectural issues for .NET developers. a control to your CarConfig application that allows the user to configure a number of options for regarding the automobile's sound system (Figure 15-9). Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies Figure The CheckedListBox type and Threads Chapter 10 - 15-9: Processes, AppDomains, Contexts, Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Leveraging the .NET Libraries LikeFour the -controls examined thus far, the
CheckedListBox type gains most of its functionality from the
Chapter - Object andCheckedListBox the .NET Remoting Layer Control12 base classSerialization type. Also, the type inherits additional functionality from its direct base Chapter 13 Building a Better Window (Introducing Windows Forms) class, ListBox (examined later in this chapter). Chapter 14 - A Better Painting Framework (GDI+)
To insert items in a CheckedListBox, call Controls Add() for each item or use the AddRange() method and Chapter 15new - Programming with Windows Forms
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 System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
// Configure the CheckedListBox. Chapter 18 - ASP.NET Web Pages and Web Controls checkedBoxRadioOptions.Location = new System.Drawing.Point (16, 48); Chapter 19 - ASP.NET Web Applications checkedBoxRadioOptions.Cursor = Cursors.Hand; checkedBoxRadioOptions.Size = new System.Drawing.Size (256, 64); Index checkedBoxRadioOptions.CheckOnClick = true; List of Figures // 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 Services
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: Platform, Second Edition for(int C# i and = 0;thei .NET < checkedBoxRadioOptions.Items.Count; i++) ISBN:1590590554 by Andrew Troelsen { © 2003 (1200 pages) // Apress Is the current item checked? This comprehensive text starts with a brief overview of the if(checkedBoxRadioOptions.GetItemChecked(i)) { C# language and then quickly moves to key technical and architectural issues for .NET developers. // Get text of checked item and append to orderinfo string. orderInfo += "Radio Item: "; orderInfo += checkedBoxRadioOptions.Items[i].ToString(); Table of Contents orderInfo += "\n"; C# and the .NET Platform, Second Edition } Introduction } Part One - Introducing C# and the .NET Platform ... Chapter 1 - The Philosophy of .NET } Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3 note - C#regarding Language the Fundamentals The final CheckedListBox type is that it supports the use of multiple columns through Chapter 4 - Object-Oriented Programming C#make the following update: the inherited MultiColumn property. Thus,with if you Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections checkedBoxRadioOptions.MultiColumn = true; Chapter 7 - Callback Interfaces, Delegates, and Events checkedBoxRadioOptions.ColumnWidth = 130; Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
You see multicolumn CheckedListBox Chapter 9 the - Understanding .NET Assemblies shown in Figure 15-10. Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 15-10: Multicolumn CheckedListBox type
C# and the .NET Platform, Second Edition ListBoxes and ComboBoxes by Andrew Troelsen
ISBN:1590590554
As mentioned, the CheckedListBox type inherits most of its functionality from the ListBox type. To illustrate Apress © 2003 (1200 pages) using the ListBoxThis type,comprehensive let's add another to the current CarConfig text feature starts with a brief overview of the application: the ability to select the make (BMW,C# Yugo, and so on) of the automobile. Figure 15-11 language and then quickly moves to key technicalshows and the desired UI. architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Figure 15-11: The ListBox type
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - begin Processes, AppDomains, Contexts, andtoThreads As always, by creating a member variable manipulate your type (in this case a ListBox type). Next, Chapter 11 Type Reflection, Late Binding, and Attribute-Based Programming configure the look and feel and insert the new widget in the Form's Controls collection, as shown here: Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
// Configure the list box. carMakeList.Location = new System.Drawing.Point (168, 48); Chapter 14 - A Better Painting Framework (GDI+) carMakeList.Size = new System.Drawing.Size (112, 67); Chapter 15 Programming with Windows Forms Controls carMakeList.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; Chapter 16 - The System.IO Namespace carMakeList.ScrollAlwaysVisible = true; Chapter 17 - Data Access with carMakeList.Sorted = ADO.NET true; Part - Web Applications and XML Web Services // Five Populate the listBox using the AddRange() method. Chapter 18 ASP.NET Web Pages and Web Controls carMakeList.Items.AddRange(new object[9] { "BMW", "Caravan", "Ford", Chapter"Grand 19 - ASP.NET Am",Web "Jeep", Applications "Jetta", "Saab", "Viper", "Yugo"}); // Add to Form's Control collection. Chapter 20 new - XMLwidget Web Services this.Controls.Add (this.carMakeList); Index Chapter 13 - Building a Better Window (Introducing Windows Forms)
List of Figures List of Tables
The update to the btnOrder_Click() event handler is also simple, as shown here: protected void btnOrder_Click (object sender, System.EventArgs e) { // Build a string to display information. string orderInfo = ""; ... // Get the currently selected item (not index of the item). if(carMakeList.SelectedItem != null) orderInfo += "Make: " + carMakeList.SelectedItem + "\n"; ... }
Fun with ComboBoxes
Like a ListBox, a C# ComboBox the user toSecond make aEdition selection from a well-defined set of possibilities. and the allows .NET Platform, However, the ComboBox type is unique in that the user can also insert additional items. Recall that ISBN:1590590554 by Andrew Troelsen ComboBox derives from ListBox (which then derives from Control). To illustrate its use, add yet another Apress © 2003 (1200 pages) GUI widget to theThis CarConfig application that allows a user to enter the name of a preferred salesperson. If comprehensive text starts with a brief overview of the the salesperson in question is not on the list, the user can enter a custom C# language and then quickly moves to key technical and name. The GUI update is shown inFigure 15-12. architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - 15-12: Understanding .NET Assemblies Figure The ComboBox type Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
This modification begins with configuring the ComboBox itself. As you can see here, the logic looks identical to that for the ListBox:
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
// ComboBox configuration. comboSalesPerson.Location = new System.Drawing.Point (152, 16); Chapter 15 - Programming with Windows Forms Controls comboSalesPerson.Size = new System.Drawing.Size (128, 21); Chapter 16 - The System.IO Namespace comboSalesPerson.Items.AddRange(new object[4] Chapter 17 - Data Access with ADO.NET { "Baby Ry-Ry", "SPARK!", "Danny Boy", Part Five - Web Applications and XML Web Services "Karin 'Baby' Johnson"}); Chapter 18 - ASP.NET Web Pages and Web Controls this.Controls.Add (this.comboSalesPerson); Chapter 14 - A Better Painting Framework (GDI+)
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index The update to the btnOrder_Click() event handler is again simple, as shown here: List of Figures List of Tables void btnOrder_Click (object sender, System.EventArgs e) protected
{ // Build a string to display information. string orderInfo = ""; ... // Use the Text property to figure out the user's salesperson. if(comboSalesPerson.Text != "") orderInfo += "Sales Person: " + comboSalesPerson.Text + "\n"; else orderInfo += "You did not select a sales person!" + "\n"; ... }
C# and the .NET Platform, Second Edition The MonthCalendar Control by Andrew Troelsen
ISBN:1590590554
The System.Windows.Forms Apress © 2003 namespace (1200 pages) provides an extremely useful widget that allows the user to select a date (or range of dates) using a friendly user text interface: This comprehensive starts the withMonthCalendar a brief overview control. of the To showcase this new control, update the existing CarConfig application to allow the user to enter in the new vehicle's delivery date. Figure 15-13 shows the C# language and then quickly moves to key technical and architectural issues for .NET developers. updated (and slightly rearranged) Form.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Figure The MonthCalendar type Remoting Layer Chapter 12 - 15-13: Object Serialization and the .NET Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 understanding - A Better Painting Framework (GDI+) the core MonthCalendar properties described in Table 15-6. To begin this new type, examine Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Table 15-6: MonthCalendar Properties Chapter 17 - Data Access with ADO.NET
MonthCalendar Property
Meaning in Life
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications BoldedDates The array of DateTime objects that determine dates are shown in bold. Chapter 20 - XML Web Services
CalendarDimensions
Index
List of Figures ListFirstDayOfWeek of Tables
The number of columns and rows of months displayed in the MonthCalendar control. The first day of the week for the MonthCalendar control.
MaxDate
The maximum allowable date that can be selected. (The default is no maximum date.)
MaxSelectionCount
The maximum number of days that can be selected in a MonthCalendar control.
MinDate
The minimum allowable date that can be selected. (The default is no minimum date.)
MonthlyBoldedDates
The array of DateTime objects that determine which monthly days to bold.
SelectionEnd
Indicates the end date of the selected range of dates.
SelectionRange
Retrieves the selection range for a MonthCalendar control.
SelectionStart
Indicates the start date of the selected range of dates.
ShowToday
Indicate whether the MonthCalendar control displays the today date at the bottom C# and the .NET Platform, Second Edition
of the control, as well as circle the current date. ISBN:1590590554 by Andrew Troelsen ShowTodayCircle Apress © 2003 (1200 pages)
ShowWeekNumbers
Indicates whether the MonthCalendar control displays the week numbers (1–52)
TodayDate
The date shown as Today in the MonthCalendar control. By default, Today is the current date at the time the MonthCalendar control is created.
This comprehensive text starts with a brief overview of the to the left of each row to of key days. C# language and then quickly moves technical and architectural issues for .NET developers.
Table of Contents TodayDateSet
Indicates whether or not the TodayDate property has been explicitly set by the
C# and the .NET Platform, Seconduser. Edition If TodayDateSet is true, TodayDate returns whatever the user has set it to. Introduction Part One - Introducing C# and the .NET offers Platform Although the MonthCalendar control a fair
bit of functionality, it is very simple to programmatically capture the
Chapter range of 1 dates - Theselected Philosophy by of the.NET user. The default behavior of this type is to always select (and circle) today's date
automatically. To obtain the currently selected date programmatically, you can update the Click event handler for the Chapter 2 - Building C# Applications order Button, as shown here: Language Part Two - The C# Programming Chapter 3
- C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C# protected void btnOrder_Click (object sender, System.EventArgs e) Chapter { 5 - Exceptions and Object Lifetime
a string to display information. Chapter // 6 -Build Interfaces and Collections orderInfo ""; Chapter string 7 - Callback Interfaces,=Delegates, and Events Chapter ... 8 - Advanced C# Type Construction Techniques
//- Programming Get ship date. Part Three with .NET Assemblies d = monthCalendar.SelectionStart; Chapter DateTime 9 - Understanding .NET Assemblies dateStr = string.Format("{0}/{1}/{2}", d.Month, d.Day, d.Year); Chapter string 10 - Processes, AppDomains, Contexts, and Threads orderInfo += "Car will be sent: " + dateStr; ... Part Four - Leveraging the .NET Libraries }
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter A Better Painting Framework (GDI+) Notice 14 that- you can ask the MonthCalendar control for the currently selected date by using the SelectionStart property. Chapter 15 - Programming with Windows Formswhich Controls This property returns a DateTime reference, you store in a local variable. Using a handful of properties of the Chapter 16 -type, The you System.IO Namespace DateTime can extract out the information you need in a custom format. (Note that this type returns the clock Chapter - Data Access withnot ADO.NET time as17 well, which you are interested in.) Part Five - Web Applications and XML Web Services
At this point I assumeWeb the Pages user will exactly one day on which to deliver the new auto. However, what if you want to Chapter 18 - ASP.NET andspecify Web Controls allow the to select a Applications range of possible shipping dates? In that case all the user needs to do is drag the cursor Chapter 19 user - ASP.NET Web across the range of possible shipping dates (Figure 15-14).
Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 15-14: Selecting multiple dates You already have seen that you can obtain the start of the selection using the SelectionStart property. The end of the selection can be determined using the SelectionEnd property. Here is the code update: protected void btnOrder_Click (object sender, System.EventArgs e) {
// Build a string to display information. C# and the .NET Platform, Second Edition string orderInfo = ""; ISBN:1590590554 by Andrew Troelsen ... Apress © 2003 (1200 pages) // Get ship date range.... comprehensive text starts with a brief overview of the DateTimeThis startD = monthCalendar.SelectionStart; C# language and then quickly moves to key technical and DateTime endD = monthCalendar.SelectionEnd; architectural issues for .NET developers. string dateStartStr = string.Format("{0}/{1}/{2}", startD.Month, startD.Day, startD.Year); string dateEndStr = string.Format("{0}/{1}/{2}", endD.Month, endD.Day, endD.Year); Table of Contents // The DateTime type supports overloaded operators! C# and the .NET Platform, Second Edition if(dateStartStr != dateEndStr) Introduction { Part One - Introducing C# and the .NET Platform orderInfo += "Car will be sent between " Chapter 1 - The Philosophy of .NET + dateStartStr + " and\n" + dateEndStr; Chapter 2 - Building C# Applications } Part Two - The C# Programming Language else // They picked a single date. Chapter 3 - C# Language Fundamentals orderInfo += "Car will be sent on " + dateStartStr; Chapter ... 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime } Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, More on theC#DateTime Type Second Edition by Andrew Troelsen
ISBN:1590590554
In the current example, you extracted a DateTime type from the MonthCalendar widget using the Apress © 2003 (1200 pages) SelectionStart and SelectionEnd properties. After this point, you used This comprehensive text starts with a brief overview of the the Month, Day, and Year properties to build a customC# format string. While this is permissible, it is not optimal, language and then quickly moves to key technical and given that the DateTime type has architectural for (Table .NET developers. a number of built-in formattingissues options 15-7). Table 15-7: DateTime Members
Table of Contents
Meaning in Life C#DateTime and the .NET Platform, Second Edition Member Introduction Part One - Introducing C# and the .NET Platform
Date
Retrieves the date of the instance with the time value set to midnight.
Chapter 1
- The Philosophy of .NET
Day 2 Chapter
Extract the day, month, and year of the current DateTime type. - Building C# Applications
Part Two - The C# Programming Language Month
Chapter 3
Year
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# DayOfWeek the day of the week represented by this instance. Chapter 5 - Exceptions andRetrieves Object Lifetime Chapter 6
- Interfaces and Collections DayOfYear Retrieves the day of the year represented by this instance.
Chapter 7
- Callback Interfaces, Delegates, and Events
Hour 8 - Advanced C# Type Extract various time-related Chapter Construction Techniquesdetails from a DateTime variable. Part Three - Programming with .NET Assemblies Minute Chapter 9
Second - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Millisecond
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries MaxValue Represent the
minimum and maximum DateTime value.
Chapter 12 - Object Serialization and the .NET Remoting Layer
MinValue
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Now 14 - A Better Painting These static members Chapter Framework (GDI+) retrieve a DateTime type representing the current dateWindows and timeForms (Now)Controls or date (Today). Chapter Today15 - Programming with Chapter 16 - The System.IO Namespace
Ticks
Retrieves the 100-nanosecond tick count for this instance.
Chapter 17 - Data Access with ADO.NET
Part Five - Web ApplicationsConvert and XMLthe Web Services ToLongDateString() current value
of the DateTime type to a string representation.
Chapter 18 - ASP.NET Web Pages and Web Controls ToLongTimeString() Chapter 19 - ASP.NET Web Applications
ToShortDateString()
Chapter 20 - XML Web Services
ToShortTimeString() Index List of Figures
Using these members, you can replace the previous formatting you programmed by hand with the List of Tables following (you will see no change in the program's output):
string dateStartStr = startD.Date.ToShortDateString(); string dateEndStr = endD.Date.ToShortDateString();
and the .NET Platform, Second Edition Setting the C# Form's Default Input Button by Andrew Troelsen
ISBN:1590590554
Many user input Forms dialog boxes) have a particular Button that will automatically respond to Apress (especially © 2003 (1200 pages) the user hitting the Enter key. For the CarConfig Form, if you wish toofensure that when the user hits the This comprehensive text starts with a brief overview the Enter key, simplyC# make use of the Form's AcceptButton property: language and then quickly moves to key technical and architectural issues for .NET developers.
this.AcceptButton = this.btnOrder; Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the Platform, Second Edition ConfiguringC#the Tab.NET Order by Andrew Troelsen
ISBN:1590590554
Next up, let's address the issue of tab order. As you know, when a Form or dialog box contains multiple Apress © 2003 (1200 pages) GUI widgets, users expect to be able to focus the Tab key. the tab order for your set This comprehensive textshift starts withusing a brief overview of Configuring the of controls requires that you understand two key properties: TabStop and TabIndex. C# language and then quickly moves to key technical and architectural issues for .NET developers.
The TabStop property can be set to true or false, based on whether or not you wish this GUI item to be reachable using the Tab key. Assuming the TabStop property has been set to true for a given widget, the Table TabOrder of Contents property is then set to establish its order of activation in the tabbing sequence (which is zero based). Consider this example: C# and the .NET Platform, Second Edition Introduction Part - Introducing C# and the .NET Platform // One Configure tabbing properties.
Chapter 1 - The Philosophy radioRed.TabIndex = of2;.NET Chapter radioRed.TabStop 2 - Building C# = Applications true; Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# The Tab Order Wizard
Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - Studio Interfaces and Collections The Visual .NET IDE supplies a Tab Order Wizard, accessed using the View | Tab Order menu Chapter selection. 7 Once - Callback activated, Interfaces, your Delegates, design timeand Form Events displays the current TabIndex value for each widget. To
change8these values, C# click each item in the Techniques order you choose (Figure 15-15). Chapter - Advanced Type Construction Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List ofFigure Figures15-15: The VS .NET Tab Order Wizard List of Tables
To exit this Tab Order Wizard, simply hit the Esc key.
C# and the .NET Second Edition Assigning ToolTips to Platform, Controls by Andrew Troelsen
ISBN:1590590554
To finish up the CarConfig Form, have one final point of interest. Most modern user interfaces support Apress © 2003 (1200we pages) tool tips. In the System.Windows.Forms type represents this functionality. These This comprehensive text namespace, starts with a the briefToolTip overview of the widgets are simply small floating windows that display a helpful message C# language and then quickly moves to key technical and when the cursor hovers over a issues .NET developers. given item. Tablearchitectural 15-8 describes thefor core members of the ToolTip type. Table 15-8: ToolTip Members
Table of Contents
Meaning in Life C#ToolTip and the .NET Platform, Second Edition Member Introduction Part One - Introducing C# and the .NET Platform
Active
Configures if the tool tip is activated or not. For example, perhaps you have a menu item that disables all tool tips for advanced users. This property allows Chapter 2 - Building C#you Applications to turn off the pop-up text. Chapter 1
- The Philosophy of .NET
Part Two - The C# Programming Language
AutomaticDelay Gets or sets the time (in milliseconds) that passes before the ToolTip appears. Chapter 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming withmilliseconds) C# AutoPopDelay The period of time (in that the ToolTip remains visible when the Chapter 5 - Exceptions cursor and Object Lifetime is stationary in the ToolTip region. The default value is 10 times the Chapter 6 Chapter 7
- Interfaces AutomaticDelay and Collections property value. - Callback Interfaces, Delegates, and Events
GetToolTip() Returns the tool tip text assigned to a specific control. - Advanced C# Type Construction Techniques Part Three - Programming with .NETof Assemblies InitialDelay The period time (in milliseconds) that the cursor must remain stationary in Chapter 9 - Understanding .NET Assemblies the ToolTip region before the ToolTip text is displayed. The default is equal to Chapter 10 - Processes, the AppDomains, Contexts, and Threads AutomaticDelay property. Chapter 8
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
ReshowDelay
The length of time (in milliseconds) that it takes subsequent ToolTip instances to appear as the cursor moves from one ToolTip region to another. The Chapter 12 - Object Serialization and the .NET Remoting Layer default is 1/5 of the AutomaticDelay property value. Part Four - Leveraging the .NET Libraries
Chapter 13 - Building a Better Window (Introducing Windows Forms)
SetToolTip() Associates a tool tip to a specific control. Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
To illustrate, addSystem.IO a tool tip to the CarConfig's Calendar type. Begin by creating a new member variable of Chapter 16 - The Namespace type ToolTip. Next, configure the set of properties for the new item. Notice that you make a call to Chapter 17 - Data Access with ADO.NET SetToolTip(), configures not only text to Part Five - Webwhich Applications and XML Webthe Services
be displayed, but also the widget to which it is assigned:
Chapter 18 - ASP.NET Web Pages and Web Controls
// Create and associate a tool tip to the calendar Chapter 19 - ASP.NET Web Applications calendarTip.Active = true; Chapter 20 - XML Web Services calendarTip.SetToolTip (monthCalendar, Index "Please select the date (or dates)\n when we can deliver your new car!"); List of Figures List of Tables
Adding ToolTips at Design Time If you wish to leverage the Visual Studio .NET IDE to build your tool tips, begin by adding a ToolTip widget to your Form using the Toolbox window. At this point, you can configure the ToolTip using the Properties window. To associate the new tip with a given widget, select the widget that should activate the tip and set the "ToolTip on" property (Figure 15-16).
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Figure- 15-16: Associating a ToolTip to a given widget Object-Oriented Programming with C#
Chapter 4 Chapter 5
- Exceptions and Object Lifetime SOURCE The CarConfig project is included under the Chapter 15 directory.
Chapter 6 - Interfaces and Collections CODE Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The TrackBar Control by Andrew Troelsen
ISBN:1590590554
The TrackBar control allows to select from a range of values, using a scroll bar-like input Apress © 2003users (1200 pages) mechanism. In many respects a TrackBar is functionally to aoftraditional scroll bar. When working This comprehensive text starts with a briefsimilar overview the with this type, youC# need to set the minimum and maximum range, the minimum and maximum change language and then quickly moves to key technical and architectural issues for developers. increments, and the starting location of .NET the slider's thumb. Each of these aspects can be set using the properties described in Table 15-9. Table of 15-9: Contents Table TrackBar Properties C# and the .NET Platform, Second Edition
TrackBar Introduction
Meaning in Life Property Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET LargeChange The number of ticks by which the TrackBar changes when an event - Building C#considered Applicationsa large change occurs (e.g., clicking the mouse button while the Part Two - The C# Programming cursor isLanguage on the sliding range and using the Page Up or Page Down key). Chapter 2 Chapter 3
- C# Language Fundamentals Maximum Configure the upper andC# lower bounds of the TrackBar's range. Chapter 4 - Object-Oriented Programming with Chapter Minimum 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Orientation
The orientation for this TrackBar. Valid values are from the Orientation enumeration (i.e., horizontally or vertically).
SmallChange The number of ticks by which the Part Three - Programming with .NET Assemblies
TrackBar changes when an event considered a small change occurs (e.g., using the arrow keys). Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
TickFrequency
Indicates how many ticks are drawn. For a TrackBar with an upper limit of
Chapter 11 - Type Reflection, Binding, and Programming 200, itLate is impractical to Attribute-Based draw all 200 ticks on a control 2 inches long. If you set Part Four - Leveraging the Libraries the.NET TickFrequency
property to 5, the TrackBar draws 20 total ticks (each tick
Chapter 12 - Object Serialization and5 the .NET Remoting Layer represents units). Chapter 13 - Building a Better Window (Introducing Windows Forms)
TickStyle Indicates how the(GDI+) TrackBar control draws itself. This affects both where the Chapter 14 - A Better Painting Framework
ticks are drawn in relation to the movable thumb and how the thumb itself is drawn (using the TickStyle enumeration).
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Chapter withorADO.NET Value17 - Data AccessGets sets the current location of the TrackBar. Use this property to obtain Part Five - Web Applications and XMLvalue Web Services the numeric contained
by the TrackBar for use in your application.
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Now you build anServices application that makes use of three TrackBars. Each widget has an upper range of Chapter 20can - XML Web
255 and a lower range of 0. As the user slides each thumb, the application intercepts the Scroll event and dynamically builds a new Color type based on the value of each slider. In this way, the user is able to view List of Figures the underlying RGB value (and see the color) for a given selection. (Of course, the List of Tables System.Windows.Forms namespace already provides a ColorDialog type for this purpose.) Index
First you need to configure each TrackBar. Assume your Form contains three private TrackBar member variables (redTrackBar, greenTrackBar, and blueTrackBar). Here is the relevant code for blueTrackBar (the remaining bars look almost identical, with the exception of the name of the Scroll event handler): // Here is the blue TrackBar. blueTrackBar.TickFrequency = 5; blueTrackBar.Location = new System.Drawing.Point (104, 200); blueTrackBar.TickStyle = System.Windows.Forms.TickStyle.TopLeft; blueTrackBar.Maximum = 255; blueTrackBar.Scroll += new System.EventHandler (this.blueTrackBar_Scroll);
Note that the default minimum value of the TrackBar is 0 and thus does not need to be explicitly set. In the event handlers for each TrackBar, you make a call to an internal private helper function named
UpdateColor(), which does the real grunt work, as shown here: C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
protected void blueTrackBar_Scroll (object sender, System.EventArgs e) Apress © 2003 (1200 pages) { This comprehensive text starts with a brief overview of the UpdateColor(); C# language and then quickly moves to key technical and } architectural issues for .NET developers. UpdateColor() is responsible for two major tasks. First you read the current value of each TrackBar and Table of Contents send to a new Color variable (using the FromArgb() member). Once you have the newly C# andthis thestate .NET data Platform, Second Edition
configured color, you update a Form-level member variable of type PictureBox (named colorBox), which in this case does not hold an actual bitmap image, but simply maintains the current background color. Part One - Introducing C# and the .NET Platform Finally, the UpdateColor() method formats this information in a string placed on the Form's color display Chapter 1 - The Philosophy of .NET label (lblCurrColor), as shown here: Introduction
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
private UpdateColor() Chapter 3 -void C# Language Fundamentals {
Chapter 4
- Object-Oriented Programming with C#
// Get the new color. - Exceptions and Object Lifetime Color c = Color.FromArgb(redTrackBar.Value, Chapter 6 - Interfaces and Collections greenTrackBar.Value, blueTrackBar.Value); Chapter 7 - Callback Interfaces, Delegates, and Events // Change the color in the PictureBox. Chapter 8 - Advanced C# Type Construction Techniques colorBox.BackColor = c; Part Three - Programming with .NET Assemblies // Set color label. Chapter lblCurrColor.Text 9 - Understanding .NET Assemblies = Chapter 10 - Processes, AppDomains, Contexts, and Threads string.Format("Current color is: ({0}, {1}, {2})", Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming redTrackBar.Value, greenTrackBar.Value, Part Four - Leveraging the .NET Libraries blueTrackBar.Value); Chapter 12 - Object Serialization and the .NET Remoting Layer } Chapter 5
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
The final is to set the initial valuesForms of each slider when the Form comes to life and render the current Chapter 15detail - Programming with Windows Controls color, as here: Chapter 16shown - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
public TrackForm() Part Five - Web Applications and XML Web Services { Chapter 18 - ASP.NET Web Pages and Web Controls Chapter InitializeComponent(); 19 - ASP.NET Web Applications Chapter CenterToScreen(); 20 - XML Web Services
// Set initial position of each slider. redTrackBar.Value = 100; List of Figures greenTrackBar.Value = 255; List of Tables blueTrackBar.Value = 0; UpdateColor(); } Index
C# and the .NET Platform, Second Edition Working with Panel Controls by Andrew Troelsen
ISBN:1590590554
As you have seenApress earlier© in this chapter, 2003 (1200 pages) the GroupBox control can be used to logically bind a number of controls (such asThis RadioButtons) to as a collective. Closely related comprehensivefunction text starts with a brief overview of the to the GroupBox is the Panel control. Panels are also used to group related controls in a logical unit. C# language and then quickly moves to key technical andOne difference is that the Panel issues for .NET developers. type derives fromarchitectural the ScrollableControl class, and thus it can support scroll bars, which is not possible with a GroupBox. Table Panels of Contents can be used to conserve screen real estate. For example, if you have a group of controls that take
upand the the entire bottom half Second of a Form, you can contain them in a Panel that is half the size and set the C# .NET Platform, Edition AutoScroll property to true. In this way, the user can use the scroll bar(s) to view the hidden items. To Introduction illustrate, let's updateC# theand previous TrackBar application. Part One - Introducing the .NET Platform
This time, each TrackBar is contained in a single
Panel.Figure 15-17 shows of the.NET update. Chapter 1 - The Philosophy Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 15-17: Working with Panel types Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
The underlying code looks almost identical to that of manipulating a GroupBox. Begin by declaring a Panel data member (panel1) and add each item using the Controls property, as shown here:
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
// Configure the panel. panel1.AutoScroll = true; Chapter 17 - Data Access with ADO.NET panel1.Controls.Add (this.label2); Part Five - Web Applications and XML Web Services panel1.Controls.Add (this.blueTrackBar); Chapter 18 - ASP.NET Web Pages and Web Controls panel1.Controls.Add (this.label3); Chapter 19 - ASP.NET Web Applications panel1.Controls.Add (this.greenTrackBar); Chapter 20 - XML Web Services panel1.Controls.Add (this.redTrackBar); Index panel1.Controls.Add (this.label1); Chapter 16 - The System.IO Namespace
List of Figures List of Tables
SOURCE CODE
The Tracker application can be found under the Chapter 15 directory.
C# and the .NET Platform, Second Edition and NumericUpDown The UpDown Controls: DomainUpDown by Andrew Troelsen
ISBN:1590590554
Windows Forms provide that function as spin controls (also known as up/down controls). Like Apress ©two 2003widgets (1200 pages) the ComboBox and ListBox types, these allow the user to choose an item from a range of This comprehensive text new startsitems with also a brief overview of the possible selections. The difference is that when using a DomainUpDown C# language and then quickly moves to key technical and or NumericUpDown control, the architectural .NET developers. information is selected using aissues smallfor pair of up and down arrows. For example, check out Figure 15-18.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3 - 15-18: C# Language Fundamentals Figure Working with UpDown types Chapter 4
- Object-Oriented Programming with C#
Chapter Given your 5 - work Exceptions with previous and Object (and Lifetime similar) types, you should find working with the UpDown widgets
painless. DomainUpDown widget allows the user to select from a set of string data. NumericUpDown Chapter 6 The - Interfaces and Collections allows selections from a range of numericand dataEvents points. Each widget derives from a common direct base Chapter 7 - Callback Interfaces, Delegates, class: UpDownBase. 15-10 describesTechniques some important properties of this class. Chapter 8 - Advanced Table C# Type Construction Part Three - Programming with .NET Assemblies
Table 15-10: UpDownBase Properties Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads UpDownBase Meaning in Life Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Property Part Four - Leveraging the .NET Libraries
InterceptArrowKeys Gets or the sets.NET a value indicating Chapter 12 - Object Serialization and Remoting Layerwhether the user can use the Up Arrow Down(Introducing Arrow keysWindows to selectForms) values Chapter 13 - Building a Betterand Window Chapter 14 - A Better PaintingGets Framework ReadOnly or sets (GDI+) a value indicating whether the text can only be changed by Chapter 15 - Programming with Windows Forms the use of the up orControls down arrows and not by typing in the control to Chapter 16 - The System.IO Namespace locate a given string Chapter 17 - Data Access with ADO.NET
Text GetsXML or sets current Part Five - Web Applications and Webthe Services
text displayed in the spin control
Chapter 18 - ASP.NET Web Pages Webthe Controls TextAlign Getsand or sets alignment of the text in the spin control Chapter 19 - ASP.NET Web Applications
UpDownAlign
Gets or sets the alignment of the up and down arrows on the spin control, using the LeftRightAlignment enumeration
Chapter 20 - XML Web Services Index List of Figures
The DomainUpDown control adds a small set of properties (Table 15-11) that allow you to configure and manipulate the textual data in the widget.
List of Tables
Table 15-11: DomainUpDown Properties DomainUpDown Property
Meaning in Life
Items
Allows you to gain access to the set of types stored in the widget
SelectedIndex
Returns the zero-based index of the currently selected item
SelectedItem
Returns the selected item itself (not its index)
Sorted
Configures whether or not the strings should be alphabetized
Wrap
Controls if the collection of items continues to the first or last item if the user continues past the end of the list
The NumericUpDown type is just as simple (Table 15-12).
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Table 15-12: NumericUpDown Properties
NumericUpDown This comprehensive Meaning text starts in Life with a brief overview of the C# language and then quickly moves to key technical and Property architectural issues for .NET developers.
DecimalPlaces
Used to configure how the numerical data is to be displayed.
ThousandsSeparator
Table of Contents
C#Hexadecimal and the .NET Platform, Second Edition Introduction Increment
Sets the numerical value to increment the value in the control when is clicked. The default is to advance the value Chapter 1 - The Philosophy of .NET by 1. Part One - Introducing C# and the Platform the.NET up or down arrow
Chapter 2
- Building C# Applications
Minimum the upper Part Two - The C# Programming Sets Language
and lower limits of the value in the control.
Maximum Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Value
Returns the current value in the control.
Chapter 6
Interfaces and Collections Here is the- code behind the sample application:
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
// Configure DomainUpDown widget. domainUpDown.Sorted = true; Chapter 9 - Understanding .NET Assemblies domainUpDown.Wrap = true; Chapter 10 - Processes, AppDomains, Contexts, and Threads domainUpDown.Items.AddRange (new object[4] { "Another Boring String named B", Chapter"Boring 11 - Type String Reflection,A", Late"BORING Binding, and Attribute-Based Programming String C", "Final Boring string (D)"}); Part Four Leveraging the .NET Libraries domainUpDown.SelectedIndex = 2; Chapter 12 - ObjectNumericUpDown Serialization and thewidget. .NET Remoting Layer // Configure Chapter 13 Building a Better Window (Introducing Forms) numericUpDown.Maximum = new decimal Windows (5000); Chapter 14 - A Better Painting Framework (GDI+) numericUpDown.ThousandsSeparator = true; Chapter 15 - Programming with Windows Forms Controls numericUpDown.UpDownAlign = LeftRightAlignment.Left; Part Three - Programming with .NET Assemblies
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
The Click handler the Form's type simply asks each type for its current value and places it Chapter 18 event - ASP.NET Webfor Pages and WebButton Controls in the appropriate Label as a formatted string, as shown here:
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
protected void btnGetSelections_Click (object sender, System.EventArgs e) Index { of Figures List // Get info from updowns... lblCurrSel.Text = string.Format("String: {0}\nNumber: {1}", domainUpDown.Text, numericUpDown.Value);
List of Tables
}
Of course, the DomainUpDown and NumericUpDown types support a number of events. If you ever need to capture when the selection changes, you can use SelectedItemChanged (for DomainUpDown types) or ValueChanged (for NumericUpDown types). Here is an example: // Intercept the SelectedItemChanged event. domainUpDown.SelectedItemChanged += new EventHandler (domainUpDown_SelectedItemChanged); ... // Handle the event.
protected void domainUpDown_SelectedItemChanged (object sender, C# and the .NET Platform, Second Edition System.EventArgs e) ISBN:1590590554 by Andrew Troelsen { Apress © 2003 (1200 pages) the string value..."; this.Text = "You changed This comprehensive text starts with a brief overview of the } C# language and then quickly moves to key technical and architectural issues for .NET developers.
SOURCE CODE
Table of Contents
The UpAndDown application is included under the Chapter 15 directory.
C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and .NET Platform, Second Edition Working with thetheErrorProvider by Andrew Troelsen
ISBN:1590590554
Most Windows Forms applications will need to validate user input in one way or another. This is especially Apress © 2003 (1200 pages) true with dialog boxes, as you should inform users a processing error before continuing This comprehensive text starts withifathey briefmake overview of the forward. (I'll examine dialog box programming later in this chapter.) C# language and then quickly moves to key technical and architectural issues for .NET developers.
The ErrorProvider type can be used to provide a visual cue of user input error. For example, assume you have a Form containing a TextBox and Button widget. If the user enters more than five characters in the Table TextBox, of Contents the error information shown in Figure 15-19 is displayed. C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4 - 15-19: Object-Oriented Programming with C# Figure The ErrorProvider in action Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Here, you have detected that the user entered more than five characters and responded by placing a - Callback Interfaces, Delegates, and Events small error icon (!) next to the TextBox object. When the user places the cursor over this icon, the Chapter 8 - Advanced C# Type Construction Techniques descriptive error text appears as a pop-up. Also, this ErrorProvider is configured to cause the icon to blink Part Three - Programming with .NET Assemblies a number of times to strengthen the visual cue (which, of course, you can't see without running the Chapter 9 - Understanding .NET Assemblies application). Chapter 7
Chapter 10 - Processes, AppDomains, Contexts, and Threads
If you wish support this type ofBinding, input validation, the first stepProgramming is to understand the properties of the Chapter 11 -to Type Reflection, Late and Attribute-Based Control (Table 15-13). Part Four class - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
Table 15-13: Control Properties Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Control
Meaning in Life
Chapter 15 - Programming with Windows Forms Controls Property Chapter 16 - The System.IO Namespace
CausesValidation Indicates whether selecting this control causes validation on the controls Chapter 17 - Data Access with ADO.NET validation Part Five - Web Applications requiring and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls
Validated
Occurs when the control is finished performing its validation logic
Chapter 19 - ASP.NET Web Applications
Validating Occurs when the control is validating user input (e.g., when the control Chapter 20 - XML Web Services Index
loses focus)
List of Figures
Every GUI widget can set the CausesValidation property to true or false. (The default is false.) If you set List of Tables
this bit of state data to true, the control forces the other controls on the Form to validate themselves when it receives focus (provided the CausesValidation property is also set to true). Once a validating control has received focus, the Validating and Validated events are fired for each control. It is in the scope of the Validating event handler in which you configure a corresponding ErrorProvider. Optionally, the Validated event can be handled to determine when the control has finished its validation cycle. To begin, assume you have set the CausesValidation property to true for the Button and TextBox and have added a member variable of type ErrorProvider. Here is the configuration code: // Configure the error provider. errorProvider1.DataMember = ""; errorProvider1.DataSource = null; errorProvider1.ContainerControl = null; errorProvider1.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.AlwaysBlink;
errorProvider1.BlinkRate = 500; C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
© 2003 (1200 pages) The ErrorProviderApress type has a small set of members. The most important item for your purposes is the BlinkStyle property, can be settext to any of the the ErrorBlinkStyle enumeration described in Thiswhich comprehensive starts withvalues a briefof overview of the C# language and then quickly moves to key technical and Table 15-14.
architectural issues for .NET developers.
Table 15-14: ErrorBlinkStyle Properties Table of Contents ErrorBlinkStyle
Meaning in Life
C#Property and the .NET Platform, Second Edition Introduction
AlwaysBlink
Causes the error icon to blink when the error is first displayed or when a new error description string is set for the control and the Chapter 1 - The Philosophy of .NET error icon is already displayed Part One - Introducing C# and the .NET Platform
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language BlinkIfDifferentError Causes the
error icon to blink only if the error icon is already
Chapter 3
- C# Language Fundamentals displayed, but a new error string is set for the control
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
NeverBlink
Indicates the error icon never blinks
The ErrorProvider also has additional members beyond BlinkStyle and BlinkRate. For example, if you wish - Callback Interfaces, Delegates, and Events to associate a custom icon to the error, you can do so using the Icon property. Nevertheless, once you Chapter 8 - Advanced C# ErrorProvider Type Construction Techniques have configured how the looks and feels, you bind the error to the TextBox within the scope Part Three - Programming with .NET Assemblies of its Validating event handler, as shown here: Chapter 7
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
protected void txtInput_Validating (object sender, CancelEventArgs e) { Part Four - Leveraging the .NET Libraries // Check if the text length is greater than 5. Chapter if(txtInput.Text.Length 12 - Object Serialization and the .NET Remoting Layer > 5) Chapter { 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - AerrorProvider1.SetError(txtInput, Better Painting Framework (GDI+) "Can't be greater than 5!"); Chapter } 15 - Programming with Windows Forms Controls Chapter else 16 - The //System.IO Things Namespace are OK, don't show anything. Chapter 17 - Data errorProvider1.SetError(txtInput, Access with ADO.NET ""); Part } Five - Web Applications and XML Web Services Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
SOURCE CODE
Index
List of Figures List of Tables
The ErrorProvider application is included under the Chapter 15 directory.
the .NET Platform, Second Edition ConfiguringC#aand Control's Anchoring Behavior by Andrew Troelsen
ISBN:1590590554
When you are creating containing Apress a© Form 2003 (1200 pages) widgets, you need to decide whether the Form should be resizable. Typically speaking, main are resizable, whereasofdialog This comprehensivewindows text starts with a brief overview the boxes are not. To configure the resizability of yourC# Form, adjust the FormBorderStyle property to any of language and then quickly moves to key technical andthe values described in Table 15architectural issues for .NET developers. 15. Table 15-15: FormBorderStyle Properties
Table of Contents
C#FormBorderStyle and the .NET Platform,Property Second Edition Introduction
Fixed3D
Meaning in Life A nonresizable, three-dimensional border
Part One - Introducing C# and the .NET Platform
FixedDialog Chapter 1 - The Philosophy of .NET Chapter 2
- Building C# Applications
FixedSingle
Part Two - The C# Programming Language
FixedToolWindow Chapter 3 - C# Language Fundamentals
A thick, nonresizable dialog box-style border A nonresizable, single-line border A tool window border that is not resizable
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
None
No border at all
Sizable Chapter 6 - Interfaces and Collections
A resizable border
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
A resizable tool window border
SizableToolWindow
Part Three - Programming with .NET Assemblies
Assume that you have configured your Form to be resizable. This brings up some interesting questions
Chapter 9 the - Understanding .NET Assemblies regarding contained controls. For example, if the user makes the Form smaller than the rectangle Chapter 10 Processes, AppDomains, Contexts, and Threads needed to display each control, should the controls adjust their size (and possibly location) to morph Chapter 11with - Type Late Binding, and Attribute-Based Programming correctly the Reflection, Form? Part Four - Leveraging the .NET Libraries
In the Windows Forms worldview, propertyLayer is used to define a relative fixed position in which Chapter 12 - Object Serialization andthe theAnchor .NET Remoting the control beWindow rendered. Every Control-derived type has an Anchor property, which can be Chapter 13 - should Buildingalways a Better (Introducing Windows Forms) set to any values from Framework the AnchorStyles Chapter 14 -ofAthe Better Painting (GDI+)enumeration described in Table 15-16. Chapter 15 - Programming with Windows Forms Controls
Table 15-16: AnchorStyles Values Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET AnchorStyles Value Meaning in Life Part Five - Web Applications and XML Web Services
Bottom control is anchored to the bottom edge of its container. Chapter 18 - ASP.NET Web Pages The and Web Controls Chapter Left 19 - ASP.NET Web Applications The control is anchored to the left edge of its container. Chapter 20 - XML Web Services
None Index
The control is not anchored to any edges of its container.
ListRight of Figures
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.
the .NET Platform, Second Edition ConfiguringC#aand Control's Docking Behavior by Andrew Troelsen
ISBN:1590590554
Another aspect ofApress Windows Forms programming is establishing the docking behavior of your controls. If © 2003 (1200 pages) you so choose, you can set a widget's Dock property configure This comprehensive text starts with a to brief overviewwhich 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 moves to key technical andproperty is honored, regardless of architectural issues for15-17 .NET developers. the Form's current dimensions. Table describes possible options. Table 15-17: DockStyle Values
Table of Contents
in Life C#DockStyle and the .NET Platform, Meaning Second Edition Value Introduction Part One - Introducing C# and the .NET Platform
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. Part Two - The C# Programming Language Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
None 5 Chapter
TheObject control is not docked. - Exceptions and Lifetime
Chapter Right 6 Chapter 7
- Interfaces and Collections The control's right edge is docked to the right edge of its containing control. - Callback Interfaces, Delegates, and Events
Top 8 Chapter
control's top edge is docked to the top of its containing control. - Advanced C#The Type Construction Techniques
Left
The control's left edge is docked to the left edge of its containing control.
Part Three - Programming with .NET Assemblies
So, for 9example, if you want to ensure that a given widget is always docked on the left side of a Form, you Chapter - Understanding .NET Assemblies would write following: Chapter 10 - the Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Four This item is the always located Part - Leveraging .NET Libraries
on the left of the Form, regardless
// of12the Form's current Chapter - Object Serialization and size. the .NET Remoting Layer myButton.Dock DockStyle.Left; Chapter 13 - Building=a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
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 System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition Building Custom Dialog Boxes by Andrew Troelsen
ISBN:1590590554
Now that you have a solid understanding Apress © 2003 (1200 pages) of some common Windows Forms controls, you need to examine the construction of custom boxes. good news isofthat This comprehensive dialog text starts withThe a brief overview theeverything you have already learned about System.Windows.Forms applies directly to dialog box programming. There is no Dialog C# language and then quickly moves to key technical and issues for .NET developers. Rather, a dialog box is nothing more than a base class in the architectural System.Windows.Forms namespace. stylized Form. Table Firstof of Contents all, understand that dialog boxes are typically configured to be nonsizable. Therefore, you will
typically set the BorderStyle property to FormBorderStyle.FixedDialog. Also, you will want to set C# and thewant .NETtoPlatform, Second Edition the ControlBox, MinimizeBox, and MaximizeBox properties to false. In this way the dialog box is configured Introduction to be a fixed constant.C# and the .NET Platform Part One - Introducing 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 Part Two - The C# Programming Language following logic: Chapter 2 Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
// Launch a modal dialog box. - Exceptions and Object Lifetime protected void mnuModalBox_Click (object sender, System.EventArgs e) Chapter 6 - Interfaces and Collections { Chapter 7 - Callback Interfaces, Delegates, and Events SomeCustomForm myForm = new SomeCustomForm(); Chapter 8 - Advanced C# Type Construction Techniques // Could assign in the ctor of SomeCustomForm as well. Part Three - Programming with .NET Assemblies myForm.BorderStyle = FormBorderStyle.FixedDialog; Chapter myForm.ControlBox 9 - Understanding .NET Assemblies = false; Chapter myForm.MinimizeBox 10 - Processes, AppDomains, = Contexts, false; and Threads Chapter myForm.MaximizeBox 11 - Type Reflection, Late Binding, and Attribute-Based Programming = false; Part FourmyForm.ShowDialog(this); - Leveraging the .NET Libraries Chapter DoSomeMoreWork(); 12 - Object Serialization and .NETcalled Remotinguntil Layer dialog is closed. //theNot Chapter 13 Building a Better Window (Introducing Windows Forms) } Chapter 5
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
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 Part Five - Web Applications and XML Web Services 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 Controls box (i.e., the launching window and dialog box can alternate focus), substitute the ShowDialog() call with a Chapter 19 - ASP.NET Web Applications call to Show(), as shown here: Chapter 17 - Data Access with ADO.NET
Chapter 20 - XML Web Services Index
// 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 Figures
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Figure 15-21: The main Form Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
When the user selects this option, a simple dialog box is displayed. The goal is to allow the user to type in Understanding .NET Assemblies some text,-which is then painted on the parent Form (but only if the OK Button is selected). Figure 15-22 Chapter 10 Processes, AppDomains, Contexts, and Threads shows the UI of your dialog box. Chapter 9
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services IndexFigure 15-22: The dialog box Form List of Figures 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# and the .NET Platform, Second Edition
by Andrew Troelsendialog box should be of no ISBN:1590590554 The code representing the custom surprise, given that a dialog box is nothing Apress © 2003 modifications. (1200 pages) more than a Form with minor Here is the relevant code: This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and // The dialogarchitectural box. issues for .NET developers.
public class SomeCustomForm : System.Windows.Forms.Form { Table of private Contents System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; C# and the .NET Platform, Second Edition private System.Windows.Forms.Label label1; Introduction private System.Windows.Forms.TextBox txtMessage; Part One - Introducing C# and the .NET Platform public SomeCustomForm() Chapter 1 - The Philosophy of .NET { Chapter 2 - Building C# Applications InitializeComponent(); Part Two - The C# Programming Language this.StartPosition = FormStartPosition.CenterParent; Chapter 3 - C# Language Fundamentals } Chapter 4 - Object-Oriented Programming with C# ... Chapter private 5 - Exceptions Object Lifetime voidand InitializeComponent() Chapter { 6 - Interfaces and Collections Chapter 7 - Callback ... Interfaces, Delegates, and Events Chapter 8 - Advanced Type Construction Techniques // OK C# Button configuration. Part Three - Programming with .NET Assemblies btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; Chapter 9 - Understanding .NET btnOK.Size = Assemblies new System.Drawing.Size (96, 24); Chapter 10 - Processes, btnOK.Text AppDomains, = "OK"; Contexts, and Threads // Reflection, Cancel Button configuration. Chapter 11 - Type Late Binding, and Attribute-Based Programming btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; Part Four - Leveraging the .NET Libraries btnCancel.Size (96, 24); Chapter 12 - Object Serialization and =thenew .NETSystem.Drawing.Size Remoting Layer btnCancel.Text = (Introducing "Cancel";Windows Forms) Chapter 13 - Building a Better Window Form configured to function as dialog box. Chapter 14 - A // Better Painting Framework (GDI+) this.Text = "Some Custom Dialog"; Chapter 15 - Programming with Windows Forms Controls this.MaximizeBox = false; Chapter 16 - The System.IO Namespace this.ControlBox = false; Chapter 17 - Data Access with ADO.NET this.MinimizeBox = false; Part Five - Web Applications and XML Web Services } Chapter 18 - ASP.NET Web Pages and Web Controls } Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index The first point of interest is in the constructor of the Form. Notice that you are setting the StartPosition List of Figures property on startup. Earlier, you directly called CenterToScreen() to ensure that the Form was centered 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# and the .NET Platform, Second Edition box's button should respond with respect to dialog box processing, use the DialogResult property, as ISBN:1590590554 by Andrew Troelsen shown here: Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
private void C# InitializeComponent() language and then quickly moves to key technical and { architectural issues for .NET developers. ... // OK Button configuration. btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; Table of Contents // Cancel Button configuration. C# and the .NET Platform, Second Edition btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; Introduction } Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Validating Form Data with the DialogResult Property
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals What exactly does it mean to assign a Button's DialogResult value? First of all, when a Button has been Chapter 4 - Object-Oriented Programming with C#
set to DialogResult.OK or DialogResult.Cancel, the Form automatically closes (meaning it is invisible but Chapter 5 - Exceptions and Object Lifetime still in memory). Also, you can query this property back in the code that launched this dialog box to see Chapter 6 - Interfaces and Collections which Button the user selected,Delegates, as shown and here: Chapter 7 - Callback Interfaces, Events Chapter 8
- Advanced C# Type Construction Techniques
protected void mnuModalBox_Click Part Three - Programming with .NET Assemblies(object
sender, System.EventArgs e) { Chapter 9 - Understanding .NET Assemblies props set inContexts, Form. and Threads Chapter // 10 -Style Processes, AppDomains, SomeCustomForm myForm = SomeCustomForm(); Chapter 11 - Type Reflection, Late Binding,new and Attribute-Based Programming // Passing in a reference to the launching dialog box is optional. Part Four - Leveraging the .NET Libraries myForm.ShowDialog(this); Chapter 12 - Object Serialization and the .NET Remoting Layer if(myForm.DialogResult == DialogResult.OK) Chapter 13 - Building a Better Window (Introducing Windows Forms) { Chapter 14 - A Better Painting Framework (GDI+) // User hit OK, do whatever. Chapter 15 - Programming with Windows Forms Controls } Chapter 16 - The System.IO Namespace DoSomeMoreWork(); Chapter 17 - Data Access with ADO.NET } Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter The DialogResult 19 - ASP.NET enumeration Web Applications specifies the following values: Chapter 20 - XML Web Services Index public enum System.Windows.Forms.DialogResult List { of Figures 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# and the .NET Platform, Second Edition this.StartPosition = FormStartPosition.CenterParent; ISBN:1590590554 by Andrew Troelsen } Apress © 2003 (1200 pages) // The dialog box's state data (and a way to get it). comprehensive text starts with a brief overview of the private This string strMessage; C# language and then public string Message quickly moves to key technical and architectural issues for .NET developers. { get{ return strMessage;} // The set function allows the owner to send Table of Contents // in a startup string that you place in the C# and the .NET Platform, Second Edition // TextBox. Introduction set Part One - Introducing C# and the .NET Platform { Chapter 1 - The Philosophy of .NET strMessage = value; Chapter 2 - Building C# Applications txtMessage.Text = strMessage; Part Two - The C# Programming Language } Chapter } 3 - C# Language Fundamentals Chapter ... 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime }
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Now, to8 transfer the value in the TextBox to Techniques this private member variable requires that you intercept the Chapter - Advanced C# Type Construction Click event for the OK Button. Remember that Part Three - Programming with .NET Assemblies the DialogResult.OK assignment already ensures that your Form is9hidden when this Button is clicked. This time, however, you need to do some additional work, as Chapter - Understanding .NET Assemblies shown here: Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
protected void btnOK_Click (object Part Four - Leveraging the .NET Libraries
sender, System.EventArgs e)
{ Chapter 12 - Object Serialization and the .NET Remoting Layer Button clicked! ConfigureWindows new message. Chapter // 13 -OK Building a Better Window (Introducing Forms) = txtMessage.Text; Chapter strMessage 14 - A Better Painting Framework (GDI+) }
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17Of - Data Access with ADO.NET That's it! course, if you had a more elaborate dialog box (such as the CarConfig Form), you would no Part Five - Web Applications and XML Web Services doubt need a number of custom properties to represent
the full set of user selections. To complete your
Chapter 18dialog - ASP.NET Web Pages and Controlsthe code that launched this dialog box to extract the example box application, you Web can update Chapter - ASP.NET internal19 message andWeb useApplications it in the program. Here is the complete menu selection logic: Chapter 20 - XML Web Services Index protected void mnuModalBox_Click (object sender, System.EventArgs e) List { of Figures 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# and the .NET Platform, Second Edition { ISBN:1590590554 Andrew Troelsen obtained from the dialog // Paintby the message box. Apress © 2003 (1200 pages) Graphics g = e.Graphics; This comprehensive new text starts with a brief New overview of the 24), g.DrawString(dlgMsg, Font("times Roman", C# language and then quickly moves to key technical and Brushes.Blue, this.ClientRectangle); architectural issues for .NET developers. } Table of Contents C# and the .NET Platform, Second Edition
SOURCE
Introduction CODE
The SimpleDialog application is included under the Chapter 15 directory.
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andForm the .NET Platform, Second Edition Understanding Inheritance by Andrew Troelsen
ISBN:1590590554
As you are aware, inheritance is thepages) pillar of OOP that allows one class to extend the functionality of Apress © 2003 (1200 another class. Typically, when you speak of inheritance, you envision This comprehensive text starts with a brief overview 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 moves to key technical and architectural issuesand for .NET Form to derive from another Form in thedevelopers. process 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 Table Contents into aof.NET assembly, other members of your team could extend these types using the .NET language of C# andchoice. the .NET Platform, Second Edition their Introduction
For One the sake of illustration, assume you have placed Part - Introducing C# and the .NET Platform
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 Two first step to Programming set a reference to the external Part - TheisC# Language
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
- Object-Oriented Programming with C# // The of Object the base Form. Chapter 5 namespace - Exceptions and Lifetime
using6 CarConfig; Chapter - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
// Your new Form is really a subclass of CarConfigForm! Chapter 8 - Advanced C# Type Construction Techniques public class DerivedForm : CarConfig.CarConfigForm Part Three - Programming with .NET Assemblies { ...} Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries If you now save and reopen the DerivedForm
type, you will see that the new class has inherited all the
Chapter 12Like - Object Serializationscenario, and the .NET Remoting widgets! any inheritance be aware that Layer any controls in the base Form that have been Chapter 13 Building a Better Window (Introducing Windows declared as private may not be repositioned by the derivedForms) type. However, if you were to update the logic Chapter 14 - A Better Painting Framework (GDI+) in the CarConfigLib.dll to specify protected members, the derived type is free to reposition these items Chapter using the 15 design - Programming time template. with Windows Forms Controls Chapter 16 - The System.IO Namespace
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). Part Five - Web Applications and XML Web Services Chapter 17 - Data Access with ADO.NET
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition
}
by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
It is worth pointingThis outcomprehensive that the Visualtext Studio .NET provides an integrated wizard (named the starts withIDE a brief overview of the C#tolanguage and then quicklyTo moves to key technical andactivate the Project | Add Inherited Inheritance Picker) create derived Forms. access its functionality, issues for .NET developers. Form menu item.architectural Once you provide a name for your new class, you are asked to specify the name of the 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.
Table of Contents
C# and the .NET Platform, Second Edition and CarConfigLib applications are included under the Chapter 15 SOURCE The MyDerivedForm Introduction CODE directory. Part One - Introducing C# and the .NET Platform
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 willLanguage examine at Part Two which - The C# Programming
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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Controls Edition Building Custom Windows Forms by Andrew Troelsen
ISBN:1590590554
If you have a background in classic COM, you are no doubt aware of the use of ActiveX controls. These Apress © 2003 (1200 pages) coclasses are simply types that implement a (huge) of (quite COM interfaces that This comprehensive text starts with anumber brief overview of complex) the provide behaviorsC# forlanguage rendering graphical content, persisting the state of the coclass, and enabling and then quickly moves to key technical and architectural issues for(among .NET developers. control/host container communication other duties). While ActiveX controls can now be regarded as a legacy technology, their spirit lives on under .NET. Table As you of Contents are already 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# theyour .NETcustom Platform, Second Edition the basis for additional types, and typically support any number of properties, methods, and events. In Introduction addition this (obvious) definition, generic classes Part One -to Introducing C# and the .NET Platform
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 .NET Properties window. Furthermore, when you are programming with generic Chapter 2 -using Building C# Applications class types, not drag theLanguage item onto Part Two - Theyou C# do Programming
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
Object-Oriented Programming with C# Acontrol is- also a class type, meaning it derives from a parent class (typically
Chapter 5 - Exceptions and Object Lifetime System.Windows.Forms.Control) and inherits a good deal of functionality in the process. Each of the GUI Chapter - Interfaces and Collections widgets6you have examined during this chapter is considered a control type. Like a simple class, controls Chapter - Callback Interfaces, andmanipulated Events support7a set of public membersDelegates, and can be directly by code. In addition, however, controls Chapter 8 - aAdvanced Construction Techniques do support GUI, andC# areType typically configured using various design time tools (such as the VS .NET Part Three - window) Programming with .NET Assemblies Properties and are "drawn" onto the owning
host using the Toolbox. To be sure, like any intrinsic
Chapter 9 Forms - Understanding .NET custom Assemblies Windows controls, your controls inherit the same set of behaviors from each class in the Chapter inheritance 10 - chain. Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Next you-have user controls. a control Part Four Leveraging the .NETLike Libraries
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 - Object Serialization and the .NET Remoting Layer System.Windows.Forms.Control. Rather, user controls derive from System.Windows.Forms.UserControl, Chapter 13 - Building a Better Window (Introducing Windows Forms) which in turn derives directly from ContainerControl. Recall that ContainerControl (and its base class Chapter 14 - A Better Painting Framework (GDI+) ScrollableControl) provide additional members that allow you to configure scrolling, tab order, and focus Chapter 15 - Programming with Windows Forms Controls logic. When you wish to build a reusable GUI widget that maintains numerous related widgets that need to Chapter 16 - The System.IO Namespace work together as a whole, you will want to derive your custom class directly from UserControl (in fact, this Chapter 17 - Data Access is the default base classwith fromADO.NET which your custom controls derive). However, if you are not interested in Part Five Web Applications XML Webcomposite Services 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.Controls Chapter 19 - ASP.NET Web Applications
Finally,20 you- XML haveWeb components. Chapter Services 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 Index a runtime user interface. However, components can be selected from the VS .NET Toolbox window and List of Figures configured List of Tablesusing the integrated Property window at design time. For example, check out the Components tab in Figure 15-25.
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Figure 15-25: The Components tab
Chapter Interfaces Collections As you 6can- see, theseand intrinsic components are not necessarily GUI in nature, but they do lend themselves Chapter 7 Callback Interfaces, Delegates, and Events 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 Construction that the design Techniques time representation is placed in the designer's icon tray Part (as Three well as - Programming a member variable with .NET in the Assemblies Form-derived
type being created). Once you select the component,
you are9able to set various.NET properties using the Properties window. Chapter - Understanding Assemblies Chapter 10 - Processes, AppDomains, Contexts, 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 Part Four - Leveraging the .NET Libraries the details of this interface by hand, but rather derive your type from Chapter 12 - Object Serialization and the .NET Remoting Layer System.ComponentModel.Component (and thus receive the canned implementation). Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Building a Custom UserControl by Andrew Troelsen
ISBN:1590590554
During the next several youpages) construct a custom UserControl named CarControl. To begin, fire up Apress pages, © 2003 (1200 Visual Studio .NET and select a new Windows Control Library workspace This comprehensive text starts with a brief overview of the named CarControlLibrary (Figure 15-26). When you are finished, rename the initial C# class to CarControl (note that the base class C# language and then quickly moves to key technical and architectural issues for .NET developers. of your type is UserControl).
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Figure 15-26: Creating a new Windows Control Library workspace
Chapter 9
- Understanding .NET Assemblies
Chapter Processes, AppDomains, Contexts, 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 Attribute-Based CarControl responsible animating a seriesProgramming of bitmaps that will change based on the Part Four state - Leveraging the .NET Libraries internal of the automobile. If the car's
current speed is safely under the car's maximum speed limit,
Chapter 12 - Object Serialization and the .NETimages Remoting Layer the CarControl loops through three bitmap that render an automobile driving safely along. If the Chapter current13 speed - Building is ten amiles Better below Window the (Introducing maximum speed, Windows the Forms) CarControl loops through four images, with the
fourth image the carFramework breaking down. Chapter 14 - A showing Better Painting (GDI+)Finally, if the car has surpassed its maximum speed, the CarControl over fivewith images, where the Controls fifth image represents a doomed automobile. Chapter 15 - loops Programming Windows Forms Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# Images and the .NET Platform, Second Edition Creating the by Andrew Troelsen
ISBN:1590590554
Given our designApress notes,©the first order of business is to create a set of five *.bmp files for use by the 2003 (1200 pages) animation loop. IfThis youcomprehensive wish to create text custom images, by activating starts with a begin brief overview of thethe Project | Add New Item menu selection and insert five new Bitmap resources. If you would rather not showcase your artistic abilities, feel C# language and then quickly moves to key technical and architectural issues for .NET developers. free to use the images that 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 Table of Contents and Dead.bmp) represent a car approaching its maximum upper limit and its ultimate (AlmostDead.bmp C# and the .NET Platform, Second Edition demise. Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C#Design and the .NET Platform, Building the Time GUISecond Edition by Andrew Troelsen
ISBN:1590590554
The next step is to open©the design time editor for the CarControl type. As you can see, you are presented Apress 2003 (1200 pages) with a Form-like designer that represents the client ofoverview the control under construction. Using the This comprehensive text starts with area a brief of the Toolbox window, C# addlanguage an ImageList type (to hold each of the bitmaps), a and then quickly moves to key technical and Timer type (to control the issues(to forhold .NETthe developers. animation cycle),architectural and a PictureBox current 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. Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure 15-27: Creating the design time GUI
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - the A Better Painting Framework (GDI+) Now, using Properties window, configure the ImageList's Images collection by adding each bitmap to Chapter 15 Programming with Windows Forms Controls the list. Be aware that you will want to add these items sequentially (Lemon1.bmp, Lemon2.bmp, Chapter 16 - TheAlmostDead.bmp, System.IO Namespace Lemon3.bmp, Dead.bmp) to ensure a linear animation loop. As you recall from Chapter 17 Data with ADO.NET Chapter 14, whenAccess you incorporate resources (such as bitmaps) into your VS .NET solutions, the Part Five - Web Applications and XML Web Services underlying *.resx file is automatically updated. Therefore,
the images will be embedded into your assembly
Chapter - ASP.NET and Web Controls with no18 extra work onWeb yourPages behalf. Chapter 19 - ASP.NET Web Applications
Also be20 aware the default width and height of *.bmp files inserted using VS .NET are 47×47 pixels. Chapter - XMLthat Web Services
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 Figures initially disabled. Index
List of Tables
C# and .NET Platform, Second Edition Implementing thetheCarControl by Andrew Troelsen
ISBN:1590590554
With this GUI prep work ©out of(1200 the way, Apress 2003 pages)you can now turn to implementation of the type members. To begin, create a new public enumeration AnimFrame, which of has a member representing each item This comprehensive text named starts with a brief overview the maintained by theC# ImageList. As you will see, you make use of this enumeration to determine the current language and then quickly moves to key technical and architectural issues for .NET developers. frame to render into the PictureBox: // Helper enum for images. public enum AnimFrames C# and the .NET Platform, Second Edition { Introduction Lemon1, Lemon2, Part One - Introducing C# and the .NET Platform Lemon3, AlmostDead, Dead Chapter 1 - The Philosophy of .NET }
Table of Contents
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter The CarControl 3 - C# Language type maintains Fundamentals a good number of private data points to represent the animation logic.
Here is4the- rundown of eachProgramming member: with C# Chapter Object-Oriented Chapter 5
- Exceptions and Object Lifetime
Chapter 6 class - Interfaces and Collections public CarControl : System.Windows.Forms.UserControl Chapter { 7 - Callback Interfaces, Delegates, and Events
data. Chapter// 8 State - Advanced C# Type Construction Techniques private System.ComponentModel.IContainer Part Three - Programming with .NET Assemblies
components; private AnimFrames currFrame = AnimFrames.Lemon1; Chapter 9 - Understanding .NET Assemblies AnimFrames currMaxFrame = AnimFrames.Lemon3; Chapterprivate 10 - Processes, AppDomains, Contexts, and Threads private bool IsAnim; Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming private int the currSp = 50; Part Four - Leveraging .NET Libraries private System.Windows.Forms.PictureBox Chapter 12 - Object Serialization and the .NET Remoting Layer pictureBox; private int maxSp = 100; Chapter 13 - Building a Better Window (Introducing Windows Forms) private System.Windows.Forms.Timer animTimer; Chapter 14 - A Better Painting Framework (GDI+) private string carPetName= "NoName"; Chapter 15 - Programming with Windows Forms Controls private Rectangle bottomRect = new Rectangle(); Chapter 16 - The System.IO Namespace private System.Windows.Forms.ImageList theImageList; Chapter 17 - Data Access with ADO.NET ... Part Five - Web Applications and XML Web Services } Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter As you 20 can- see, XML Web you have Services 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 Index member of the ImageList is to be rendered. The currMaxFrame variable is used to mark the current upper List of Figures 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# and the = .NET Platform, Second Edition pictureBox.Image ISBN:1590590554 by Andrew Troelsen theImageList.Images[(int)AnimFrames.Lemon1]; Apress © 2003 (1200 pages) // Figure out size of bottom rect. This comprehensive text starts with a brief overview of the bottomRect.X = 0; C# language and then quickly moves to key technical and bottomRect.Y = this.Height - 50; architectural issues for .NET developers. bottomRect.Height = this.Height - pictureBox.Height; bottomRect.Width = this.Width; }
Table of Contents C# and the .NET Platform, Second Edition Introduction Once you have carved out the dimensions of each rectangle, call StretchBox() from the default Part One - Introducing C# and the .NET Platform
constructor.
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Defining the Custom Events
Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# is sent out when the CarControl's speed approaches the of the automobile. The first event, AboutToBlow, Chapter 5 Exceptions and Object Lifetime upper limit. BlewUp is sent to the container when the current speed is greater than the allowed maximum. Chapter - Interfaces and Collections Each of6 these events leverages a custom delegate (CarEventHandler) that can hold the address of any Chapter 7 Callback Interfaces, Delegates, Events method returning void and taking a single and System.String as its sole parameter. You'll fire these events in Chapter 8 - Advanced Techniques just a moment, but forC# theType timeConstruction being, add the following members to the public sector of the CarControl: Part Three - Programming with .NET Assemblies
Chapter 9 events - Understanding .NET Assemblies // Car / custom delegate. Chapter 10 - Processes, AppDomains, Contexts, and Threads msg); public delegate void CarEventHandler(string Chapter 11 - Type CarEventHandler Reflection, Late Binding, and Attribute-Based Programming public event AboutToBlow; Part Four event - Leveraging the .NET Libraries BlewUp; public CarEventHandler
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Defining the Custom Properties
Chapter 15 - Programming with Windows Forms Controls Chapter 16class - Thetype, System.IO Like any customNamespace controls may define a set of properties to allow the outside world to interact Chapter - Data Access withFor ADO.NET with the17state of the widget. your current purposes, you are only interested in defining three properties. Part Five and XML enables Web Services First, you- Web haveApplications Anim. This property or disables
the Timer type:
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 -to ASP.NET Web Applications // Used configure the internal Timer type. Chapter 20 bool - XML Web public AnimServices Index { List of Figures get {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# and the .NET Platform, Second Edition by Andrew=Troelsen carPetName value; Apress © 2003 (1200 pages) Invalidate();
} }
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 the .NET Platform, Second Edition Here is the complete logic:
Table of Contents Introduction
Part One - Introducing C# and the .NET Platform
// Adjust currSp, currMaxFrame and fire our events. - The Philosophy of .NET public int Speed Chapter 2 - Building C# Applications { Part Two - The C# Programming Language get{return currSp;} Chapter 3 - C# Language Fundamentals set Chapter{4 - Object-Oriented Programming with C# Chapter 5 -currSp Exceptions Object Lifetime = and value; Chapter 6 -currFrame Interfaces and=Collections currMaxFrame; Chapter 7 -// Callback Interfaces, Delegates, and Events About to explode? Chapter 8 -if Advanced C# Type Construction ((maxSp - currSp) = maxSp) Chapter 12 -if Object Serialization and the .NET Remoting Layer Chapter 13 -{Building a Better Window (Introducing Windows Forms) currSp = Framework maxSp; (GDI+) Chapter 14 - A Better Painting BlewUp("Ug...you're toast..."); Chapter 15 - Programming with Windows Forms Controls currMaxFrame = AnimFrames.Dead; Chapter 16 - The System.IO Namespace } Chapter 17 - Data Access with ADO.NET } Part Five - Web Applications and XML Web Services } Chapter 1
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Index As you can see, if the current speed is 10 miles below the maximum upper speed, you fire the List AboutToBlow of Figures 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
andAnimation the .NET Platform, Second Edition ControllingC#the by Andrew Troelsen
ISBN:1590590554
The next detail toApress attend©to2003 is ensuring that the Timer type advances the current frame to render within the (1200 pages) PictureBox. Again, recall that the number of frames loopoverview through of depends on the current speed of the This comprehensive text starts with atobrief the automobile. You C# onlylanguage want to bother adjusting the image in the PictureBox if the Anim property has been and then quickly moves to key technical and forevent .NET developers. set to true. Beginarchitectural by handling issues the Tick for the Timer type, and flesh out the details as follows: private void animTimer_Tick(object sender, System.EventArgs e) { C# and the .NET Platform, Second Edition if(IsAnim) Introduction pictureBox.Image = theImageList.Images[(int)currFrame]; Part One - Introducing C# and the .NET Platform // Bump frame. Chapterstring 1 - ThesPhilosophy of .NET = Enum.Format(typeof(AnimFrames), currFrame, "D"); Chapterint 2 -iBuilding C# Applications = int.Parse(s); Part Two - The C# Programming int nextFrame = i +Language 1; ChaptercurrFrame 3 - C# Language Fundamentals = (AnimFrames)nextFrame; Chapterif 4 (currFrame - Object-Oriented Programming with C# > currMaxFrames) Chapter 5 -currFrame Exceptions and Lifetime = Object AnimFrames.Lemon1; Chapter } 6 - Interfaces and Collections
Table of Contents
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
the Name .NET Platform, Second Edition Rendering C# theand Pet by Andrew Troelsen
ISBN:1590590554
Before you can take your control for a spin, you have one final detail to attend to: displaying the car's Apress © 2003 (1200out pages) moniker. To do this, handle the Paint event for your andofwithin This comprehensive text starts with aCarControl, brief overview the the handler, render the CarControl's pet C# name into the bottom rectangular region of the client area: language and then quickly moves to key technical and architectural issues for .NET developers.
private void CarControl_Paint(object sender, System.Windows.Forms.PaintEventArgs e) Table of Contents { C# and the .NET Platform, Second Edition // Render the petname on the bottom of the control. Introduction Graphics g = e.Graphics; Part One - Introducing C# and the .NET Platform 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); Part Two The C# Programming Language } Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# At this point, the initial crack at theLifetime CarControl is complete. Go ahead and build your project. Chapter 5 - Exceptions and Object Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Testing theC#CarControl Type Second Edition by Andrew Troelsen
ISBN:1590590554
Like all .NET types, you ©are now able to make use of your custom control from any language targeting the Apress 2003 (1200 pages) CLR. For your current purposes, build a C# tester Beginofbythe closing down the current This comprehensive text starts withapplication. a brief overview workspace and creating a new Windows Forms project named CarCtrlClient. To allow your current project C# language and then quickly moves to key technical and architectural for .NET to reference auxiliary controls,issues right-click yourdevelopers. Toolbox 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 Table of Contents Toolbox named, of course, CarControl. C# and the .NET Platform, Second Edition
Begin building your GUI by placing a CarControl onto the Form designer. Notice that the Anim, PetName, Introduction andOne Speed propertiesC# areand all the exposed through Part - Introducing .NET Platform
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 Part Two - The C# Programming Language
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 - Object-Oriented Programming with 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 Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Figure The client-side GUI Chapter 18 - 15-28: ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
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 Services Index
List of Figures
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:
and the .NET Platform, Second Edition private void C# mainForm_Load(object sender, System.EventArgs e) ISBN:1590590554 by Andrew Troelsen { Apress © 2003=(1200 pages) carControl1.Anim true; lblCurrSp.Text This comprehensive = text starts with a brief overview of the C# language and then quickly moves tocarControl1.Speed.ToString()); key technical and string.Format("Speed is: {0}", architectural issues for .NET developers. }
Table Contents The of final aspect of this client-side design is to capture the incoming events from the CarControl widget. C# and the .NET Platform,Forms Second Edition Like all other Windows GUI types, you are able to handle events using the Properties window. Introduction Handle the AboutToBlow and BlewUp events, and write some informative message to the output Label: Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET // Client-side event handlers.
Chapter 2 -void Building C# Applications private carControl1_AboutToBlow(string msg) Part { Two - The C# Programming Language
ChapterlblEventMsg.Text 3 - C# Language Fundamentals = msg; Chapter 4 }
- Object-Oriented Programming with C#
Chapter 5 -void Exceptions and Object Lifetime private carControl1_BlewUp(string msg) Chapter 6 - Interfaces and Collections { ChapterlblEventMsg.Text 7 - Callback Interfaces, = Delegates, msg; and Events
} Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
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 Attribute-Based Programming OOP, GDI+, and Windows Forms. Chapter 10 - Processes, AppDomains, Contexts, and Threads Part Four - Leveraging the .NET Libraries
Chapter 12 -do Object and the .NET Remoting Layer the process of .NET Windows Control While you have Serialization enough information to continue exploring Chapter 13 Building a Better Window (Introducing Windows development, there is one additional programmatic aspectForms) to contend with: design time functionality. Chapter - A Better Painting Framework Before 14 I describe exactly what this boils (GDI+) down to, you need to understand the role of a key design timeChapter - Programming with Windows Forms Controls centric 15 namespace. Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the Second Edition Select Members of .NET thePlatform, System.ComponentModel Namespace by Andrew Troelsen
ISBN:1590590554
The System.ComponentModel namespace defines a number of such types that allow you to describe how Apress © 2003 (1200 pages) your custom controls and components should themselves time. For example, you can This comprehensive text starts display with a brief overviewatofdesign the opt to supply a textual description of each property, define a default event, or group related members into C# language and then quickly moves to key technical and architectural for .NET developers. a custom category (for displayissues 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). Table of Contents C# and the .NETSelect Platform, Second of Edition Table 15-18: Members System.ComponentModel Introduction
System.ComponentModel Part One - Introducing C# and the .NET Applied Platform Attribute Chapter 1 - The Philosophy of .NET
to
Chapter 2 - Building C# Applications BrowsableAttribute
Properties events
Part Two - The C# Programming Language and
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
CategoryAttribute Properties - Interfaces and Collections and events
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
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 Construction TechniquesDefines a small block of text to be displayed DescriptionAttribute Properties Part Three - Programming with .NET Assemblies and events
Chapter 9
- Understanding .NET Assemblies
at the bottom of the property browser when the user selects a property or event.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
DefaultPropertyAttribute
Properties
Specifies the default property for the component. This property is selected in the Part Four - Leveraging the .NET Libraries property browser when a user clicks the Chapter 12 - Object Serialization and the .NET Remoting Layer control. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 13 - Building a Better Window (Introducing Windows Forms)
DefaultValueAttribute Properties Chapter 14 - A Better Painting Framework (GDI+)
Sets a simple default value for a property that Chapter 15 - Programming with Windows Forms Controlswill be applied when the control is reset to its default state. Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NETProperties LocalizableAttribute Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
DefaultEventAttribute
Index
List of Figures 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.
and the .NET Platform, Second Edition of CarControl Enhancing C# the Design Time Appearance by Andrew Troelsen
ISBN:1590590554
To illustrate the use of some these new attributes, assume you want to create a custom category Apress © 2003of (1200 pages) (called "Car Configuration") to which each property and event of theofCarControl belong. Also, let's supply This comprehensive text starts with a brief overview the a friendly description for each member and default value for each property. To do so, simply update each C# language and then quickly moves to key technical and architectural issues for .NET developers. of the properties and events of the CarControl type to support the [Category], [DefaultValue], and [Description] attributes. For example: Table of Contents
using System.ComponentModel; ... Introduction public class CarControl : System.Windows.Forms.UserControl Part One - Introducing C# and the .NET Platform { Chapter... 1 - The Philosophy of .NET Chapter[Category("Car 2 - Building C# Applications Configuration"), Part Two - The C# Programming when Language Description("Sent the car is approaching terminal speed.")] Chapterpublic 3 - C# event Language Fundamentals CarEventHandler AboutToBlow; Chapter... 4 - Object-Oriented Programming with C# Chapter[Category("Car 5 - Exceptions andConfiguration"), Object Lifetime ChapterDescription("Pet 6 - Interfaces and Collections name for your auto."), Name")] ChapterDefaultValue("No 7 - Callback Interfaces, Delegates, and Events public string PetName {...} Techniques Chapter 8 - Advanced C# Type Construction } Part Three - Programming with .NET Assemblies C# and the .NET Platform, Second Edition
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, 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 Part Four - Leveraging the .NET Libraries not ensure that the underlying value of the data point wrapped by a given property will be automatically Chapter 12 - Object Serialization and the .NET Remoting Layer initialized to the default value. Thus, although you specify a default value of "No Name" to the PetName Chapter 13 - Building a Better Window (Introducing Windows Forms) 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 Paintinginitialization Framework syntax: (GDI+) constructor via member Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
private string carPetName= "NoName";
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter ASP.NET Web Pages and comes Web Controls Rather,18 the- [DefaultValue] attribute into play when the programmer "resets" the value of a given Chapter 19using - ASP.NET Web Applications property the Properties window. To reset a property using VS .NET, select the property of interest, Chapter right-click 20 the - XML description Web Services pane, and click "Reset". Also note the description appears in the lower pane of
the Properties window (Figure 15-29). Index List of Figures List of Tables
Figure 15-29: Resetting a property to the default value
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
The [Category] attribute only bepages) realized if the programmer selects the categorized view of the Apress ©will 2003 (1200 Properties window (as opposed to the default view) as of seen This comprehensive text startsalphabetical with a brief overview thein Figure 15-30. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Figure 15-30: The custom category
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Defining a Default Property and Default Event
Part Four - Leveraging the .NET Libraries
Chapter 12 -toObject Serialization and the like .NET Remotinginto Layer In addition describing and grouping members a common category, you may also want to Chapter 13 Building a Better Window (Introducing Windows configure your controls (or components) to support defaultForms) behaviors. A given control may support a Chapter - A Better Painting Framework (GDI+)property for a class using the [DefaultProperty] attribute as default 14 property. When you define the default Chapter follows:15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 -the Data default Access withproperty ADO.NET for this control. // Mark Part Five - Web Applications and XML Web Services [DefaultProperty("Anim")]
Chapter 18 class - ASP.NET Web Pages and Web Controls public CarControl Chapter:19 - ASP.NET Web Applications System.Windows.Forms.UserControl Chapter {...}20 - XML Web Services Index List of Figures
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# and the .NET Platform, Second Edition this type on the ToolBox using the default "gear" icon. If you wish to specify a custom image, your first step Andrew Troelsen is to insert a new by *.bmp file into your project (CarControl.bmp)ISBN:1590590554 that is configured to be 16×16 pixels in size Apress © 2003 (1200 pages) (established via the Width and Height properties). This comprehensive text starts with a brief overview of the C# language and then quickly key and value to Embedded Resource to Once you have created the image as you see moves fit (andto set thetechnical Build Action issues within for .NET ensure the imagearchitectural data is contained thedevelopers. assembly), your final task is to make use of the [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.
Table of Contents
C# and the .NET Platform, Second Edition
[ToolboxBitmap(typeof(CarControl), "CarControl")] [DefaultEvent("BlewUp"), DefaultProperty("Anim")] Part One - Introducing C# and the .NET Platform public class CarControl : System.Windows.Forms.UserControl Chapter 1 - The Philosophy of .NET {...} Introduction
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3 -doC# Language Fundamentals Once you so, you will find that when the programmer adds the widget to the toolbox, your custom Chapter 4 -be Object-Oriented Programming with C# image will displayed on the VS .NET Toolbox. Chapter 5
- Exceptions and Object Lifetime So, that6 wraps up our examination of the process of building custom Windows Forms controls. Obviously, Chapter - Interfaces and Collections
complete this topic Delegates, (especiallyand programming for design time support) would require a book all Chapter 7 coverage - Callback of Interfaces, Events
of its own.-IfAdvanced you are interested in additional details regarding developing custom Windows Forms controls, C# Type Construction Techniques pick up a copy of User Interfaces in C#: Windows Forms and Custom Controls (MacDonald, Apress Part Three - Programming with .NET Assemblies 2002). Chapter 8 Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, and Threads SOURCE The CarControl Contexts, and CarControlTestForm projects are included under the Chapter 15 Chapter 11 Type Reflection, Late Binding, and Attribute-Based Programming CODE directory. Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
This chapter rounded off© your current understanding of Windows Forms by examining the programming of Apress 2003 (1200 pages) numerous GUI widgets from the simple to the more exotic (MonthCalendar). As you have seen, This comprehensive text(Button) starts with a brief overview of the each and every Windows Forms control type derives from System.Windows.Forms.Control, which defines C# language and then quickly moves to key technical and architectural issues for .NETtypes developers. 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. Table of Contents
In and the latter halfPlatform, of this chapter, learned how to build custom dialog boxes using Windows Forms and C# the .NET Second you Edition examined a number of issues related to dialog boxes. Next, you learned how to derive a new Form from Introduction an existing Form typeC# using inheritance. Part One - Introducing andForm the .NET Platform 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 Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Chapter C# 16: The System.IO Namespace ISBN:1590590554 by Andrew Troelsen Apress full-blown © 2003 (1200desktop pages) applications, the ability to save information between user When you are creating This comprehensive text starts awith a briefofoverview of the sessions is imperative. This chapter examines number IO-related topics as seen through the eyes of C# language and then quickly moves to key technical and the .NET Framework. The first order of business is to explore the core types defined in the System.IO architectural issues for .NET developers. 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 characterbased, binary-based, string-based, and memory-based data stores. Table of Contents C# and the .NET Platform, Second Edition
Finally, to showcase some of these concepts using a cohesive example, I conclude this chapter with a
Introduction complete Windows Forms application, which allows the end user to manage a collection of Car types that Part One - Introducing C# and the .NET Platform
can be persisted to (and recovered from) a file 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 Part Two - Theof C# Programming Language examination ADO.NET).
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# Exploring the System.IO Namespace
Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections In the framework of .NET, the System.IO namespace is the region of the base class libraries devoted to Chapter 7 Callback Interfaces, Events file-based (and memory-based)Delegates, input and and output services. Like any namespace, System.IO defines a set Chapter of classes, 8 - interfaces, Advanced C# enumerations, Type Construction structures, Techniques and delegates, most all of which are contained in Part mscorlib.dll. Three - Programming In addition towith the .NET typesAssemblies contained
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 Understanding Assemblies reference both assemblies, you should be ready to go). Chapter 10 -toProcesses, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer and write data to string buffers as well as to raw memory locations. To give you a roadmap of the Chapter 13 - Building a Better Window (Introducing Windows Forms) functionality in System.IO, Table 16-1 outlines the core (nonabstract) classes. Part Four - Leveraging the .NET Libraries
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Table 16-1: Key Members of the System.IO Namespace
Chapter 16 - The System.IO Namespace
Creatable IO Meaning Chapter 17 - Data Access with ADO.NETin Life Type Part Five - Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls
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 Services structure. The Directory and File types expose their functionality primarily File Index as static methods. The DirectoryInfo and FileInfo types expose similar ListFileInfo of Figures functionality from a valid object variable. Chapter 19 - ASP.NET Web Applications
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# and the Random access to streamed data, stored in memory, rather than a .NET Platform, Second Edition physical file. ISBN:1590590554 by Andrew Troelsen 2003 (1200 pages) BufferedStreamApress © Provides temporary storage for a stream of bytes that may be committed This comprehensive text startstime. with a brief overview of the to storage at a later
C# language and then quickly moves to key technical and
issues forallow .NET you developers. BinaryReader architectural These types to store and retrieve primitive data types (integers, Booleans, strings, and whatnot) as a binary value. BinaryWriter Table of Contents C# the .NET Platform, Second Edition In and addition to these creatable types, System.IO defines a number of enumerations, as well as a set of Introduction abstract classes (Stream, TextReader, TextWriter, and so forth) that define a shared polymorphic interface Part One - Introducing C# will andread the .NET Platform to all descendents. You about many of
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
these types in this chapter.
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Second Edition The Directory(Info) andPlatform, File(Info) Types by Andrew Troelsen
ISBN:1590590554
System.IO provides four©types that pages) allow you to manipulate individual files, as well as interact with a Apress 2003 (1200 machine's directory structure. The first two types, Directory and File,ofexpose creation, deletion, copying, This comprehensive text starts with a brief overview the and moving operations using various static members. The closely related FileInfo and DirectoryInfo types C# language and then quickly moves to key technical and architectural for .NET developers. expose similar functionality asissues instance-level methods (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 Table of Contents choices for recursive operations, as the Directory and File class members tend to return strings rather than C# the .NET Platform, Second Edition fileand objects. Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - 16-1: Data Access withand ADO.NET Figure The FileDirectory-centric types Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
The Abstract FileSystemInfo Base Class
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Index The DirectoryInfo and FileInfo types receive many behaviors from the abstract FileSystemInfo type. By and
large, the members of the FileSystemInfo class can be used to discover general characteristics (such as List of Figures 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# and the .NET Platform, Second Edition Property by Andrew Troelsen Attributes CreationTime
ISBN:1590590554
Apress © 2003 (1200 pages)
Gets or sets the attributes associated to the current file that are
This comprehensive text starts with a brief overview of the represented by the FileAttributes enumeration. C# language and then quickly moves to key technical and architectural issues for .NET developers.
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.
Table of Contents
Extension
Used to retrieve a file's extension.
C# and the .NET Platform, Second Edition Introduction FullName
Gets the full path of the directory or file.
Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming to.Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
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 Object Lifetime possible; otherwise, retrieves the fully qualified name.
Chapter 8 - Advanced C# also Typedefines Construction Techniques The FileSystemInfo type the Delete() method. This is implemented by derived types to delete Part Three withthe .NET Assemblies a given file- Programming or directory from hard drive. As
well, Refresh() can (and should) be called prior to obtaining
Chapter attribute 9 information - Understanding to ensure .NETthat Assemblies the statistics regarding the current file (or directory) are not outdated. Chapter 10 - Processes, AppDomains, Contexts, 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 Part Four - Leveraging the .NET Libraries the initial construction. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Working with the DirectoryInfo Type
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
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 with ADO.NET addition to the functionality provided by its FileSystemInfo base class, DirectoryInfo offers the members in Part Five - Web Applications and XML Web Services Table 16-3. Chapter 16 - The System.IO Namespace
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Table 16-3: Key Members of the DirectoryInfo Type
Chapter 20 - XML Web Services
DirectoryInfo Index
Meaning in Life
ListMembers of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
// Create a new directory bound to the current directory. Apress © 2003 (1200 pages) DirectoryInfo dir1 = new DirectoryInfo("."); This comprehensive text starts with a brief overview of the // Create a new directory bound to C:\Foo\Bar, note the use of the symbol @. C# language and then quickly moves to key technical and DirectoryInfoarchitectural dir2 = new issuesDirectoryInfo(@"C:\Foo\Bar"); for .NET developers.
Table of Contents
If you map to aSecond nonexistent C# and attempt the .NETtoPlatform, 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 Part One - Introducing C# and the .NET Platform 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): Introduction
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
class3 MyDirectory Chapter - C# Language Fundamentals {
Chapter 4
- Object-Oriented Programming with C#
public static void Main(String[] args) - Exceptions and Object Lifetime { Chapter 6 - Interfaces and Collections DirectoryInfo dir = new DirectoryInfo(@"C:\WinNT"); Chapter 7 - Callback Interfaces, Delegates, and Events // Dump directory information. Chapter 8 - Advanced C# Type Construction Techniques Console.WriteLine("***** Directory Info *****"); Part Three - Programming with .NET Assemblies Console.WriteLine("FullName: {0} ", dir.FullName); Chapter 9 - Understanding .NET Assemblies Console.WriteLine("Name: {0} ", dir.Name); Chapter 10 - Processes, AppDomains, Contexts, and Threads Console.WriteLine("Parent: {0} ", dir.Parent); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Console.WriteLine("Creation: {0} ",Programming dir.CreationTime); Part Four - Leveraging the .NET Libraries Console.WriteLine("Attributes: {0} ", dir.Attributes.ToString()); Chapter 12 - Object Serialization and the .NET Remoting Layer Console.WriteLine("Root: {0} ", dir.Root); Chapter 13 - Building a Better Window (Introducing Windows Forms) Console.WriteLine("**************************\n"); Chapter}14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls Chapter 5
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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 MeaningSecond in Life C# and the .NET Platform, Edition Enumeration byValue Andrew Troelsen
ISBN:1590590554
Apress © 2003 (1200 pages)
Archive
Represents the archive status of the file or directory.
This comprehensive text starts with a brief overview of the Applications use this attribute to mark files for backup or C# language and then quickly moves to key technical and removal. architectural issues for .NET developers.
Compressed Table of Contents Directory
The file or directory is compressed. The item is a directory (rather than a file).
C# and the .NET Platform, Second Edition
Encrypted
Introduction
The file or directory is encrypted.
Part One - Introducing C# and the .NETThe Platform Hidden file 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.
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Offline4 Chapter
The file directory is offline. The data of the file is not - Object-Oriented Programming withorC#
Chapter 5
immediately available. - Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections ReadOnly The file or directory is read only.
Chapter 7
- Callback Interfaces, Delegates, and Events
System The fileTechniques is a system file. The file is part of the operating system Chapter 8 - Advanced C# Type Construction or is used Part Three - Programming with .NET Assemblies exclusively by the operating system. Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the with .NET Platform, Second Edition Type Enumerating Files the DirectoryInfo by Andrew Troelsen
ISBN:1590590554
You can extend the current MyDirectory Apress © 2003 (1200 pages) class to use some methods of the DirectoryInfo type. First, use the GetFiles() method to read all *.bmp under theoverview "C:\WinNT" directory. This method returns an This comprehensive files text located starts with a brief 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 moves to key technical and architectural issues for are .NETexplored developers. needed (full details of the FileInfo type later in this chapter): class MyDirectory { C# and the .NET Platform, Second Edition public static void Main(String[] args) Introduction { Part One - Introducing C# and the .NET Platform DirectoryInfo dir = new DirectoryInfo(@"C:\WinNT"); Chapter 1 - The ...Philosophy of .NET Chapter 2 - Building Applications // GetC#all files with a *.bmp extension. Part Two - TheFileInfo[] C# Programming Language bitmapFiles = dir.GetFiles("*.bmp");
Table of Contents
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented with C# // How manyProgramming were found?
Chapter 5 Chapter 6
- Exceptions and Object Lifetime Console.WriteLine("Found {0} *.bmp files\n", bitmapFiles.Length); - Interfaces // Nowand print Collections out info for each file.
Chapter 7
foreach (FileInfo f in - Callback Interfaces, Delegates, and bitmapFiles) Events
Chapter 8
{ - Advanced C# Type Construction Techniques
Console.WriteLine("***************************\n"); Part Three - Programming with .NET Assemblies Chapter 9
Console.WriteLine("File name: {0} ", f.Name); - Understanding .NET Assemblies
Console.WriteLine("File size: {0} ", f.Length); Chapter 10 - Processes, AppDomains, Contexts, and Threads Console.WriteLine("Creation: {0} ", f.CreationTime); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging Console.WriteLine("Attributes: the .NET Libraries
{0} ", f.Attributes.ToString()); Console.WriteLine("***************************\n"); Chapter 12 - Object Serialization and the .NET Remoting Layer } Chapter 13 - Building a Better Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 -run Data with ADO.NET Once you theAccess application, you see a listing something like that shown in Figure 16-3. (Your bitmaps may Part Five - Web Applications and XML Web Services vary!)
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 16-3: Bitmap file information
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Edition Creating Subdirectories with Second the DirectoryInfo Type by Andrew Troelsen
ISBN:1590590554
You can programmatically extend directory structure using the DirectoryInfo.CreateSubdirectory() method. Apress © 2003 (1200 a pages) This method can This create a single subdirectory, well as multiple nested comprehensive text starts as with a brief overview of thesubdirectories. 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 moves to key technical and architectural issues for .NET developers.
class MyDirectory { Table of Contents public static void Main(String[] args) C# and the .NET Platform, Second Edition { Introduction DirectoryInfo dir = new DirectoryInfo(@"C:\WinNT"); Part One - Introducing C# and the .NET Platform ... Chapter 1 - The Philosophy of .NET try Chapter 2 - Building C# Applications { Part Two - The C# Programming Language // Create \MyFoo off root. Chapter 3 - C# Language Fundamentals dir.CreateSubdirectory("MyFoo"); Chapter 4 - Object-Oriented Programming with C# // Create \MyBar\MyQaaz off root. Chapter 5 - Exceptions and Object Lifetime dir.CreateSubdirectory(@"MyBar\MyQaaz"); Chapter 6 - Interfaces } and Collections catch(IOException e) and { Console.WriteLine(e.Message);} Chapter 7 - Callback Interfaces, Delegates, Events } Chapter 8 - Advanced C# Type Construction Techniques } Three - Programming with .NET Assemblies Part Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and e) the { .NET Platform, Second Edition catch(IOException Console.WriteLine(e.Message); } by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Second Edition The Static Members ofPlatform, the Directory Class by Andrew Troelsen
ISBN:1590590554
Now that you have seen©the Apress 2003DirectoryInfo (1200 pages) type in action, you can learn about the Directory type. By and large, the members of the Directory the same provided This comprehensive mimic text starts with a functionality brief overview 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 moves to key technical and architectural issues for to .NET return strings rather than objects. Due thedevelopers. common public interface of each type, I assume you will consult online help to view each member of the Directory class. Table This of final Contents iteration of the MyDirectory class lists the names of all drives mapped to the current computer
and uses static Directory.Delete() C# and the the .NET Platform, Second Editionmethod to remove the \MyFoo and \MyBar\MyQaaz subdirectories previously created: Introduction Part One - Introducing C# and the .NET Platform
Chapter - The Philosophy of .NET class1 MyDirectory Chapter { 2
- Building C# Applications
Part Twopublic - The C# static Programming voidLanguage Main(String[]
args) { Chapter 3 - C# Language Fundamentals DirectoryInfo dir = with new C# DirectoryInfo(@"C:\WinNT"); Chapter 4 - Object-Oriented Programming Chapter 5
- Exceptions and Object Lifetime
Chapter 6
// Nowand call some static members of the Directory class. - Interfaces Collections
Chapter 7
// List all drives onand current computer. - Callback Interfaces, Delegates, Events
string[] drives = Directory.GetLogicalDrives(); Console.WriteLine("Here are your drives:"); Part Three - Programming with .NET Assemblies foreach(string s in drives) Chapter 9 - Understanding .NET Assemblies { Chapter 10 - Processes, AppDomains, Contexts, and Threads Console.WriteLine("->{0} ", s); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Part Four - Leveraging the .NET Libraries // Delete what was created. Chapter 12 - Object Serialization and the .NET Remoting Layer Console.Write("Going to delete\n->" + dir.FullName + Chapter 13 - Building"\\MyBar\\MyQaaz.\nand\n->" a Better Window (Introducing Windows + Forms) dir.FullName + Chapter 14 - A Better"\\MyFoo.\n" Painting Framework (GDI+) a key to continue!"); +"Press Chapter 15 - Programming with Windows Forms Controls Console.Read(); Chapter 16 - The System.IO Namespace try Chapter 17 - Data { Access with ADO.NET Part Five - Web Applications and XML Web Services Directory.Delete(@"C:\WinNT\MyFoo"); Chapter 18 - ASP.NET // WebThe Pagessecond and Webparameter Controls specifies if you // wish to blow away any internal subdirectories. Chapter 19 - ASP.NET Web Applications Directory.Delete(@"C:\WinNT\MyBar", true); Chapter 20 - XML Web Services } Index List of Figures catch(IOException e) List of Tables { Console.WriteLine(e.Message); } } } Chapter 8
- Advanced C# Type Construction 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.
and the .NET Platform, Second Edition The FileInfoC#Class by Andrew Troelsen
ISBN:1590590554
The role of the FileInfo to obtain Apressclass © 2003is (1200 pages) a number of details regarding existing files on your hard drive (time created, size, file attributes, and so starts forth) with as well as aid in the of creation, copying, moving, and This comprehensive text a brief overview the destruction of files. In addition to the set of functionality inherited by FileSystemInfo, Table 16-5 describes C# language and then quickly moves to key technical and architectural issues for .NETclass. developers. some core members unique to the FileInfo Table 16-5: FileInfo Core Members
Table of Contents
Meaning in Life C#FileInfo and the .NET Platform, Second Edition Member Introduction Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language
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
- Object-Oriented Programming with C# CreateText() Creates StreamWriter type that writes a new text file Chapter 5 - Exceptions and Object aLifetime Chapter 6 - Interfaces and Collections Delete() Deletes the file to which a FileInfo instance is bound Chapter 7 - Callback Interfaces, Delegates, and Events
Directory instance ofTechniques the parent directory Chapter 8 - Advanced C#Gets Type an Construction Part Three - Programming Gets with .NET Assemblies DirectoryName the full path to a
Chapter 9
file
- Understanding .NET Assemblies
Length Gets the size of the current file or directory Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, LateaBinding, and Programming MoveTo() Moves specified fileAttribute-Based to a new location, providing the option to specify a Part Four - Leveraging the new .NETfilename Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Name13 - Building a Better GetsWindow the name of the fileWindows Forms) Chapter (Introducing Chapter 14 - A Better Painting Framework (GDI+) Open() Opens a file with various read/write and sharing privileges Chapter 15 - Programming with Windows Forms Controls
OpenRead()
Creates a read-only FileStream
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET OpenText() Creates a StreamReader type (described later) that reads from an existing Part Five - Web Applications and text fileXML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
OpenWrite()
Creates a read/write FileStream type
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
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 Figures 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: Index
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# and the .NET Platform, Second Edition fs.Close(); ISBN:1590590554 by Andrew Troelsen f.Delete(); Apress © 2003 (1200 pages) return 0; This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
} }
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 the .NET Platform, Second Edition When you run this application, you will be able to find your newly created *.txt file under the C drive.
Table of Contents Introduction
Part One - Introducing C# and the .NET Platform
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:
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
// Open (or create) a file with read/write attributes (no sharing), - Exceptions and Object Lifetime // and store file handle in a FileStream object. Chapter 6 - Interfaces and Collections FileInfo f2 = new FileInfo(@"C:\HelloThere.ini"); Chapter 7 - Callback Interfaces, Delegates, and Events FileStream s = f2.Open(FileMode.OpenOrCreate,FileAccess.ReadWrite, Chapter 8 - Advanced C# Type Construction Techniques FileShare.None); Part ...Three - Programming with .NET Assemblies Chapter 9 - Understanding .NET Assemblies s.Close(); Chapter 10 - Processes, AppDomains, Contexts, and Threads f2.Delete(); Chapter 5
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
This version of the Serialization overloaded Open() requires three parameters. The first parameter specifies Chapter 12 - Object and the method .NET Remoting Layer the general flavor ofathe open request (e.g., makeWindows a new file, open an existing file, append to a file, and so Chapter 13 - Building Better Window (Introducing Forms) on), which using the FileMode enumeration (Table 16-6). Chapter 14 -isAspecified Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Table 16-6: FileMode Enumeration Chapter 16 - The System.IO NamespaceValues Chapter 17 - Data Access with ADO.NET in Life FileMode Meaning Part Five - Web Applications and XML Web Services Enumeration
Chapter 18 - ASP.NET Web Pages and Web Controls Value Chapter 19 - ASP.NET Web Applications
Append Opens the file if it exists and seeks to the end of the file. If the specified Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition
FileAccess by Andrew TroelsenMeaning in Life Enumeration Apress Value © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the Specifies read-only access to the file (i.e., data can only be C# language and then quickly moves to key technical and from the file) architectural issues obtained for .NET developers.
Read ReadWrite
Specifies read and write access to the file (i.e., data can be added to or obtained from the file)
Table of Contents
C#Write and the .NET Platform, Second Edition Specifies write access to the file (i.e., data can only be added to
the file)
Introduction
Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language
Table 16-8: FileShare Enumeration Chapter 3 - C# Language FundamentalsValues Chapter 4
- Object-Oriented Programming with C# FileShare Meaning in Life
Chapter 5 - Exceptions and Object Lifetime Enumeration Chapter 6 - Interfaces and Collections Value Chapter 7
- Callback Interfaces, Delegates, and Events
None 8 - Advanced C# Type Declines sharing of the current file. Any request to open the file (by this Chapter Construction Techniques process or another Part Three - Programming with .NET Assemblies process) fails until the file is closed. Chapter Read 9
- Understanding .NET Assemblies Allows subsequent opening of the file for reading. If this flag is not
Chapter 10 - Processes, AppDomains, Contexts, and Threads specified, any request to open the file for reading (by this process or Chapter 11 - Type Reflection, another Late Binding, and Attribute-Based process) fails until the fileProgramming is closed. Part Four - Leveraging the .NET Libraries
ReadWrite Allows opening of the file for reading or writing. If this flag is Chapter 12 - Object Serialization and subsequent the .NET Remoting Layer 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 Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter Windows Forms Controls Write 15 - Programming with Allows subsequent opening of the file for writing. If this flag is not Chapter 16 - The System.IO Namespace specified, any request to open the file for writing (by this process or
process) fails until the file is closed. Chapter 17 - Data Access withanother ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
The FileInfo.OpenRead() and FileInfo.OpenWrite() Members
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Index In addition to the Open() method, the FileInfo class also has members named OpenRead() and
OpenWrite(). List of Figures 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# and the .NET Members Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
Another "open-centric" member of the FileInfo type is OpenText(). Unlike Open(), OpenRead(), and Apress © 2003 (1200 pages) OpenWrite(), the OpenText() method returns an instance of the StreamReader type, rather than a This comprehensive text starts with a brief overview of the FileStream-derived type: C# language and then quickly moves to key technical and architectural issues for .NET developers.
// Get a StreamReader object. FileInfo f5 = new FileInfo(@"C:\bootlog.txt"); Table of Contents sreader = f5.OpenText(); StreamReader C# and the .NET Platform, Second Edition ... Introduction sreader.Close(); Part One - Introducing C# and the .NET Platform
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, as shown here: Part Two - The C# Programming Language Chapter 3
- C# Language Fundamentals // Get StreamWriters. Chapter 4 some - Object-Oriented Programming with C#
FileInfo f6 = newand FileInfo(@"D:\AnotherTest.txt"); Chapter 5 - Exceptions Object Lifetime f6.Open(FileMode.Create, FileAccess.ReadWrite); Chapter 6 - Interfaces and Collections StreamWriter swriter = f6.CreateText(); - Callback Interfaces, Delegates, and Events ... Chapter 8 - Advanced C# Type Construction Techniques swriter.Close(); Part Three - Programming with .NET Assemblies FileInfo f7 = new FileInfo(@"D:\FinalTest.txt"); Chapter 9 - Understanding .NET Assemblies f7.Open(FileMode.Create, FileAccess.ReadWrite); Chapter 10 - Processes, AppDomains, Contexts, and Threads StreamWriter swriterAppend = f7.AppendText(); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming ... Part Four - Leveraging the .NET Libraries swriterAppend.Close(); Chapter 7
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter At this point, 14 - Ayou Better have Painting a goodFramework feel for the(GDI+) functionality provided by the FileInfo type. (You will see exactly
what to15 do-with the FileStream, StreamReader, and StreamWriter types shortly.) Chapter Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
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 Part Five - Web Applications and XML Web Services help for an exhaustive listing of each member. Chapter 17 - Data Access with ADO.NET
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The Abstract Stream Class by Andrew Troelsen
ISBN:1590590554
In the world of IOApress manipulation, a stream © 2003 (1200 pages) represents a chunk of data. The abstract System.IO.Stream class defines a number of members that starts provide support synchronous This comprehensive text with a brieffor overview 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 moves to key technical and architectural issues for .NET developers. hierarchy.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure Stream-derived types and Attribute-Based Programming Chapter 11 - 16-5: Type Reflection, Late Binding, Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Stream descendents represent data as a raw stream of bytes (rather than text-based data). Also, some
Chapter 13 - Building a Better Window (Introducing Windows Streams-derived types support seeking, which refers to theForms) process of obtaining and adjusting the current Chapter A Better Painting Framework (GDI+) the functionality provided by the Stream class, take note of position14in -the stream. To begin understanding Chapter 15members - Programming with in Windows Forms Controls the core described Table 16-9. Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Table 16-9: Abstract Stream Members Part Five - Web Applications and XML Web Services
Stream Member
Meaning in Life
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services whether the current stream supports reading, seeking, and/or CanRead Determine Index writing.
CanSeek
List of Figures
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 of bytesSecond (or a single byte) to the current stream and advance C#Write and the .NET Platform, Edition
WriteByte()
current position in this stream by the number of bytes written. ISBN:1590590554 by the Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Working with FileStreams
The FileStream class provides implementations for the abstract Stream members in a manner appropriate for file-based streaming. It is a fairly primitive stream; it can read or write bytes or arrays of bytes. Like the Table of Contents DirectoryInfo and FileInfoSecond types, Edition FileStream provides the ability to open existing files as well as create new C# and the .NET Platform, files. FileStreams are typically configured using the FileMode, FileAccess, and FileShare enumerations. Introduction For example, the following logic creates a new file (test.dat) in the application directory: Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET // Create a newC#file in the working directory. Chapter 2 - Building Applications
FileStream myFStream = Language new FileStream("test.dat", Part Two - The C# Programming FileAccess.ReadWrite); ChapterFileMode.OpenOrCreate, 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime Let's experiment with the synchronous read/write capabilities of the FileStream type. To write a stream of
Chapter Interfaces and to Collections bytes to6 a -file, make calls the inherited WriteByte() or Write() method, both of which advance the Chapter 7 Callback Interfaces, Delegates, Eventsback from a file, simply call Read() or ReadByte(). internal file pointer automatically. To read and the bytes Chapter Advanced C# Type Construction Techniques Here is8an-example: Part Three - Programming with .NET Assemblies
Chapter 9
.NET Assemblies // Write- Understanding bytes to the *.dat file.
Chapter 10 -iProcesses, Contexts, and Threads for(int = 0; i AppDomains, < 256; i++) Chapter myFStream.WriteByte((byte)i); 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part - Leveraging the position. .NET Libraries // Four Reset internal
Chapter 12 - Object Serialization myFStream.Position = 0;and the .NET Remoting Layer Chapter 13 -bytes Buildingfrom a Better Window (Introducing // Read the *.dat file. Windows Forms) Chapter 14 -iA = Better Framework for(int 0; Painting i < 256; i++) (GDI+) Chapter Console.Write(myFStream.ReadByte()); 15 - Programming with Windows Forms Controls
myFStream.Close(); Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
SOURCE CODE
The BasicFileApp project is included under the Chapter 16 subdirectory.
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index
Working with MemoryStreams
List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
© 2003 (1200 to pages) The output of thisApress logic is identical that of the previous FileStream example. The only difference is where you store the information (to file or memory). addition tooverview the inherited members, MemoryStream This comprehensive text startsInwith a brief of the C# language and then quickly moves code to key technical and supplies other members. For example, the previous used the Capacity property to specify how much issues for operation. .NET developers. memory to carvearchitectural out for the streaming Table 16-10 shows the core MemoryStream type members.
Table of Contents
Table 16-10: MemoryStream Core Members
C# and the .NET Platform, Second Edition
MemoryStream Introduction
Meaning in Life
Member Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Capacity
Gets or sets the number of bytes allocated for this stream
Part Two - The C# Programming Language GetBuffer() Returns the
array of unsigned bytes from which this stream was
Chapter 3
- C# Language Fundamentals created
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
ToArray()
Chapter 6
Writes the entire stream contents to a byte array, regardless of the Position property
- Interfaces and Collections WriteTo() Writes the entire Chapter 7 - Callback Interfaces, Delegates, and contents Events of this MemoryStream to another streamChapter 8
derived type (such as a file) - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Notice 9the-possible interplay between the MemoryStream and FileStream types. Using the WriteTo() Chapter Understanding .NET Assemblies method, can easilyAppDomains, transfer dataContexts, stored inand memory to a file. Furthermore, you can also retrieve the Chapter 10you - Processes, Threads memory a byte array: Chapter 11stream - Type as Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
// Dump data to and file. Chapter 12 -memory Object Serialization the .NET Remoting Layer FileStream dumpFile new FileStream("Dump.dat", FileMode.Create, Chapter 13 - Building a Better=Window (Introducing Windows Forms) ChapterFileAccess.ReadWrite); 14 - A Better Painting Framework (GDI+)
myMemStream.WriteTo(dumpFile); Chapter 15 - Programming with Windows Forms Controls // Dump memory data to a byte array. byte[] bytesinMemory = myMemStream.ToArray(); Chapter 17 - Data Access with ADO.NET myMemStream.Close(); Chapter 16 - The System.IO Namespace
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Working with BufferedStreams
Index
List of Figures
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# the .NET Platform, Second Edition Theand Streamer project illustrates working with the FileStream, MemoryStream, and ISBN:1590590554 by Andrew Troelsen BufferedStream types, and is located under the Chapter 16 subdirectory. Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform,and Second Edition Working with StreamWriters StreamReaders by Andrew Troelsen
ISBN:1590590554
The StreamWriterApress and StreamReader classes are useful whenever you need to read or write character© 2003 (1200 pages) based data (e.g.,This strings). Both of these default with Unicode comprehensive texttypes startswork with by a brief overview 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 moves to key technical and architectural issues for .NET developers. simple, let's assume that the default Unicode encoding fits the bill. (Be sure to check out the System.Text namespace for other possibilities.) Table StreamReader of Contentsderives from an abstract type named TextReader, as does the related StringReader type
(discussed laterPlatform, in this chapter). The TextReader base class provides a very limited set of functionality to C# and the .NET Second Edition each of these descendents, specifically the ability to read and peek into a character stream. Introduction Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language Figure 16-6. Chapter 1
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the Meaning in Life .NET Platform, Second Edition Member Name by Andrew Troelsen
ISBN:1590590554
Apress © 2003 (1200 pages)
Close()
Closes the writer and frees any associated resources. In the process,
This comprehensive text starts with a brief overview of the the buffer is automatically flushed. C# language and then quickly moves to key technical and architectural issues for .NET developers.
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.
Table of Contents NewLine
Used to make the new line constant for the derived writer class. The
C# and the .NET Platform, Second default Edition line terminator is a carriage return followed by a line feed ("\r\n"). Introduction
Write()
Writes a line to the text stream, without a new line constant.
Part One - Introducing C# and the .NET Platform
Chapter WriteLine() 1 - The Philosophy of Writes .NET a line to the text stream, with a new line constant. Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# Console.In inherits from TextWriter and Console.Out from TextReader.) Here, TextWriter moves the Chapter 5 - Exceptions and Object Lifetime information to a specified file. Chapter 4 Chapter 6
- Interfaces and Collections
Chapter 7 - Callback Interfaces, andappropriate Events The derived StreamWriter classDelegates, provides an implementation for the Write(), Close(), and Chapter - Advanced C# Type Construction Techniques Flush()8methods, as well as defines the additional AutoFlush property. This property, when set to true, Part Three - Programming withall .NET Assemblies forces StreamWriter to flush data every time
you perform a write operation. Be aware that you can gain
Chapter 9 - Understanding .NETAutoFlush Assemblies better performance by setting to false, provided you always call Close() when you are done Chapter writing 10 with- aProcesses, StreamWriter. AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Writing to a Text File
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter Building aofBetter Window (Introducing Windows Now for13an- example working with the StreamWriter type.Forms) The following class creates a new file named Chapter thoughts.txt 14 - A using Better thePainting FileInfoFramework class. Using (GDI+) the CreateText() method, you can obtain a valid StreamWriter.
At this point, you add some textual dataForms to the Controls new file, as shown here: Chapter 15 - Programming with Windows Chapter 16 - The System.IO Namespace Chapter 17 class - Data Access with ADO.NET public MyStreamWriterReader Part { Five - Web Applications and XML Web Services
Chapter public 18 - ASP.NET static Web Pages int Main(string[] and Web Controls args) Chapter { 19 - ASP.NET Web Applications
//Web Make a file in the application directory. Chapter 20 - XML Services FileInfo f = new FileInfo("Thoughts.txt"); List of Figures // 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..."); } } Index
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and issues for *.txt .NETfile developers. Figure 16-7:architectural The contents of your
As you can see, the StreamWriter has indeed written your data to a file. Do be aware that the Write() and Table of Contents WriteLine() methods have each been C# and the .NET Platform, Second Editionoverloaded numerous times to provide a number of ways to add textual and numeric data (which defaults to Unicode encoding).
Introduction
Part One - Introducing C# and the .NET Platform
Reading - The from Philosophy a Text of .NET File
Chapter 1 Chapter 2
- Building C# Applications
NowTwo you- need toProgramming understand how to programmatically Part The C# Language
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 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Table 16-12: TextReader Core Members
Chapter 7 - Callback Interfaces, Delegates, Events TextReader Member Meaning inand Life Chapter Name8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Peek() - Understanding .NET Returns the next available character without actually changing the Assemblies position of the reader
Chapter 9
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, Programming Read() Reads data and fromAttribute-Based an input stream Part Four - Leveraging the .NET Libraries
ReadBlock()
Reads a maximum of count characters from the current stream and writes the data to a buffer, beginning at index
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter ReadLine() 14 - A Better Painting Framework Reads a line (GDI+) of characters from the current stream and returns the
as a string null string indicates EOF) Chapter 15 - Programming withdata Windows Forms(a Controls Chapter 16 - The System.IO Namespace
ReadToEnd()
Reads all characters from the current position to the end of the TextReader and returns them as one string
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
If you now extend the current MyStreamWriterReader class to use a StreamReader, you can read in the
Chapter - ASP.NET Applications textual 19 data from the Web thoughts.txt file, as shown here: Chapter 20 - XML Web Services Index
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 Figures
Running the program, youthe would the output shown in Figure 16-8. C# and .NETsee Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents
Figure 16-8: Reading from a file
C# and the .NET Platform, Second Edition Introduction
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 of next 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: Part One - Introducing C# and the .NET Platform
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
// Be sure to add a reference to System.Windows.Forms.dll - Object-Oriented Programming with C# // and specify a proper 'using' directive to access the Chapter 5 - Exceptions and Object Lifetime // MessageBox type. Chapter 6 Interfaces and string allOfTheDataCollections = sr.ReadToEnd(); Chapter 7 - Callback Interfaces, Delegates, "Here and Events MessageBox.Show(allOfTheData, it is:"); Chapter 8 - Advanced C# Type Construction Techniques sr.Close(); Chapter 4
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies As you 10 can- see, the StreamReader and StreamWriter types provide a custom implementation of the Chapter Processes, AppDomains, Contexts, and Threads
abstract defined by their respective base classes. Just remember that these two types are Chapter 11members - Type Reflection, Late Binding, and Attribute-Based Programming concerned with moving data Part Four - Leveraging thetext-based .NET Libraries
to and from a specified file.
Chapter 12 - Object Serialization and the .NET Remoting Layer
SOURCE CODE
The StreamWriterReaderApp project is included under the Chapter 16 subdirectory.
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Working with StringWriters by Andrew Troelsen
ISBN:1590590554
Using the StringWriter StringReader Apressand © 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 comprehensive text you starts withtoaappend brief overview 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 moves to key technical and architectural for .NET developers. type) or the GetStringBuilder() method, which overridden ToString() methodissues (to receive a System.String returns an instance of System.Text.StringBuilder. Table To illustrate, of Contents reengineer the previous example to write the character information to a StringWriter instance
rather than.NET a generated As you should notice, the two programs are nearly identical, given that both C# and the Platform, file. Second Edition StringWriter and StreamWriter inherit the same base class functionality, as shown here: Introduction Part One - Introducing C# and the .NET Platform
Chapter 1 class - The Philosophy of .NET public MyStringWriterReader Chapter { 2 - Building C# Applications Part Twopublic - The C# static Programming int Language Main(string[]
args) { Chapter 3 - C# Language Fundamentals // Get a StringWriter Chapter 4 - Object-Oriented Programming withand C# write some stuff. StringWriter writer = new StringWriter(); Chapter 5 - Exceptions and Object Lifetime writer.WriteLine("Don't forget Mother's Day this year..."); Chapter 6 - Interfaces and Collections writer.WriteLine("Don't forget Father's Day this year..."); Chapter 7 - Callback Interfaces, Delegates, and Events writer.WriteLine("Don't forget these numbers:"); Chapter 8 - Advanced C# Type Construction Techniques for(int i = 0; i < 10; i++) Part Three - Programming with .NET Assemblies writer.Write(i + " "); Chapter 9 - Understanding .NET Assemblies writer.Write(writer.NewLine); // Insert a carriage return. Chapter 10 - Processes, AppDomains, Contexts, and Threads writer.Close(); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Console.WriteLine("Stored thoughts in a StringWriter..."); Part Four - Leveraging the .NET Libraries // Get a copy of the contents (stored in a string) and pump Chapter 12 - Object Serialization and the .NET Remoting Layer // to console. Chapter 13 - Building a Better Window (Introducing Windows Console.WriteLine("Contents: {0} Forms) ", writer.ToString()); Chapter 14 - A return Better Painting 0; Framework (GDI+) Chapter } 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace } Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
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 Controls StringBuilder maintained the StringWriter, simply add the following logic: Chapter 19 - ASP.NET Web by Applications Chapter 20 - XML Web Services
// For StringBuilder type! Index using System.Text; List of Figures ... 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# and the .NET Platform, Second Edition allOfTheData = str.ToString(); ISBN:1590590554 by Andrew Troelsen Console.WriteLine("Original says:\n{0} ", allOfTheData); Apress © 2003 (1200 pages) return 0; This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
} }
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.
Table of Contents
C# and the .NET Platform, Second Edition Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Working with StringReaders by Andrew Troelsen
ISBN:1590590554
Next is the StringReader which (as you would expect) functions identically to the related Apress ©type, 2003 (1200 pages) StreamReader class. In fact, the StringReader classa does nothing more This comprehensive text starts with brief overview 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 moves to key technical and architectural issues for .NET developers.
// Now dump using a StringReader. StringReader sr = new StringReader(writer.ToString()); Table of Contents string input = null; C# and the .NET Platform, Second Edition while ((input = sr.ReadLine()) != null) Introduction { Part One - Introducing C# and the .NET Platform Console.WriteLine (input); Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications sr.Close(); Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Figure 416-9 shows the output. Chapter - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Figure 16-9: Manipulating the StringBuilder
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
If you were paying attention to the previous sample applications, you may have noticed one limitation of the Index TextReader List of Figures 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# and the .NET Platform, Second Edition Working with Binary Data (BinaryReaders and BinaryWriters) by Andrew Troelsen
ISBN:1590590554
The final two coreApress classes provided by the System.IO namespace are BinaryReader and BinaryWriter, © 2003 (1200 pages) both of which derive directly from System.Object. These allowofyou This comprehensive text starts with a brieftypes overview 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 moves to key technical and issues .NET developers. stream. The BinaryWriter class also provides course) Write() toarchitectural place a data type for in the corresponding some other familiar-looking members (Table 16-13). Table of 16-13: Contents Table BinaryWriter Core Members C# and the .NET Platform, Second Edition
BinaryWriter Member Introduction
Meaning in Life
Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language
Flush()
Flushes the binary stream
Chapter 3
- C# Language Fundamentals
Seek() Chapter 4
Sets the with position - Object-Oriented Programming C# in the current stream
Chapter 5
Lifetime Write() - Exceptions and ObjectWrites a value to the current stream
Chapter 6
- Interfaces and Collections
Chapter 7 - Callbackclass Interfaces, Delegates, Events The BinaryReader complements theand functionality offered by BinaryWriter with the members Chapter 8 -inAdvanced C# Type Construction Techniques described Table 16-14. Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies Table 16-14: BinaryReader Core Members Chapter 10 - Processes, AppDomains, Contexts, and Threads
BinaryReader Meaning in and Life Chapter 11 - Type Reflection, Late Binding, Attribute-Based Programming Member Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and access the .NETtoRemoting Layer stream. BaseStream Enables the underlying Chapter 13 - Building a Better Window (Introducing Windows Forms)
Close() Closes the binary reader. Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls PeekChar() Returns the next available character without actually advancing the Chapter 16 - The System.IOposition Namespace in the stream. Chapter 17 - Data Access with ADO.NET
Read() a given set of bytes or Part Five - Web ApplicationsReads and XML Web Services
characters and stores them in the incoming array. Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications ReadXXXX() The BinaryReader class defines numerous ReadXXXX methods that Chapter 20 - XML Web Services grab the next type from the stream (ReadBoolean(), ReadByte(), Index ReadInt32(), and so forth). List of Figures 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# and the .NET Platform, Edition binWrit.Write("Hello asSecond binary info..."); ISBN:1590590554 by Andrew Troelsen int myInt = 99; Apress © 2003 (1200 pages) float myFloat = 9984.82343F; ThismyBool comprehensive text starts with a brief overview of the bool = false; C# language and then moves 'e', to key 'l', technical and 'o'} ; char[] myCharArray quickly = { 'H', 'l', architectural issues for .NET developers. binWrit.Write(myInt); binWrit.Write(myFloat); binWrit.Write(myBool); Table of Contents binWrit.Write(myCharArray); C# and the .NET Platform, Second Edition // Reset internal position. Introduction binWrit.BaseStream.Position = 0; Part One - Introducing C# and the .NET Platform // 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); Part Two - The C# Programming Language int temp = 0; Chapter 3 - C# Language Fundamentals while(binRead.PeekChar() != -1) Chapter 4 - Object-Oriented Programming with C# { Chapter 5 - Exceptions and Object Lifetime Console.Write(binRead.ReadByte()); Chapter 6 - Interfacestemp and Collections = temp + 1; Chapter 7 - Callback Interfaces, if(temp Delegates, == 5) and Events Chapter 8 - Advanced{C# Type Construction Techniques Part Three - Programming with //.NET Add Assemblies a blank line every 5 bytes. temp = 0; Chapter 9 - Understanding .NET Assemblies Console.WriteLine(); Chapter 10 - Processes, AppDomains, Contexts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Part Four - Leveraging the .NET Libraries // Clean things up. Chapter 12 - Object Serialization and the .NET Remoting Layer binWrit.Close(); Chapter 13 - Building a Better Window (Introducing Windows Forms) binRead.Close(); Chapter 14 - A Better Painting Framework (GDI+) myFStream.Close(); Chapter 15 - Programming with Windows Forms Controls } Chapter 16 - The System.IO Namespace } Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications SOURCE The BinaryReaderWriter application is included under the Chapter 16 subdirectory. Chapter 20 - XML Web Services CODE Index List of Figures List of Tables
and the .NETDirectories Platform, Second Edition "Watching"C#Files and by Andrew Troelsen
ISBN:1590590554
Now that you have a better handle on the use of various readers and writers, next we'll check out the role of the Apress © 2003 (1200 pages) FileSystemWatcher class. This type can be quite helpful you wish This comprehensive text starts with a briefwhen overview 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 moves to key technical and issues for .NET developers. actions specified architectural by the NotifyFilters enumeration (while many of these members are selfexplanatory, check online help for further details): Table of Contents
public enum System.IO.NotifyFilters { Introduction Attributes, CreationTime, Part One - Introducing C# and the .NET Platform DirectoryName, FileName, Chapter 1 - The Philosophy of .NET LastAccess, LastWrite, Chapter 2 Building C# Applications Security, Size, Part } Two - The C# Programming Language C# and the .NET Platform, Second Edition
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# The first you will need to takeLifetime to work with the FileSystemWatcher type is to set the Path property to specify Chapter 5 step - Exceptions and Object
the name location) ofCollections the directory that contains the files to be monitored, as well as the Filter property that Chapter 6 (and - Interfaces and defines7the- file extension of the Delegates, files to be and monitored. Chapter Callback Interfaces, Events Next, you will set the NotifyFilter property using members of the System.IO.NotifyFilters enumeration. Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
At this point, you may choose to handle the Changed, Created, and Deleted events, all of which work in - Understanding .NET Assemblies conjunction with the FileSystemEventHandler delegate. As well, the Renamed event may also be handled via the Chapter 10 - Processes, AppDomains, Contexts, andset Threads RenamedEventHandler type. Last but not least, the EnableRaisingEvents property to true to begin spying on Chapter 11 Type Reflection, Late Binding, and Attribute-Based Programming your file set. Chapter 9
Part Four - Leveraging the .NET Libraries
To illustrate, assume you have and created a new directory on your C drive named ParanoidFolder that contains two Chapter 12 - Object Serialization the .NET Remoting Layer *.txt files whatever wish).(Introducing The following console application will monitor the *.txt files within the Chapter 13(named - Building a Betteryou Window Windows Forms) ParanoidFolder, andPainting print outFramework messages(GDI+) in the event that the files are created, deleted, modified, or renamed: Chapter 14 - A Better Chapter 15 - Programming with Windows Forms Controls
public TheWatcher Chapter 16 class - The System.IO Namespace { Chapter 17 - Data Access with ADO.NET public static void Main() Part Five - Web Applications and XML Web Services Chapter{18 - ASP.NET Web Pages and Web Controls
Establish which directory to watch Chapter 19 -// ASP.NET Web Applications of course you have this directory...) Chapter 20 -// XML(assume Web Services FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"C:\ParanoidFolder"; List of Figures // 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'); } Index
// Event handlers (note the signature of the delegate targets!) C# and the .NETOnChanged(object Platform, Second Edition private static void source, FileSystemEventArgs e) ISBN:1590590554 by Andrew Troelsen { Apress © 2003 (1200 pages) // Specify what is done when a file is changed, created, or deleted. This comprehensive text starts{0} with {1}!", a brief overview of the Console.WriteLine("File: e.FullPath, e.ChangeType); C# language and then quickly moves to key technical and } architectural issues for .NET developers. private static void OnRenamed(object source, RenamedEventArgs e) { // Specify what is done when a file is renamed. Table of Contents Console.WriteLine("File: {0} renamed to\n{1}", e.OldFullPath, e.FullPath); C# and the .NET Platform, Second Edition } Introduction } Part One - Introducing C# and the .NET Platform
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, Part Two -aThe Programming creating newC#*.txt file, deletingLanguage a *.txt file,
or whatnot. You will see the console application print out various bits of
Chapter 3 - regarding C# Language information theFundamentals state of the text files (Figure 16-10). Chapter 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure 16-10: Watching some *.txt files
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layeris included under the Chapter 16 subdirectory. SOURCE The MyDirectoryWatcher application Chapter CODE 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition IO A Brief Word Regarding Asynchronous by Andrew Troelsen
ISBN:1590590554
You have alreadyApress seen the asynchronous © 2003 (1200 pages) support provided by the .NET Framework during our examination of delegates (Chapter andstarts the .NET layerof (Chapter 12). Needless to say, This comprehensive7)text with aRemoting brief overview the numerous types in the System.IO namespace support asynchronous operations. Specifically, any type C# language and then quickly moves to key technical and issues for .NET developers. deriving from the architectural abstract System.IO.Stream type inherits BeginRead(), BeginWrite(), EndRead(), and EndWrite() methods. As you would expect, each of these methods works in conjunction with the IAsyncResult type: Table of Contents C# and the .NET Platform, Second Edition
public abstract class System.IO.Stream : MarshalByRefObject, Part One - Introducing C# and the .NET Platform IDisposable Chapter 1 - The Philosophy of .NET { Chapter ... 2 - Building C# Applications Part Twopublic - The C# virtual Programming Language IAsyncResult BeginRead(byte[] buffer, int offset, Chapter 3 -int C# Language count, Fundamentals AsyncCallback callback, object state); Chapter public 4 - Object-Oriented Programming with BeginWrite(byte[] C# virtual IAsyncResult buffer, int offset, Chapter 5 -int Exceptions andAsyncCallback Object Lifetime count, callback, object state); Chapter public 6 - Interfaces virtual and Collections int EndRead(IAsyncResult asyncResult); virtual void EndWrite(IAsyncResult asyncResult); Chapter public 7 - Callback Interfaces, Delegates, and Events } Chapter 8 - Advanced C# Type Construction Techniques Introduction
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
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 Attribute-Based Programming need to read or write to a Stream derivative asynchronously, unless perhaps you are building a .NETPart Four - Leveraging the .NET Libraries aware photo-editing application (where the image files can be quite large indeed). Nevertheless, should Chapter 12 - Object Serialization and the .NET Remoting Layer the need arise, just remember Stream-derived types automatically support this behavior. Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Edition A WindowsC# Forms Car Platform, LoggerSecond Application by Andrew Troelsen
ISBN:1590590554
Speaking of Chapter 12©(see preceding section), as you can surely surmise, the types of the System.IO Apress 2003 the (1200 pages) namespace workThis naturally with the .NET object serialization model.ofGiven comprehensive text starts with a brief overview 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 moves to key technical and architectural issues for .NET CarLogApp allows the end user to create andevelopers. inventory 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. Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5 - 16-11: Exceptions Figure Theand car Object logger Lifetime application Chapter 6 - Interfaces and Collections Chapter The topmost 7 - Callback File menu Interfaces, providesDelegates, a numberand of choices Events that operate on the underlying ArrayList. Table 16-15
describes possibleC# selections. Chapter 8 -the Advanced Type Construction Techniques Part Three - Programming with .NET Assemblies
Table 16-15: File Menu Options of the CarLogApp Project Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
File Submenu Item
Meaning in Life
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter Make12 New - Object Car Serialization Displaysand a custom the .NETdialog Remoting box that Layer allows the user to configure a new Car
and refreshes the DataGrid. Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Clear All Cars
Empties the ArrayList and refreshes the DataGrid.
Chapter 15 - Programming with Windows Forms Controls
Open16 Car- File Allows the user to open an existing *.car file and refreshes the DataGrid. This Chapter The System.IO Namespace is ADO.NET the result of a BinaryFormatter. Chapter 17 - Data Access file with Part Five - Web Applications and XML Web Services
Save Car File
Saves all cars displayed in the DataGrid to a *.car file.
Chapter 18 - ASP.NET Web Pages and Web Controls
Exit 19 - ASP.NET Web Exits the application. Chapter Applications Chapter 20 - XML Web Services
I will not bother to detail the menu construction logic, as you have already seen these steps during the Index formal discussion of Windows Forms. The first task is to define the Car type itself. This is the class that List of Figures
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; } }
and the .NET Platform, Second Edition Next, you need toC# add a few members to the main Form class. The overall UI of the DataGrid type is ISBN:1590590554 by Andrew configured using a small setTroelsen of properties, all of which have been assigned using the Properties window of Apress © 2003 (1200 pages) the Visual Studio .NET IDE. The most important property for this example is the ReadOnly member (set to This the comprehensive text starts with ainbrief overview ofThe theremaining configurations establish true), which prevents user from editing the cells the DataGrid. C# language and then quickly moves to key technical and the type's color scheme and physical dimensions (which you can explore at your leisure). architectural issues for .NET developers.
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. Table of Contents Once these Car types have been added to the collection, you call a helper function named UpdateGrid(), as C# and the .NET Platform, Second Edition shown here: Introduction
Part One - Introducing C# and the .NET Platform
public class mainForm : System.Windows.Forms.Form - The Philosophy of .NET { Chapter 2 - Building C# Applications // ArrayList for object serialization. Part Two - The C# Programming Language private ArrayList arTheCars = null; Chapter 3 - C# Language Fundamentals ... Chapter public 4 - Object-Oriented Programming with C# mainForm() Chapter { 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections InitializeComponent(); Chapter 7 - Callback Interfaces, Delegates, and Events CenterToScreen(); Chapter 8 - Advanced Type cars. Construction Techniques // AddC#some Part Three - Programming with arTheCars = .NET newAssemblies ArrayList(); Chapter 9 - Understanding arTheCars.Add(new .NET Assemblies Car("Siddhartha", "BMW", "Silver")); arTheCars.Add(new Car("Chucky", Chapter 10 - Processes, AppDomains, Contexts, and Threads "Caravan", "Pea Soup Green")); arTheCars.Add(new Car("Fred", "Audi TT", "Red")); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming // Display in grid. Part Four - Leveraging the .NETdata Libraries UpdateGrid(); Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter } 13 - Building a Better Window (Introducing Windows Forms) ... 14 - A Better Painting Framework (GDI+) Chapter } Chapter 15 - Programming with Windows Forms Controls Chapter 1
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part - Web Applications and XML Web Services TheFive UpdateGrid() method is responsible for creating
a System.Data.DataTable type that contains a row for
Chapter 18 in - ASP.NET Web Pages Web Controls each Car the ArrayList. Once and the DataTable has been populated, you then bind it the DataGrid type. Chapter 1917 - examines ASP.NET Web Chapter the Applications ADO.NET types (such as the DataTable) in much greater detail, so here the Chapter XMLbasics Web Services focus is20on- the for the time being. Here is the code: Index List of Figures 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# and the .NET Platform, Second Edition newRow = inventory.NewRow(); ISBN:1590590554 by Andrew Troelsen Name"] = c.petName; newRow["Pet Apress © 2003 (1200 pages) newRow["Car Make"] = c.make; ThisnewRow["Car comprehensive text starts with a brief overview of the Color"] = c.color; C# language and then quickly moves to key technical and inventory.Rows.Add(newRow); architectural issues for .NET developers.
} // Now bind this data table to the grid. carDataGrid.DataSource = inventory; Table of Contents } C# and the .NET Platform, Second Edition } Introduction
Part One - Introducing C# and the .NET Platform
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 Part Two -as The C# Programming Language created a result of some SQL query, you
Chapter 3
can also use this type as a stand-alone entity.
- C# Language Fundamentals
Once you a new DataTable, you need toC# establish the set of columns that should be listed in the table. Chapter 4 -have Object-Oriented Programming with The System.Data.DataColumn type represents a single column. Given that this iteration of the Car type has Chapter 5 - Exceptions and Object Lifetime three public fields (make, and pet name), create three DataColumns and insert them in the table Chapter 6 - Interfaces and color, Collections using the DataTable.Columns property. - Callback Interfaces, Delegates, and Events
Chapter 7
Chapter 8 need - Advanced Type Construction Next, you to addC# each row to the table.Techniques Recall that the main Form maintains an ArrayList that contains Part Three - Programming with .NET that Assemblies some number of Car types. Given ArrayList
implements the IEnumerable interface, you can fetch each
Chapter 9 the - Understanding .NET Assemblies Car from collection, read each public field, and compose and insert a new DataRow in the table. Finally, Chapter - Processes, AppDomains, Contexts, and widget Threadsusing the DataSource property. the new10DataTable is bound to the GUI DataGrid Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
NowFour then! If you run the at this Part - Leveraging the application .NET Libraries
point, you will find that the grid is indeed populated with the
default 12 set-of automobiles. Thisand is athe good start, but youLayer can do better. Chapter Object Serialization .NET Remoting Chapter 13 - Building a Better Window (Introducing Windows Forms)
Implementing the Add New Car Logic
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
The CarLogApp project defines another Form-derived type (AddCarDlg) that functions as a modal dialog Chapter 16 - The System.IO Namespace box (Figure Fromwith 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 andFive two -ListBox types (to allow the user select Part Web Applications and XML Webto Services
the color and make).
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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 and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen // Make Apress public for easy access. © 2003 (1200 pages) public Car theCar = null; This comprehensive text starts with a brief overview of the ... C# language and then quickly moves to key technical and protected void btnOK_Click architectural issues for .NET (object developers.sender, System.EventArgs e) { // Configure a new Car when user clicks OK button. Table of Contents theCar = new Car(txtName.Text, listMake.Text, listColor.Text); } .NET Platform, Second Edition C# and the } Introduction Part One - Introducing C# and the .NET Platform
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
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals protected void menuItemNewCar_Click Chapter 4 - Object-Oriented Programming with C# (object sender, System.EventArgs e)
{
Chapter 5
- Exceptions and Object Lifetime
// Show the dialog and check for OK click. - Interfaces and Collections AddCarDlg d = new AddCarDlg(); Chapter 7 - Callback Interfaces, Delegates, and Events if(d.ShowDialog() == DialogResult.OK) Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies // Add new car to array list. Chapter 9 - Understanding .NET Assemblies arTheCars.Add(d.theCar); Chapter 10 - Processes, AppDomains, Contexts, and Threads UpdateGrid(); Chapter } 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part } Four - Leveraging the .NET Libraries Chapter 6
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
No surprises just show the Form as a modal dialog box, and if the OK button has been clicked, Chapter 14 - A here. BetterYou Painting Framework (GDI+) you read public Car member variable, addControls it to the ArrayList, and refresh your grid. Chapter 15the - Programming with Windows Forms Chapter 16 - The System.IO Namespace
The Serialization Logic
Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
The core behindWeb the Pages Save Car File and Open Car File Click event handlers should pose no problems Chapter 18 logic - ASP.NET and Web Controls at this point. When the user chooses to save the current inventory, you create a new file and use a Chapter 19 - ASP.NET Web Applications BinaryFormatter to serialize Chapter 20 - XML Web Servicesthe 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 Index is yet another standard dialog box and is illustrated in Figure 16-13.
List of Figures List of Tables
Figure 16-13: The standard File Save dialog box
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
Notice that the SaveFileDialog is listing Apress © 2003 (1200 pages)a custom file extension (*.car). While I leave the task of investigating the complete functionality of the SaveFileDialog in your capable hands, it is worth pointing out that this has This comprehensive text starts with a brief overview of the been assigned using the Filter property. This property takes an OR-delimited string that represents the text C# language and then quickly moves to key technical and issues for .NET developers. to be used in the architectural drop-down File name and Save as type combo boxes. Here is the full implementation: protected void menuItemSave_Click (object sender, System.EventArgs e) { C# and the .NET Platform, Second Edition // Configure look and feel of save dialog box. Introduction SaveFileDialog mySaveFileDialog = new SaveFileDialog(); Part One - Introducing C# and the .NET Platform mySaveFileDialog.InitialDirectory = "."; Chapter mySaveFileDialog.Filter 1 - The Philosophy of .NET = "car files (*.car)|*.car|All files (*.*)|*.*"; Chapter mySaveFileDialog.FilterIndex 2 - Building C# Applications = 1; Part TwomySaveFileDialog.RestoreDirectory - The C# Programming Language = true; Chapter mySaveFileDialog.FileName 3 - C# Language Fundamentals = "carDoc"; Chapter // 4 -Do Object-Oriented Programming with C# you have a file? Chapter if(mySaveFileDialog.ShowDialog() 5 - Exceptions and Object Lifetime == DialogResult.OK) Chapter { 6 - Interfaces and Collections Stream myStream = null; Chapter 7 - Callback Interfaces, Delegates, and Events if((myStream = mySaveFileDialog.OpenFile()) != null) Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies // Save the cars! Chapter 9 - Understanding .NET Assemblies BinaryFormatter myBinaryFormat = new BinaryFormatter(); Chapter 10 - Processes, AppDomains, Contexts, and Threads myBinaryFormat.Serialize(myStream, arTheCars); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming myStream.Close(); Part Four - Leveraging the .NET Libraries } Chapter 12 - Object Serialization and the .NET Remoting Layer } Chapter 13 - Building a Better Window (Introducing Windows Forms) }
Table of Contents
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls Chapter 16 that - Thethe System.IO Namespace Also note OpenFile() member of the SaveFileDialog type returns a Stream that represents the Chapter 17 Data Access with specified file selected by the ADO.NET end user. As seen in Chapter 13, this is the very thing needed by the Part Five - Web Applications and XML Web Services BinaryFormatter type.
Chapter 18 - ASP.NET Web Pages and Web Controls
The logic the Web OpenApplications Car File Click event handler looks very similar. This time you create an instance Chapter 19 behind - ASP.NET of the System.Windows.Forms Chapter 20 - XML Web Services 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:
Index
List of Figures 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# and the .NET // Get the Platform, cars! Second Edition by Andrew Troelsen BinaryFormatter myBinaryFormatISBN:1590590554 = new BinaryFormatter(); Apress © 2003 (1200 = pages) arTheCars (ArrayList)myBinaryFormat.Deserialize(myStream);
}
ThismyStream.Close(); comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and UpdateGrid(); architectural issues for .NET developers.
} }
Table of Contents C# and the .NET Platform, Second Edition Introduction At this point, the application can save and load the entire set of Car types held in the ArrayList using a Part One - Introducing C# and the .NET Platform
BinaryFormatter. The final menu items are self-explanatory, as shown here:
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
protected void menuItemClear_Click (object sender, System.EventArgs e) { Chapter 3 - C# Language Fundamentals arTheCars.Clear(); Chapter UpdateGrid(); 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime } Chapter 6 - Interfaces and Collections protected void menuItemExit_Click (object sender, System.EventArgs e) Chapter 7 Callback Interfaces, Delegates, and Events { Chapter 8 Application.Exit(); - Advanced C# Type Construction Techniques Part } Three - Programming with .NET Assemblies Part Two - The C# Programming Language
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
This wraps ourReflection, exploration of Binding, the System.IO namespace. Programming Over the course of this chapter you have seen Chapter 11 - up Type Late and Attribute-Based howFour to read and writethe data to binary, character-based, Part - Leveraging .NET Libraries
and memory streams. In the next chapter you will come to understand how to interact with XML-based data readers (and writers). Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building aThe Better Window (Introducing Windows Forms) SOURCE CarLogApp project is included under the Chapter 16 subdirectory. Chapter 14 - A Better Painting Framework (GDI+) CODE Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
This chapter began by examining use of the Directory(Info) and File(Info) types. As you have seen, Apress © 2003 (1200the pages) these classes allow you to manipulate a physical filea or directory onof your This comprehensive text starts with brief overview thehard drive. C# language and then quickly moves to key technical and
Next you examined a numberissues of types from the abstract Stream class, including FileStream, architectural forderived .NET developers. 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. Table When of you Contents are interested in persisting textual data, the StreamReader and StreamWriter types usually fit theand bill.the .NET Platform, Second Edition C# Introduction
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.
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Chapter C# 17: Data Access with ADO.NET ISBN:1590590554 by Andrew Troelsen
Overview
Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and Unless you are aarchitectural video game issues developer for .NET by trade, developers. you 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 Table of Contents known as ADO.NET, which as you will see is a major overhaul of the classic ADO object model. C# and the .NET Platform, Second Edition
This chapter begins by examining some core types defined in the System.Data namespace-specifically Introduction DataColumn, DataRow, DataTable. These Part One - Introducing C# and and the .NET Platform
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 Part Two - The C# Programming Language custom views based on a given DataTable, and submit queries against your in-memory DataSet. Chapter 3
- C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C# After examining how to manually build and manipulate a DataSet by hand, you'll examine how to obtain a Chapter 5 Exceptions and Object Lifetime populated DataSet from a Database Management System (DBMS) such as MS SQL Server, Oracle, or Chapter 6 - Interfaces Collections MS Access. During theand process, you will examine the role of .NET data providers and come to understand Chapter 7 Callback Interfaces, Delegates, and Events the use of ADO.NET data adapters, command objects, and command builders. Chapter 8
- Advanced C# Type Construction Techniques
In contrast to the intrinsically world Part Three - Programming withdisconnected .NET Assemblies
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 - Understanding .NET Assemblies reader is ideal when you simply wish to obtain a result set from a data store for display purposes. We wrap Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming how these integrated tools can be used to lessen the amount of ADO.NET code you would otherwise need Part Four - Leveraging the .NET Libraries to write by hand. Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The Need for ADO.NET by Andrew Troelsen
ISBN:1590590554
The very first thing you must Apress © 2003understand (1200 pages) when approaching ADO.NET is that it is not simply the latest and greatest version of classic ADO. While it is true with that athere some symmetry between the two systems This comprehensive text starts briefis overview of the (e.g., each has the concept of connection and command objects), some familiar types (e.g., the C# language and then quickly moves to key technical and architectural issues for .NET developers. Recordset) no longer exist. Furthermore, 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) Table of Contents systems using the .NET platform. C# and the .NET Platform, Second Edition
Unlike classic ADO, which was primarily designed for tightly coupled client/server systems, ADO.NET Introduction greatly the notion of the the .NET primitive ADO disconnected Part One extends - Introducing C# and Platform
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 for processing using a Part Two - data The C# Programming Language Chapter 3
related data adapter.
- C# Language Fundamentals
Another major difference between classic ADO and ADO.NET is that ADO.NET has full support for XML - Object-Oriented Programming with C# data representation. In fact, the data obtained from a data store is internally represented, and transmitted, Chapter 5 - Exceptions and Lifetime as XML. Given that XML is Object often transported between layers using standard HTTP, ADO.NET is not limited Chapter 6 Interfaces and Collections by firewall constraints. Chapter 4
Chapter 7
- Callback Interfaces, Delegates, and Events
As you 8might be aware, ADO makesTechniques use of the COM marshaling protocol to move data between Chapter - Advanced C#classic Type Construction tiers. While this was appropriate in some situations, COM marshaling poses a number of limitations. For Part Three - Programming with .NET Assemblies example, most firewalls are configured to reject COM RPC packets, which made moving data between Chapter 9 - Understanding .NET Assemblies machines tricky. Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer comprise ADO.NET use the CLR memory management protocol, adhere to the same programming Chapter - work Building a many Better languages. Window (Introducing Windows Forms) model,13 and with Therefore, the types (and their members) are accessed in the Chapter 14 - A Better Painting (GDI+) language you use. same manner, regardless of Framework which .NET-aware Part Four - Leveraging the .NET Libraries
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andof theADO.NET .NET Platform, Second Edition The Two Faces by Andrew Troelsen
ISBN:1590590554
The ADO.NET libraries can be(1200 used in two conceptually unique manners: connected or disconnected. Apress © 2003 pages) When you are making use of the connected layer, will overview make use a .NET data reader. As you will This comprehensive text starts withyou a brief ofof the see later in this chapter, data readers provide a way to pull records from C# language and then quickly moves to key technical and a data store using a forward-only, architectural issues .NET developers. read-only approach (much like a firefor hose cursor). As 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 Table of insert, Contents you to update, or remove records using a related command object. C# and the .NET Platform, Second Edition
The disconnected layer, on the other hand, allows you to obtain a set of DataTable types (typically Introduction contained within a DataSet) as a local Part One - Introducing C# andthat the serves .NET Platform
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 Two client- The application is able to Language manipulate the Part C# Programming
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 - Object-Oriented Programming with C# immediately. Chapter 5
- Exceptions and Object Lifetime
Chapter - Interfaces Collections In some6 respects, this and approach may remind you of the classic ADO disconnected Recordset. The key Chapter 7 Callback Interfaces, and Events difference is that a disconnectedDelegates, Recordset represents a single set of record data, whereas ADO.NET Chapter 8 can - Advanced Type Construction DataSets model aC# collection of related Techniques tables. In fact, it is technically possible to obtain a client-side Part Threethat - Programming with Assemblies DataSet represents all of .NET the tables found
within the remote database. However, as you would expect,
Chapter 9 -will Understanding .NET Assemblies a DataSet more commonly contain a reasonable subset of information. Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NETData Platform, Second Edition The Role ofC#ADO.NET Providers by Andrew Troelsen
ISBN:1590590554
Rather than providing a ©single set of objects to communicate to a variety of data stores, ADO.NET makes use Apress 2003 (1200 pages) of multiple data providers. Simply put, a data is a overview set of types (within some .NET assembly) that This comprehensive text startsprovider with a brief of the understand how to communicate with a specific data source. Although the names of these types will differ C# language and then quickly moves to key technical and architectural issues for .NET developers. among data providers, each provider will 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 Table of Contents to provide connected and disconnected access to the underlying data store (see Figure 17-1). C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Figure data providers access Chapter 12 - 17-1: ObjectADO.NET Serialization and the .NETprovide Remoting Layer to a given DBMS. Chapter 13 - Building a Better Window (Introducing Windows Forms)
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 Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 In - The System.IO Namespace Note version 1.0 of the .NET platform, data providers were termed managed providers. Therefore, if you Chapter 17 are - Data Access with reading earlier ADO.NET .NET literature (including the first edition of this text), understand that these two Part Five - Web Applications and XML Web Services terms are completely synonymous with
each other.
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
The Role of the IDbConnection and IDbTransaction Interfaces
Chapter 20 - XML Web Services
Index First we have the IDbConnection type, which is implemented by a data provider's connection object. This List of Figures interface defines 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# and the .NET Platform, Second Edition
As you can see, the overloaded BeginTransaction() method provides access to an IDbTransaction-compatible ISBN:1590590554 by Andrew Troelsen type. Using the members defined by this interface, you are able to programmatically interact with a transactional Apress © 2003 (1200 pages) session and the underlying data store: This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers. public interface System.Data.IDbTransaction : IDisposable
{ IDbConnection Connection { get; } Table of IsolationLevel Contents IsolationLevel { get; } C# and the .NETCommit(); Platform, Second Edition void Introduction void Rollback(); Part } One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
The Role of the IDbCommand, IDbDataParameter, and IDataParameter - C# Language Fundamentals Interfaces Chapter 4 - Object-Oriented Programming with C# Chapter 3 Chapter 5
- Exceptions and Object Lifetime
Next up, we have the IDbCommand interface, which will be implemented by a data provider's command object. - Interfaces and Collections Like other data access object models, command objects allow programmatic manipulation of SQL statements, Chapter 7 - Callback Interfaces, Delegates, and Events stored procedures, and parameterized queries (note that each parameter object implements the Chapter 8 - Advanced C# Type Construction Techniques IDbDataParameter type). In addition, command objects also provide access to the data provider's data reader Part Three - Programming with .NET Assemblies type via the overloaded ExecuteReader() method: Chapter 6
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
public interface System.Data.IDbCommand : IDisposable { Part Four - Leveraging the .NET Libraries string CommandText { get; set; } Chapter 12 - Object Serialization and the .NET Remoting Layer int CommandTimeout { get; set; } Chapter 13 - Building a Better Window (Introducing Windows Forms) CommandType CommandType { get; set; } Chapter IDbConnection 14 - A Better Painting Framework (GDI+) Connection { get; set; } Chapter IDataParameterCollection 15 - Programming with Windows Forms Controls Parameters { get; } Chapter IDbTransaction 16 - The System.IO Namespace Transaction { get; set; } Chapter UpdateRowSource 17 - Data Access with ADO.NET UpdatedRowSource { get; set; } Part Fivevoid - WebCancel(); Applications and XML Web Services Chapter System.Data.IDbDataParameter 18 - ASP.NET Web Pages and Web Controls CreateParameter(); Chapter int 19 - ASP.NET ExecuteNonQuery(); Web Applications ExecuteReader(); Chapter System.Data.IDataReader 20 - XML Web Services Index System.Data.IDataReader ExecuteReader(System.Data.CommandBehavior behavior); object ExecuteScalar(); List of Figures void Prepare(); List of Tables } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
public interface System.Data.IDataParameter Apress © 2003 (1200 pages) { This comprehensive text starts with a brief overview of the DbType DbType { get; set; } C# language and then quickly moves to key technical and ParameterDirection Direction { get; set; } architectural issues for .NET developers. bool IsNullable { get; } string ParameterName { get; set; } Table of string Contents SourceColumn { get; set; } DataRowVersion SourceVersion { get; set; } C# and the .NET Platform, Second Edition object Value { get; set; } Introduction } One - Introducing C# and the .NET Platform Part 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 represent 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. Part Two - The C# Programming Language
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
The Role of theandIDbDataAdapter and IDataAdapter Interfaces - Interfaces Collections
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 9
- Understanding .NET Assemblies
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 Construction Techniques IDbDataAdapter interface defines a set of properties that are used to maintain the SQL statements for the Part Three - Programming with .NET Assemblies related SELECT, INSERT, UPDATE, and DELETE operations: Chapter 10 - Processes, AppDomains, Contexts, and Threads
public interface System.Data.IDbDataAdapter : System.Data.IDataAdapter { Part Four - Leveraging the .NET Libraries IDbCommand DeleteCommand { get; set; } Chapter 12 - Object Serialization and the .NET Remoting Layer IDbCommand InsertCommand { get; set; } Chapter IDbCommand 13 - Building a Better Window (Introducing Forms) SelectCommand { get;Windows set; } Chapter IDbCommand 14 - A Better Painting Framework (GDI+) UpdateCommand { get; set; } Chapter 15 - Programming with Windows Forms Controls } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
In addition to these four properties, ADO.NET Part Five - Web Applications and XML an Web Services
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 Controls pull DataSets between theApplications caller and underlying data store using the Fill() and Update() methods. Also, the Chapter 19 - ASP.NET Web IDataAdapter interface allows you to map database column names to a more human-readable display name Chapter 20 - XML Web Services via the TableMappings property:
Index
List of Figures
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 and the .NET Platform, Second Edition data provider, youC# are able to iterate over the result set using a forward-only, read-only manner. by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
public interface System.Data.IDataReader : IDisposable, This comprehensive text starts with a brief overview of the System.Data.IDataRecord C# language and then quickly moves to key technical and { architectural issues for .NET developers. int Depth { get; } bool IsClosed { get; } RecordsAffected { get; } Table ofint Contents void Close(); C# and the .NET Platform, Second Edition System.Data.DataTable GetSchemaTable(); Introduction bool NextResult(); Part One - Introducing C# and the .NET Platform Read(); Chapterbool 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Finally, as you can see, IDataReader extends IDataRecord, which defines an additional set of members that - Object-Oriented Programming with C# allow you to extract out a strongly typed value from the stream, rather than casting the generic System.Object Chapter 5 - Exceptions Objectoverloaded Lifetime retrieved from the dataand reader's indexer method: Chapter 4 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
public interface System.Data.IDataRecord Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies int FieldCount { get; } Chapterobject 9 - Understanding .NET Assemblies this[ string name ] { get; } Chapterobject 10 - Processes, AppDomains, this[ int i ] {Contexts, get; }and Threads Chapterbool 11 - Type Reflection, Late Binding, and Attribute-Based Programming GetBoolean(int i); Part Four Leveraging the .NET Libraries byte GetByte(int i); Chapterlong 12 - Object Serialization i, and long the .NET Remoting Layer byte[] buffer, GetBytes(int fieldOffset, Chapter 13 -int Building a Better Window (Introducing Windows Forms) bufferoffset, int length); Chapterchar 14 - AGetChar(int Better Painting Framework i); (GDI+) GetChars(int i, longForms fieldoffset, char[] buffer, Chapterlong 15 - Programming with Windows Controls bufferoffset, int length); Chapter 16 -int The System.IO Namespace ChapterSystem.Data.IDataReader 17 - Data Access with ADO.NET GetData(int i); string GetDataTypeName(int i); Part Five - Web Applications and XML Web Services GetDateTime(int ChapterDateTime 18 - ASP.NET Web Pages and Webi); Controls GetDecimal(int ChapterDecimal 19 - ASP.NET Web Applications i); double GetDouble(int i); Chapter 20 - XML Web Services Type GetFieldType(int i); Index float GetFloat(int i); List of Figures 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 pointthe you.NET should have a Second better idea of the common functionality found among all .NET C# and Platform, Edition data providers. Recall that even though the exact names of theISBN:1590590554 implementing types will differ among data by Andrew Troelsen providers, you areApress able to program against these types in a similar manner, given the beauty of interface-based © 2003 (1200 pages) polymorphism: This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers. System.Data.OleDb.OleDbConnection c; // Implements IDbConnection!
System.Data.Odbc.OdbcConnection c2; System.Data.Oracle.OracleConnection c3; Table of Contents System.Data.SqlServerCe.SqlCeConnection c4; C# and the .NET Platform, Second Edition System.Data.SqlClient.SqlConnection c5;
// // // //
Implements Implements Implements Implements
IDbConnection! IDbConnection! IDbConnection! IDbConnection!
Introduction Part One - Introducing C# and the .NET Platform
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, Part Two - The C# Programming Language
you can call the interface methods directly from an object
Chapter 3 reference. - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, Namespaces Second Edition Understanding ADO.NET by Andrew Troelsen
ISBN:1590590554
.NET version 1.1 Apress ships with five data providers out of the box, each of which is logically represented by a © 2003 (1200 pages) specific .NET namespace. In addition, ADO.NET defines common This comprehensive text starts with a briefsome overview of thenamespaces 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 moves to key technical and architectural issues for .NET developers.
Table 17-1: ADO.NET Namespaces ADO.NET Namespace Table of Contents
Meaning in Life
C# and the .NET Platform, Second Edition
System.Data
This core namespace defines types that represent tables, rows, columns, constraints, and DataSets. This namespace does not Part One - Introducing C# and the .NET Platform define types to connect to a data source. Rather, it defines the Chapter 1 - The Philosophy of .NET types that represent the data itself. Introduction
Chapter 2
- Building C# Applications
System.Data.Common This namespace contains Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime System.Data.OleDb This namespace defines the types that allow you to connect to an Chapter 6 - Interfaces and Collections OLE DB-compliant data source. Typically you will use this Chapter 7 Chapter 8
- Callback Interfaces, Delegates, and Events namespace only if you need to communicate with a data store that - Advanced C# Type Construction Techniques does not have a custom data provider.
Part Three - Programming with .NET Assemblies
System.Data.Odbc
Chapter 9
This namespace defines the types that constitute the ODBC data provider.
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter System.Data.OracleClient 11 - Type Reflection, LateThis Binding, namespace and Attribute-Based defines the Programming types that constitute the Oracle data Part Four - Leveraging the .NET Libraries provider.
Chapter 12 - Object Serialization and the .NET Remoting Layer
System.Data.SqlClient
This namespace defines the types that constitute the SQL data provider.
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
System.Data.SqlServerCe This namespace defines the types that constitute the SQL CE data Chapter 15 - Programming with Windows Forms Controls provider. Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET System.Data.SqlTypes Represents native data types used by Microsoft SQL Server. Part Five - Web Applications and XML Web Services Although you are
always free to use the corresponding CLR data
Chapter 18 - ASP.NET Web Pages types, and Web theControls SqlTypes are optimized to work with SQL Server. Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services The System.Data, System.Data.Common, System.Data.OleDb, System.Data.SqlClient, Index System.Data.Odbc, and System.Data.SqlTypes namespaces are all contained within the System.Data.dll List of Figures 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# and the .NET Platform, Second Edition The Types of System.Data by Andrew Troelsen
ISBN:1590590554
Of all the ADO.NET namespaces, System.Data is the lowest common denominator. You simply cannot Apress © 2003 (1200 pages) build ADO.NET applications without specifying this namespace in your data access applications. This This comprehensive text starts with a brief overview of the namespace contains types that are shared among all ADO.NET data providers, regardless of the C# language and then quickly moves to key technical and architectural issues System.Data for .NET developers. 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 Table Contents like),ofthese types are little more than OO representations of common database primitives (tables, rows, C# and the constraints, .NET Platform, Second Edition columns, and so on). Table 17-2 lists some of the core types, grouped by related functionality. Introduction Part One17-2: - Introducing C# andof the .NET Platform Table Key Members the System.Data
Chapter 1
Namespace
- The Philosophy of .NET
System.Data Type Meaning in Life - Building C# Applications
Chapter 2
Part Two - The C# Programming Language DataColumnCollection 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 - Object-Oriented Programming DataTable. with C# Chapter 5
- Exceptions and Object Lifetime
ConstraintCollection The ConstraintCollection represents all constraints (foreign key - Interfaces and Collections constrains, unique constraints) assigned to a given DataTable. Constraint
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
Constraint represents an OO wrapper around a single constraint - Advanced C# Type Construction Techniques
assigned to one or Part Three - Programming with .NET Assemblies
more DataColumns.
Chapter 9 - Understanding .NET Assemblies DataRowCollection These types represent a collection of rows for a DataTable Chapter 10 - Processes, AppDomains, Contexts, and Threads (DataRowCollection) and a specific row of data in a DataTable
DataRow
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming (DataRow). Part Four - Leveraging the .NET Libraries
DataRowView DataRowView you Layer to carve out a predefined "view" from an Chapter 12 - Object Serialization and the .NETallows Remoting existing row.
DataView Chapter 13 - Building a Better Window (Introducing Windows Forms) DataView type represents a customized view of a DataTable that Chapter 14 - A Better Painting The Framework (GDI+) can be used for sorting, filtering, searching, editing, and navigation. Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace DataSet Represents an in-memory cache of data that may consist of multiple Chapter 17 - Data Access with related ADO.NET DataTables. Part Five - Web Applications and XML Web Services
ForeignKeyConstraint ForeignKeyConstraint Chapter 18 - ASP.NET Web Pages and Web Controls represents an action restriction enforced on a set of columns in a primary key/foreign key relationship. Chapter UniqueConstraint 19 - ASP.NET Web Applications The UniqueConstraint type represents a restriction on a set of columns Chapter 20 - XML Web Services Index
in which all values must be unique.
List of Figures
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.
the .NET Platform, Second Edition Examining C# theandDataColumn Type by Andrew Troelsen
ISBN:1590590554
The DataColumnApress type represents single column maintained by a DataTable. Collectively speaking, the © 2003 (1200 apages) set of all DataColumn types bound to a given This comprehensive text startsDataTable with a briefrepresents overview ofthe thefoundation of a table's schema information. For example, assume you have a table named Employees C# language and then quickly moves to key technical andwith three columns (EmpID, architecturalProgrammatically, issues for .NET developers. 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. Table of Contents
If you a background in relational C# and have the .NET Platform, Second Editiondatabase theory, you know that a given column in a data table can be assigned a set of constraints (e.g., configured as a primary key, assigned a default value, configured to Introduction contain information, and so Platform on). Also, Part One -read-only Introducing C# and the .NET
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 column2maps to an integer, while FirstName and LastName map to an array of characters. The Chapter - Building C# Applications DataColumn has numerous properties that Part Two - The class C# Programming Language
allow you to configure these very things. Table 17-3
provides of some core properties. Chapter 3 a-rundown C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Table 17-3: Properties of the DataColumn - Exceptions and Object Lifetime
Chapter 5
Chapter 6 - Interfaces and Collections DataColumn Meaning in Life Chapter 7 - Callback Interfaces, Delegates, and Events Property Chapter 8
- Advanced C# Type Construction Techniques
AllowDBNull Used to Assemblies indicate if a Part Three - Programming with .NET
row can specify null values in this column. The default value is true. Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts,are andused Threads AutoIncrement These properties to configure the auto-increment behavior for Chapter 11 - Type Reflection,a Late Binding, and Attribute-Based Programming given column. This can be helpful when you wish to ensure unique AutoIncrementSeed Part Four - Leveraging the .NET Libraries values in a given DataColumn (such as a primary key). By default, a AutoIncrementStep Chapter 12 - Object Serialization DataColumn and the .NET doesRemoting not support Layer auto-incrementation. Chapter 13 - Building a Better Window (Introducing Windows Forms)
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 Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
ColumnMapping property determines how a DataColumn is represented when a Chapter 16 - The System.IO This Namespace DataSet is saved as an XML document using the DataSet.WriteXml() Chapter 17 - Data Access with ADO.NET Part Five - Web Applications method. and XML Web Services
Chapter 18 - ASP.NET Web Pages Webthe Controls ColumnName Gets and or sets name of the column in the Columns collection (meaning Chapter 19 - ASP.NET Web Applications how it is represented internally by the DataTable). If you do not set the Chapter 20 - XML Web Services ColumnName explicitly, the default values are Column with (n+1) Index numerical suffixes (i.e., Column1, Column2, Column3, and so forth). List of Figures
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
Gets or sets a valueSecond indicating whether the values in each row of the C# and the .NET Platform, Edition must be unique or if repeating values are permissible. If a ISBN:1590590554 by Andrewcolumn Troelsen column is assigned a primary key constraint, the Unique property should Apress © 2003 (1200 pages) be set to true.
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Building a DataColumn Table of Contents
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 Introduction whatever reason) must be read-only. Assuming you wish to build your DataColumn in the Click event Part One - Introducing C# and the .NET Platform handler of a Button type within a Windows Forms application, you would write the following logic: C# and the .NET Platform, 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 - Object-Oriented Programming C# colFName = newwith DataColumn(); Chapter // 5 -Set Exceptions and Object Lifetime a bunch of values. Chapter colFName.DataType 6 - Interfaces and Collections = Type.GetType("System.String"); Chapter colFName.ReadOnly 7 - Callback Interfaces, Delegates, = true; and Events Chapter colFName.Caption 8 - Advanced C# Type = Construction Techniques "First Name"; Part Three - Programming with .NET = Assemblies colFName.ColumnName "FirstName"; Chapter // 9 -Display Understanding DataColumn's .NET Assemblies values. temp AppDomains, = "ColumnContexts, type: and " +Threads colFName.DataType + "\n" + Chapter string 10 - Processes, only?and " Attribute-Based + colFName.ReadOnly Chapter 11 - Type Reflection,"Read Late Binding, Programming + "\n" + "Caption: Part Four - Leveraging the .NET Libraries " + colFName.Caption + "\n" + "Column " + colFName.ColumnName + "\n" + Chapter 12 - Object Serialization and theName: .NET Remoting Layer "Nulls + colFName.AllowDBNull; Chapter 13 - Building a Better Window allowed? (Introducing"Windows Forms) "Column Chapter MessageBox.Show(temp, 14 - A Better Painting Framework (GDI+) properties"); } Chapter 15 - Programming with Windows Forms Controls Part Two - The C# Programming Language
Chapter 16 - The System.IO Namespace Chapter 17 -the Data Access withinADO.NET This gives result shown Figure 17-2. Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Adding a DataColumn to a DataTable This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and
The DataColumnarchitectural type does not typically existdevelopers. as a stand-alone entity, but is instead inserted into a related issues for .NET 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: Table of Contents C# and the .NET Platform, Second Edition Introduction // Build the FirstName column. Part One - Introducing C# and=the .NET Platform DataColumn myColumn new DataColumn();
Chapter ... 1
- The Philosophy of .NET
// Create a newC#DataTable. Chapter 2 - Building Applications DataTable myTable = newLanguage DataTable("MyTable"); Part Two - The C# Programming // The property returns a DataColumnCollection type. Chapter 3 Columns - C# Language Fundamentals // Use Add() method to insert the column in the table. Chapter 4 the - Object-Oriented Programming with C# myTable.Columns.Add(myColumn); Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
- Advanced Type Constructionto Techniques Configuring a C# DataColumn Function As a Primary Key
Chapter 8
Part Three - Programming with .NET Assemblies
One common rule of database development is that a table should have at least one column that functions Chapter 9 - Understanding .NET Assemblies as the primary key. A primary key constraint used to uniquely identify a record (row) in a given table. In Chapter 10 - Processes, AppDomains, Contexts,isand Threads keeping11with the current Employees example, assume you now wish to build a new DataColumn type to Chapter - Type Reflection, Late Binding, and Attribute-Based Programming represent the EmpID the field. This column Part Four - Leveraging .NET Libraries
will be the primary key of the table and thus should have the AllowDBNull and Unique properties configured as shown here: Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
// This is functioning as a primary key. Chapter 14 -column A Better Painting Framework (GDI+) DataColumn colEmpIDwith = Windows new DataColumn(EmpID, Type.GetType("System.Int32")); Chapter 15 - Programming Forms Controls colEmpID.Caption = "Employee ID"; colEmpID.AllowDBNull = false; Chapter 17 - Data Access with ADO.NET colEmpID.Unique = true; Chapter 16 - The System.IO Namespace
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 DataColumn - ASP.NET Web Applications Once the has been correctly set up to function as a primary key, the next step is to assign this Chapter 20 - XML Web Services DataColumn to the DataTable's PrimaryKey property. You will see how to do in just a bit during the Index discussion of the DataTable, so put this on the back burner for the time being. List of Figures 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# and the .NET Platform, Second Edition myColumn.AutoIncrement = true; by Andrew Troelsen myColumn.AutoIncrementSeed = 500; Apress © 2003 (1200 pages) myColumn.AutoIncrementStep = 12;
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET to developers. Here, the Foo column has been configured ensure 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.
Table of Contents
C# thethe .NET Platform, Edition Toand prove point, insertSecond this DataColumn in a DataTable. Then add a number of new rows to the table, Introduction which of course automatically bumps the value in the Foo column, as shown here: Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET protected void btnAutoCol_Click (object sender, System.EventArgs e) Chapter 2 Building C# Applications { Part Two// - The C# Programming Language Make a data column that
maps to an int.
Chapter DataColumn 3 - C# Language Fundamentals myColumn = new DataColumn(); Chapter myColumn.ColumnName 4 - Object-Oriented Programming with C# = "Foo"; Chapter myColumn.DataType 5 - Exceptions and Object = Lifetime System.Type.GetType("System.Int32");
the auto-increment behavior. Chapter // 6 -Set Interfaces and Collections = true; Chapter myColumn.AutoIncrement 7 - Callback Interfaces, Delegates, and Events = 500; Chapter myColumn.AutoIncrementSeed 8 - Advanced C# Type Construction Techniques myColumn.AutoIncrementStep = Part Three - Programming with .NET Assemblies
12; // Add this column to a new DataTable. Chapter 9 - Understanding .NET Assemblies myTable = new DataTable("MyTable"); Chapter DataTable 10 - Processes, AppDomains, Contexts, and Threads myTable.Columns.Add(myColumn); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming // Add 20 new rows. Part Four - Leveraging the .NET Libraries DataRow r; Chapter 12 - Object Serialization and the .NET Remoting Layer for(int i =0; i < 20; i++) Chapter 13 - Building a Better Window (Introducing Windows Forms) { Chapter 14 - A Better Painting Framework (GDI+) r = myTable.NewRow(); Chapter 15 - Programming with Windows Forms Controls myTable.Rows.Add(r); Chapter } 16 - The System.IO Namespace Chapter // 17 -Now Data list Access the with ADO.NET value in each row. Part Fivestring - Web Applications and XML Web Services temp = ""; Chapter DataRowCollection 18 - ASP.NET Web Pages and Web rows = Controls myTable.Rows; Chapter for(int 19 - ASP.NET Applications i Web = 0;i < myTable.Rows.Count; i++) Chapter { 20 - XML Web Services Index DataRow currRow = rows[i]; List of Figures 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 and the .NET Platform, Second Edition comfortable with C# database terminology), I would like to discuss the ColumnMapping property. The ISBN:1590590554 by Andrew Troelsen DataColumn.ColumnMapping property is used to configure how this column should be represented in Apress © 2003 (1200 pages) XML, if the owning DataSet dumps its contents using the WriteXml() method. The value of the comprehensive textusing startsthe with a brief overview of the ColumnMapping This property is configured MappingType enumeration (Table 17-4). C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 17-4: Values of the MappingType Enumeration MappingType Enumeration
Meaning in Life
Table of Contents Value C# and the .NET Platform, Second Edition
Attribute Introduction
The column is mapped to an XML attribute.
Part One - Introducing C# and the .NET Platform
Element
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
The column is mapped to an XML element (the default).
Hidden Part Two - The C# Programming Language
The column is mapped to an internal structure.
Chapter 3
The column is mapped to text.
- C# Language Fundamentals SimpleContent
Chapter 4
- Object-Oriented Programming with C#
Chapter 5 - Exceptions Object Lifetime property is MappingType.Element. Assume that you have The default value of theand ColumnMapping Chapter 6 Interfaces 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 Interfaces, Delegates, and Events the EmpID appear as shown here: Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 500 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
However, DataColumn's property is set to MappingType.Attribute, you see the Chapter 12 if - the Object Serialization ColumnMapping and the .NET Remoting Layer following representation: Chapter 13 XML - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
ThisFive chapter the and ADO.NET/XML integration Part - Webexamines Applications XML Web Services
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 Controls examination of the related DataRow type. Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML WebThe Services SOURCE DataColumn application is included under the Chapter 17 subdirectory. IndexCODE List of Figures List of Tables
the .NET Platform, Examining C# theandDataRow TypeSecond Edition by Andrew Troelsen
ISBN:1590590554
As you have seen, a collection of DataColumn objects represents the schema of a table. A DataTable Apress © 2003 (1200 pages) maintains its columns using the internal DataColumnCollection type.ofInthe contrast, a collection of DataRow This comprehensive text starts with a brief overview types represents C# thelanguage actual data in the table. Thus, if you have 20 listings and then quickly moves to key technical and in a table named Employees, architectural issues for20 .NET developers. you can represent these entries using DataRow types. Using the members of the DataRow class, you are able to insert, remove, evaluate, and manipulate the values in the table. Table Working of Contents with a DataRow is a bit different from working with a DataColumn, because you cannot create a
direct this type, but rather obtain a reference from a given DataTable. For example, assume C# and instance the .NET of Platform, Second Edition you wish to insert a new row in the Employees table. The DataTable.NewRow() method allows you to Introduction obtain next slot in C# theand table, which point you Part Onethe - Introducing theat .NET Platform
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
Part // Two Build - TheaC# new Programming Table. Language
DataTable empTable = new DataTable("Employees"); Chapter 3 - C# Language Fundamentals // Add FirstName and LastName Chapter 4 EmpID, - Object-Oriented Programming with C# columns to table... ... 5 Chapter
- Exceptions and Object Lifetime // Build a new Employee record. Chapter 6 - Interfaces and Collections
DataRow = empTable.NewRow(); Chapter 7 -row Callback Interfaces, Delegates, and Events row["EmpID"] = 102; - Advanced C# Type Construction Techniques row["FirstName"] = "Joe"; Part Three - Programming with .NET Assemblies row["LastName"] = "Blow"; Chapter 9 - Understanding .NET Assemblies // Add it to the Table's DataRowCollection. Chapter 10 - Processes, AppDomains, Contexts, and Threads empTable.Rows.Add(row); Chapter 8
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter Building a Better Window (Introducing Notice 13 how- the DataRow class defines an indexerWindows that canForms) be used to gain access to a given DataColumn Chapter 14 - A position Better Painting by numerical as wellFramework as column(GDI+) name. Also notice that the DataTable maintains another internal Chapter collection 15 (DataRowCollection) - Programming with Windows to hold Forms each row Controls of data. The DataRow type defines the core members,
grouped functionality, in Table 17-5. Chapter 16by - related The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Table Key Membersand of the Type Part Five17-5: - Web Applications XMLDataRow Web Services Chapter 18 - ASP.NET Web Pages and Web Controls
DataRow Member
Meaning in Life
Chapter 19 - ASP.NET Web Applications
Chapter HasErrors 20 - XML Web Services The HasErrors property returns a Boolean value indicating if there are Index GetColumnsInError()
errors in a columns collection.
List of Figures
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()
Begin, or cancel an edit operation on a DataRow object. C# and the .NETend, Platform, Second Edition
EndEdit()
by Andrew Troelsen Apress © 2003 (1200 pages)
CancelEdit()
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language Thisand method then quickly marks moves this rowtotokey betechnical removedand when the AcceptChanges() architectural issuesisfor .NET developers. method called.
Delete() IsNull() Table of Contents
Gets a value indicating whether the specified column contains a null value.
C# and the .NET Platform, Second Edition Introduction
Understanding the DataRow.RowState Property
Part One - Introducing C# and the .NET Platform
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 Two see the process of inserting, removing, Part - The C# Programming Language
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 - Object-Oriented Programming with C# assigned any value from the DataRowState enumeration (Table 17-6). Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Table 17-6: Values Interfaces, of the DataRowState Enumeration Chapter 7 - Callback Delegates, and Events Chapter 8 - Advanced C# Type Construction DataRowState Meaning in Techniques Life Part Three - Programming with .NET Assemblies Enumeration
Chapter 9 - Understanding .NET Assemblies Value Chapter 10 - Processes, AppDomains, Contexts, and Threads
Added11 - Type Reflection, Late TheBinding, row hasand been added to a DataRowCollection, and Chapter Attribute-Based Programming Part Four - Leveraging the .NETAcceptChanges() Libraries
has not been called.
Chapter 12 - Object Serialization and thehas .NET Remoting Layer Deleted The row been deleted, via the Delete() method of the DataRow. Chapter 13 - Building a Better Window (Introducing Windows Forms)
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 - Programming with Windows Forms Controls before it is added to a collection, or if it has been removed from a Chapter 16 - The System.IO Namespace collection. Chapter 14 - A Better Painting Framework (GDI+)
Chapter 17 - Data Access with ADO.NET
Part Modified Five - Web Applications and The XML rowWeb hasServices been modified,
and AcceptChanges() has not been
called. Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Unchanged
The row has not changed since AcceptChanges() was last called.
Chapter 20 - XML Web Services Index
List Figures the various states a DataRow may have, the following class documents the changes to the To of illustrate 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# and the .NET Platform, Second Edition Console.WriteLine("->Row state: {0}\n", myRow.RowState.ToString()); ISBN:1590590554 by Andrew Troelsen // Now add it to table. Apress © 2003 (1200 pages) Console.WriteLine("Added DataRow to DataTable"); This comprehensive text starts with a brief overview of the myTable.Rows.Add(myRow); C# language and then quickly moves to key{0}\n", technical and Console.WriteLine("->Row state: myRow.RowState.ToString()); architectural issues for .NET developers. // Trigger an accept. Console.WriteLine("Called AcceptChanges() on DataTable"); myTable.AcceptChanges(); Table of Contents Console.WriteLine("->Row state: {0}\n", myRow.RowState.ToString()); C# and the .NET Platform, Second Edition // Modify it. Introduction Console.WriteLine("Modified DataRow"); Part One - Introducing C# and the .NET Platform 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. Part Two - The C# Programming Language Console.WriteLine("Deleted DataRow"); Chapter 3 - C# Language Fundamentals myRow.Delete(); Chapter 4 - Object-Oriented Programming with C#state: {0}\n", myRow.RowState.ToString()); Console.WriteLine("->Row Chapter 5 - Exceptions and Object Lifetime myRow.AcceptChanges(); Chapter } 6 - Interfaces and Collections Chapter 7 - Callback Interfaces, Delegates, and Events } Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
The output be seen in .NET Figure 17-4. Chapter 9 - can Understanding Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Figure Examining row state Chapter 19 - 17-4: ASP.NET Web Applications Chapter 20 - XML Web Services
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 Figures 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. Index
SOURCE CODE
The DataRowState is included under the Chapter 17 subdirectory.
C# and the .NET Platform, Second Edition Details of the DataTable by Andrew Troelsen
ISBN:1590590554
The DataTable isApress an in-memory representation of a tabular block of data. While you can manually © 2003 (1200 pages) compose a DataTable programmatically, you will more commonly This comprehensive text starts with a brief overview 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 moves to key technical and architectural issues for .NET developers.
Table 17-7: Key Members of the DataTable DataTable Table of Contents
Meaning in Life Property C# and the .NET Platform, Second Edition Introduction
CaseSensitive
This property indicates whether string comparisons within the table are case-sensitive (or not). The default value is "false".
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET ChildRelations This property returns the collection of child relations Chapter 2 - Building C# Applications
(DataRelationCollection) Part Two - The C# Programming Language
for this DataTable (if any).
Chapter 3
Columns- C# Language Fundamentals As you have seen, this property returns the collection of columns that - Object-Orientedbelong Programming with C# to this table.
Chapter 4 Chapter 5
- Exceptions and Object Lifetime Constraints Gets the collection of constraints maintained by the table Chapter 6 - Interfaces and Collections Chapter 7
(ConstraintCollection). - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type DataSet GetsConstruction the DataSetTechniques that contains this table (if any). Part Three - Programming with .NET Assemblies
DefaultView GetsAssemblies a customized view of the table that may include a filtered view, or a Chapter 9 - Understanding .NET cursor position.
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection,Gets Late or Binding, and Attribute-Based Programming MinimumCapacity sets the initial number of rows in this table (the default is 25). Part Four - Leveraging the .NET Libraries
ParentRelations
Gets the collection of parent relations for this DataTable.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Forms) PrimaryKey Gets or sets an array ofWindows columns that function as primary keys for the Chapter 14 - A Better Painting Framework data table. (GDI+) Chapter 15 - Programming with Windows Forms Controls
Rows
As you have seen, this property returns the collection of rows that belong to this table.
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part TableName Five - Web Applications Gets and XML or sets Webthe Services name of
the table. This same property may also be
specified as a Controls constructor parameter. Chapter 18 - ASP.NET Web Pages and Web Chapter 19 - ASP.NET Web Applications
To help20visualize the key components of a DataTable, consider Figure 17-5. Be aware that this is not a Chapter - XML Web Services traditional class hierarchy that illustrates the "is-a" relation between these types (e.g., the DataRow does Index notofderive from DataRowCollection). Rather, this diagram points out the logical "has-a" relationships List Figures between the DataTable's core items (e.g., the DataRowCollection has a number of DataRow types). List of Tables
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4 - 17-5: Object-Oriented Programming with C#DataTable Figure The structure of an ADO.NET Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Building a Complete DataTable by Andrew Troelsen
ISBN:1590590554
Now that you have been©exposed the basics, let's see a complete example of creating and manipulating Apress 2003 (1200to pages) an in-memory data table. Assume you are interested building a DataTable representing the current This comprehensive text starts with a in brief overview of the inventory in a database named Cars. The Inventory table will contain four columns: CarID, Make, Color, C# language and then quickly moves to key technical and architectural for will .NETfunction developers. and PetName. Also, the CarIDissues column as 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. Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7 - 17-6: Callback Interfaces, Delegates, and Events Figure The DataTable under construction Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
The process begins by creating a new DataTable type. When you do so, you specify the friendly name of Chapter 9 - Understanding .NET Assemblies 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 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
// Create a new DataTable. Chapter 12 - Object Serialization and the .NET Remoting Layer DataTable inventoryTable = (Introducing new DataTable("Inventory"); Chapter 13 - Building a Better Window Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
The next step is to programmatically insert each column using the Add() method of the
Chapter 16 - The System.IO Namespace DataColumnCollection (accessed using the DataTable.Columns property). The following logic adds the Chapter 17 Data Access with ADO.NET CarID, Make, Color, and PetName columns to the current DataTable (recall that the underlying data type Part Five -column Web Applications Web Services of each is set usingand theXML DataType property):
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
// DataColumn var.
Chapter 20 - XMLmyDataColumn; Web Services DataColumn Index // Create CarID column and add to table. List of Figures 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# and the .NET Platform, Second Edition myDataColumn.DataType = Type.GetType("System.String"); ISBN:1590590554 by Andrew Troelsen myDataColumn.ColumnName = "Color"; Apress © 2003 (1200 pages) inventoryTable.Columns.Add(myDataColumn); This comprehensive textadd startsto with a brief overview of the // Create PetName column and table. C# language and then quickly moves to key technical and myDataColumn = new DataColumn(); architectural issues for .NET developers. myDataColumn.DataType = Type.GetType("System.String"); myDataColumn.ColumnName = "PetName"; myDataColumn.AllowDBNull = true; Table of Contents inventoryTable.Columns.Add(myDataColumn); C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Before you add the rows, you will do well to take 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 Part TwoFor - The Programming Language types. theC# Inventory table, assume the
CarID column is the only aspect of the primary key, as shown
Chapter here: 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5 -the Exceptions and Object // Make ID column theLifetime primary key column. Chapter 6 Interfaces and Collections DataColumn[] PK = new DataColumn[1]; Chapter Callback Interfaces, Delegates, and Events PK[0]7 = -inventoryTable.Columns["CarID"]; Chapter 8 - Advanced C# Type Construction inventoryTable.PrimaryKey = PK; Techniques Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies Last but least, you AppDomains, need to add valid data to the table. Assuming you have an appropriate ArrayList Chapter 10not - Processes, Contexts, and Threads
maintaining Car types, you can the table shown here: Programming Chapter 11 - Type Reflection, Latefill Binding, andas Attribute-Based Part Four - Leveraging the .NET Libraries
// Iterate over the array list fill Layer rows (remember, the ID is Chapter 12 - Object Serialization and the .NETto Remoting // auto-incremented). Chapter 13 - Building a Better Window (Introducing Windows Forms) foreach(Car c in arTheCars) Chapter 14 - A Better Painting Framework (GDI+) { Chapter 15 - Programming with Windows Forms Controls DataRow newRow; newRow = inventoryTable.NewRow(); Chapter 17 - Data Access with ADO.NET newRow["Make"] = c.make; Part Five - Web Applications and XML Web Services newRow["Color"] = c.color; Chapter 18 - ASP.NET Web Pages and Web Controls newRow["PetName"] = c.petName; Chapter 19 - ASP.NET Web Applications inventoryTable.Rows.Add(newRow); Chapter 20 - XML Web Services } Chapter 16 - The System.IO Namespace
Index List of Figures List To of display 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# and the .NET Platform, Second Edition specify the numerical index of the column, which can be very helpful when you need to iterate over each ISBN:1590590554 byprevious Andrew Troelsen column. Thus, the code could be updated as shown here (and still achieve the same end result): Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
foreach(Car cC#in arTheCars) language and then quickly moves to key technical and { architectural issues for .NET developers. // Specify columns by index. DataRow newRow; newRow Table of Contents = inventoryTable.NewRow(); newRow[1] = c.make; C# and the .NET Platform, Second Edition newRow[2] = c.color; Introduction Part OnenewRow[3] - Introducing=C#c.petName; and the .NET Platform inventoryTable.Rows.Add(newRow); Chapter 1 - The Philosophy of .NET } Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
- Object-Oriented Programming with C# Manipulating a DataTable: Deleting Rows
Chapter 4 Chapter 5
- Exceptions and Object Lifetime What if6you- wish to remove a row from a data table? One approach is to call the Delete() method of the Chapter Interfaces and Collections
DataRowCollection SimplyDelegates, specify the index (or DataRow) representing the row to remove. Assume Chapter 7 - Callback type. Interfaces, and Events you update- your GUI as shown in Figure 17-8. Advanced C# Type Construction Techniques
Chapter 8
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - 17-8: Data Access with rows ADO.NET Figure Removing from the DataTable Part Five - Web Applications and XML Web Services
If you look the previous screen shot, will notice that you specified the second row in the DataTable, Chapter 18 -atASP.NET Web Pages and Webyou Controls and therefore CarID 1020 has been marked as deleted. The following logic behind the new Button's Click Chapter 19 - ASP.NET Web Applications event handler removes the specified row from your in-memory DataTable: Chapter 20 - XML Web Services Index
//ofRemove List Figures 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 and the .NET Platform, Second Edition been marked for C# deletion, a DataTable may reject the delete operation via RejectChanges(), as shown ISBN:1590590554 by Andrew Troelsen here: Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
// Mark a rowC#as deleted, but reject the changes. language and then quickly moves to key technical and protected void btnRemoveRow_Click (object sender, System.EventArgs e) architectural issues for .NET developers. { inventoryTable.Rows[(int.Parse(txtRemove.Text))].Delete(); Do more work Table of // Contents ... C# and the .NET Platform, Second Edition inventoryTable.RejectChanges(); // Restore previous RowState value. Introduction } Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Manipulating a DataTable: Applying Filters and Sort Orders
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals You may to see a smallProgramming subset of a DataTable's data, as specified by some sort of filtering criteria. Chapter 4 wish - Object-Oriented with C#
For example, what if you wish to only see a certain make of automobile from the in-memory Inventory Chapter 5 - Exceptions and Object Lifetime table? The method of the DataTable class provides this very functionality. Update your GUI once Chapter 6 - Select() Interfaces and Collections again, this allowing users to specify aand string that represents the make of the automobile they are Chapter 7 -time Callback Interfaces, Delegates, Events interested -inAdvanced viewing (Figure 17-9). The result will be placed into a Windows Forms message box. C# Type Construction Techniques
Chapter 8
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications XML Web Services Figure 17-9: Specifyingand a filter
Chapter 18 - ASP.NET Web Pages and Web Controls
The Select() methodWeb has been overloaded a number of times to provide different selection semantics. At Chapter 19 - ASP.NET Applications its most20basic level, parameter sent to Select() is a string that contains some conditional operation. To Chapter - XML Webthe Services begin, observe the following logic for the Click event handler of your new Button: Index List of Figures
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# and the .NET Platform, Second Edition ISBN:1590590554 by Andrew Troelsen MessageBox.Show(strMake, txtMake.Text + " type(s):"); Apress © 2003 (1200 pages)
}
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
}
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 Table of Contents of DataRow types that represent each row that matches the filter criteria (Figure 17-10). C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Figure 17-10: Filtered data
Chapter - Advanced C# Type Construction Techniques A filter 8string can be composed of any number of relational operators. For example, what if you wanted to Part - Programming with .NET findThree all cars with an ID greater thanAssemblies 1030? You
Chapter 9
could write the following (see Figure 17-11 for output):
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
// Now show the pet names of all cars with ID greater than 1030.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming DataRow[] properIDs; Part Four newFilterStr - Leveraging the .NET Libraries string = "ID > '1030'";
Chapter 12 - Object Serialization and the .NET Remoting Layer properIDs = inventoryTable.Select(newFilterStr); Chapter 13 strIDs - Building=a Better string null;Window (Introducing Windows Forms) Chapter 14 -iA = Better Framework (GDI+) for(int 0; Painting i < properIDs.Length; i++) Chapter 15 - Programming with Windows Forms Controls { Chapter DataRow 16 - The System.IO temp = Namespace properIDs[i];
temp["PetName"] Chapter strIDs 17 - Data += Access with ADO.NET + " is ID + Web temp["ID"] Part Five - Web Applications and"XML Services
+ "\n";
} Chapter 18 - ASP.NET Web Pages and Web Controls MessageBox.Show(strIDs, "Pet names of cars where ID > 1030"); Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition
If you want the results in descending order, call Select(), as shown here: by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
// Return results in descending order. This comprehensive text starts with a brief overview of the makes = inventoryTable.Select(filterStr, "PetName DESC"); C# language and then quickly moves to key technical and architectural issues for .NET developers.
In general, the sort string contains the column name followed by "ASC" (ascending, which is the default) or "DESC" (descending). If need be, multiple columns can be separated by commas. Table of Contents C# and the .NET Platform, Second Edition
Manipulating a DataTable: Updating Rows
Introduction
Part One - Introducing C# and the .NET Platform
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. you have the DataRow(s) Part Two - Once The C# Programming Language
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 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime // Find rowsand you want to edit with a filter. Chapter 6 -the Interfaces Collections
protected void Interfaces, btnChange_Click (object Chapter 7 - Callback Delegates, and Events sender, System.EventArgs e) { Chapter 8
- Advanced C# Type Construction Techniques
//- Programming Build a filter. Part Three with .NET Assemblies filterStr "Make='BMW'"; Chapter string 9 - Understanding .NET=Assemblies string strMake = null; // Find all rows matching the filter. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming DataRow[] makes = inventoryTable. Select(filterStr); Part Four - Leveraging the .NET Libraries // Change all Beemers to Colts! Chapter 12 - Object Serialization and the .NET Remoting Layer for(int i = 0; i < makes.Length; i++) Chapter 13 - Building a Better Window (Introducing Windows Forms) { Chapter 14 - A Better Painting Framework (GDI+) DataRow temp = makes[i]; Chapter 15 - Programming withtemp["Make"] Windows Forms Controls strMake += = "Colt"; Chapter 16 - The System.IO Namespace makes[i] = temp; Chapter } 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services } Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
The DataRow class provides the BeginEdit(), EndEdit(), and CancelEdit() methods, which allow you Chapter 20 - XML Webalso Services to edit the content of a row while temporarily suspending any associated validation rules. In the previous Index logic, each row was validated with each assignment. (Also, if you capture any events from the DataRow, List of Figures
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. }
the .NET Platform, Second Edition Although you areC# freeand to manually call these methods on a given DataRow, these members are by Andrew Troelsen automatically called when you edit a DataGrid widget that has ISBN:1590590554 been bound to a DataTable. For example, 2003 from (1200 pages) when you select aApress row to© edit a DataGrid, that row is automatically placed in edit mode. When you This comprehensive starts with a brief overview of behavior, the shift focus to a new row, EndEdit() is text called automatically. To test this assume you have C# language and then quickly moves to key technical and manually updated each car to be of a given Make using the DataGrid (Figure 17-12). architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime Figure Editing in a DataGrid Chapter 6 - 17-12: Interfaces and rows Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8 -request Advanced Typethe Construction If you now all C# BMWs, message Techniques box correctly returns all rows, as the underlying DataTable Part Three - Programming with .NET Assemblies associated to the DataGrid has been automatically updated
Chapter 9
(Figure 17-13).
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Figure The updated set of BMW autos Chapter 18 - 17-13: ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform, Type Second Edition Understanding DataView by Andrew Troelsen
ISBN:1590590554
In database nomenclature, a view object is a stylized representation of a table. For example, using Apress © 2003 (1200 pages) Microsoft SQL Server, you could create view for current Inventory This comprehensive textastarts withyour a brief overview of thetable that returns a new table only containing automobiles of a given color. In ADO.NET, the DataView C# language and then quickly moves to key technical type and allows you to programmatically architectural issues for .NET developers. extract a subset of data from the DataTable. One great advantage of holding multiple views of the same table is that you can bind these views to Table various of Contents GUI widgets (such as the DataGrid). For example, one DataGrid might be bound to a DataView
showing autos in the Inventory, while another may be configured to display only green automobiles. On C# and theall .NET Platform, Second Edition a related note, the DataTable type provides the DefaultView property that returns the default DataView for Introduction the One table. Part - Introducing C# and the .NET Platform 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 Part Two - The C# Programming Language 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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - 17-14: XML Web Services Figure Creating multiple views for a single DataTable Index List of Figures
To of begin, 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# and the .NET Platform, Second Edition MakeTable(); ISBN:1590590554 Andrew Troelsen // Make by views. Apress © 2003 (1200 pages) CreateViews(); This comprehensive text starts with a brief overview of the ... C# language and then quickly moves to key technical and architectural issues for .NET developers.
}
Table of Contents
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 the .NET Platform, Second Edition Introduction
Part One - Introducing C# and the .NET Platform
private void CreateViews() - The Philosophy of .NET { Chapter 2 - Building C# Applications // Set the table that is used to construct these views. Part Two - The C# Programming Language redCarsView = new DataView(inventoryTable); Chapter 3 - C# Language Fundamentals coltsView = new DataView(inventoryTable); Chapter // 4 -Now Object-Oriented Programming withusing C# configure the views a filter. Chapter redCarsView.RowFilter 5 - Exceptions and Object Lifetime = "Color = 'red'"; Chapter coltsView.RowFilter 6 - Interfaces and Collections = "Make = 'colt'"; Chapter // 7 -Bind Callback toInterfaces, grids. Delegates, and Events Chapter RedCarViewGrid.DataSource 8 - Advanced C# Type Construction = Techniques redCarsView; Part Three - Programming with .NET Assemblies ColtsViewGrid.DataSource = coltsView; Chapter } 9 - Understanding .NET Assemblies Chapter 1
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
As you see, the DataView class supports Part Fourcan - Leveraging the .NET Libraries
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 - Object Serialization and the .NET Remoting Layer the grid's DataSource property accordingly. That's it! Because DataGrids are smart enough to detect Chapter 13 - Building a Better Window (Introducing Windows Forms) changes to their underlying data source, if you click the Make Beemers Colts button, the ColtsViewGrid is Chapter 14 - A Better Painting Framework (GDI+) updated automatically. Chapter 15 - Programming with Windows Forms Controls
Chapter 16 -toThe In addition theSystem.IO RowFilter Namespace property, Table 17-8 describes some other members of the DataView class. Chapter 17 - Data Access with ADO.NET Part Five17-8: - Web Applications andDataView XML Web Services Table Members of the Type
Chapter 18 - ASP.NET Web Pages and Web Controls
DataView Member
Meaning in Life
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index AddNew() List of Figures
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# andthe the .NET Platform, Edition Understanding Role of theSecond DataSet by Andrew Troelsen
ISBN:1590590554
You have been examining how(1200 to build Apress © 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 comprehensiveastext starts withentities, a brief overview the typically contained in a DataSet. Simply put, a DataSet is an in-memory representation of any number of C# language and then quickly moves to key technical and tables (which may be just a single architectural issues for .NET developers. 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. Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5 - 17-15: Exceptions Objectof Lifetime Figure Theand anatomy a DataSet Chapter 6 - Interfaces and Collections
The Tables propertyInterfaces, of the DataSet allowsand youEvents to access the DataTableCollection that contains the Chapter 7 - Callback Delegates, individual Another important collection used by the DataSet is the DataRelationCollection. Chapter 8 DataTables. - Advanced C# Type Construction Techniques Given that- aProgramming DataSet is awith disconnected version Part Three .NET Assemblies
of a database schema, it can programmatically represent the parent/child relationships between its tables. Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, 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 Part Four - Leveraging the .NET Libraries property. At this point, you can navigate between the connected tables as you search for data. You will see Chapter 12 - Object Serialization and the .NET Remoting Layer how this is done a bit later in the chapter. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter The ExtendedProperties 14 - A Better Painting property Framework provides (GDI+) access to the PropertyCollection type, which allows you to
associate extra information to the DataSet as name/value pairs. This information can literally be Chapter 15 any - Programming with Windows Forms Controls anything if it hasNamespace no bearing on the data itself. For example, you can associate your company's Chapter 16at- all, Theeven System.IO name to which can then function as in-memory metadata, as shown here: Chapter 17a-DataSet, Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter // Make 18 -aASP.NET DataSet Weband Pagesadd and some Web Controls metadata.
DataSet = new DataSet("MyDataSet"); Chapter 19 -ds ASP.NET Web Applications ds.ExtendedProperties.Add("CompanyName", "Intertech, Inc"); Chapter 20 - XML Web Services // Print out the metadata. Index Console.WriteLine(ds.ExtendedProperties["CompanyName"].ToString()); List of Figures 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
Meaning in Life C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Indicates whether string comparisons in DataTable objects are case
This comprehensive text starts with a brief overview of the sensitive (or not). C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents 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 the .NET Platform, Second Edition
EnforceConstraints
Introduction
Gets or sets a value indicating whether constraint rules are followed when attempting any update operation.
Part One - Introducing C# and the .NET Platform
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
Part Two - The C# Programming Language
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
- Object-Oriented Programming with C# Tables Provides access to the collection of tables maintained by the DataSet. Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections The methods of the DataSet mimic some and of the functionality provided by the aforementioned properties. In Chapter 7 - Callback Interfaces, Delegates, Events
addition8 to-interacting withType XMLConstruction streams, other methods exist to allow you to copy the contents of your Chapter Advanced C# Techniques DataSet, well as establish and Part Three as - Programming with the .NETbeginning Assemblies
ending points of a batch of updates. Table 17-10
describes core methods. Chapter 9 -some Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
Table 17-10: Methods of the Mighty DataSet
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging Librariesin DataSet Method the .NET Meaning
Life
Chapter 12 - Object Serialization and the .NET Remoting Layer
AcceptChanges() Commits the changes made Forms) to this DataSet since it was loaded or the Chapter 13 - Building a Better Window all (Introducing Windows last time AcceptChanges() was called. Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windowsclears Forms the Controls Clear() Completely DataSet data by removing every row in each Chapter 16 - The System.IO table. Namespace Chapter 17 - Data Access with ADO.NET
Clone()
Clones the structure of the DataSet, including all DataTables, as well as all relations and any constraints.
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications Copy() Copies both the structure and data for this DataSet. Chapter 20 - XML Web Services
GetChanges()
Index
List of Figures 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# and the .NET Platform, Second Edition one), let's run through some specifics. Once this discussion of the ADO.NET DataSet is complete, the ISBN:1590590554 Andrew Troelsen remaining bulk ofby this chapter will focus on how to obtain DataSet types from external sources (such as a Apress © 2003 (1200 pages) relational database) using the types defined by the System.Data.SqlClient and System.Data.OleDb namespaces. This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Building an In-Memory DataSet Table To illustrate of Contents the use of a DataSet, create a new Windows Forms application that maintains a single
DataSet, threeSecond DataTable objects named Inventory, Customers, and Orders. The columns for C# and thecontaining .NET Platform, Edition each table will be minimal but complete, with one column marking the primary key for each table. Most Introduction importantly, you can model relationships between Part One - Introducing C# andthe theparent/child .NET Platform
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
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging theCars .NETdatabase Libraries Figure 17-16: The
Chapter 12 - Object Serialization and the .NET Remoting Layer
Here, the is the parent(Introducing table to theWindows Orders table, Chapter 13 Inventory - Building table a Better Window Forms)which maintains a foreign key (CarID) column. the Customers table is the(GDI+) parent table to the Orders table. (Again note the foreign key, Chapter 14Also, - A Better Painting Framework CustID.) you will soon with see, Windows when youForms add DataRelation types to your DataSet, they may be used to Chapter 15As - Programming Controls navigate the tables to obtain and manipulate the related data. Chapter 16between - The System.IO Namespace Chapter 17 - Data Access with 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:
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
public class mainForm : System.Windows.Forms.Form { Index // Inventory DataTable. List of Figures 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 Services
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# and the .NET Platform, Edition public string petName, make,Second color; by Andrew Troelsen public Car(string petName, string make, ISBN:1590590554 string color) Apress © 2003 (1200 pages) { This comprehensive text starts with a brief overview of the this.petName = petName; C# language and then quickly moves to key technical and this.color = color; architectural issues for .NET developers. this.make = make; } }
Table of Contents C# and the .NET Platform, Second Edition
public class Customer { Part One - Introducing C# and the .NET Platform public Customer(string fName, string lName, int currentOrder) Chapter 1 - The Philosophy of .NET { Chapter 2 - Building C# Applications this.firstName= fName; Part Two - The C# Programming Language this.lastName = lName; Chapter 3 - C# Language Fundamentals = currentOrder; this.currCarOrder Chapter } 4 - Object-Oriented Programming with C# Chapter // 5 -Make Exceptions and Object Lifetime public for easy access. Chapter public 6 - Interfaces and Collections string firstName, lastName; Chapter public 7 - Callback Delegates, and Events intInterfaces, currCarOrder; Chapter } 8 - Advanced C# Type Construction Techniques Introduction
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies The main maintains two ArrayList types and thatThreads hold a set of cars and customers, which are populated Chapter 10 Form - Processes, AppDomains, Contexts,
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 Part Four - Leveraging the .NET Libraries and Customer DataTables to their corresponding DataGrid widgets. Notice that the following code binds a Chapter 12 - Object Serialization and the .NET Remoting Layer given DataTable in the DataSet using the SetDataBinding() method: Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
// Your list of Cars and Customers. private ArrayList arTheCars, arTheCustomers;
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
public mainForm() { Chapter 18 - ASP.NET Web Pages and Web Controls // Fill the car array list with some cars. Chapter 19 - ASP.NET Web Applications arTheCars = new ArrayList(); Chapter arTheCars.Add(new 20 - XML Web Services Car("Chucky", "BMW", "Green")); Index ... List of Figures // Fill 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"); } Part Five - Web Applications and XML Web Services
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# and the .NET Platform, Second Edition each table is assigned a primary key that is autoincremented. Here is some partial table-building logic ISBN:1590590554 by Andrew (check out the source code Troelsen for complete details): Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
private void C# MakeOrderTable() language and then quickly moves to key technical and { architectural issues for .NET developers. ... // Add table to the DataSet. carsDataSet.Tables.Add(customersTable); Table of Contents // .NET Create OrderID, CustID, CarID columns and add to table... C# and the Platform, Second Edition // Make the ID column the primary key column... Introduction // Add some orders. Part One - Introducing C# and the .NET Platform i = 0; ofi .NET < arTheCustomers.Count; i++) Chapter for(int 1 - The Philosophy { Chapter 2 - Building C# Applications DataRow newRow; Part Two - The C# Programming Language newRow = ordersTable.NewRow(); Chapter 3 - C# Language Fundamentals Customer c = (Customer)arTheCustomers[i]; Chapter 4 - Object-Oriented Programming with C# newRow["CustID"] = i; Chapter 5 - Exceptions and Object Lifetime newRow["CarID"] = c.currCarOrder; Chapter 6 - Interfaces and Collections carsDataSet.Tables["Orders"].Rows.Add(newRow); Chapter 7 - Callback Interfaces, Delegates, and Events } Chapter 8 - Advanced C# Type Construction Techniques } Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter The MakeInventoryTable() 10 - Processes, AppDomains, and MakeCustomerTable() Contexts, and Threads helper functions behave almost identically (again,
check source code for full details). Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NETUsing Platform,the Second Edition ExpressingC#Relations DataRelation Type by Andrew Troelsen
ISBN:1590590554
The really interesting work happens in the BuildTableRelationship() helper function. Once a DataSet has Apress © 2003 (1200 pages) been populated with a number of tables, you can optionally chooseof to the programmatically model their This comprehensive text starts with a brief overview parent/child relationships. Be aware that this is not mandatory. You can C# language and then quickly moves to key technical andhave a DataSet that does little else architectural issues for .NET developers. than hold a collection of DataTables in memory (even 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 Table of Contents the data source. C# and the .NET Platform, Second Edition
The System.Data.DataRelation type is an OO wrapper around a table-to-table relationship. When you Introduction create DataRelation type, specify a friendly name, Part Onea- new Introducing C# and the .NET Platform
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 is basically bound by the sameLanguage rules as a Part Two - The C# Programming
relational database. Here is the complete implementation of the
BuildTableRelationship() helper function: Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
private BuildTableRelationship() Chapter 5 -void Exceptions and Object Lifetime { Chapter 6
- Interfaces and Collections a DataRelation Chapter // 7 -Create Callback Interfaces, Delegates, obj. and Events
DataRelation dr = new DataRelation("CustomerOrder", - Advanced C# Type Construction Techniques carsDataSet.Tables["Customers"].Columns["CustID"], Part Three - Programming with .NET Assemblies carsDataSet.Tables["Orders"].Columns["CustID"]); Chapter 9 - Understanding .NET Assemblies // Add to the DataSet. Chapter 10 - Processes, AppDomains, Contexts, and Threads carsDataSet.Relations.Add(dr); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming // Create another DataRelation obj. Part Four - Leveraging the .NET Libraries dr = new DataRelation("InventoryOrder", Chapter 12 - Object Serialization and the .NET Remoting Layer carsDataSet.Tables["Inventory"].Columns["CarID"], Chapter 13 - Building a Better Window (Introducing Windows Forms) carsDataSet.Tables["Orders"].Columns["CarID"]); Chapter // 14 -Add A Better Framework (GDI+) to Painting the DataSet. Chapter carsDataSet.Relations.Add(dr); 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace } Chapter 8
// Parent. // Child.
// Parent. // Child.
Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
As you 18 can- see, a given is held in the DataRelationCollection maintained by the DataSet. Chapter ASP.NET WebDataRelation Pages and Web Controls The DataRelation type offers a number of properties that allow you to obtain a reference to the child Chapter 19 - ASP.NET Web Applications and/or 20 parent table that is participating in the relationship, specify the name of the relationship, and so on, Chapter - XML Web Services and these are listed in Table 17-11.
Index
List of Figures
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# and the .NET Platform, Second Edition
Navigating by Between Related Tables Andrew Troelsen
ISBN:1590590554
Apress © 2003 (1200 pages)
To illustrate how a DataRelation allows you to move between related tables, extend your GUI to include a This comprehensive text starts with a brief overview 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 moves the information about that customer's which is placed in a simple message box (Figure 17-17). The architectural issues fororder, .NET developers. Button's Click event handler is as shown here (error checking removed for clarity): Table of Contents protected void btnGetInfo_Click (object sender, System.EventArgs e) C# and the .NET Platform, Second Edition { Introduction string strInfo = ""; Part OneDataRow - Introducing C# and=the .NET Platform drCust null;
Chapter DataRow[] 1 - The Philosophy of .NET= null; drsOrder Chapter // 2 -Get Building C# Applications the specified CustID from the TextBox. Part Twoint - ThetheCust C# Programming Language = int.Parse(this.txtCustID.Text);
Chapter // 3 -Now C# Language based on Fundamentals CustID, get the correct row in Customers table.
= carsDataSet.Tables["Customers"].Rows[theCust]; Chapter drCust 4 - Object-Oriented Programming with C# += "Cust #" Lifetime + drCust["CustID"].ToString() + "\n"; Chapter strInfo 5 - Exceptions and Object from customer table to order table. Chapter // 6 -Navigate Interfaces and Collections drCust.GetChildRows(carsDataSet.Relations["CustomerOrder"]); Chapter drsOrder 7 - Callback=Interfaces, Delegates, and Events order Chapter // 8 -Get Advanced C# number. Type Construction Techniques foreach(DataRow inAssemblies drsOrder) Part Three - Programming withr.NET strInfo += "Order Number: " + r["OrderID"] + "\n"; - Understanding .NET Assemblies // Now navigate from order table to inventory table. Chapter 10 - Processes, AppDomains, Contexts, and Threads DataRow[] drsInv = Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming drsOrder[0].GetParentRows(carsDataSet.Relations["InventoryOrder"]); Part Four - Leveraging the .NET Libraries // Get Car info. Chapter 12 - Object Serialization and the .NET Remoting Layer foreach(DataRow r in drsInv) Chapter 13 - Building a Better Window (Introducing Windows Forms) { Chapter 14 - A strInfo Better Painting += Framework "Make: "(GDI+) + r["Make"] + "\n"; Chapter 15 - Programming with Windows Forms Controls strInfo += "Color: " + r["Color"] + "\n"; Chapter 16 - The System.IO Namespace strInfo += "Pet Name: " + r["PetName"] + "\n"; Chapter } 17 - Data Access with ADO.NET Part FiveMessageBox.Show(strInfo, - Web Applications and XML Web Services "Info based on cust ID"); Chapter 18 - ASP.NET Web Pages and Web Controls } Chapter 9
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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); the .NETget Platform, Second Edition // Now based C# onand CustID, the correct row in the Customers table. ISBN:1590590554 by Andrew Troelsen DataRow drCust = null; Apress © 2003 (1200 pages) drCust = carsDataSet.Tables["Customers"].Rows[theCust]; This comprehensive text starts with a brief overview of+the strInfo += "Cust #" + drCust["CustID"].ToString() "\n"; C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 the .NET Platform, Second Edition you do, you can read information out of the table, as shown here:
Table of Contents Introduction
Part One - Introducing C# and the .NET Platform
// 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"]); Part Two - The C# Programming Language // Get order number. Chapter 3 - C# Language Fundamentals foreach(DataRow r in drsOrder) Chapter 4 -+= Object-Oriented Programming C# strInfo "Order Number: " + with r["OrderID"] + "\n"; Chapter 1
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections Your final is to navigate from the Orders to its parent table (Inventory), using the Chapter 7 step - Callback Interfaces, Delegates, andtable Events
GetParentRows() method. At this point, youTechniques can read information from the Inventory table using the Make, Chapter 8 - Advanced C# Type Construction PetName, Color columns, as shown here: Part Three - and Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
Chapter // Now 10 navigate - Processes, from AppDomains, orderContexts, table and to Threads inventory table.
DataRow[] drsInv = Late Binding, and Attribute-Based Programming Chapter 11 - Type Reflection, Part Four drsOrder[0].GetParentRows(carsDataSet.Relations["InventoryOrder"]); - Leveraging the .NET Libraries
foreach(DataRow r in drsInv) Chapter 12 - Object Serialization and the .NET Remoting Layer { Chapter 13 - Building a Better Window (Introducing Windows Forms) +=Painting "Make: " + r["Make"] + "\n"; Chapter strInfo 14 - A Better Framework (GDI+) += "Color: " + r["Color"] Chapter strInfo 15 - Programming with Windows Forms Controls + "\n"; strInfo += "Pet Name: " + r["PetName"] + "\n";
Chapter 16 - The System.IO Namespace
}
Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 example - ASP.NETofWeb Pages and Web Controls As a final navigating relations programmatically, the following code prints out the values in the Chapter - ASP.NET Web Applications Orders19 table that is obtained indirectly using the InventoryOrders relationship: Chapter 20 - XML Web Services Index
protected void btnGetChildRels_Click (object sender, System.EventArgs e)
List { of Figures 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# and the .NET info Platform, += Second "\t" +Edition arrRows[i][dc]; ISBN:1590590554 by Andrew } Troelsen Apress © 2003 (1200 pages) info += "\n"; This}comprehensive text starts with a brief overview of the } C# language and then quickly moves to key technical and architectural issues for .NET developers.
MessageBox.Show(info, "Data in Orders Table obtained by child relations");
}
Table of Contents
}
C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Figure 17-18 shows the output.
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies Figure Navigating parent/child relations Chapter 10 - 17-18: Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer and navigate around each table to make any necessary updates, deletes, or inserts. Once this is done, Chapter 13 - Building a Better Window (Introducing Windows Forms) 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 Better (GDI+) connected! is Painting one finalFramework item of interest regarding the DataSet before addressing this issue. Part Four - Leveraging the .NET Libraries
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# Writing and the .NET Platform, Second Edition Reading and XML-Based DataSets by Andrew Troelsen
ISBN:1590590554
A major design goal of ADO.NET to apply a liberal use of XML infrastructure. Using the DataSet type, Apress © 2003 (1200was pages) you can write an This XMLcomprehensive representationtext of the contents your tables, of relations, and other schematic details starts with a of brief overview the to a given streamC# (such as a file). To do so, simply call the WriteXml() method, as shown here: language and then quickly moves to key technical and architectural issues for .NET developers.
protected void btnToXML_Click (object sender, System.EventArgs e) { Table of Contents // Write your entire DataSet to a file in the app directory. C# and the .NET Platform, Second Edition carsDataSet.WriteXml("cars.xml"); Introduction MessageBox.Show("Wrote CarDataSet to XML file in app directory"); Part One - Introducing C# and the .NET Platform btnReadXML.Enabled = true; Chapter 1 - The Philosophy of .NET } Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals If you now your new file in the Visualwith Studio Chapter 4 -open Object-Oriented Programming C# .NET IDE (Figure 17-19), you will see that the entire
DataSet been transformed to Lifetime XML. Chapter 5 has - Exceptions and Object Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Figure 17-19: The Cars database as XML
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
To test the ReadXml() method of the DataSet, perform a little experiment. The CarDataSet application has
Chapter 19that - ASP.NET Web a Button will clear outApplications the current DataSet completely (including all tables and relations). After the inChapter 20 XML Web Services memory representation has been gutted, instruct the DataSet to read in the cars.xml file, which as you Index would guess restores the entire DataSet, as shown here: List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5 - 17-20: Exceptions Lifetime Figure Theand finalObject GUI update Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
In addition the abilityC# toType persist the contents of a DataSet as XML, be aware that the WriteXmlSchema() Chapter 8 -toAdvanced Construction Techniques and ReadXmlSchema() methods may also be Part Three - Programming with .NET Assemblies 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 - Understanding .NET Assemblies you are able to manipulate the contents using the types of the System.Xml.dll assembly (see Chapter 18). Chapter 10 - Processes, AppDomains, Contexts, 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 Attribute-Based Programming and/or tweak the type definitions using VS .NET (Figure 17-21). Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 17-21: The Cars XML schema file SOURCE CODE
The CarDataSet application is included under the Chapter 17 subdirectory.
C# and theTest .NET Platform, Second Edition Building a Simple Database by Andrew Troelsen
ISBN:1590590554
Now that you understand how(1200 to create Apress © 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 comprehensive text starts withhow a brief overview 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 moves to key technical and architectural issues the for .NET developers. sample Cars database that models Inventory, Orders, and Customers tables examined during the chapter. Table The of first Contents version is a SQL script that builds the tables (including their relationships) and is intended for
users 7.0 Second (and greater). C# and of theSQL .NETServer Platform, 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 Introduction the One script, be sure thatC# the path the SQL Part - Introducing and thelisted .NET in Platform
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 Part Two - The C# Programming Language
CREATE [Cars] ON (NAME = N'Cars_Data', FILENAME Chapter 3 DATABASE - C# Language Fundamentals =N'C:\MSSQL7\Data \Cars_Data.MDF' , Chapter 4 - Object-Oriented Programming with C# SIZE = FILEGROWTH = 10%) Chapter 5 2, - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections LOG ON = Interfaces, N'Cars_Log', FILENAME Chapter 7 (NAME - Callback Delegates, and Events
= N' C:\MSSQL7\Data\Cars_Log.LDF' , - Advanced C# Type Construction Techniques SIZE = 1, FILEGROWTH = 10%) Part Three - Programming with .NET Assemblies GO Chapter 8 Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11your - Type Reflection, Latedo, Binding, andthe Attribute-Based Programming Now run script. Once you open up SQL Server Enterprise Manager. You should see the Cars Part Four - Leveraging the .NET Libraries database with all three interrelated tables
(with some sample data to boot) as well as a single stored
Chapter 12 - Object Serialization and the .NET Remoting Layer procedure. Chapter 13 - Building a Better Window (Introducing Windows Forms)
The second of the Cars database is for users of MS Access. Under the Access DB folder you will Chapter 14 - Aversion Better Painting Framework (GDI+) find the15 cars.mdb file, which same information and underlying structure as the SQL Server Chapter - Programming withcontains Windowsthe Forms Controls version.16During remainder of this chapter, I will assume that you are connecting to the SQL Server Chapter - The the System.IO Namespace
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. Part Five - Web Applications and XML Web Services Chapter 17 - Data Access with ADO.NET
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Selecting aC# Data Provider by Andrew Troelsen
ISBN:1590590554
As mentioned earlier in © this chapter, .NET 1.1 ships with five data providers. The first of these is the OleDb Apress 2003 (1200 pages) data provider, which is composed of the types in the System.Data.OleDb namespace. The OleDb This comprehensive text starts defined with a brief overview 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 moves to key technical and architectural issues for .NET Thus, like with classic ADO, you may use thedevelopers. ADO.NET data provider to access SQL Server, Oracle, or 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 Table of Contents translations occur behind the scenes, which can affect performance. By and large, this namespace is C# and the .NET Second to Edition useful when youPlatform, are attempting communicate with a data source that does not have a specific data Introduction provider assembly. Part One - Introducing C# and the .NET Platform
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 SQLTwo provider andProgramming provides the Language same functionality Part - The C#
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 - Object-Oriented Programming with C# Chapter 5 interested - Exceptions Object If you are in and making useLifetime of the System.Data.Oracle, System.Data.Odbc, or Chapter 6 Interfaces and Collections System.Data.SqlServerCe namespaces, I will assume you will check out the details as you see fit. Chapter 7 as - Callback Interfaces, Delegates, and Events However, you would hope, once you are comfortable with one data provider, you can easily manipulate Chapter 8 - Advanced Type Construction Techniques other providers. RecallC# that while the exact names of the types will differ between namespaces (for Part Three -OleDbConnection Programming withvs. .NET Assemblies example, SqlConnection
vs. OdbcConnection), semantically related types can be
Chapter Understandingmanner .NET Assemblies treated9in a- polymorphic given the IDbCommand, IDbConnection, IDbDataAdapter, and Chapter IDataReader 10 - Processes, interfacesAppDomains, et al. Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
To begin, we'll examine connect Part Four - Leveraging thehow .NETto Libraries
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 - Object Serialization and the .NET Remoting Layer System.Data.dll assembly): Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
// Using the OleDb with data provider. Chapter 15 - Programming Windows Forms Controls using System.Data; using System.Data.OleDb;
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 have - ASP.NET Webout Pages Web Controls Once we checked howand to interact with a data store using the OleDb data provider, we will see Chapter - ASP.NET Webtypes Applications how to 19 make use of the within the System.Data.SqlClient namespace. Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and .NET Platform, Second Edition The Types of thethe System.Data.OleDb Namespace by Andrew Troelsen
ISBN:1590590554
Table 17-12 provides a© walkthrough of the core types of the System.Data.OleDb namespace. Note that Apress 2003 (1200 pages) each type sports This an "OleDb-" prefix. comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and issues for .NET developers. Table 17-12: Keyarchitectural Types of the System.Data.OleDb Namespace
System.Data.OleDb Type Table of Contents
Meaning in Life
C# and the .NET Platform, Second Edition
OleDbCommand
Introduction
Represents a SQL query command to be made to a data source.
Part OleDbConnection One - Introducing C# and the .NET Represents Platforman
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.
Part Two - The C# Programming Language
OleDbDataReader Provides a way of reading a forward-only stream of data records Chapter 3 - C# Language Fundamentals Chapter 4
from a data - Object-Oriented Programming with source. C#
Chapter 5
- Exceptions and Object Lifetime OleDbErrorCollection OleDbErrorCollection maintains a collection of warnings or errors - Interfaces and Collections returned by the data source, each of which is represented by an OleDbError Chapter 7 - Callback Interfaces, Delegates, andtype. Events OleDbError When an error is encountered, an exception of OleDbException Chapter 8 - Advanced C# Type Construction Techniques is thrown. type OleDbException Chapter 6
Part Three - Programming with .NET Assemblies
OleDbParameterCollection Much like classic ADO, the OleDbParameterCollection collection Chapter 9 - Understanding .NET Assemblies holds onto the parameters sent to a stored procedure in the database. Each parameter is of type OleDbParameter.
OleDbParameter Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and .NET Platform, Layer Second Edition Working with thetheConnected of ADO.NET by Andrew Troelsen
ISBN:1590590554
The first step to take when working with the OleDb data provider is to establish a session with the data source Apress © 2003 (1200 pages) using the OleDbConnection type (which, as youwith recall, implements IDbConnection interface). Much like the This comprehensive text starts a brief overview the of the classic ADO Connection object, OleDbConnection types are provided with C# language and then quickly moves to key technical and a formatted connection string, architectural issues for .NET developers. containing a number of name/value pairs separated by semicolons. This information is used to identify the name 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 Table of Contents name/value pair.) C# and the .NET Platform, Second Edition
The connection string may be set using the OleDbConnection.ConnectionString property or including it as a Introduction constructor argument.C# Assume wish to connect Part One - Introducing and theyou .NET Platform
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
Part // Two Build - TheaC# connection Programming string. Language
OleDbConnection cn Fundamentals = new OleDbConnection(); Chapter 3 - C# Language cn.ConnectionString "Provider=SQLOLEDB.1;" + Chapter 4 - Object-Oriented = Programming with C# ID=sa;Pwd=;Initial Chapter "User 5 - Exceptions and Object Lifetime Catalog=Cars;" + Source=(local);"; Chapter "Data 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction 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 - Understanding .NET Assemblies name of the machine that maintains the database (for simplicity, I have assumed no specific password is required Chapter 10system - Processes, AppDomains, and for local administrators). TheContexts, final point of Threads interest is the Provider segment, which specifies the name of Chapter 11 Type Reflection, Late Binding, and Attribute-Based Programming the OLE DB provider that will be used to access the data store. Table 17-13 describes some possible values. Part Three - Programming with .NET Assemblies
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object and the .NET Remoting Layer Table 17-13: CoreSerialization OLE DB Providers Chapter 13 - Building a Better Window (Introducing Windows Forms)
Provider Segment Meaning in Life Chapter 14 - A Better Painting Framework (GDI+) Value
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Microsoft.JET.OLEDB.4.0 You want to use the Jet OLE DB provider to connect to an Access Chapter 17 - Data Access with ADO.NET database. Part Five - Web Applications and XML Web Services
MSDAORA YouWeb wantControls to use the OLE DB provider for Oracle. Chapter 18 - ASP.NET Web Pages and Chapter 19 - ASP.NET Web Applications SQLOLEDB You want to use the OLE DB provider for MS SQL Server. Once you have Chapter 20 - XML Web Services configured the connection string, the next step is to open a session with Index List of Figures
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 settings and transactional information. Table 17-14 gives a partial rundown.
Table 17-14: Members of the OleDbConnection Type
C# and the .NET Platform, Second Edition
OleDbConnection Meaning in Life by Andrew Troelsen Member Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the
BeginTransaction() Used to programmatically commit, abort, or roll back a transaction. C# language and then quickly moves to key technical and architectural issues for .NET developers. CommitTransaction()
RollbackTransaction() Table of Contents Close()
Closes the connection to the data source.
C# and the .NET Platform, Second Edition
ConnectionString
Introduction
Gets or sets the string used to open a session with a data store.
Part One - Introducing C# and theThis .NETread-only Platform ConnectionTimeout
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
Part Two - The C# Programming Language "Connect
Timeout" segment in the connection string (e.g., Connect Timeout=30). Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
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 - Interfaces and Collections Chapter 7
and Events Open() - Callback Interfaces, Delegates, Opens a database connection with the current property settings.
Chapter 8
- Advanced C# Type Construction Techniques
GetOleDbSchemaTable() Obtains schema Part Three - Programming with .NET Assemblies
information from the data source.
Chapter 9
Provider - Understanding .NET Assemblies Gets the name of the provider maintained by the connection object.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
State 11 - Type Reflection, Late Gets the and current state of the Programming connection, represented by the Chapter Binding, Attribute-Based ConnectionState enumeration. Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
As you can see, the properties of the OleDbConnection type are typically read-only in nature, and are only useful when you wish to obtain the characteristics of a connection at runtime. When you wish to override default Chapter 15 - Programming with Windows Forms Controls settings, you must alter the construction string itself. For example, ponder the following code, which changes the Chapter - The System.IO default 16 connection timeout Namespace setting from 15 seconds to 30 seconds (via the Connect Timeout segment of the Chapter 17 Data Access with ADO.NET connection string): Chapter 14 - A Better Painting Framework (GDI+)
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
OleDbConnection cn = new OleDbConnection(); cn.ConnectionString = "Provider=SQLOLEDB.1;" + Chapter "User 20 - XMLID=sa;Pwd=;Initial Web Services Catalog=Cars;" + Index "Data Source=(local);Connect Timeout=30"; List of Figures 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 Applications
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, and the .NET Platform, Second Edition Fetching,C#Open by Andrew Troelsen Apress © 2003 (1200 pages)
}
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quicklyof moves toakey technical type and if it is currently in the process of While it may be enticing to ponder the notion asking connection architectural issues for .NET developers. 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, Table of Contents understand that it is always safe to close a connection whose connection state is currently C# and the .NET Platform, Second Edition ConnectionState.Closed. Introduction
Part One - Introducing C# and the .NET Platform
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 - Object-Oriented Programming with C# shown 4here: Part Two - The C# Programming Language
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
// Be sure to update the data source segment if necessary! - Callback Interfaces, Delegates, and Events OleDbConnection cn = new OleDbConnection(); Chapter 8 - Advanced C# Type Construction Techniques cn.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0;" + Part Three - Programming with .NET Assemblies @"data source = C:\cars.mdb"; Chapter 9 - Understanding .NET Assemblies cn.Open(); Chapter 7
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Once the- Leveraging connection the has.NET beenLibraries made, you Part Four
can read and manipulate the contents of your data table.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Obtaining Database Schema Information Using Connection Types
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Connection objects can also used toForms obtainControls schema information from a given database through the Chapter 15 - Programming withbe Windows GetOleDbSchemaTable() As you are most likely aware, "schema information" is little more than Chapter 16 - The System.IO method. Namespace metadata describes the database Chapter 17 that - Data Access with ADO.NET itself, rather than the tabular data it is maintaining. The GetOleDbSchemaTable() two parameters, Part Five - Web Applications method and XMLtakes Web Services
the first of which is a member of the
OleDbSchemaGuid type. This typeControls exposes a number of read-only fields that map to the sort of metadata Chapter 18 - ASP.NET class Web Pages and Web you are19 interested in Web obtaining (table names, stored procedure names, views, and whatnot). Chapter - ASP.NET Applications Chapter 20 - XML Web Services
The second parameter is an array of System.Object types that represents what (if any) restrictions should be
Index placed on the schema information returned by the call. Be aware that the exact format of this array of List of Figures 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# and the .NET Platform, Second Edition
}
by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
As you will see, itThis is also possible to obtain schema for a specific table in a database using data reader comprehensive text starts with details a brief overview of the C#to language types (more details come). and then quickly moves to key technical and architectural issues for .NET developers.
Building a SQL Command via OleDbCommand Table of Contents
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 Introduction implements the IDbCommand interface) is an OO representation of a SQL query, table name, or stored Part One - Introducing C# and the .NET Platform 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 the .NET Platform, Second Edition
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
public enum System.Data.CommandType - C# Language Fundamentals { Chapter 4 - Object-Oriented Programming with C# StoredProcedure, Chapter 5 - Exceptions and Object Lifetime TableDirect, Chapter 6 - Interfaces and Collections Text // Default value. Chapter 7 - Callback Interfaces, Delegates, and Events } Chapter 3
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding Assemblies If the command type does .NET indeed represent a SQL query, the CommandText property can be used to get or set Chapter the query 10 text. - Processes, When creating AppDomains, an OleDbCommand Contexts, and Threads type, you may establish the SQL query as a constructor
parameter directly via theLate CommandText Chapter 11 -or Type Reflection, Binding, andproperty. Attribute-Based Programming Part Four - Leveraging the .NET Libraries
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 Better Window (Introducing Windows Forms) (functionally equivalent) ways to build an OleDbCommand type that associates a SQL SELECT statement with Chapter 14 - A Better Painting Framework (GDI+) an OleDbConnection variable named "cn": Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
// Specify SQL command and connection as constructor parameters. string strSQL1 = "Select Make from Inventory where Color='Red'"; Part Five - Web Applications and XML Web Services OleDbCommand myCommand1 = new OleDbCommand(strSQL1, cn); Chapter 18 - ASP.NET Web Pages and Web Controls // Specify SQL command and connection via properties. Chapter 19 - ASP.NET Web Applications string strSQL2 = "Select Make from Inventory where Color='Red'"; Chapter 20 - XML Web Services OleDbCommand myCommand2 = new OleDbCommand(); Index myCommand.Connection = cn; List of Figures myCommand.CommandText = strSQL2; Chapter 17 - Data Access with ADO.NET
List of Tables
Realize that at this point, you have not literally submitted the SQL query to the Cars database, but rather prepped 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 in Life C# and theMeaning .NET Platform, Second Edition Member by Andrew Troelsen CommandText
ISBN:1590590554
Apress © 2003 (1200 pages)
Gets or sets the SQL command text or the provider-specific syntax to run
This comprehensive text starts with a brief overview of the against the data source. C# language and then quickly moves to key technical and architectural issues for .NET developers.
CommandTimeout Table of Contents 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 the .NET Platform, Second CommandType Edition enumeration. The default value is CommandType.Text, which Introduction
represents a SQL query.
Part One - Introducing C# and the .NET Platform
Connection
Gets or sets the OleDbConnection used by this instance of the OleDbCommand.
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Parameters Gets the collection Part Two - The C# Programming Language
of OleDbParameter types used for a parameterized query.
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Cancel()
Cancels the execution of a command.
ExecuteReader() Returns an instance of an OleDbDataReader, which provides forward-only, Chapter 5 - Exceptions and Object Lifetime Chapter 6
read-only access to the underlying data. - Interfaces and Collections
Chapter 7 - Callback Interfaces, and Events ExecuteNonQuery() ThisDelegates, method issues the command text to the data store, without returning an Chapter 8 - Advanced C# Type Construction Techniques OleDbDataReader type. Part Three - Programming with .NET Assemblies
ExecuteScalar() A lightweight Chapter 9 - Understanding .NET Assembliesversion of the ExecuteNonQuery() method, designed specifically for singleton queries as obtaining a record count). Chapter 10 - Processes, AppDomains, Contexts, and(such Threads Chapter 11 - Type Reflection, Creates Late Binding, and Attribute-Based Prepare() a prepared (or compiled)Programming version of the command on the data Part Four - Leveraging the .NET Libraries source.
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and .NET Platform, Second Edition Working with thetheOleDbDataReader by Andrew Troelsen
ISBN:1590590554
Once you have established the(1200 active connection and SQL command, the next step is to truly submit the Apress © 2003 pages) query to the dataThis source. As you would a overview number of comprehensive textguess, starts there with a are brief of ways the to do so. The OleDbDataReader type (which implements IDataReader) is the simplest and fastest way to C# language and then quickly moves to key technical and obtain information from a data store. architectural issuesforward-only for .NET developers. This class represents a read-only, stream of data returned one record at a time. Given this, it should stand to reason that data readers are useful only when submitting SQL selection statements to the underlying data store. Table of Contents
The OleDbDataReader usefulEdition when you need to iterate over large amounts of data very quickly and have C# and the .NET Platform, is Second no need to work an in-memory DataSet representation. For example, if you request 20,000 records from a Introduction table to -store in a textC# file,and it would be rather memory intensive Part One Introducing the .NET Platform
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 untilTwo you-explicitly close the session. Part The C# Programming Language Chapter 3
- C# Language Fundamentals
To illustrate, the following example issues a simple SQL query against the Cars database, using the - Object-Oriented Programming with C# ExecuteReader() method of the OleDbCommand type. Using the Read() method of the returned Chapter 5 - Exceptions Object Lifetime OleDbDataReader, youand dump each member to the standard IO stream: Chapter 4 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
public class OleDbDR Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies static void Main(string[] args) Chapter { 9 - Understanding .NET Assemblies Chapter 10 - Processes, Contexts, and Threads // MakeAppDomains, a connection. Chapter 11 - Type Reflection, Late Binding, Attribute-Based Programming OleDbConnection cn =and new OleDbConnection(); Part Four - Leveraging the .NET Libraries cn.ConnectionString = "Provider=SQLOLEDB.1;" + Chapter 12 - Object Serialization and the .NET Remoting Layer "User ID=sa;Pwd=;Initial Catalog=Cars;" + Chapter 13 - Building"Data a BetterSource=(local);Connect Window (Introducing Windows Forms) Timeout=30"; Chapter 14 - A cn.Open(); Better Painting Framework (GDI+) ... 15 - Programming with Windows Forms Controls Chapter //System.IO Create Namespace a SQL command. Chapter 16 - The string = "SELECT Make FROM Inventory WHERE Color='Red'"; Chapter 17 - Data Access strSQL with ADO.NET myCommand = new OleDbCommand(strSQL, cn); Part Five - WebOleDbCommand Applications and XML Web Services // Obtain a data reader a la ExecuteReader(). Chapter 18 - ASP.NET Web Pages and Web Controls OleDbDataReader myDataReader; Chapter 19 - ASP.NET Web Applications myDataReader = myCommand.ExecuteReader(); Chapter 20 - XML Web Services // Loop over the results. Index Console.WriteLine("***** Red cars obtained from a DataReader *****"); List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Figure 17-22: Reading records with the OleDbDataReader Part One - Introducing C# and the .NET Platform
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 in your Part Twoapplication: - The C# Programming Language Chapter 3
- C# Language Fundamentals
Chapter // Get 4 the - Object-Oriented value in the Programming 'Make'with column. C#
Console.WriteLine("Red car: {0} ", myDataReader["Make"].ToString()); Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
When you are finished using the DataReader, make sure to terminate the session using the appropriately Chapter 8 - Advanced C# Type Construction Techniques named method, Close(). Part Three - Programming with .NET Assemblies
Chapter 9 -toUnderstanding .NET Assemblies In addition the Read() and Close() methods, there are a number of other methods that allow you to obtain Chapter 10 -typed Processes, AppDomains, Contexts, and Threads a strongly value from a specified column in a given format (e.g., GetBoolean(), GetByte(), and so Chapter 11 - Type Programming forth). Thus, if youReflection, know thatLate the Binding, column and you Attribute-Based are attempting to access has been typed as a Boolean data Part Four Leveraging .NET Libraries type, you- can avoid anthe explicit cast by making
a call to GetBoolean(). Finally, understand that the FieldCount
Chapter 12returns - Object the .NET Remoting property theSerialization number of and columns in the currentLayer record. Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Specifying the Data Reader's Command Behavior
Chapter 15 - Programming with Windows Forms Controls
Chapter - The Namespace As you 16 may haveSystem.IO noticed, the OleDbCommand.ExecuteReader() method has been overloaded. One version Chapter of this member 17 - Datatakes Access a value with ADO.NET from the CommandBehavior enumeration. This type supports the following Part values: Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 enum - ASP.NET Web Applications public System.Data.CommandBehavior Chapter 20 - XML Web Services { Index CloseConnection, Default,
KeyInfo, SchemaOnly, List of Figures 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# and the .NET of Platform, Second Edition Console.WriteLine("State connection is: {0}", cn.State); by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the
Obtaining Multiple Setsmoves Using atechnical OleDbDataReader C# languageResult and then quickly to key and architectural issues for .NET developers.
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 are able to specify both SQL SELECT statements using a semicolon delimiter: Table of Contents C# and the .NET Platform, Second Edition Introduction string theSQL = "SELECT * From Inventory;SELECT * from Customers"; Part One - Introducing C# and the .NET Platform
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 aware thatC# youProgramming are always returned the Part Two - The Language
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
- Object-Oriented Programming with C#
do Chapter 5
- Exceptions and Object Lifetime
{ Chapter 6
- Interfaces and Collections
Chapterwhile(myDataReader.Read()) 7 - Callback Interfaces, Delegates, and Events
{
Chapter 8
- Advanced C# Type Construction Techniques
// Read the info of the current result set. } Chapter 9 - Understanding .NET Assemblies }while(myDataReader.NextResult()); Part Three - Programming with .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Obtaining Schema Information Using a OleDbDataReader
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
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 - Programming with Windows Forms Controls the entire database), the OleDbDataReader.GetTableSchema() method returns a DataTable that describes Chapter 16 - The System.IO Namespace the characteristics of the table specified by the SQL SELECT statement: Chapter 14 - A Better Painting Framework (GDI+)
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
DataTable dt = myDataReader.GetSchemaTable();
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List ofSOURCE Figures List ofCODE Tables
The OleDbDataReaderApp application is included under the Chapter 17 subdirectory.
C# and the .NET Platform, Second Edition Inserting, Updating, and Deleting Records Using OleDbCommand by Andrew Troelsen
ISBN:1590590554
As you have just Apress seen, the ExecuteReader() method allows you to examine the results of a SQL SELECT © 2003 (1200 pages) statement using aThis forward-only, read-only flow of information. However, comprehensive text starts with a brief overview of thewhen you wish to submit SQL commands that result in the modification of a given table, you make C# language and then quickly moves to key technical use and of the architectural issues formethod. .NET developers. 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, Table of Contents meaning this method has nothing to do with obtaining populated DataSet types via a data adapter. C# and the .NET Platform, Second Edition
To illustrate modifying a data source via ExecuteNonQuery(), assume you wish to insert a new record into the Introduction Inventory table of the C# Cars database. Once you Part One - Introducing and the .NET Platform
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
Part class Two -UpdateWithCommandObj The C# Programming Language
{ Chapter 3
- C# Language Fundamentals void Main(string[] args) Chapter static 4 - Object-Oriented Programming with C# Chapter { 5
- Exceptions and Object Lifetime
Chapter 6
// Open connection to Cars db. - Interfaces andaCollections
Chapter 7
OleDbConnection cn = and newEvents OleDbConnection(); - Callback Interfaces, Delegates,
cn.ConnectionString = "Provider=SQLOLEDB.1;" + "User ID=sa;Pwd=;Initial Catalog=Cars;" + Part Three - Programming with .NET Assemblies "Data Source=(local);Connect Timeout=30"; Chapter 9 - Understanding .NET Assemblies cn.Open(); Chapter 10 - Processes, AppDomains, Contexts, and Threads // SQL INSERT statement. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming string sql = "INSERT INTO Inventory" + Part Four - Leveraging the .NET Libraries "(CarID, Make, Color, PetName) VALUES" + Chapter 12 - Object Serialization and the .NET Remoting Layer "('777', 'Honda', 'Silver', 'NoiseMaker')"; Chapter 13 - Building a Betterthe Window (Introducing Windows Forms) // Insert record. Chapter 14 - A OleDbCommand Better Painting Framework cmd = (GDI+) new OleDbCommand(sql, cn); Chapter 15 - Programming with Windows Forms Controls try Chapter 16 - The Namespace { System.IO cmd.ExecuteNonQuery(); } Chapter 17 - Data Access with ADO.NET catch(Exception ex) Part Five - Web{Applications and XML Web Services Console.WriteLine(ex.Message); } Chapter 18 - ASP.NET cn.Close(); Web Pages and Web Controls Chapter } 19 - ASP.NET Web Applications } Chapter 20 - XML Web Services Chapter 8
- Advanced C# Type Construction Techniques
Index List of Figures
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# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
Apress © 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 the numberofofthe affected records: comprehensive text that startsrepresents with a brief overview C# language and then quickly moves to key technical and architectural issues for .NET developers.
try {
Console.WriteLine("Number of rows effected: {0}", cmd.ExecuteNonQuery()); Table of Contents }
C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
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 Part Two SOURCE - The C# Programming The UpdateDBWithCommandObj Language
application is included under the Chapter 17
CODE subdirectory. Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
- Exceptions and Object Lifetime Working with Parameterized Queries
Chapter 5 Chapter 6
- Interfaces and Collections The previous insert, update, andDelegates, delete logic Chapter 7 - Callback Interfaces, andworked Events 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 Construction Techniques objects, than as a with value.NET within a hard-coded Part Threerather - Programming Assemblies
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 - Understanding .NET Assemblies assigned to the CommandText property). Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer convenient manner to tweak SQL statements programmatically. When you wish to map a textual parameter Chapter 13 - Building a Better Window (Introducing Windows Forms) to a member in the command object's parameters collection, simply create a new OleDbParameter type and Chapter - AOleDbCommand's Better Painting Framework (GDI+) add it to14the internal collection using the Parameters property. In addition, make use of Chapter - Programming with Windows Controls the "@"15symbol in the string itself. WhileForms you are free to make use of this technique whenever a SQL query is Chapter 16it-isThe System.IO Namespace involved, most helpful when you wish to trigger a stored procedure. Part Four - Leveraging the .NET Libraries
Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Executing aC#Stored Procedure Using OleDbCommand by Andrew Troelsen
ISBN:1590590554
Astored procedure is a named block of SQL code stored at the database. Stored procedures can be Apress © 2003 (1200 pages) constructed to return a set of rows (or native data types) tooverview the calling and may take any This comprehensive text starts with a brief 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 moves to key technical and architectural issues for .NET the obvious differences of being located on adevelopers. data store rather than a binary business object. Let's add a simple stored procedure to the existing Cars database called GetPetName, which takes an Table inputofparameter Contents of type integer. (If you ran the supplied SQL script, this stored proc is already defined.)
This isthe the.NET numerical ID of the car for which you are interested in obtaining the pet name, which is returned C# and Platform, Second Edition as an output parameter of type char. Here is the syntax: Introduction Part One - Introducing C# and the .NET Platform
Chapter 1 PROCEDURE - The Philosophy of .NET CREATE GetPetName Chapter@carID 2 - Building int,C# Applications Part Two @petName - The C# Programming char(20) output Language
AS Chapter 3
- C# Language Fundamentals SELECT = PetName fromwith Inventory where CarID = @carID Chapter 4 @petName - Object-Oriented Programming C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Now that you have a stored procedure in place, let's see the code necessary to execute it. Begin as always - Callback Interfaces, Delegates, and Events by creating a new OleDbConnection, configure your connection string, and open the session. Next, create Chapter 8 - Advanced C# Type Construction Techniques a new OleDbCommand type, making sure to specify the name of the stored procedure and set the Part Three - Programming with .NET Assemblies CommandType property accordingly, as shown here: Chapter 7
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
// Open connection to data store. OleDbConnection cn = new OleDbConnection(); Part Four - Leveraging the .NET Libraries cn.ConnectionString = "Provider=SQLOLEDB.1;" + Chapter 12 - Object Serialization and the .NET Remoting Layer "User ID=sa;Pwd=;Initial Catalog=Cars;" + Chapter 13 - Building a Better Window (Introducing Windows Forms) "Data Source=(local);Connect Timeout=30"; Chapter 14 - A Better Painting Framework (GDI+) cn.Open(); Chapter 15 -aProgramming with Windows Controls proc. // Make command object for Forms the stored Chapter 16 The System.IO Namespace OleDbCommand myCommand = new OleDbCommand("GetPetName", cn); Chapter 17 - Data Access with ADO.NET myCommand.CommandType = CommandType.StoredProcedure; Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Specifying Parameters Using the OleDbParameter Type
Chapter 20 - XML Web Services
Index The next task is to establish the parameters used for the call. To illustrate the syntax of parameterized List of Figures queries, you will use the OleDbParameter type. This class maintains a number of properties that allow you List of Tables the name, size, and data type of the parameter, as well as its direction of travel. Table 17-16 to configure
describes some key properties of the OleDbParameter type. Table 17-16: Key Members of the OleDbParameter Type
OleDbParameter Meaning inSecond Life Edition C# and the .NET Platform, Property by Andrew Troelsen DataType DbType
ISBN:1590590554
Apress © 2003 (1200 pages)
Establishes the type of the parameter, in terms of .NET
This comprehensive text starts with a brief overview of the C# language and thenorquickly moves to data key technical Gets sets the native type fromand the data source, represented architectural issues for .NET developers.
as a CLR data type
Direction Table of Contents
Gets or sets whether the parameter is input-only, output-only, bidirectional, or a return value parameter
C# and the .NET Platform, Second Edition
IsNullable
Introduction
Gets or sets whether the parameter accepts null values
Part One - Introducing C# and theGets .NET or Platform OleDbType sets 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
Part Two - The C# Programming Language
Chapter Precision 3 - C# Language Fundamentals Gets or sets the maximum number of digits used to represent the Chapter 4
Value property - Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Scale
Gets or sets the number of decimal places to which the Value property is resolved
Size 8 - Advanced C# Type Construction Gets or setsTechniques the maximum parameter size of the data Chapter Part Three - Programming with .NET Assemblies
Value
Chapter 9
Gets or sets the value of the parameter
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter Given that 11 -you Type have Reflection, one input Late and Binding, one output and Attribute-Based parameter, youProgramming can configure your types as follows. Note Part thatFour you -then Leveraging add these theitems .NET Libraries to the OleDbCommand
type's ParametersCollection (which is, again,
accessed the Parameters Chapter 12 via - Object Serializationproperty): and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A the Betterparameters Painting Framework // Create for (GDI+) the call. Chapter OleDbParameter 15 - Programming theParam with Windows = newForms OleDbParameter(); Controls
// Input param. Chapter 16 - The System.IO Namespace theParam.ParameterName = "@carID"; Chapter 17 - Data Access with ADO.NET theParam.OleDbType OleDbType.Integer; Part Five - Web Applications=and XML Web Services theParam.Direction = ParameterDirection.Input; Chapter 18 - ASP.NET Web Pages and Web Controls theParam.Value 1;Applications // Car ID = 1. Chapter 19 - ASP.NET = Web myCommand.Parameters.Add(theParam); Chapter 20 - XML Web Services // Output param. theParam = new OleDbParameter(); List of Figures theParam.ParameterName = "@petName"; List of Tables theParam.OleDbType = OleDbType.Char; theParam.Size = 20; theParam.Direction = ParameterDirection.Output; myCommand.Parameters.Add(theParam); Index
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
SOURCE CODE
ISBN:1590590554
OleDbStoredProc project included under ThisThe comprehensive text starts with is a brief overview ofthe the Chapter 17 subdirectory. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the Layer .NET Platform, Edition The Disconnected and Second the OleDbDataAdapter Type by Andrew Troelsen
ISBN:1590590554
At this point you should understand how to connect to a data source using the OleDbConnection type, Apress © 2003 (1200 pages) issue a commandThis (using the OleDbCommand and iterate over a result set comprehensive text starts and with OleDbParameter a brief overview oftypes), the using the OleDbDataReader. As you have just seen, these types allow you to obtain and alter data using C# language and then quickly moves to key technical and architectural issuesHowever, for .NET developers. the connected layer of ADO.NET. when you 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 Table Contents dataof access than the forward-only, read-only world of the data reader. C# and the .NET Platform, Second Edition
To shift gears, we now need to examine the role of the OleDbDataAdapter type and understand how it is Introduction our One vehicle to obtaining populated Part - Introducing C#aand the .NETDataSet. PlatformIn
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 Part Two -returned): The C# Programming Language Chapter 3
- C# Language Fundamentals // Fills the data set with records Chapter 4 - Object-Oriented Programming with C#from a given source table.
public Fill(DataSet string tableName); Chapter 5 int - Exceptions and Object yourDS, Lifetime Chapter 6
- Interfaces and Collections // Fills the data set with the and records Chapter 7 - Callback Interfaces, Delegates, Events located between
// the given bounds from a given source table. - Advanced C# Type Construction Techniques public int Fill(DataSet yourDS, int startRecord, Part Three - Programming with .NET Assemblies int maxRecord, string tableName); Chapter 8 Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part - Leveraging the .NET method Librarieshas TheFour OleDbDataAdapter.Fill()
also been overloaded to return to you a populated DataTable
Chapter 12 - Object and the .NET Remoting Layer type, rather than a Serialization full-blown DataSet: Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 int - A Better Painting Framework (GDI+) public Fill(System.Data.DataTable dataTable); Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Note- Web It is also worth pointing outWeb thatServices one version Part Five Applications and XML
of the Fill() method will automatically populate a
ADO Recordset type with the contents of a given ADO.NET DataTable. Chapter 18 classic - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
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 Index connection information and the SQL SELECT statement used to populate the DataTable/DataSet type at List of Figures 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 Services
// 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# and .NET Platform, Second Edition // will be used to the update the data source ISBN:1590590554 by Andrew Troelsen // given a DataTable in the DataSet. Apress © 2003 (1200 pages) myDataAdapter.Update(myDS, "Inventory"); This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and issues for .NET developers. Now, if you have architectural a 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.
Table of Contents
C# the .NET Platform, Second Edition (SelectCommand, UpdateCommand, DeleteCommand, and In and addition to these four key properties Introduction InsertCommand),Table 17-17 describes some additional members of the OleDbDataAdapter type. Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET Table 17-17: Core Members of the OleDbDataAdapter Chapter 2 - Building C# Applications
OleDbDataAdapter Member
Meaning in Life
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#SQL commands that will be issued to the data DeleteCommand Used to establish Chapter 5 - Exceptions and Object Lifetime store when the Fill() and Update() methods are called. Each of these
InsertCommand
Chapter 6
- Interfaces and Collections properties is set using an OleDbCommand type.
Chapter 7
- Callback Interfaces, Delegates, and Events
SelectCommand
UpdateCommand Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Fill()
Chapter 9
Fills a given table in the DataSet with some number of records
- Understanding .NETbased Assemblies on the current SELECT command. Chapter 10 - Processes, AppDomains, Contexts, and Threads
GetFillParameters() Returns alland parameters used when performing the select command. Chapter 11 - Type Reflection, Late Binding, Attribute-Based Programming Part Four - Leveraging the .NET Libraries Update() Calls the
respective INSERT, UPDATE, or DELETE statements for
Chapter 12 - Object Serialization each and the .NET Remoting inserted, updated,Layer or deleted row for a given table in the Chapter 13 - Building a Better Window (Introducing Windows Forms) DataSet. Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Filling a DataSet Using the OleDbDataAdapter Type
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services To understand the functionality of the data adapter
types, let's begin by learning how to use a data adapter
Chapter - ASP.NET Web Pages andThe Webfollowing Controls code populates a DataSet (containing a single table) to fill a 18 DataSet programmatically. Chapter 19OleDbDataAdapter: - ASP.NET Web Applications using an Chapter 20 - XML Web Services Index public static int Main(string[] args) List { of Figures 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# and the .NET Platform, Second Edition
Notice that unlike your work during the first half of this chapter,ISBN:1590590554 you did not manually create a DataTable by Andrew Troelsen type and add it to the DataSet. Also, you did not call ExecuteReader() from a command object to stream Apress © 2003 (1200 pages) over the result set. Rather, you specified the Inventory table as the second parameter to the Fill() method, This comprehensive text starts with a brief overview 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 moves to key technical and friendly name, thearchitectural data adapter will simply the table "Table": issues for .NETname developers. // This DataSet has a single table called 'Table'. Table of dAdapt.Fill(myDS); Contents C# and the .NET Platform, Second Edition Introduction
Internally, Fill() buildsC# theand DataTable, given the Part One - Introducing the .NET Platform
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 Part Two - The C# Programming Language
// Create a Language SELECT Fundamentals command as string type. Chapter 3 - C# string = "SELECT * FROM Inventory"; Chapter 4 sqlSELECT - Object-Oriented Programming with C# OleDbDataAdapter dAdapt new OleDbDataAdapter(sqlSELECT, cn); Chapter 5 - Exceptions and Object =Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
As an alternative, you can associate the OleDbCommand to the OleDbDataAdapter, using the Chapter 8 - Advanced C# Type Construction Techniques SelectCommand property, as shown here: Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
// Create a SELECT command object. OleDbCommand selectCmd = new OleDbCommand("SELECT * FROM Inventory", cn); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming // Make a data adapter and associate commands. Part Four - Leveraging the .NET Libraries OleDbDataAdapter dAdapt = new OleDbDataAdapter(); Chapter 12 - Object Serialization and the .NET Remoting Layer dAdapt.SelectCommand = selectCmd; Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Controls The PrintTable() helper method is little Forms more than some formatting razzle-dazzle: Chapter 16 - The System.IO Namespace Chapter 17 static - Data Access ADO.NET public voidwith PrintTable(DataSet ds) Part { Five - Web Applications and XML Web Services
Chapter // 18 -Get ASP.NET Web Pagestable and Web Controls Inventory from DataSet. Chapter Console.WriteLine("Here 19 - ASP.NET Web Applications is what we have right now:\n"); Chapter DataTable 20 - XML WebinvTable Services = ds.Tables["Inventory"]; Index
// Print the Column names.
for(int curCol= 0; curCol< invTable.Columns.Count; curCol++) List of Figures { 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# and the Names .NET Platform, UsingSecond the OleDbDataAdapter Edition Type by Andrew Troelsen
ISBN:1590590554
The default behavior of © a 2003 data(1200 adapter Apress 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 comprehensive text starts with a brief overview of the name (e.g., LName) to a more friendly display name to (e.g., Name). C# language and then quickly moves key Last technical and When you wish to do so, you will need to establisharchitectural specific column issues mappings for .NET developers. for the table 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 Table of Contents System.Data.Common namespace). Once you have a reference to this entity, you are able to establish C# and the .NET Platform, Second Edition unique column names for a specific table. For example, the following code alters the display names for Introduction the CarID, Make, and PetName columns of the Inventory table: Part One - Introducing C# and the .NET Platform
Chapter 1 -reference The Philosophy of .NET // Must this namespace Chapter - Building C# Applications // to2 get definitions of DataTableMapping! Part Two -System.Data.Common; The C# Programming Language using
Chapter ... 3
- C# Language Fundamentals
Chapter // Establish 4 - Object-Oriented column mappings Programmingfor with the C# Inventory table
// by5 adding new and DataColumnMapping types Chapter - Exceptions Object Lifetime // to6 the DataTableMapping Chapter - Interfaces and Collections type. DataTableMapping tblMapper = and Events Chapter 7 - Callback Interfaces, Delegates, Chapter dAdapt.TableMappings.Add("Table", 8 - Advanced C# Type Construction Techniques"Inventory");
tblMapper.ColumnMappings.Add("CarID", Part Three - Programming with .NET Assemblies
"ID"); tblMapper.ColumnMappings.Add("Make", "Brand"); Chapter 9 - Understanding .NET Assemblies tblMapper.ColumnMappings.Add("PetName", "Friendly name of Car"); Chapter 10 - Processes, AppDomains, Contexts, and Threads // Create and fill the DataSet. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming dAdapt.Fill(myDS); Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 -explicitly Buildingalter a Better Window DataColumnMappingCollection (Introducing Windows Forms) Here, you the internal type before making the call to Fill(). Chapter 14 - A note Betterthat Painting Framework (GDI+)name of the table to interact with at the time you add in your Furthermore, you specify the friendly Chapter - Programming with than Windows Forms Controls unique 15 table mapping, rather at the time you call the Fill() method (recall that by default, the name of Chapter 16 populated - The System.IO Namespace the newly DataTable is simply "Table"). Chapter 17 - Data Access with ADO.NET
If you run this application, now find the output Part Five - Web Applicationsyou andwill XML Web Services
shown in Figure 17-23.
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and .NET Platform, Second Edition Working with thetheSQL Data Provider by Andrew Troelsen
ISBN:1590590554
Before you see the details of inserting, updating, and removing records using a data adapter, I would like Apress © 2003 (1200 pages) to introduce the SQL data provider. As you recall, OleDb provider you to access any OLE DBThis comprehensive text starts withthe a brief overview of allows the compliant data store, but incurs overhead via the COM interoperability layer lurking in the background. C# language and then quickly moves to key technical and architectural issues for .NET developers.
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 Table functionality of Contents of the SQL data provider, which should look very familiar, given your work with the OleDb provider 17-18). Second Edition C# and the(Table .NET Platform, Introduction
Table Core Types ofthe the.NET System.Data.SqlClient Part One17-18: - Introducing C# and Platform Chapter 1
Namespace
- The Philosophy of .NET
System.Data.SqlClient Meaning in Life Type - Building C# Applications
Chapter 2
Part Two - The C# Programming Language
Chapter SqlCommand 3 - C# Language Fundamentals Represents a Transact-SQL query to execute at a SQL Server Chapter 4
data source. - Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
SqlConnection
Represents an open connection to a SQL Server data source.
SqlDataAdapter Represents a set of data commands and a database Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8
connection used to fill the DataSet and update the SQL Server - Advanced C# Type Construction Techniques
data source. Part Three - Programming with .NET Assemblies Chapter 9 - Understanding .NET Assemblies SqlDataReader Provides a way of reading a forward-only stream of data Chapter 10 - Processes, AppDomains, Contexts, and a Threads records from SQL Server data source. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
SqlErrors SqlErrors Part Four - Leveraging the .NET Libraries
maintains a collection of warnings or errors returned by SQL Server, each of which is represented by a SQLError Chapter SqlError 12 - Object Serialization and the .NET Remoting Layer type. When an error is encountered, an exception of type Chapter 13 - Building a Better Window (Introducing Windows Forms) SqlException SQLException is thrown. Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls SqlParameterCollection SqlParametersCollection holds onto the parameters sent to a Chapter 16 The System.IO Namespace stored procedure held in the database. Each parameter is of SqlParameter
type SQLParameter. Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Given that these types almost identical to working with the OleDb data provider, you should Chapter 18 -working ASP.NETwith Web Pages and is Web Controls already19 know what toWeb do with them, as they have a similar public interface. To help you get comfortable Chapter - ASP.NET Applications with this20new set Web of types, the remainder of the examples use the SQL data provider (don't forget to specify Chapter - XML Services you are using the System.Data.SqlClient namespace!) Index List of Figures
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 Wrapper SQL Server C# and the .NET Platform, Native Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
SqlBinary SqlInt64
ISBN:1590590554
binary, varbinary, timestamp, image
This comprehensive text starts bigint with a brief overview of the C# language and then quickly moves to key technical and bit architectural issues for .NET developers.
SqlBit SqlDateTime Table of Contents SqlNumeric
C# and the .NET Platform, Second Edition
SqlDouble
Introduction
datetime, smalldatetime decimal float
Part One - Introducing C# and the .NET Platform SqlInt32 int
Chapter 1
- The Philosophy of .NET
SqlMoney - Building C# Applications Part Two The SqlString C# Programming Language Chapter 2 Chapter 3
money, smallmoney nchar, ntext, nvarchar, sysname, text, varchar, char
- C# Language Fundamentals
SqlNumeric numeric - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime SqlSingle real Chapter 4 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
SqlInt16
smallint
Chapter 8 - Advanced C# Type Construction Techniques System.Object sql_variant Part Three - Programming with .NET Assemblies
SqlByte
Chapter 9
- Understanding .NET Assemblies
tinyint
Chapter 10 - Processes, AppDomains, Contexts, uniqueidentifier and Threads SqlGuid Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Inserting Records Using the SqlDataAdapter
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 you - A have Betterflipped Painting Framework (GDI+) Now that from the OleDb provider to the realm of the SQL provider, you can return to the Chapter - Programming Forms Controls task of 15 understanding thewith role Windows of data adapters. Let's examine how to insert new records into a given table Chapter using the 16 SqlDataAdapter - The System.IO (which Namespace is nearly identical to using the OleDbDataAdapter, OdbcDataAdapter,
and OracleDataAdapter types). As always, begin by creating an active connection, as shown here: Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 class - ASP.NET Web Pages and Web Controls public MySqlDataAdapter Chapter 19 - ASP.NET Web Applications { Chapter public 20 - XML Web static Services void Main() Index
{
List of Figures // 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# and the .NET Platform, Second Edition
ISBN:1590590554 Troelsen The deletion logicbyisAndrew really more of a good housekeeping chore for the current application. Here, you Apress © 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 comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and architectural issues for .NET developers. If you wish to make use of parameterized queries, the 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 Table of Contents column in the Inventory table, as shown here (and yes, you could avoid the use of the parameter objects if C# and theand .NET Platform, Second Edition you wish directly hard code the INSERT statement): Introduction Part One - Introducing C# and the .NET Platform
public static void Main()
Chapter 1 {
- The Philosophy of .NET
Chapter ... 2 - Building C# Applications Part Two// - The C# Programming Language Build the insert command!
Chapter 3 dAdapt.InsertCommand - C# Language Fundamentals = new SqlCommand("INSERT INTO Inventory" + Chapter 4 - Object-Oriented Programming withPetName) C# "(CarID, Make, Color, VALUES" + Chapter 5
- Exceptions "(@CarID, and Object @Make, Lifetime @Color, @PetName)", cn)"; Chapter SqlParameter 6 - Interfaces andworkParam Collections = null; Chapter // 7 -CarID. Callback Interfaces, Delegates, and Events
= dAdapt.InsertCommand.Parameters.Add(new Chapter 8 workParam - Advanced C# Type Construction Techniques SqlParameter("@CarID", Part Three - Programming with .NET AssembliesSqlDbType.Int)); = "CarID"; Chapter workParam.SourceColumn 9 - Understanding .NET Assemblies = DataRowVersion.Current; Chapter workParam.SourceVersion 10 - Processes, AppDomains, Contexts, and Threads // Make. workParam = dAdapt.InsertCommand.Parameters.Add(new Part Four - Leveraging the .NET Libraries SqlParameter("@Make", SqlDbType.VarChar)); Chapter 12 - Object Serialization and the .NET Remoting Layer workParam.SourceColumn = "Make"; Chapter 13 - Building a Better Window (Introducing Windows Forms) workParam.SourceVersion = DataRowVersion.Current; Chapter 14 - A Better Painting Framework (GDI+) // Color. Chapter 15 - Programming with Windows Forms Controls workParam = dAdapt.InsertCommand.Parameters.Add(new Chapter 16 - The System.IO Namespace SqlParameter("@Color", SqlDbType.VarChar)); ChapterworkParam.SourceColumn 17 - Data Access with ADO.NET= "Color"; Part Five - Web Applications and XML Web workParam.SourceVersion = Services DataRowVersion.Current; Chapter// 18 PetName. - ASP.NET Web Pages and Web Controls ChapterworkParam 19 - ASP.NET=Web Applications dAdapt.InsertCommand.Parameters.Add(new Chapter 20 - XML Web Services SqlParameter("@PetName", SqlDbType.VarChar)); Index workParam.SourceColumn = "PetName"; workParam.SourceVersion = DataRowVersion.Current; List of Figures } of Tables List Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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# and the = .NET Platform, Second Edition newRow["Color"] "Pink"; ISBN:1590590554 by Andrew Troelsen newRow["PetName"] = "Cranky"; Apress © 2003 (1200 pages) myDS.Tables["Inventory"].Rows.Add(newRow); comprehensive text starts a brief overview of the // Send This back to database and with reprint. C# language and then quickly moves to key technical and try architectural issues for .NET developers. { dAdapt.Update(myDS, "Inventory"); myDS.Dispose(); Table of Contents myDS = new DataSet(); C# and the .NET Platform, Second Edition dAdapt.Fill(myDS, "Inventory"); Introduction PrintTable(myDS); Part One - Introducing C# and the .NET Platform } Chapter 1 - The Philosophy of .NET catch(Exception e){ Console.Write(e.ToString()); } Chapter 2 - Building C# Applications } Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4 -run Object-Oriented Programming C# shown in Figure 17-24. When you the application, you see thewith output Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and theRecords .NET Platform, Secondthe Edition by Andrew Troelsen
ISBN:1590590554
Now that you can insert new rows, let's look at how you can update existing rows, which you might guess Apress © 2003 (1200 pages) will look quite similar to the process of inserting new rows (as well as the process of deleting existing This comprehensive text starts with a brief overview of the rows). Again, start the process by obtaining a connection and creating a new SqlDataAdapter. Next, set C# language and then quickly moves to key technical and the value of the UpdateCommand the same general approach as when setting the value of architectural issuesproperty, for .NET using developers. the InsertCommand. Here is the relevant code in Main(): Table of Contents public static void Main() C# { and the .NET Platform, Second Edition Introduction // Create a connection and adapter (same as previous code). Part One... - Introducing C# and the .NET Platform
the UpdateCommand. Chapter // 1 -Establish The Philosophy of .NET Chapter dAdapt.UpdateCommand 2 - Building C# Applications = new SqlCommand
("UPDATE Inventory Part Two - The C# Programming LanguageSET
Make = @Make, Color = " + "@Color, PetName = @PetName " + Chapter 3 - C# Language Fundamentals "WHERE CarID = @CarID" , cn); Chapter 4 - Object-Oriented Programming with C# parameters for each column in Inventory table. Chapter // 5 -Build Exceptions and Object Lifetime // Same as before, but now you are populating the ParameterCollection Chapter 6 - Interfaces and Collections // of the UpdateCommand: Chapter 7 - Callback Interfaces, Delegates, and Events SqlParameter workParam = null; Chapter 8 - Advanced C# Type Construction Techniques workParam = dAdapt.UpdateCommand.Parameters.Add(new Part Three - Programming with .NET Assemblies SqlParameter("@CarID", SqlDbType.Int)); Chapter 9 - Understanding .NET Assemblies workParam.SourceColumn = "CarID"; Chapter 10 - Processes, AppDomains, Contexts, and Threads workParam.SourceVersion = DataRowVersion.Current; Chapter // 11 -Do Type Reflection, Late Binding, and Attribute-Based Programming the same for PetName, Make, and Color params Part Four... - Leveraging the .NET Libraries Chapter // 12 -Fill Objectinitial Serialization and the .NET Remoting Layer data set. Chapter DataSet 13 - Building a Better Window (Introducing myDS = new DataSet(); Windows Forms) Chapter dAdapt.Fill(myDS, 14 - A Better Painting Framework (GDI+) "Inventory"); Chapter PrintTable(myDS); 15 - Programming with Windows Forms Controls Chapter // 16 -Change The System.IO columns Namespace in second row to 'FooFoo'. changeRow = myDS.Tables["Inventory"].Rows[1]; Chapter DataRow 17 - Data Access with ADO.NET = "FooFoo"; Part FivechangeRow["Make"] - Web Applications and XML Web Services = "FooFoo"; Chapter changeRow["Color"] 18 - ASP.NET Web Pages and Web Controls changeRow["PetName"] Chapter 19 - ASP.NET Web Applications= "FooFoo"; back to database and reprint. Chapter // 20 -Send XML Web Services try Index { List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - 17-25: Programming withexisting Windows Formsusing Controls Figure Updating records a data adapter Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with 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 Controls property. While having absolute control over the SQL used to insert, update, and delete records does Chapter 19 - ASP.NET Web Applications 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 Services SQL commands by hand. You are, however, provided with some helper types. Part Five - Web Applications and XML Web Services
Index
List ofSOURCE Figures List ofCODE Tables
The UpdateRowsWithSqlAdapter project is found under the Chapter 17 subdirectory.
C# and the .NET Commands Platform, Second Using Edition CommandBuilder Types Auto-Generating SQL by Andrew Troelsen
ISBN:1590590554
Each ADO.NET data provider that pages) ships with .NET 1.1 provides a command builder type. Using this type, Apress © 2003 (1200 you are able to automatically obtain objects thatoverview contain the correct INSERT, DELETE, and This comprehensive command text starts with a brief of the UPDATE command types based on the initial SELECT statement. For example, the SqlCommandBuilder C# language and then quickly moves to key technical and architectural issues contained for .NET developers. automatically generates the values within the SqlDataAdapter's InsertCommand, 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. Table of Contents
Anand obvious question at this pointEdition is how a command builder is able to build these SQL commands on the C# the .NET Platform, Second fly. The short answer is metadata. At runtime, when you call the Update() method of a data adapter, the Introduction related builder willthe read thePlatform database's Part One command - Introducing C# and .NET
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. Part Two - The C# Programming Language Chapter 3
- C# Language Fundamentals
Consider the following example, which deletes a row in a DataSet using the auto-generated SQL - Object-Oriented Programming with C# statements. Furthermore, this application will print out the underlying command text of each command Chapter 5 object: - Exceptions and Object Lifetime Chapter 4 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
static void Main(string[] args) Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies DataSet theCarsInventory = new DataSet(); Chapter// 9 Make - Understanding .NET Assemblies connection. ChapterSqlConnection 10 - Processes, AppDomains, cn = newContexts, and Threads Chapter 11 -SqlConnection("server=(local);User Type Reflection, Late Binding, and Attribute-BasedID=sa;Pwd=;database=Cars"); Programming Part Four Leveraging the .NET Libraries // Autogenerate INSERT, UPDATE, and DELETE commands Chapter// 12 based - Objecton Serialization the .NETcommand. Remoting Layer exitingand SELECT ChapterSqlDataAdapter 13 - Building a Better Window (Introducing Windows Forms) da = new SqlDataAdapter("SELECT * FROM Inventory", cn); ChapterSqlCommandBuilder 14 - A Better Painting Framework invBuilder (GDI+) = new SqlCommandBuilder(da); out values of the generated command objects. Chapter// 15 Print - Programming with Windows Forms Controls command: {0}", ChapterConsole.WriteLine("SELECT 16 - The System.IO Namespace Chapter 17 -da.SelectCommand.CommandText); Data Access with ADO.NET Console.WriteLine("UPDATE command: {0}", Part Five - Web Applications and XML Web Services Chapter 18 -invBuilder.GetUpdateCommand().CommandText); ASP.NET Web Pages and Web Controls command: {0}", ChapterConsole.WriteLine("INSERT 19 - ASP.NET Web Applications invBuilder.GetInsertCommand().CommandText); Chapter 20 - XML Web Services Console.WriteLine("DELETE command: {0}", Index invBuilder.GetDeleteCommand().CommandText); List of Figures // 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
Based on the initial SQL SELECT statement, SqlCommandBuilder type generates the following This comprehensive text startsthe with a brief overview of the C# and language and parameterized then quickly moves to key technical and UPDATE, INSERT, DELETE queries: architectural issues for .NET developers.
UPDATE Inventory SET CarID = @p1 , Make = @p2 , Color = @p3 , PetName = @p4 WHERE ( (CarID = @p5) AND Table of Contents ((@p6 = 1 AND Make IS NULL) OR (Make = @p7)) AND C# and the .NET Platform, Second Edition ((@p8 =1 AND Color IS NULL) OR (Color = @p9)) AND Introduction ((@p10 = 1 AND PetName IS NULL) OR (PetName = @p11)) ) Part One - Introducing C# and the .NET Platform 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 Part Two - The C# Programming Language ((@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 Programming ((@p64 = -1Object-Oriented AND PetName IS NULL)with OR C# (PetName = @p7)) ) Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections Now, while may Interfaces, love the idea of getting something Chapter 7 - you Callback Delegates, and Events for nothing, do understand that command builders
do come some very restrictions.Techniques Specifically, a command builder is only able to auto-generate Chapter 8 with - Advanced C# critical Type Construction SQLThree commands for use by a data if all Part - Programming with .NET adapter Assemblies Chapter 9
of the following conditions are true:
- Understanding .NET Assemblies
The SELECT command only interacts with a single table (e.g., no joins).
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11single - Type Reflection, Lateattributed Binding, and The table has been withAttribute-Based a primary key. Programming Part Four - Leveraging the .NET Libraries
The representing thethe primary key is accounted for in your SQL SELECT statement. Chapter 12column(s) - Object Serialization and .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
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 - Programming with Windows Forms Controls the data-centric tools provided by VS .NET and discuss strongly typed DataSets. Chapter 14 - A Better Painting Framework (GDI+) Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access ADO.NET SOURCE Thewith MySqlCommandBuilder project is found under the Chapter 17 subdirectory. Part Five - Web Applications and XML Web Services CODE
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Windows Platform, Second EditionExample A CompleteC#ADO.NET Forms by Andrew Troelsen
ISBN:1590590554
Now assume youApress have a© new Windows 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 comprehensive text startsand withdelete a briefexisting overview of the When finished, the user may submit the modified DataSet back to the database using a Button type. C# language and then quickly moves to key technical andFirst, assume the following constructor logic:architectural issues for .NET developers. public class mainForm : System.Windows.Forms.Form { C# and the .NET Platform, Second Edition private SqlConnection cn = new Introduction SqlConnection("server=(local);uid=sa;pwd=;database=Cars"); Part One - Introducing C# and the .NET Platform private SqlDataAdapter dAdapt; Chapter private 1 - The Philosophy of .NET SqlCommandBuilder invBuilder; Chapter private 2 - Building C# Applications DataSet myDS = new DataSet(); Part Twoprivate - The C# Programming Language System.Windows.Forms.DataGrid dataGrid1; Chapter private 3 - C# Language Fundamentals System.Windows.Forms.Button btnUpdateData; Chapter 4 - Object-Oriented Programming with C# ... Chapter public 5 - Exceptions and Object Lifetime mainForm() Chapter { 6 - Interfaces and Collections InitializeComponent(); Chapter 7 - Callback Interfaces, Delegates, and Events // Create the initial Techniques SELECT SQL statement. Chapter 8 - Advanced C# Type Construction dAdapt = new SqlDataAdapter("SELECT * FROM Inventory", cn); Part Three - Programming with .NET Assemblies // Autogenerate the INSERT, UPDATE, Chapter 9 - Understanding .NET Assemblies // and AppDomains, DELETE statements. Chapter 10 - Processes, Contexts, and Threads invBuilder = new SqlCommandBuilder(dAdapt); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming // Fill and bind. Part Four - Leveraging the .NET Libraries dAdapt.Fill(myDS, "Inventory"); Chapter 12 - Object Serialization and the .NET Remoting Layer dataGrid1.DataSource = myDS.Tables["Inventory"].DefaultView; Chapter 13 - Building a Better Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+) ... Chapter 15 - Programming with Windows Forms Controls }
Table of Contents
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Fivepoint, - Web Applications and XML Web Services At this the SqlDataAdapter has all the information
it needs to submit changes back to the data store.
Chapter 18 - ASP.NET Pages and Web Controls Now assume that youWeb have the following logic behind the Button's Click event: Chapter 19 - ASP.NET Web Applications Chapter 20 -void XML Web Services private btnUpdateData_Click(object sender, System.EventArgs e) Index { List of Figures try 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Figure 17-26: All good things do come ... Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET SOURCE TheApplications WinFormsExample project is included under the Chapter 17 subdirectory. Chapter 2 - Building C#
CODE Part Two - The C# Programming Language Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform,(and SecondAdding Edition Filling a Multitabled DataSet DataRelations) by Andrew Troelsen
ISBN:1590590554
Let's come full circle and an additional Windows Forms example that mimics the application you Apress © build 2003 (1200 pages) created during the first half of this chapter. The GUIaisbrief simple enough. In Figure 17-27 you can see three This comprehensive text starts with overview of the DataGrid types that hold the data retrieved from the Inventory, Orders, and Customers tables of the Cars C# language and then quickly moves to key technical and architectural issues for .NET developers. database. In addition, the single Button pushes any and all changes back to the data store.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - 17-27: Type Reflection, Late Binding, and Attribute-Based Programming Figure Viewing related DataTables Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
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 Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
public class mainForm : System.Windows.Forms.Form { Chapter 17 - Data Access with ADO.NET private System.Windows.Forms.DataGrid custGrid; Part Five - Web Applications and XML Web Services private System.Windows.Forms.DataGrid inventoryGrid; Chapter 18 - ASP.NET Web Pages and Web Controls private System.Windows.Forms.Button btnUpdate; Chapter 19 - ASP.NET Web Applications private System.Windows.Forms.DataGrid OrdersGrid; Chapter 20 - XML Web Services ... Index // Here is the connection. List of Figures 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 System.IO Namespace
The Form's constructor does the grunge work of creating your data-centric member variables and filling and the .NET Platform, Second Edition the DataSet. AlsoC# note that there is a call to a private helper function, BuildTableRelationship(), as shown ISBN:1590590554 by Andrew Troelsen here: Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
public mainForm() C# language and then quickly moves to key technical and { architectural issues for .NET developers. InitializeComponent(); Create adapters. Table of // Contents
invTableAdapter = new SqlDataAdapter("Select * from Inventory", cn); C# and the .NET Platform, Second Edition custTableAdapter = new SqlDataAdapter("Select * from Customers", cn); Introduction = new SqlDataAdapter("Select Part OneordersTableAdapter - Introducing C# and the .NET Platform
* from Orders", cn); // Autogenerate commands. Chapter 1 - The Philosophy of .NET new SqlCommandBuilder(invTableAdapter); Chapter invBuilder 2 - Building C#= Applications orderBuilder = newLanguage SqlCommandBuilder(ordersTableAdapter); Part Two - The C# Programming custBuilder = new SqlCommandBuilder(custTableAdapter); Chapter 3 - C# Language Fundamentals // Add tables to DS. Chapter 4 - Object-Oriented Programming with C# invTableAdapter.Fill(carsDS, "Inventory"); Chapter 5 - Exceptions and Object Lifetime custTableAdapter.Fill(carsDS, "Customers"); Chapter 6 - Interfaces and Collections ordersTableAdapter.Fill(carsDS, "Orders"); Chapter 7 - Callback Interfaces, Delegates, and Events // Build relations between tables. Chapter BuildTableRelationship(); 8 - Advanced C# Type Construction Techniques Part } Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
The BuildTableRelationship() helper function does just what Programming you would expect. Recall that the Cars Chapter 11 - Type Reflection, Late Binding, and Attribute-Based database expresses athe number of parent/child Part Four - Leveraging .NET Libraries
relationships. The code looks identical to the logic seen
earlier in chapter, as shownand here: Chapter 12this - Object Serialization the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter private 14 -void A Better BuildTableRelationship() Painting Framework (GDI+)
{ Chapter 15 - Programming with Windows Forms Controls a DR Namespace obj. Chapter // 16 -Create The System.IO dr ADO.NET = new DataRelation("CustomerOrder", Chapter DataRelation 17 - Data Access with Part Five - WebcarsDS.Tables["Customers"].Columns["CustID"], Applications and XML Web Services
carsDS.Tables["Orders"].Columns["CustID"]); Chapter 18 - ASP.NET Web Pages and Web Controls relation to the DataSet. Chapter // 19 -Add ASP.NET Web Applications carsDS.Relations.Add(dr); // Create another DR obj. Index dr = new DataRelation("InventoryOrder", List of Figures 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 Services
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# and the .NET Platform, Second Edition ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) invTableAdapter.Update(carsDS, "Inventory"); This comprehensive text starts with a brief "Customers"); overview of the custTableAdapter.Update(carsDS, C# language and then quickly moves to key and ordersTableAdapter.Update(carsDS, technical "Orders"); architectural issues for .NET developers.
} catch(Exception ex) { Table of Contents MessageBox.Show(ex.Message); C# and the .NET Platform, Second Edition } Introduction } Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2 -update, Building C#will Applications Once you you find each table in the Cars database correctly altered. Part Two - The C# Programming Language
SOURCE The WinFormsMultiTableDataSet project is included under the Chapter 17 Chapter 3 - C# Language Fundamentals CODE subdirectory. Chapter 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Bring In theC#Wizards! by Andrew Troelsen
ISBN:1590590554
To wrap up this chapter, like to offer Apress ©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 that the of goal This comprehensive text sections starts with brief overview 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 moves to key technical and .NET illustrate the use architectural of a number issues of keyfor tools in developers. order to prime the pump for further exploration on your own terms. If you wish to follow along, create a brand new C# Windows Forms application named WinFormsVsNetWizardsApp. Table of Contents C# and the .NET Platform, Second Edition
Revisiting the Solutions Explorer
Introduction
Part One - Introducing C# and the .NET Platform
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 Part Two -ofThe C# Programming number connections to your Language 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
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Figure Adding a new data connection Chapter 19 - 17-28: ASP.NET Web Applications Chapter 20 - XML Web Services Index At this point you are provided with the Data Link Properties dialog box, which allows you to specify the name and List of Figures location of the database you wish to communicate with. For this example, connect to your local Cars database List of Tables (Figure 17-29).
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4 - 17-29: Object-Oriented Programming withconnection C# Figure Configuring the new data Chapter 5 - Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Once you have added a SQL connection, you are then able to view the underlying data source (Figure 17-30). As - Callback Interfaces, Delegates, and Events you would guess, each database item (tables, views, stored procedures, and whatnot) can be opened from within Chapter 8 - Advanced C# Type Construction Techniques VS .NET by simply double-clicking the item of interest. To take things out for a test drive, double-click the Part Three - Programming with .NET Assemblies Inventory table and GetPetName stored procedure. Chapter 7
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Figure 17-31: Design time connection configuration
Chapter 6
- Interfaces and Collections Once you doneInterfaces, so, select Delegates, this item from Icon Tray, and using the Properties window, select the name of Chapter 7 -have Callback and the Events
your Cars from theConstruction ConnectionString property drop-down list. At this point, you should be pleased to Chapter 8 -connection Advanced C# Type Techniques seeThree that a-valid connection string been created Part Programming with .NEThas Assemblies
and configured on your behalf (within the #region code
block): 9 - Understanding .NET Assemblies Chapter Chapter 10 - Processes, AppDomains, Contexts, and Threads
public Form1 : Late System.Windows.Forms.Form Chapter 11 class - Type Reflection, Binding, and Attribute-Based Programming { Four - Leveraging the .NET Libraries Part sqlConnection1; Chapter private 12 - ObjectSystem.Data.SqlClient.SqlConnection Serialization and the .NET Remoting Layer ... 13 - Building a Better Window (Introducing Windows Forms) Chapter private void InitializeComponent() { Chapter 15 - Programming with Windows Forms Controls this.sqlConnection1 = new System.Data.SqlClient.SqlConnection(); Chapter 16 - The System.IO Namespace this.sqlConnection1.ConnectionString = " "; Chapter 17 - Data Access with ADO.NET ... Part Five - Web Applications and XML Web Services } Chapter 18 - ASP.NET Web Pages and Web Controls } Chapter 14 - A Better Painting Framework (GDI+)
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index 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 may List of Figures 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 build 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Figure- 17-32: Specifying the connection for the new SqlDataAdapter Object-Oriented Programming with C#
Chapter 4 Chapter 5
- Exceptions and Object Lifetime
Chapter 6 step - Interfaces andtoCollections The next allows you configure how the data adapter should submit data to the data store (Figure 17-33). Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services IndexFigure 17-33: Specifying data store updates List of Figures 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 SQL 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals Figure Creating Programming the initial SELECT logic Chapter 4 - 17-34: Object-Oriented with C# Chapter 5
- Exceptions and Object Lifetime
Once you are finished with the data adapter configuration tool, open your code window and check out the - Interfaces and Collections InitializeComponent() method. As you can see, the new SqlCommand data members are configured Chapter 7 - Callback Interfaces, Delegates, and Events 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 Construction Techniques same syntax by hand during the chapter. However, here is a partial snapshot: Chapter 6
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
public class Form1 : System.Windows.Forms.Form { Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming private System.Data.SqlClient.SqlConnection sqlConnection1; Part Four - Leveraging the .NET Libraries private System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1; Chapter 12 - Object Serialization and the .NET Remoting Layer private System.Data.SqlClient.SqlCommand sqlSelectCommand1; Chapter private 13 - Building a Better Window (Introducing Windows Forms) System.Data.SqlClient.SqlCommand sqlInsertCommand1; Chapter private 14 - A Better Painting Framework (GDI+) System.Data.SqlClient.SqlCommand sqlUpdateCommand1; Chapter private 15 - Programming with Windows Forms Controls System.Data.SqlClient.SqlCommand sqlDeleteCommand1; Chapter private 16 - The System.IO Namespace void InitializeComponent() Chapter { 17 - Data Access with ADO.NET Part Five - Webthis.sqlDataAdapter1.DeleteCommand Applications and XML Web Services = this.sqlDeleteCommand1; Chapter 18 - ASP.NET this.sqlDataAdapter1.InsertCommand Web Pages and Web Controls = this.sqlInsertCommand1; this.sqlDataAdapter1.SelectCommand = this.sqlSelectCommand1; Chapter 19 - ASP.NET Web Applications this.sqlDataAdapter1.TableMappings.AddRange Chapter 20 - XML Web Services (new System.Data.Common.DataTableMapping[] { Index List of Figures 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 - Processes, AppDomains, Contexts, and Threads
System.Data.SqlDbType.Int, 4, "CarID")); C# and the .NET Platform, Second Edition
...
by Andrew Troelsen Apress © 2003 (1200 pages)
} }
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and issues for .NET developers. Hopefully, things architectural look quite familiar. 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 Table of Contents 17-35). C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure namesWindows at design time Chapter 13 - 17-35: BuildingAltering a Bettercolumn Windowdisplay (Introducing Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Using the Configured Data Adapter
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with 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 and 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 Controls contents of the Inventory table via a Button Click event: Part Five - Web Applications and XML Web Services
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
private void btnLoadInventory_Click(object sender, System.EventArgs e) { List of Figures DataSet myDS = new DataSet(); List of Tables sqlConnection1.Open(); sqlDataAdapter1.Fill(myDS); dataGrid1.DataSource = myDS.Tables["Inventory"]; } Index
Design Time Connections and Data Adapters, Take Two The previous example illustrated how you can gain design time assistance for connection and data adapter types, 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 Connections 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# and the .NET Platform, Second Edition SqlCommand type that is preconfigured to trigger the underlying stored proc: by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
this.sqlCommand1.CommandText = "dbo.[GetPetName]"; This comprehensive text starts with a brief overview of the this.sqlCommand1.CommandType = System.Data.CommandType.StoredProcedure; C# language and then quickly moves to key technical and this.sqlCommand1.Connection = this.sqlConnection1; architectural issues for .NET developers. this.sqlCommand1.Parameters.Add( new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", 4, Table ofSystem.Data.SqlDbType.Int, Contents System.Data.ParameterDirection.ReturnValue, false, C# and the .NET Platform, Second Edition ((System.Byte)(0)), ((System.Byte)(0)), "", Introduction System.Data.DataRowVersion.Current, null)); Part One - Introducing C# and the .NET Platform 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)); Part Two - The C# Programming Language this.sqlCommand1.Parameters.Add( Chapter 3 - C# Language Fundamentals new System.Data.SqlClient.SqlParameter("@petName", Chapter 4 - Object-Oriented Programming with C# System.Data.SqlDbType.VarChar, 20, Chapter 5 - Exceptions and Object Lifetime System.Data.ParameterDirection.Output, false, Chapter 6 - Interfaces and Collections ((System.Byte)(0)), ((System.Byte)(0)), "", Chapter 7 - Callback Interfaces, Delegates, and Events System.Data.DataRowVersion.Current, null)); Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NETgenerated Assemblies Again, once the wizards have the initial code, you are free to tweak and change things to your liking. Chapter By way10 of -example, Processes, select AppDomains, one of theContexts, SqlCommand and Threads types and check out the Parameters property of the
Properties As you would guess, the dialog Programming editor allows you to edit parameter objects at design Chapter 11 -window. Type Reflection, Late Binding, and resulting Attribute-Based time. Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, SecondTime Edition Working with DataSets at Design by Andrew Troelsen
ISBN:1590590554
In the previous code samples, you pages) directly created and allocated a DataSet type in your code base. As you Apress © 2003 (1200 would guess, VSThis .NET also offers design time support for the mighty In fact, VS .NET allows you comprehensive text starts with a brief overview ofDataSet. the to generate two types of DataSets: C# language and then quickly moves to key technical and architectural issues for .NET developers.
Untyped DataSets: This corresponds to the DataSets examined thus far in the chapter. Untyped DataSets are simply variables of type System.Data.DataSet. Table of Contents
Typed DataSets: This optionEdition allows you to generate a new .NET class type that derives from the C# and the .NET Platform, 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. Part One - Introducing C# and the .NET Platform Introduction
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 Part TwoDataSet - The C#has Programming Language of type been added and allocated
to a new instance, which can then be manipulated in your
Chapter code. 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime Working with Typed DataSets at Design Time - Interfaces and Collections
Chapter 6
Chapter 7 -wrap Callback Interfaces, Delegates, and Now, let's up this chapter by checking outEvents the role of typed DataSets. First of all, understand the Chapter 8 - Advanced C#the Type Construction Techniques typed DataSets perform same function as an untyped DataSet (they contain a client-side cache of Part Three Programming .NET Assemblies data) and -are populated with and updated via a corresponding
data adapter. The key difference is, simply put,
Chapter - Understanding ease of9use. For example, .NET whenAssemblies you use untyped DataSets, you are required to drill into the internal Chapter structure 10 of - the Processes, DataTable AppDomains, type using Contexts, the Rows and and Threads Columns properties. While nothing is horribly wrong
with this11approach, it would be nice to build wrapper class that hides the internal complexities from view. Chapter - Type Reflection, Late Binding, anda Attribute-Based Programming For Four example, rather than writing this: Part - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) // A basic untyped DataSet. Chapter lblCarID.Text 14 - A Better=Painting myDS.Tables["Inventory"].Rows[0]["CarID"]; Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
you can write the following:
Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
// A typed DataSet. Chapter 18 - ASP.NET Web Pages and Web Controls lblCarID.Text myDS.Inventory[0].CarID; Chapter 19 - ASP.NET=Web Applications Chapter 20 - XML Web Services Index
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 Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# Figure Creating a typed DataSet at design time Chapter 5 - 17-36: Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
From the dialog box simply supply a name (such as CarsDataSet) and reconfirm the tables to wrap. At this - Callback Interfaces, Delegates, and Events point, you can make use of your new DataSet-derived type as follows:
Chapter 7 Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
private -void btnLoadInventory_Click(object sender, System.EventArgs e) Understanding .NET Assemblies { Chapter 10 - Processes, AppDomains, Contexts, and Threads sqlConnection1.Open(); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming sqlDataAdapter1.Fill(carsDataSet1); Part Four - Leveraging the .NET Libraries dataGrid1.DataSource = carsDataSet1.Inventory; Chapter 12 - Object Serialization and the .NET Remoting Layer } Chapter 9
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 you - Programming with to Windows Forms Controls Note that no longer need make use of the Tables property to gain access to the contained Inventory Chapter table. Using 16 - The a strongly System.IO typed Namespace DataSet, you simply reference the Inventory property. Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Under the Hood of the Typed DataSets
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter - ASP.NET Applications Activate19the Solution Web Explorer and click the Show all Files button. You will find that your strongly typed Chapter DataSet 20is-represented XML Web Services by 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 Index 17-37). List of Figures List of Tables
Figure 17-37: Typed DataSets have a related "code behind" file C# and the .NET Platform, Second Edition
ISBN:1590590554 Troelsen If you switch overby to Andrew Class View, you will find that the newly generated CarsDataSet class defines a © 2003 (1200 pages)the rows and tables it is responsible for maintaining (Figure 17-38). number of nestedApress classes to represent
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - 17-38: Type Reflection, Late Binding, type and Attribute-Based Figure The DataSet-derived maintains a set Programming of nested classes. Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
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 Painting Framework (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 Better Window (Introducing Windows Forms) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
[Serializable()] ... Part Five - Web Applications and XML Web Services public class CarsDataSet : DataSet {...} Chapter 17 - Data Access with ADO.NET
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Chapter 20 - to XML Webout Services If you were check the nested InventoryDataTable type, you would see that in addition to deriving Index from System.Data.DataTable, this new type is enumerable, and contains a number of private DataColumn List of Figures types that 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# and the .NET Platform, Second Edition tend to offer better performance. by Andrew Troelsen
ISBN:1590590554
Apressup © 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 you are looking for with a solid complement to this Thishere. comprehensive text starts a brief overview of the chapter, I recommend checking C# Guide language and then quickly moves to key technical and 2002). outA Programmer's to ADO.NET in C# by Mahesh Chand (Apress, architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Summary
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
ADO.NET is a new data©access technology developed with the disconnected n-tier application firmly in Apress 2003 (1200 pages) mind. The System.Data namespace contains the core typesofyou This comprehensive text startsmost with of a brief overview theneed to programmatically interact with rows, columns, tables, and views. As you have seen, the System.Data.SqlClient and C# language and then quickly moves to key technical and architectural issues for .NET System.Data.OleDb namespaces define thedevelopers. types you need to establish an active connection. The centerpiece of ADO.NET is the DataSet. This type represents an in-memory representation of any Table number of Contents of tables 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# the .NET relations Platform, on Second them while disconnected from the remote data store. Introduction Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language connected layer of ADO.NET, and came to understand the role of data reader types. Chapter 1
Chapter 3
- C# Language Fundamentals
Chapter 4 - Object-Oriented Programming C#of the tools available from VS .NET. As you have seen, We wrapped things up by checking out a with subset Chapter 5 - Exceptions and Object do Lifetime the numerous integrated wizards indeed help you with mundane and repetitive coding details. Like any Chapter code generation 6 - Interfaces 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 Interfaces, andshould Eventsbe able to tweak the wizard-generated code to suit your needs. Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Part Five:C# Web Applications andISBN:1590590554 XML Web Services by Andrew Troelsen Apress © 2003 (1200 pages)
Chapter List This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Chapter 18: ASP.NET Web Pages and Web Controls Table of Contents
Chapter 19: ASP.NET Web Applications
C# and the .NET Platform, Second Edition Introduction Chapter 20: XML Web Services
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Chapter C# 18: ASP.NET Web Pages and Web Controls ISBN:1590590554 by Andrew Troelsen Apress © 2003applications (1200 pages) in this text have focused on Windows Forms and console-based Until now, all of the example This comprehensive text explore starts with a the brief.NET overview of the front ends. In the next two chapters, you how platform facilitates the construction of C# language and then quickly moves to key technical and browser-based presentation layers. To begin, you'll quickly review a number of key Web-centric atoms architectural issues for .NET developers. (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 classic ASP. Of course, if you are already "Web aware," feel free to skim or skip these initial sections Table of Contents entirely. On the other hand, if you come to ASP.NET with limited Web development experience, this primer C# and the .NET Platform, Second Edition will provide a valuable frame of reference for the chapters that follow. Introduction
Part One - Introducing C# and the .NET Platform
With this Web primer complete, the remainder 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 Part Two - The logic C# Programming presentation and businessLanguage logic into
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#, - Object-Oriented Programming C#interpreted scripting languages (such as VBScript). Given (such as VB .NET, MC++, etc.), ratherwith than Chapter this last5point, - Exceptions it is critical and toObject understand Lifetime that you simply cannot build ASP.NET applications without solid
knowledge OOP, interfaces, and attributes. Chapter 6 - of Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
- Advanced C# Type Construction Techniques The Role of HTTP
Chapter 8
Part Three - Programming with .NET Assemblies
Web applications are very .NET different animals than traditional desktop applications (to say the least). The first Chapter 9 - Understanding Assemblies obvious10difference is that a production-level will always involve at least two networked Chapter - Processes, AppDomains, Contexts,Web and application Threads machines course, duringLate development it isAttribute-Based entirely possible to have a single machine play the role of Chapter 11 -(of Type Reflection, Binding, and Programming bothFour client and server). this fact, Part - Leveraging theGiven .NET Libraries
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 Object Serialization and and the .NET Remoting Layer question Hypertext Transfer Protocol (HTTP). Chapter 13is- the Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
When a client machine launches a Web browser (such as Netscape Navigator or Microsoft Internet
Chapter 15 -an Programming with Explorer), HTTP request is Windows made to Forms accessControls a particular resource (such as an *.aspx file or *.htm file) Chapter 16 The System.IO Namespace located on a server machine. HTTP is a text-based protocol that is built upon a standard request/response Chapter 17 -For Data Access with ADO.NET paradigm. example, if you navigate to http://www.intertech-inc.com, the browser software Part Five - Web Applications and XML Web Services leverages a Web technology termed Domain Name
System (DNS), which converts the registered URL into
Chapter 18 -numerical ASP.NET Web Web ControlsAt this point, the browser opens a socket connection afour-part valuePages (aka and an IP address). Chapter 19via - ASP.NET (typically port 80),Web andApplications sends the HTTP request to the default page at the Intertech-inc.com Web site. Chapter 20 - XML Web Services
Once the hosting Web server receives the incoming HTTP request, the specified resource may contain Index
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 Figures
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# and the .NET Platform, Second Edition are currently logged onto your site. As you will see in the next chapter, ASP.NET provides numerous ways by Andrew Troelsen to handle state, many of which are commonplace to any Web ISBN:1590590554 platform (session variables, cookies, and Apress © 2003 (1200 pages) application variables) as well as some new techniques (such as view state and the application cache). This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andWeb the .NET Platform, Secondand Edition Understanding Applications Web Servers by Andrew Troelsen
ISBN:1590590554
Now that you better understand thepages) role of HTTP and the underlying request/response cycle of the Web, Apress © 2003 (1200 we need to qualify some further terminology. begin, a Web application This comprehensive text startsTo with a brief overview 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 moves to key technical and components (.NET or classic architectural for .NET developers. COM binaries) stored within aissues particular directory (and 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. Table of Contents
AWeb server a software product in charge of hosting your Web applications and typically provides a C# and the .NETisPlatform, Second Edition number of related services such as integrated security, File Transfer Protocol (FTP) support, mail Introduction exchange services, and forth. Internet Information Part One - Introducing C# so and the .NET Platform
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 Part Two - The C# Programming Language
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 - Object-Oriented Programming with C# *.asp versus *.aspx), IIS will load the correct host process based on the incoming HTTP request. Chapter 3 Chapter 5
- Exceptions and Object Lifetime
Chapter When you 6 -build Interfaces ASP.NET and Collections Web applications, you will be required to interact with IIS. Be aware, however,
that IIS7is not automatically selected whenand youEvents install the Windows OS 2000 or XP Professional Edition Chapter - Callback Interfaces, Delegates, (you can't ASP.NET theConstruction "Home" editions of Windows). Therefore, depending on the configuration Chapter 8 -run Advanced C#on Type Techniques of your development machine, youAssemblies may be required Part Three - Programming with .NET
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 - Understanding .NET Assemblies select "Add/Remove Windows Components." Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
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 - Object Serialization and the .NET Remoting Layer will execute correctly (you will simply get back a blank page). Luckily, you can reconfigure IIS to Chapter 13 host - Building Better Window (Introducing Windows Forms) command line tool (using the /i flag). .NET aapplications by running the aspnet_regiis.exe Part Four - Leveraging the .NET Libraries
Chapter 14 - A Better Painting Framework (GDI+)
Assuming have IIS properly installed on your workstation, you can interact with IIS from the Chapter 15 -you Programming with Windows Forms Controls Administrative folder Namespace (located in the Control Panel folder). For the purposes of this chapter, we are Chapter 16 - TheTools System.IO only concerned the with Default Web Site node (Figure 18-2). Chapter 17 - Datawith Access ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures 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# and the .NET Platform, Second Edition
ISBN:1590590554 Andrew Troelsen When you createby ASP.NET Web applications using VS .NET, you will automatically receive a new virtual Apress © 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 Forcomprehensive the sake of illustration, you overview wish to create text startsassume with a brief of the a simple Web application named C#islanguage thenfolder quickly to key technical Cars. The first step to createand a new onmoves your machine to holdand the collection of files that constitute issues for .NET developers. this new site (for architectural example, C:\CarsWebSite).
Next, you need to create a new virtual directory to host the Cars site. Simply rightclick the Default Web Site Table nodeofofContents IIS and select New | Virtual Directory from the context menu. This menu selection launches an C# and the .NET Platform, Second Edition integrated wizard. Skip past the welcome screen and give your Web site a name (Cars). Next, you are Introduction asked to specify the physical folder on your hard drive that contains the various files and images that Part One - Introducing theC:\CarsWebSite). .NET Platform represent this site (in C# thisand case,
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 to the files it Language contains, the Part Two - The C# Programming
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 - Object-Oriented Programming with C# Property dialog boxes integrated within IIS). When you are finished, you will see that your new virtual Chapter 5 - Exceptions and Object Lifetime directory has been registered with IIS (Figure 18-3). Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Figure 18-3: The Cars virtual directory
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition The Role ofC#HTML by Andrew Troelsen
ISBN:1590590554
Once you have configured a virtual directory to host your Web application, you need to create the content Apress © 2003 (1200 pages) itself. Recall that This Webcomprehensive application is simply the with termagiven to the setofofthe files that constitute the functionality text starts brief overview of the site. To be C# sure, a vast number of these files will contain syntactic language and then quickly moves to key technical and tokens defined by the Hypertext architectural issuesisfor .NET developers. Markup Language (HTML). HTML a standard markup language used to describe how literal text, images, external links, and various HTML-based GUI widgets are rendered by the client-side browser. Table This of particular Contents aspect of Web development is one of the major reasons that many programmers dislike
building Web-based programs. C# and the .NET Platform, 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 Introduction to have working knowledge of HTML as you work Part One -a Introducing C# and the .NET Platform
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
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals An HTML consists of a set of tags thatwith describe Chapter 4 file - Object-Oriented Programming C# the look and feel of a given Web page. As you would
expect,5the- basic structure of an HTML document tends to remain the same. For example, *.htm files (or Chapter Exceptions and Object Lifetime alternatively, *.html files) and close with and tags, typically define a section, Chapter 6 - Interfaces andopen Collections and so 7forth. Keep inInterfaces, mind that Delegates, HTML is not case sensitive. Therefore, in the eyes of the hosting browser, Chapter - Callback and Events , , and are identical. - Advanced C# Type Construction Techniques
Chapter 8
Part Three - Programming with .NET Assemblies
To illustrate some HTML basics, open Visual Studio .NET, insert an empty HTML file using the File | New |
Chapter 9 -selection, Understanding .NETthis Assemblies File menu and save file under your physical directory as default.htm. If you examine the new Chapter 10 Processes, AppDomains, and Threads *.htm file created by the IDE, you willContexts, find something like the following: Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Chapter 16 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Chapter 12 - Object Serialization and the .NET Remoting Layer
Index List of Figures
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# and the the .NET tags Platform, are usedSecond to specify Edition the text string that should be placed in the title bar of the Web browser application. ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition HTML FormC#Development by Andrew Troelsen
ISBN:1590590554
The real action ofApress an *.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 inputof widgets. Simply put, an HTML form is This comprehensive texttostarts with a briefuser overview 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 moves to key technical and architectural for .NETan developers. Web application via HTTP. 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: Table of Contents C# and the .NET Platform, Second Edition
Part One - Introducing C# and the .NET Platform Chapter 1 - The Philosophy of .NET Chapter 2 - Building C# Applications Introduction
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals This form been assigned the ID and friendly Chapter 4 has - Object-Oriented Programming with C#name of "MainForm". Typically, the opening tag
supplies action attribute that specifies Chapter 5 an - Exceptions and Object Lifetimethe URL to which to submit the form data, as well as the method of transmitting that data itself (POST or GET). You will examine this aspect of the tag in just a bit. Chapter 6 - Interfaces and Collections For the7time being, let's look at Delegates, the sort of and items that can be placed in an HTML form. The Visual Studio Chapter - Callback Interfaces, Events .NET IDE an C# HTML on the Toolbox dialog box that allows you to select each HTML-based UI Chapter 8 provides - Advanced Typetab Construction Techniques widget (Figure 18-4). Part Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 18-4: The HTML Controls Toolbox Table 18-1 gives a rundown of some of the more common HTML GUI widgets. Table 18-1: Common HTML GUI Types
HTML GUI Widget Button
in Life C#Meaning and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
A button that does not support the type attribute used to trigger a SUBMIT or
This comprehensive text starts with a brief overview of the RESET. This sort of button can be used to trigger a block of client-side script C# language and then quickly moves to key technical and code or any otherfor logic that does not require a trip to the Web server. architectural issues .NET developers.
Checkbox
Standard UI selection elements.
Radio Button Table of Contents C#Listbox and the .NET Platform, Second Edition Introduction Dropdown Part One - Introducing C# and the .NET Platform
Image1 Chapter
Allows you to specify an image to render onto the form. - The Philosophy of .NET
Chapter - BuildingThis C# Applications Reset2Button button element has its type attribute set to RESET. This instructs the Part Two - The C# Programming Language browser to clear out the
Chapter 3
values in each UI element on the page to their default
- C# Language values.Fundamentals
Chapter 4
- Object-Oriented Programming with C# Submit Thisand button element has its type attribute set to SUBMIT, which sends the form Chapter 5 - Exceptions Object Lifetime
Button
Chapter 6
data to the recipient of a request.
- Interfaces and Collections
Chapter 7 - CallbackThese Interfaces, Delegates, Events Text Field UI elements areand used to hold a single line (or multiple lines) of text. The Chapter 8 - Advanced C# TypeField Construction Password renders Techniques input data using an asterisk (*) character mask.
Text Area
Part Three - Programming with .NET Assemblies
Password- Understanding .NET Assemblies Field
Chapter 9
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Note As shown later in this chapter, the System.Web.UI.HtmlControls namespace defines managed .NET types that correspond to these raw HTML widgets.
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Building an HTML-Based User Interface
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Before you add the HTML widgets to the HTML , it is worth pointing out that VS .NET allows you to edit the overall look and feel of the *.html file itself using the integrated Properties window. For example, if Chapter 17 - Data Access with ADO.NET you were to select DOCUMENT (Figure 18-5), you would be able to set the background color of the page Part Five - Web Applications and XML Web Services (in addition to other details). Chapter 16 - The System.IO Namespace
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 18-5: Editing an HTML document via VS .NET Now, update the of the default.html file to display some literal text that prompts the user to enter a
user name and password and choose a background color of your liking (be aware that you can enter and C# and the .NET Platform, Second Edition format textual content directly onto the HTML designer): by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and This Isissues thefor Cars Site architectural .NET Web developers. Prompt for user input--> Table ofThe Cars Login Page C# and the .NET Platform, Second Edition
Introduction Please C# enter your Part One - Introducing and the .NET user Platform name and password.
Chapter 1 - The Philosophy of .NET Chapter 2 - Building C# Applications Part Two - The C# Programming Language Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections Here, the tag defines the heading (or size) of the text to display. denotes a line break,
Chapter 7 Callback Interfaces, and Events marks a paragraph, and willDelegates, italicize the text in question. Chapter 8
- Advanced C# Type Construction Techniques
NowThree let's -build the HTMLwith form.NET itself. In general, Part Programming Assemblies
each HTML widget is described using a name attribute (used to identify the item programmatically) and a type attribute (used to specify which UI element you are Chapter 9 - Understanding .NET Assemblies interested in placing in the declaration). Depending Chapter 10 - Processes, AppDomains, Contexts, and Threads on which UI widget you manipulate, you will find additional attributes specific to that particular item. As you would expect, each UI element and its Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming attributes can be modified using the Properties window. Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
The UI you will build here will contain two text fields (one of which is a Password widget), as well as two
Chapter 13 - Building Better Window (Introducing Windows Forms) button types (one fora submitting the form data and the other to reset the form data to the default values): Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Chapter 17 - Data Access with ADO.NET
User Name: Part
Chapter 18 ASP.NET Web Pages and Web
Password: Controls Chapter
Chapter 20 - XML Web Services
Index List of
List of Tables Chapter 16 - The System.IO Namespace
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction
Figure 18-6: TheC# initial at the default.htm Part One - Introducing andcrack the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
page
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition The Role ofC#Client-Side Scripting by Andrew Troelsen
ISBN:1590590554
Now that you have a better understanding of how to construct an HTML form, the next issue is to examine Apress © 2003 (1200 pages) the role of client-side scripting. A given *.html may contain blocks script code that will be emitted in This comprehensive text startsfile with a brief overview ofof the the response stream and processed by the requesting browser. There are C# language and then quickly moves to key technical and two major reasons that clientarchitectural issues for .NET developers. side scripting is used: To validate user input before posting back to the Web server Table of Contents
Tothe interact with the Document Object Model (DOM) of the target browser C# and .NET Platform, Second Edition Introduction
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 Part Twosubmitting - The C# Programming before the form dataLanguage to the 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 - Object-Oriented Programming with C# user than posting back on a slow connection, only to server. 4(After all, nothing is more annoying to the Chapter - Exceptions and Object Lifetime receive5instructions to address input errors! ) Part One - Introducing C# and the .NET Platform
Chapter 6
- Interfaces and Collections In addition validating user input, client-side Chapter 7 -toCallback Interfaces, Delegates, andscripts Eventscan 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 Construction Techniques expose a set of objects that can be leveraged to control how the browser should behave. One major Part Three - Programming with .NET Assemblies annoyance is the fact that different browsers tend to expose similar, but not identical, object models. Thus, Chapter 9 - Understanding .NET Assemblies if you emit a block of client-side script code that interacts with the DOM, it may not work identically on all Chapter 10 - Processes, AppDomains, Contexts, and Threads browsers. Chapter 8
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four the .NETthe Libraries Note- Leveraging ASP.NET provides HttpRequest.Browser
property, which allows you to determine at runtime
Chapter 12 the - Object Serialization and the .NET Remoting Layer request. capacities of the browser that sent the current Chapter 13 - Building a Better Window (Introducing Windows Forms)
There are scripting languages that(GDI+) can be used to author client-side script code. Two of the more Chapter 14 -many A Better Painting Framework popular15are VBScript andwith JavaScript. is a subset of the Visual Basic 6.0 programming language. Chapter - Programming WindowsVBScript Forms Controls 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 with ADO.NET browser, do not use VBScript for your client-side scripting logic. Chapter 16 - The System.IO Namespace
Part Five - Web Applications and XML Web Services
Chapter 18 -popular ASP.NET Web Pages and Web Controls The other scripting language is JavaScript. Be very aware that JavaScript is in no way, shape, or Chapter - ASP.NET Web Applications form a 19 subset of the Java language. While JavaScript and Java have a somewhat similar syntax, Chapter 20 -isXML Services programming language, and thus is far less powerful than Java itself. The JavaScript notWeb a full-fledged Index good news is that all modern day Web browsers support JavaScript, which makes it a natural candidate List for of client-side Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction
Figure 18-7: Capturing widget events Part One - Introducing C# andHTML the .NET Platform 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
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
- Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime This Is the Cars Web Site Chapter 6 - Interfaces and Collections Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer BGCOLOR="#66ccff"> Chapter Chapter Chapter 17 - Chapter 2 - Building C# Applications Part Two - The C# Programming Language ... Chapter 3 id - C# Fundamentals Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections At this point, you canInterfaces, open yourDelegates, browser ofand choice and navigate to the default.html page hosted by your Chapter 7 - Callback Events
Cars virtual directory and test out your client-side script logic: Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
http://localhost/Cars/default.htm
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
andForm the .NET Platform, Second Edition SubmittingC# the Data (GET and POST) by Andrew Troelsen
ISBN:1590590554
Now that you have a simple HTML page, you need to examine how to transmit the form data back to the Apress © 2003 (1200 pages) Web server for processing. When you build an with HTML form,overview you typically This comprehensive text starts a brief of thesupply an action attribute on the opening tag to specify the recipient of the incoming form data. Possible receivers include mail C# language and then quickly moves to key technical and architectural .NETPage developers. servers, other HTML files, an issues Active for Server (classic or .NET), and so forth. For this example, you use a classic ASP file named ClassicAspPage.asp. Update your default.html file by specifying the following attribute in the opening tag, as shown here: Table of Contents C# and the .NET Platform, Second Edition
Part One - Introducing C# and the .NET Platform ... Chapter 1 - The Philosophy of .NET Introduction
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter This extra 3 -attribute C# Language specifies Fundamentals that when the Submit button for this form is clicked, the form data should be
sent to 4the-ClassicAspPage.asp file located within Chapter Object-Oriented Programming with C# the Cars virtual directory on the current machine (i.e., localhost). you specify method = "GET" as the mode of transmission, the form data is appended to Chapter 5 -When Exceptions and Object Lifetime the query as a set ofCollections name/value pairs separated by ampersands. For example: Chapter 6 string - Interfaces and Chapter 7
- Callback Interfaces, Delegates, and Events
http://localhost/Cars/ClassicASPPage.asp?txtUserName= Chapter 8 - Advanced C# Type Construction Techniques Andrew&txtPassword=thisismypassword&btnSubmit=Submit Part Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
The other method of transmitting form data to the Web server is to specify method = "POST":
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
< form ID="MainForm" Chapter 12 name="MainForm" - Object Serialization and the .NET Remoting Layer action="http://localhost/Cars/ClassicAspPage.asp" method = "POST"> Chapter 13 - Building a Better Window (Introducing Windows Forms) ...
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with In this case, the form data is ADO.NET not appended to the query string, but instead is written to a separate line Part Five - Web Applications and XML Web Services within the HTTP header. Using POST, the form data
is not directly visible to the outside world and is
Chapter 18 a- wee ASP.NET Web secure Pages and Webimportantly, Controls therefore bit more (more POST data is not limited by character length). For the Chapter 19 - make ASP.NET Applications time being, useWeb of HTTP GET to send the form data to the receiving *.asp page. Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the Active .NET Platform, Second Edition Building a Classic Server Page by Andrew Troelsen
ISBN:1590590554
A classic Active Server a hodgepodge of HTML and server-side script code. If you have never ApressPage © 2003 is (1200 pages) worked with classic ASP, understand that the goal is to dynamically This comprehensive text starts withof a ASP brief overview of the build HTML on the fly using server-side scriptC# logic and a small set of classic COM objects and related language and then quickly moves to key technical and COM libraries. For example, architecturalVBScript issues for developers. you may have a server-side (or.NET JavaScript) block that reads a table from a data source using classic ADO and returns the rows as a generic HTML table. Table For this of Contents example, 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 the form .NET data Platform, Second to Edition but it makes the point). The server-side script logic will make use of VBScript (as denoted by the Introduction "language" directive).C# and the .NET Platform Part One - Introducing 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 Part Two - The C# Programming Language *.asp file with the following HTML and scripting logic: Chapter 2 Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
- Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections Chapter 7 - Callback Interfaces, Delegates, and Events The Cars Page Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies ChapterHere Understanding .NET Assemblies is what you sent me: Chapter
- Processes, AppDomains, Contexts, and Threads User Name: Chapter Programming Part Four Leveraging the .NET Libraries Password: Chapter Chapter
13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 5
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with 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 Controls a number of properties, methods, and events. You call the Request.QueryString() method to examine the Chapter 19 - ASP.NET Web Applications values contained in each HTML widget submitted via method = "GET". Part Five - Web Applications and XML Web Services
Chapter 20 - XML Web Services
Index Also note that the notation is a shorthand way of saying "Insert the following directly into the List of Figures 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: ...
Obviously, the Request and Response objects of classic ASP provide a number of additional members beyond Write() and QueryString(). Furthermore, classic ASP also defines a small number of additional
COM objects (Session, Server, Application, and so on) that you can use while constructing your Web C# and the .NET Platform, Second Edition application. by Andrew Troelsen
ISBN:1590590554
Apress © 2003 (1200COM pages)objects are effectively dead. However, you will see that the Note Under ASP.NET, these System.Web.UI.Page basetext class defines named that provide similar This comprehensive starts with identically a brief overview of properties the C# language and then quickly moves to key technical and functionality. architectural issues for .NET developers.
To test the ASP logic, simply load the default.htm page from a browser and submit the form data. Once the script is processed on the Web server, you are returned a brand new (dynamically generated) HTML Table of Contents display (Figure 18-8). C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Figure The C# dynamically generated HTML Chapter 8 - 18-8: Advanced Type Construction Techniques Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Responding to POST Submissions
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Currently, your default.htm file specifies HTTP GET as the method of sending the form data to the target *.asp file. Using this approach, the values contained in the various GUI widgets are appended to the end of Chapter 12 - Object Serialization and the .NET Remoting Layer the query string. It is important to note that the ASP Request.QueryString() method is only able to extract Chapter 13 - Building a Better Window (Introducing Windows Forms) data submitted via the GET method. Part Four - Leveraging the .NET Libraries
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming Controls If you would rather submitwith formWindows data to Forms the Web resource using HTTP POST, the Request.Form collection Chapter can be 16 used - The to read System.IO the values Namespace on the server. For example: Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
ChapterHere ASP.NET Web Pages and Web isControls what you sent me: Chapter
- ASP.NET Web Applications Chapter 20 -User XML Web Services Name: Index
Password: List of Figures List of Tables
That wraps up the Web development primer. Hopefully those of you who are new to Web development have a better understanding of what goes on behind the scenes. Now, before we check out how the .NET platform improves upon the current state of affairs, let's take a brief moment to bash (which is to say "critique") classic ASP. SOURCE CODE
The default.html and ClassicAspPage.asp files are included under the ClassicAspCars subdirectory.
C# and with the .NET Platform,ASP Second Edition The Problem(s) Classic by Andrew Troelsen
ISBN:1590590554
While many successful Apress Web © 2003applications (1200 pages) have been created using classic ASP, this architecture is not without its downside. Perhaps the biggest downfall classic ASP isofthe same point that makes it a This comprehensive text starts with of a brief overview the powerful platform: server-side scripting languages. Scripting languages such as VBScript and JavaScript C# language and then quickly moves to key technical and architectural issues developers. are interpreted, typeless entities thatfor do.NET not lend themselves to robust OO programming techniques. For example, under classic ASP, there was no concept of classical inheritance, attributes, strongly typed data, or classical polymorphism (although the interface-driven nature of classic COM did allow for interfaceTable of polymorphism). Contents based C# and the .NET Platform, Second Edition
Another problem with classic ASP is the fact that an *.asp page does not yield very modularized code. Introduction Given ASP is a blend of HTML and script in Part Onethat - Introducing C# and the .NET Platform
a single page, most ASP Web applications are a
confused of Philosophy two very different Chapter 1 mix - The of .NET programming techniques. While it is true that classic ASP allows you to partition2 reusable code distinct include files, the underlying object model does not support true Chapter - Building C# into Applications separation of C# concerns. In an ideal world, Part Two - The Programming Language
a Web framework would allow the presentation logic (i.e., HTML tags) to exist independently from the business logic (i.e., functional code). Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C# A final issue to consider here is the fact that classic ASP demands a good deal of boiler-plate, redundant
Chapter 5 - that Exceptions Object Lifetimeprojects. Almost all Web applications need to validate user input, script code tends toand repeat between Chapter 6 Interfaces and Collections repopulate the state of HTML widgets before emitting the HTTP response, generate an HTML table of Chapter 7 so - Callback data, and forth. Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andof the .NET Platform, Second Edition Some Benefits ASP.NET by Andrew Troelsen
ISBN:1590590554
ASP.NET addresses each of the limitations of classic ASP (and brings a number of new bells and whistles Apress © 2003 (1200 pages) to the game). First and foremost, ASP.NET files (*.aspx) not useof server-side scripting languages. As This comprehensive text starts with a briefdo overview the mentioned earlier, ASP.NET allows you to use real programming languages such as C#, MC++, and C# language and then quickly moves to key technical and issues for .NET developers. Visual Basic .NETarchitectural (or any other .NET-aware language). Because of this, you can apply all of the technique you have learned throughout this book directly to your Web development efforts. As you would expect, *.aspx pages can make use of the .NET class libraries as well as the functionality provided by any of your Table of Contents custom assemblies. Like always, simply access the Add References dialog box and find the assembly in C# and the .NET Platform, Second Edition question. Introduction
Note While it is true you .NET can literally Part One - Introducing C# that and the Platformuse
any .NET assembly, it should make sense that the types
are of no use within a Web application. Surprisingly, Chapter 1 within - The System.Windows.Forms.dll Philosophy of .NET is extremely useful when programming with ASP.NET, given that you can Chapter 2 System.Drawing.dll - Building C# Applications use C# GDI+ to dynamically generate Part Two - The Programming Language
an image file on the Web server (as seen at the end of this
Chapter 3 chapter). - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C# Next, ASP.NET applications provide numerous ways to decrease the amount of code you need to write to
Chapter 5 - For Exceptions and Object the Lifetime begin with. example, through use of server-side Web controls, you can build a browser-based front Chapter 6 Interfaces and Collections end using various GUI widgets that emit raw HTML tags automatically. Other Web controls are used to Chapter - Callbackvalidation Interfaces, and Events perform7 automatic of Delegates, your GUI items, which decreases (if not eliminates) the amount of clientChapter 8 - Advanced C#responsible Type Construction Techniques side JavaScript you are for authoring. To add to the current laundry list of benefits, ponder the Part Three -aspects Programming with .NET Assemblies additional of ASP.NET:
Chapter 9
- Understanding .NET Assemblies ASP.NET supportsAppDomains, a technique Contexts, termed code Chapter 10 - Processes, and behind, Threads which allows you to separate your presentation
logic your businessLate logic. Chapter 11 from - Type Reflection, Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
ASP.NET makes use of true compiled .NET assemblies, not interpreted scripting languages, which results in much faster execution.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter ASP.NET 14 - A Better Web controls Painting allow Framework programmers (GDI+) to build the GUI of a Web app in a manner similar to
building a traditional desktop application. Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
ASP.NET Web controls automatically maintain their state during postbacks using a hidden form field named __VIEWSTATE.
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Controlsobject oriented. You no longer need to examine the Form ASP.NET Web applications are Web completely Chapter 19 - ASP.NETcollections Web Applications or QueryString to obtain the values submitted by the client (although these techniques are Chapter - XML Web Services still20 supported). Index List ofASP.NET Figures Web applications can be easily configured using standard IIS settings or using a Web
configuration file (web.config). List ofapplication Tables ASP.NET Web applications are extremely simple to deploy given that .NET assemblies are not registered into the system registry. To begin seeing these and other benefits in action, let's get to know the ASP.NET namespaces, all of which are contained within the System.Web.dll assembly.
C# and the .NET Platform, Second Edition The ASP.NET Namespaces by Andrew Troelsen
ISBN:1590590554
The .NET base class libraries contain numerous namespaces focused on Web-based technologies. Apress © 2003 (1200 pages) Generally speaking, these namespaces bewith grouped three major This comprehensive text can starts a briefinto overview of the categories: core Web atoms (e.g., types that allow you to interact with the HTTP request and response, C# language and then quickly moves to key technical and configuration types, e-mail, and issues forand .NET developers. security types), UIarchitectural widgets (WebForm HTML controls), and XML Web services (examined in Chapter 20).Table 18-2 documents the ASP.NET-centric namespaces. Table of 18-2: Contents Table ASP.NET Namespaces C# and the .NET Platform, Second Edition
Web-Centric Namespace Introduction
Meaning in Life
Part One - Introducing C# and the .NET Platform
System.Web
System.Web defines core types that enable browser/Web server communication (such as request and response capabilities, Chapter 2 - Building C# Applicationscookie manipulation, and file transfer). Chapter 1
- The Philosophy of .NET
Part Two - The C# Programming Language
System.Web.Caching This namespace contains types that facilitate caching support Chapter 3 - C# Language Fundamentals Chapter 4
for a Web - Object-Oriented Programming with application. C#
Chapter 5 - Exceptions and Object Lifetime System.Web.Configuration This namespace contains types that allow you to Chapter 6 - Interfaces and Collections programmatically interact with the project's Web.config file. Chapter 7 - Callback Interfaces, Delegates, and Events
System.Web.Mail Defines the types that allow you to integrate e-mail functionality. - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies System.Web.SessionState Defines the types that allow you to maintain stateful information Chapter 9 - Understanding .NET Assemblies on a per-user basis (e.g., session state variables). Chapter 8
Chapter 10 - Processes, AppDomains, Contexts, and Threads
System.Web.Security
Defines types that allow you to programmatically secure your site.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and These the .NET Remoting Layer System.Web.UI namespaces define a number of types that allow you to Chapter 13 Building a Better Window build (Introducing a GUI front Windows end forForms) your Web application. System.Web.UI.WebControls Chapter 14 - A Better Painting Framework (GDI+)
System.Web.UI.HtmlControls
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
The Core Types of System.Web
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
The System.Web namespace defines the minimal and complete set of types that allow you to build an ASP.NET Web application. Table 18-3 is a quick rundown of some items of interest, many of which are Chapter 20 - XML Web Services examined in greater detail throughout this chapter. Chapter 19 - ASP.NET Web Applications Index
List of Figures
Table 18-3: Core Types of the System.Web Namespace
List of Tables
System.Web Type Meaning in Life C# and the .NET Platform, Second Edition HttpApplication
ISBN:1590590554 by Andrew Troelsen The HttpApplication class defines the members common to all Apress © 2003 (1200 pages)
ASP.NET applications. As you will see, the global.asax file defines a
This comprehensive text starts with a brief overview of the class derived from HttpApplication. C# language and then quickly moves to key technical and architectural issues for .NET developers.
HttpApplicationState
The HttpApplicationState class enables developers to share global information across multiple sessions in an ASP.NET application.
Table of Contents HttpBrowserCapabilities
Enables the server to compile information on the capabilities of the
C# and the .NET Platform, Second browser Editionthat sent the HTTP request. Introduction
HttpCookie
Provides a type-safe way to access multiple HTTP cookies.
Part One - Introducing C# and the .NET Platform
Chapter HttpRequest 1 - The Philosophy of Provides .NET an object-oriented way to enable browser-to-server Chapter 2
communication. - Building C# Applications
Part Two - The C# Programming Language
HttpResponse
Provides an object-oriented way to enable server-to-browser communication.
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NETWeb Platform, Second Editionby Hand Creating anC#ASP.NET Application by Andrew Troelsen
ISBN:1590590554
ASP.NET Web applications typically make use of a technique termed code behind, which allows you to Apress © 2003 (1200 pages) separate your programming code from HTML logic. While this is certainly the recommended This comprehensive textyour starts with presentation a brief overview of the approach, it is stillC# technically possible to avoid using a code behind file language and then quickly moves to key technical andand directly embed .NET code within architectural issues for .NET the *.aspx file. However, be very aware that ifdevelopers. you choose to build your ASP.NET pages in this manner, you are essentially re-creating a major issue found with classic ASP (the hodgepodge of script blocks and HTML presentation tags in a single server-side file). Table of Contents
Nevertheless, walk through an example of building a single-paged Web application that does not make C# and the .NETlet's Platform, Second Edition use of code behind, and learn some basic features of ASP.NET in the process. Create a new virtual directory Introduction named to a specific Part One CarsInventoryPage - Introducing C# andthat themaps .NET Platform
directory on your hard drive. Next, create a new file named
CarsInventoryPage.aspx and save it in the physical directory you just created. Chapter 1 - The Philosophy of .NET Chapter 2
- Building C# Applications
Coding the *.aspx File
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals For this4example (and this example only),with you C# will avoid the use of a code behind file, and therefore your Chapter - Object-Oriented Programming
server-side willLifetime be embedded directly within the *.aspx file. The goal of this page is simple: Chapter 5 - programming Exceptions andlogic Object Open a6connection to the database (created in Chapter 17) and display the current inventory. To do so, Chapter - Interfaces and Cars Collections you will7make use ofInterfaces, three ASP.NET WebForm controls (a Label, DataGrid, and Button type) and a block of Chapter - Callback Delegates, and Events server-side- C# code. Here is the complete page, with analysis to follow: Advanced C# Type Construction Techniques
Chapter 8
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries This is the cars inventory page Chapter 13 - Building a Better Window (Introducing Windows Forms) void GetTheData(object sender, EventArgs e) Chapter 14 - A Better Painting Framework (GDI+) { Chapter 15 - Programming with Windows Forms Controls SqlConnection sqlConn = Chapter 16 - The System.IO Namespace new SqlConnection("Data Source=.;Initial Catalog=Cars;UID=sa;PWD="); Chapter 17 -sqlConn.Open(); Data Access with ADO.NET Part Five - Web Applicationscmd and XML SqlCommand = Web Services Chapter 18 - ASP.NET Web Pages and Web Controls* From Inventory", sqlConn); new SqlCommand("Select Chapter 19 -inventoryGrid.DataSource ASP.NET Web Applications = cmd.ExecuteReader(); Chapter 20 -inventoryGrid.DataBind(); XML Web Services Index sqlConn.Close(); List of Figures } List of Tables Click on the button below to fill the DataGrid Chapter 12 - Object Serialization and the .NET Remoting Layer
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
The Directive Apress © 2003 (1200 pages)
This comprehensive starts withfile a brief overviewopen of the The first thing to be aware of is that atext given *.aspx will typically with a set of page-level directives. C# language and then quickly moves to key technical and ASP.NET directives are always denoted with markers, and may be qualified with various architectural issues for .NET developers. attributes to inform the ASP.NET runtime how to process the information.
Every *.aspx file must have at minimum a directive that is used to define the managed language used within the page (via the language directive). Also, the directive may also define the name C# and the .NET Platform, Second Edition of the related code behind file (if any), enable tracing, and so forth. Table 18-4 documents some of the more Introduction interesting -centric attributes.
Table of Contents
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET Table 18-4: Some (But Not All) of the @Page Attributes
Chapter 2
- Building C# Applications
Attribute of the Meaning Part Two - The C# Programming Language
in Life
@Page Chapter 3 Directive - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
ClassName
Chapter 6
This attribute allows you to define a specific name for the autogenerated class type.
- Interfaces and Collections CodeBehind This attribute used to specify the name of the related code behind Chapter 7 - Callback Interfaces, Delegates, andisEvents Chapter 8
file. - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies EnableViewState Indicates whether
view state is maintained across page requests (more
Chapter 9
- Understanding .NET Assemblies details later). True if view state is maintained; otherwise, false. The Chapter 10 - Processes, AppDomains, Contexts, and Threads default value is true. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Inherits Defines Part Four - Leveraging the .NET Libraries
a code behind class for the page to inherit. Can be any class derived from the Page class. Used to specify the name of the class in Chapter 12 - Object Serialization and the .NET Remoting Layer the code behind file from which this type derives. Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter Trace14 - A Better Painting Framework Indicates(GDI+) whether tracing is enabled (true or false). Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
The Chapter 17 - Data AccessDirective with ADO.NET Part Five - Web Applications and XML Web Services
In addition to the directive, a given *.aspx file may specify further directives. In this example, you make use of the directive (in conjunction with the Namespace attribute) to explicitly state that Chapter 19 - ASP.NET Web Applications this page is using types within the System.Data.SqlClient namespace. As you would guess, if you need to Chapter 20 - XML Web Services make use of additional .NET namespaces, you simply specify multiple directives. Chapter 18 - ASP.NET Web Pages and Web Controls
Index
List ofNote Figures The directive is only necessary if you are not making use of code behind. When you List of Tables do make use of code behind, you will reference external namespaces using the C# "using" keyword.
Given your current knowledge of .NET, you may wonder how this *.aspx file avoided specifying the System.Data or System namespaces. The reason is due to the fact that all *.aspx pages automatically have access to a small set of key .NET namespaces: System System.Collections System.Configuration System.IO System.Text System.Text.RegularExpressions
All of the System.Web-centric namespaces
C# and the .NET Platform, Second Edition
ISBN:1590590554 by Andrew Troelsen ASP.NET does define a number of other directives that may appear in an *.aspx file above and beyond Apress © 2003 (1200 pages) and ; however, I'll reserve comment for the time being.
This comprehensive text starts with a brief overview of the language and then quickly moves to key technical and The "Script" C# Block architectural issues for .NET developers.
Even though server-side scripting is dead under ASP.NET, code that is embedded within an *.aspx file is scoped within tags. Note that it is critical that all of your server-side code blocks are defined to execute Table ofserver, Contents at the using the runat="server" attribute: C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
void GetTheData(object sender, EventArgs e)
Chapter 1 {
- The Philosophy of .NET
Chapter... 2 - Building C# Applications Part } Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# The signature of this helper method should look strangely familiar. Recall from our examination of Windows Chapter 5 - Exceptions and Object Lifetime
Forms 6that- aInterfaces given event must match the pattern defined by a related .NET delegate. And, just like Chapter andhandler Collections Windows when you wishDelegates, to handleand a server-side button click, the delegate in question is Chapter 7 Forms, - Callback Interfaces, Events
System.EventHandler (which, as you recall, can only call methods that take a System.Object as the first - Advanced C# Type Construction Techniques parameter and a System.EventArgs as the second). Part Three - Programming with .NET Assemblies Chapter 8
Chapter 9 -scope Understanding .NET Assemblies Within the of the GetTheData() method, you make use of standard ADO.NET logic to bind the records Chapter 10 Processes, AppDomains, Contexts, and Threads returned by the DataReader to a variable of DataGrid. Now, if you have a background in classic ASP, I am Chapter Type Reflection, Latedays Binding, and Attribute-Based pleased11to-inform you that your of nested for-loops andProgramming table-centric HTML tags are over. Rather than Part Four - Leveraging .NETtable Libraries manually building thethe HTML by hand,
ASP.NET DataGrids automatically emit the correct tag set
Chapter 12 - Object Serialization and the .NET Remoting Layer automatically. Chapter 13 - Building a Better Window (Introducing Windows Forms)
The ASP.NET Widget Declarations Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
The final point of interest is the declaration of the Button, Label, and DataGrid WebForm controls. Like classic ASP and raw HTML, ASP.NET Web widgets are scoped within elements. This time, however, the Chapter 17 - Data Access with ADO.NET opening element is marked with the runat="server" attribute. This again is critical, as this tag informs Part Five - Web Applications and XML Web Services the ASP.NET runtime that before the HTML is emitted into the response stream, the contained ASP.NET Chapter 18 - ASP.NET Web Pages and Web Controls widgets have a chance to render their HTML appearance. Chapter 16 - The System.IO Namespace
Chapter 19 - ASP.NET Web Applications
Chapter 20 -Web XMLcontrols Web Services ASP.NET are declared with and tags, and are also marked with the Index runat="server" attribute. Within the opening tag, you will specify the name of the WebForm control (such as List Label, of Figures Button, DataGrid) and any number of name/value pairs that will be used at runtime to render the correct
HTML. Now, as you will see in the next example, these name/value pairs correspond directly to properties of List of Tables the corresponding class type. For example, when you declare a DataGrid and specify BackColor="White", you have basically set the BackColor property of the System.Web.UI.WebControls.DataGrid type. In any case, ponder the following declarations:
Click on the button below to fill the DataGrid
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
Apress © 2003 type (1200 has pages) Finally, notice that the Button made use of the OnClick attribute to specify the name of the serverside function thatThis will be called whentext the starts user clicks Button widget. At this point, you can open a browser comprehensive with athe brief overview of the C#CarsInventoryPage.aspx language and then quicklypage: moves to key technical and and navigate to the architectural issues for .NET developers.
http://localhost/FirstAspNetWebApp/CarsInventoryPage.aspx The of results are seen in Figure 18-9. Table Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - 18-9: ASP.NET Web Figure Your firstApplications ASP.NET Web application Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition The ASP.NET Compilation Cycle by Andrew Troelsen
ISBN:1590590554
One question thatApress may be on your © 2003 (1200 mind pages) at this point is how exactly your block of C# code was executed by the ASP.NET runtime. As you are already well aware, the CLR can of only This comprehensive text starts with a brief overview theinteract with CIL code that is contained within aC# .NET assembly (obviously, your *.aspx file is not a .NET binary, but a simple text file). language and then quickly moves to key technical and architectural for .NET developers. Behind the scenes, when the issues initial HTTP request comes in for a given *.aspx file, the runtime will parse all of the code within the blocks and generate a brand new dynamic assembly. This image is then persisted to file, and stored under a very specific location (sometimes called the shadow directory) on the Table Contents Webof server machine: C# and the .NET Platform, Second Edition Introduction
:\\Microsoft .NET\Framework\\Temporary ASP.NET Files
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2 -directory, Building C# Under this youApplications will find a subdirectory that reflects the name of the hosting virtual directory. From Part Two - The Programming here, you will C# need to drill downLanguage through some
further auto-generated folders (which are named based on
Chapter various3hash - C# algorithms) Language until Fundamentals you find the name of the compiled *.dll assembly. Again, the name of your
.NET assembly will be unique (Figure 18-10). Chapter 4 - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Figure The location of the dynamically created assembly Chapter 15 - 18-10: Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17.NET - Data Access with Like any assembly, youADO.NET are able to open up the binary using ildasm.exe and check out the underlying Part - Web Applications andLooking XML Web CIL,Five manifest, and metadata. at Services Figure 18-11,
you can see that your immediate base class is
Chapter 18 - ASP.NET Web Pages and Web Controls System.Web.UI.Page. Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Figure 18-11: *.aspx files become classes that extend System.Web.UI.Page. After the assembly has been created upon the initial HTTP request, it will be reused for all subsequent requests, and thus will not have to be recompiled. Understanding this factoid should help explain why the first request of an *.aspx page takes the longest, and subsequent hits to the same page are extremely efficient. Now, open up your CarsInventoryPage.aspx file in Notepad and make some sort of code update, such as changing the Text value for the Button type:
ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and If you save this file and request the page once again, you will indeed find a time lag. Also, if you were to look architectural issues for .NET developers.
at the shadow directory, you will find another auto-generated *.dll. Because the runtime is smart enough to detect changes to *.aspx files, it becomes painfully simple to update a running Web application. All you Table needoftoContents do is place the updated *.aspx files into the directory of the Web applications and the ASP.NET C# runtime and the will .NET takePlatform, care of the Second rest.Edition Clients who are currently using the older version of the .NET assembly are completely unaware of the change as they still make use of the previous version. However, new clients will Introduction automatically receive C# theand latest greatest assembly. Figure 18-12 illustrates the ASP.NET compilation Part One - Introducing theand .NET Platform cycle. 1 - The Philosophy of .NET Chapter Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - 18-12: Processes, Contexts, and Threads Figure TheAppDomains, ASP.NET compilation cycle Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Note This is a huge improvement to classic ASP, where updating ASP files typically involved reregistering COM servers and rebooting the Web server.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Controlling the Generated Class Name
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
As you have seen, the ASP.NET compilation cycle will automatically generate a class derived from System.Web.UI.Page when the initial HTTP request comes through. By default, the name of this class will Part Five - Web Applications and XML Web Services be based on the filename of the *.aspx file; however, this can be changed by using the ClassName attribute Chapter 18 - ASP.NET Web Pages and Web Controls of the @Page directive: Chapter 17 - Data Access with ADO.NET
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Index
List of Figures List of Tables If you were now to open this auto-generated *.dll using ildasm.exe, you would find that the name of your
derived class is indeed CarsInventory, rather than CarsInventoryPage_aspx. Cool! At this point you have seen that you can indeed embed your C# code directly within a *.aspx file. However, this is evil and I will not take this approach for the remainder of this text. Speaking of "evil things," you may agree that it is a bit of a drag to manually build a virtual directory by hand. Given both of these issues, let's check out how VS .NET will not only build a virtual directory automatically, but also automatically configure ASP.NET pages to make use of an associated code behind file. SOURCE CODE
The CarsInventoryPage.aspx file is included under the CarsInventoryPage subdirectory.
and the .NETWeb Platform, Second Editionvia VS .NET Creating anC#ASP.NET Application by Andrew Troelsen
ISBN:1590590554
Visual Studio .NET simplifies process Apress © 2003 the (1200 pages) of building ASP.NET Web applications in a number of ways. To illustrate, let's now re-create the previous Web with pageausing the functionality This comprehensive text starts brief overview of the of VS .NET. First, create a new C# Web Application project workspace named BetterAspNetCarApp (Figure 18-13). C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
Advanced C# Type Construction Techniques Figure- 18-13: Creating an ASP.NET application project with VS .NET
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies Before 10 you- click the OKAppDomains, button, takeContexts, a minuteand to notice that the Location text box maps not to a specific Chapter Processes, Threads
folder on hard drive, but rather to theand URL of the machine hosting this Web application. The Visual Chapter 11 your - Type Reflection, Late Binding, Attribute-Based Programming Studio solution the files.NET (*.sln) are stored Part Four.NET - Leveraging Libraries
under the "My Documents\Visual Studio Projects" subfolder. Once the new project workspace has been will notice that a design time template has been Chapter 12 - Object Serialization and the .NET created, Remotingyou Layer opened automatically (Figure 18-14). Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Figure 18-14: Your design time template
Index
List of Figures
Much like a Windows Forms application, this template represents the visual appearance of the *.aspx file List of Tables you are constructing. The difference, of course, is that you are using HTML-based WebForm controls rather than Win32-based Windows Forms controls. Note that the default name for this page is WebForm1; however, using the VS .NET Properties window, you are free to change this to a more fitting name (such as BetterAspNetCarApp.aspx). Note The GUI of an *.aspx page may be authored in two manners. If the pageLayout property of the DOCUMENT object is set to GridLayout (the default), you will be able to use absolute position of your GUI widgets. While this is very Windows Forms-like, be aware that older browsers may not support absolute positioning of HTML elements. If you wish to build a GUI that will be displayed correctly in all browsers, you should switch the pageLayout property to FlowLayout. Next, click the Show All Files button and check out the Solution Explorer window (Figure 18-15). You have been given a number of new files and external assembly references.
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Figure 18-15: Initial files an Assemblies ASP.NET application Part Three - Programming with of .NET Chapter 9
- Understanding .NET Assemblies
Chapter - Processes, You will10get to know theAppDomains, role of theseContexts, files overand theThreads course of this chapter; for now, Table 18-5 hits the Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming highlights. Part Four - Leveraging the .NET Libraries
Chapter 12 - Object and the .NET Remoting Layer Table 18-5: Initial Serialization Project Files Chapter 13 - Building a Better Window (Introducing Windows Forms)
Generated Files of Meaning in Life an ASP.NET Web Chapter 15 - Programming with Windows Forms Controls Application Chapter 16 - The System.IO Namespace Project Chapter 14 - A Better Painting Framework (GDI+)
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Services assemblyinfo.cs Like Web any VS .NET
project, this file is used to hold common
Chapter 18 - ASP.NET Web Pages assembly-level and Web Controls attributes. Chapter 19 - ASP.NET Web Applications
*.aspx
Chapter 20 - XML Web Services
*.aspx.cs Index List*.aspx.resx of Figures List of Tables
Global.aspx Global.aspx.cs Global.aspx.resx Web.config
Every ASP.NET page in your application is represented by three related files. The *.aspx file is used to define the WebForm controls used by the page. The *.aspx.cs file is the code behind file that will hold your related C# code. Finally, if your page makes use of any .NET resource, they will be defined in the *.aspx.resx file. As explained later in this chapter, your ASP.NET Web applications may optionally define a class type that derives from the HttpApplication type. These files set up this scenario. ASP.NET Web applications also make use of *.config files. Unlike a desktop application, however, this file will always be named web.config regardless of the name of the Web application.
Next, if you open IIS, you see that a new virtual directory (BetterAspNetCarApp) has been automatically created on your behalf. As you can see, each file in the workspace has been included in this virtual directory. The physical folder to which this virtual directory is mapped can be located under a subdirectory of :\Inetpub\wwwroot\.
Examining the Initial *.aspx File
If you examine the C# structure and theof .NET yourPlatform, *.aspx fileSecond (by switching Edition to the HTML view on the IDE's designer), you will find a skeleton of an ASP.NET Web page. Note ISBN:1590590554 that the directive now bydeclaration Andrew Troelsen makes use of theApress Codebehind and pages) Inherits attributes: © 2003 (1200 This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and Table of Contents C# and the .NET Platform, Second Edition Introduction WebForm1 Part One - Introducing C# and the .NET Platform Chapter 1 - The Philosophy of .NET Chapter Part Two The C# Programming Language 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# Chapter Chapter 6 - Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Recall that the Codebehind attribute is used to define the name of the source code file that contains the "real" code used by this page, while the Inherits attribute specifies the name of the class in the file that Part Four - Leveraging the .NET Libraries functions as your immediate base class. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Examining the Code Behind File
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Now, ensure that the Show all Files option has been selected and open up this page's code behind file (BetterAspNetCarApp.aspx.cs):
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
using System; using System.Collections; Chapter 19 - ASP.NET Web Applications using System.ComponentModel; Chapter 20 - XML Web Services using System.Data; Index using System.Drawing; List of Figures using System.Web; List of Tables using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls;
Chapter 18 - ASP.NET Web Pages and Web Controls
namespace BetterAspNetCarApp { public class WebForm1 : System.Web.UI.Page { private void Page_Load(object sender, System.EventArgs e) { } override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent()
{ C#this.Load and the .NET+= Platform, Second Edition new System.EventHandler(this.Page_Load);
} }
by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
}
First, because you are making use of a code behind file, you have no need to use the directive, but can opt for the C# "using" keyword. Next, notice how the class specified by the Inherits C# and the .NET Platform, Second Edition attribute of the directive has a base class of System.Web.UI.Page. Also, your page has Introduction been wired up to handle two lifetime events: Init and Load (more information on a page's life cycle later in Part One - Introducing C# and the .NET Platform this chapter).
Table of Contents
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition Coding theC# BetterAspNetCarApp Web Application by Andrew Troelsen
ISBN:1590590554
Rather than manually defining all ofpages) the Web widgets used by this *.aspx file (as you did in the previous example), Apress © 2003 (1200 you can make use of the VS .NET designer andwith theaWeb tabofofthe the IDE's Toolbox (Figure 18-16). This comprehensive text starts briefForms overview C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - 18-16: Understanding .NET Assemblies Figure The ASP.NET Web Controls Toolbox Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter Create 11 a GUI - Type thatReflection, mimics the Late previous Binding, *.aspx and Attribute-Based file. Notice thatProgramming you are able to leverage the IDE's Properties Part window Four to - Leveraging automatically the add .NETthe Libraries name/value
pairs used for the control's ASP declaration. Handling the Button's
Click event also simplified when VS Remoting .NET. Like a Windows Forms application, simply activate the event Chapter 12 - is Object Serialization and using the .NET Layer view from Properties window, and(Introducing type in the name of the event handler function. As you would expect, your Chapter 13 -the Building a Better Window Windows Forms) code behind has Painting been updated to handle this event using standard C# event syntax. In addition, notice that Chapter 14 - Afile Better Framework (GDI+) the class in the code fileForms has member Chapter 15 defined - Programming withbehind Windows Controlsvariables that correspond to the ASP.NET Web widgets declared file. Namespace Chapter 16 in- the The *.aspx System.IO Chapter 17 - Data Access with ADO.NET
At this point, all you need to do is implement the event handler to bind the data from the Inventory table to the DataGrid widget:
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
using System.Data.SqlClient; ... Index public class WebForm1 : System.Web.UI.Page List { of Figures List of Tables // Widget member variables. protected System.Web.UI.WebControls.Button btnGetTheData; protected System.Web.UI.WebControls.DataGrid inventoryGrid; Chapter 20 - XML Web Services
private void Page_Load(object sender, System.EventArgs e) {} override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.btnGetTheData.Click += new System.EventHandler(this.btnGetTheData_Click); this.Load += new System.EventHandler(this.Page_Load); }
private void btnGetTheData_Click(object sender, System.EventArgs e) C# and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen SqlConnection sqlConn = Apress © 2003 (1200 pages) new SqlConnection("Data Source=.;Initial Catalog=Cars;UID=sa;PWD="); This comprehensive text starts with a brief overview of the sqlConn.Open(); C# language and=then quickly moves to key technical and SqlCommand cmd architectural issues for .NET developers. new SqlCommand("Select * From Inventory", sqlConn); inventoryGrid.DataSource = cmd.ExecuteReader(); inventoryGrid.DataBind(); Table of Contents sqlConn.Close(); C# and the .NET Platform, Second Edition } Introduction } Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2 now - Building C# ASP.NET Applications You can take your application out for a test drive. Of course, the output is identical to the Part Two - The C# Programming Language CarsInventoryPage Web application.
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C# The Role of the \bin Directory - Exceptions and Object Lifetime
Chapter 5
Chapter 6 -use Interfaces and When you VS .NET asCollections the starting point for your ASP.NET Web applications, you will find that the virtual Chapter 7 Callback Interfaces, Delegates, and Events directory has a subdirectory named \bin. Each time you compile your current project, VS .NET will store the latest Chapter 8 - Advanced C# *.dll Typeassembly Construction Techniques and greatest copy of the within this folder. However, as you may be guessing, this is not the *.dll Part Three Programming with .NET Assemblies loaded by-the CLR. As always, when the initial
HTTP request comes in, the runtime will copy this precompiled
Chapter *.dll into9 the - Understanding shadow directory .NETfor Assemblies subsequent use. Chapter 10 - Processes, AppDomains, Contexts, and Threads
Note One nice by-product of the "precompilation" cycle is that the name of the *.dll assembly in the shadow directory is the same as the item in the \bin folder (rather than the auto-generated filename seen in the Part Four - Leveraging the .NET Libraries previous example). Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building aThe Better Window (Introducing Windows Forms)under the Chapter 18 subdirectory. SOURCE BetterAspNetCarApp files are included Chapter 14 - A Better Painting Framework (GDI+) CODE Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the Second Edition The Composition of.NET anPlatform, ASP.NET Page by Andrew Troelsen
ISBN:1590590554
Recall that the directive Apress © 2003 (1200 pages)is used to specify the name of the code behind file, as well as the name of the classThis in said file that becomes yourwith base class: comprehensive text starts a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers. Table of Contents C# Second Asand youthe can.NET see,Platform, the value of the Edition Inherits attribute is the fully qualified name of the System.Web.UI.PageIntroduction derived type (which by default will be named WebForm1). Because the Inherits attribute works in Part One - Introducing C#specified and the .NET Platform conjunction with the file by the Codebehind
attribute, be aware that if you wish to change the
Chapter 1 the - The Philosophy of .NET name of class in your code behind as follows: Chapter 2 - Building C# Applications Part Two - The C# Programming Language public class CarInventoryPage
: System.Web.UI.Page
Chapter { ...3 } - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime you will6need to updateand theCollections value of the related *.aspx file's Inherits attribute identically: Chapter - Interfaces Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
When you first begin to work with code behind, one slightly odd concept to wrap your head around is that when you are writing code in the *.aspx file, you can reference the custom methods and properties defined Part Four - Leveraging the .NET Libraries in the designated code behind file. Assume you have built a simple function that obtains the current time Chapter 12 - Object Serialization and the .NET Remoting Layer and date: Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
public class SomeWebForm: System.Web.UI.Page { Chapter 16 - The System.IO Namespace ... Chapter 17 - Data Access with ADO.NET public string GetDateTime() Part Five - Web Applications and XML Web Services { return DateTime.Now.ToString(); } Chapter 18 - ASP.NET Web Pages and Web Controls } Chapter 15 - Programming with Windows Forms Controls
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Index To reference this method in your *.aspx code, you can write the following: List of Figures List of Tables
...
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# and the .NET Platform, Second Edition public void GetDateTime() ISBN:1590590554 by Andrew Troelsen { Apress © 2003 (1200 pages) Response.Write("It is now " + DateTime.Now.ToString()); This comprehensive text starts with a brief overview of the } C# language and then quickly moves to key technical and architectural issues for .NET developers.
}
And then simply call:
Table of Contents
C# and the .NET Platform, Second Edition
Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2 you - Building Applications Again, if wish to C# follow the standard philosophy of ASP.NET, you will attempt to avoid making use of Part Two - The C# Programming Language server-side code logic within your *.aspx files.
However, in the event that you do wish to trigger a method in
Chapter 3 -behind C# Language Fundamentals your code file, do attempt to build methods that can be invoked as cleanly as possible (as seen Chapter 4 this - Object-Oriented here). In way, all of yourProgramming "real" code iswith safeC# within your *.aspx.cs file while the GUI widgets defined in Chapter 5 -file Exceptions and Object the *.aspx can be scrapped asLifetime needed. Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and .NET Platform, Second The Derivation ofthean ASP.NET PageEdition by Andrew Troelsen
ISBN:1590590554
Each *.aspx file isApress ultimately © 2003represented (1200 pages) by a class deriving from System.Web.UI.Page. Like any base class, this type provides a polymorphic to all derived types.ofHowever, the Page type is not the This comprehensive textinterface starts with a brief overview the only member in your inheritance hierarchy. Figure 18-17 documents the full chain of inheritance for a C# language and then quickly moves to key technical and custom page. architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals Figure The derivation of an ASP.NET Chapter 4 - 18-17: Object-Oriented Programming with C# page Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Key Members of the Delegates, System.Web.UI.Page Type - Callback Interfaces, and Events
Chapter 7 Chapter 8
- Advanced C# Type Construction Techniques
The first parent class of interest is Page itself. Here you will find numerous properties that mimic the classic COM objects of classic ASP. Table 18-6 describes some (but by no means all) of the core Chapter 9 - Understanding .NET Assemblies properties. Part Three - Programming with .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Table 18-6: Properties of the Page Type
Part Four - Leveraging the .NET Libraries
Chapter System.Web.UI.Page 12 - Object Serialization and Meaning the .NET Remoting in LifeLayer
Property Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Application
Gets the HttpApplicationState object provided by the runtime
Chapter 15 - Programming with Windows Forms Controls
Chapter Cache16 - The System.IO Namespace Indicates the Cache object in which to store data for the page's
application Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
IsPostBack
Gets a value indicating whether the page is being loaded in response to a client postback, or if it is being loaded and Chapter 19 - ASP.NET Web Applications accessed for the first time Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 20 - XML Web Services
Request Index List of Figures ListResponse of Tables
Gets the HttpRequest object that provides access data from incoming HTTP requests Gets the HttpResponse object that allows you to send HTTP response data back to a client browser
Server
Gets the HttpServerUtility object supplied by the HTTP runtime
Session
Gets the System.Web.SessionState.HttpSessionState object, which provides information about the current request's session
Trace
Provides access to the System.Web.TraceContext type, which allows you to log custom messages during debugging sessions
and the the .NET Platform, Second Interacting C# with Incoming HTTPEdition Request by Andrew Troelsen
ISBN:1590590554
As you have seenApress earlier© in this chapter, 2003 (1200 pages) the basic flow of a Web session begins with a client logging onto a site, filling in userThis information, and clicking a Submit to post back comprehensive text starts with abutton brief overview of thethe HTML form data to a given Web page for processing. In most cases, the opening tag of the form statement specifies an action and method C# language and then quickly moves to key technical and architectural .NET developers. attribute that indicates the file issues on thefor Web server that will be sent the data in the various HTML widgets, and the method of sending this data (GET or POST). Here is an example: Table of Contents
C# and the .NET Platform, Second Edition Introduction
Part Oneclassic - Introducing C# and the .NET Platform Unlike ASP, ASP.NET does not support
an object named Request. However, all ASP.NET pages do
Chapter 1 -System.Web.UI.Page.Request The Philosophy of .NET inherit the property, which provides access to the raw HTTP request. Under Chapter 2 Building C#manipulates Applications an instance of the HttpRequest class type. Table 18-7 lists some core the hood, this property Part Two - The Programming members that,C# not surprisingly,Language mimic the
Chapter 3
same members found within the classic COM Request object.
- C# Language Fundamentals
Chapter Table 18-7: 4 - Object-Oriented Members of the Programming HttpRequest with Type C# Chapter 5
- Exceptions and Object Lifetime
System.Web.HttpRequest - Interfaces and Collections Member
Chapter 6 Chapter 7
Meaning in Life
- Callback Interfaces, Delegates, and Events
Chapter ApplicationPath 8 - Advanced C# Type Construction Gets Techniques the virtual path to the currently executing server Part Three - Programming with .NET Assemblies application.
Chapter 9
Browser
- Understanding .NET Assemblies
Provides information about incoming client's browser capabilities.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Cookies Part Four - Leveraging the .NET Libraries
Gets a collection of client's cookie variables.
Chapter 12 - Object Serialization and the .NET Remoting Layer
FilePath
Indicates the virtual path of the current request. This property is read-only.
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Files 15 - Programming with Windows Forms Gets the collection of client-uploaded files (multipart MIME Chapter Controls Chapter 16 - The System.IO Namespace
format).
Chapter Filter 17 - Data Access with ADO.NET
Gets or sets a filter to use when reading the current input
Part Five - Web Applications and XML Web Services stream.
Chapter 18 - ASP.NET Web Pages and Web Controls
Form 19 - ASP.NET Web Applications Chapter
Gets a collection of Form variables.
Chapter 20 - XML Web Services Headers
Gets a collection of HTTP headers.
Index
HttpMethod
List of Figures List of Tables
Indicates the HTTP data transfer method used by the client (GET, POST).
IsSecureConnection
Indicates whether the HTTP connection is secure (that is, HTTPS).
QueryString
Gets the collection of QueryString variables.
RawUrl
Gets the current request's raw URL.
RequestType
Indicates the HTTP data transfer method used by the client (GET, POST).
ServerVariables
Gets a collection of Web server variables.
UserHostAddress
Gets the IP host address of the remote client.
UserHostName
Gets the DNS name of the remote client.
Again, for those of you who have experience with classic ASP, it is important to point out that there is no
object named Request (or Response). Thus, when you author a block of ASP.NET code such as the C# and the .NET Platform, Second Edition following: by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
You Are: This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
what you are really doing is accessing the ServerVariables property on the underlying HttpRequest type, as shown here: Table of Contents
You Second Edition C# and the Are: .NET Platform, Two - The C# Programming Language Part Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
- Exceptions and Object Lifetime Obtaining Browser Statistics
Chapter 5 Chapter 6
- Interfaces and Collections The first of HttpRequest is the Browser property, which provides access to an underlying Chapter 7 interesting - Callbackaspect Interfaces, Delegates, and Events
HttpBrowserCapabilities HttpBrowserCapabilities Chapter 8 - Advanced C# object. Type Construction Techniques in turn exposes a set of members that allow you to programmatically investigate statistics Part Three - Programming with various .NET Assemblies
regarding the browser that sent the incoming HTTP request. To illustrate, assume you have a new ASP.NET Web application that contains a single *.aspx file. When the Chapter 9 - Understanding .NET Assemblies user clicks the Button Web control, the server-side event handler will create a System.String that contains Chapter 10 - Processes, AppDomains, Contexts, and Threads various statistics about the client-side browser and display the results on a Label Web control. The Button Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Click event handler is as follows: Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
private void btnGetBrowserStats_Click(object sender, System.EventArgs e) { Chapter 14 - A Better Painting Framework (GDI+) string theInfo = ""; Chapter 15 - Programming with Windows Forms Controls theInfo += String.Format("
Is the client AOL? {0}", Chapter 16 - The System.IO Namespace Request.Browser.AOL); Chapter 17 - Data Access with ADO.NET theInfo += Part Five - Web Applications and XML Web Services String.Format("Does the client support ActiveX? {0}", Chapter 18 - ASP.NET Web Pages and Web Controls Request.Browser.ActiveXControls); Chapter theInfo 19 - ASP.NET Applications +=Web String.Format("Is the client a Beta? {0}", Chapter 20 - XML Web Services Request.Browser.Beta); Index theInfo += List of Figures String.Format("Dose the client support Applets? {0}", List of Tables Request.Browser.JavaApplets); theInfo += String.Format("Does the client support Cookies? {0}", Request.Browser.Cookies); theInfo += String.Format("Does the client support VBScript? {0}", Request.Browser.VBScript); lblOutput.Text = theInfo; } Chapter 13 - Building a Better Window (Introducing Windows Forms)
Here you are testing for a number of browser capabilities. As you would guess, it is (very) helpful to discover a browser's support for ActiveX controls, Java Applets, and client-side VB Script code. If the calling browser does not support a given Web technology, your *.aspx page would be able to take an alternative course of action.
Simplified Access Server Variables C# and the to .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
Another aspect of HttpRequest is a simplified manner to obtain server variables. In classic ASP, you Apress © 2003 (1200 pages) accessed server variables using a parameterized property of the Request object. Using this collection This comprehensive text starts with a brief overview of the required you to memorize numerous string literals such as this one: C# language and then quickly moves to key technical and architectural issues for .NET developers.
string agent = Request.ServerVariables["HTTP_USER_AGENT"]; Table of Contents
While are still able toSecond accessEdition server variables using this classic ASP-like mindset, ASP.NET provides C# and you the .NET Platform, strongly typed properties of the HttpRequest type for an identical purpose. To illustrate, update your current Introduction *.aspx to include aC# new Button type. In the Click Part Onefile - Introducing and the .NET Platform
event handler, scrape out various server-side
characteristics. example: Chapter 1 - The For Philosophy of .NET Chapter 2
- Building C# Applications
private void btnGetRequestStats_Click(object Part Two - The C# Programming Language
sender, System.EventArgs e) { Chapter 3 - C# Language Fundamentals theInfo = ""; Chapter string 4 - Object-Oriented Programming with C# theInfo += String.Format("Path of Virtual directory? {0}", Chapter 5 - Exceptions and Object Lifetime Request.ApplicationPath); Chapter 6 - Interfaces and Collections theInfo += String.Format("Byte length of request? {0}", Chapter 7 - Callback Interfaces, Delegates, and Events Request.ContentLength); Chapter 8 - Advanced C# Type Construction Techniques theInfo += String.Format("Virtual path? {0}", Part Three - Programming with .NET Assemblies Request.FilePath); Chapter 9 - Understanding .NET Assemblies theInfo += String.Format("Http method? {0}", Chapter 10 - Processes, AppDomains, Contexts, and Threads Request.HttpMethod); Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming theInfo += String.Format("Raw URL? {0}", Part Four - Leveraging the .NET Libraries Request.RawUrl); Chapter theInfo 12 - Object+= Serialization and the .NET Remotingaddress? Layer String.Format("IP {0}", Chapter 13 - Building a Better Window (Introducing Windows Forms) Request.UserHostAddress); Chapter theInfo 14 - A Better Framework (GDI+) +=Painting String.Format("DNS name? {0}", Chapter 15 - Programming with Windows Forms Controls Request.UserHostName); Chapter lblOutput.Text 16 - The System.IO Namespace = theInfo; Chapter // 17 -Now Data save Access all with ADO.NET stats to file. Part FiveRequest.SaveAs(@"C:\temp\requestDump.txt", - Web Applications and XML Web Services true); } Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Notice that the final line of this server-side event handler makes a call to HttpRequest.SaveAs(). This method allows you to dump out all the characteristics regarding the current HTTP request to a physical file on the List of Figures Web server (which may optionally include header information, specified via the second System.Boolean List of Tables parameter). As you would guess, this functionality can be quite helpful during debugging. Index
Note Be aware that if your Web application makes use of any file IO logic (such as the HttpRequest.SaveAs() method), the target file must be configured for writing.
Access to Incoming Form Data The final aspect of the HttpResponse type we will examine here is the use of the Form and QueryString properties. These two properties allow you to examine the incoming form data using name/value pairs, and function identically to classic ASP. Recall from our discussion of classic ASP at the onset of this chapter that if the data is submitted using HTTP GET, the form data is accessed using the QueryString property, whereas data submitted via HTTP POST is obtained using the Form property. While you could most certainly make use of the HttpRequest.Form and HttpRequest.QueryString properties to access client-supplied form data on the Web server, these old school techniques are (for the most part) unnecessary. Given that ASP.NET now supplies you with server-side Web controls, you are able to treat
HTML form widgets as true objects. Therefore, rather than obtaining the value within a text box as follows: C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
string firstName = Request.Form["txtFirstName"];
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and you can simply ask the server-side widget directly: architectural issues for .NET developers.
string firstName = txtFirstName.Text; Table of Contents C# and the .NET Platform, Second Edition
Not only does this approach lend itself to solid OO principals, but you do not need to concern yourself with Introduction howOne the -form data was (GET or POST) Part Introducing C#submitted and the .NET Platform
before obtaining the values. Of course, this is not to say that you will never need to make use of the Form or QueryString properties in ASP.NET, but rather to say Chapter 1 - The Philosophy of .NET that the need to do so has greatly diminished. Chapter 2
- Building C# Applications
Part Two - The C# Programming Language SOURCE The FunWithHttpRequest
files are included under the Chapter 18 subdirectory.
Chapter 3 - C# Language Fundamentals CODE Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the the .NET Platform, Second Interacting C# with Outgoing HTTPEdition Response by Andrew Troelsen
ISBN:1590590554
Now that you have a better understanding how a System.Web.UI.Page-derived type can interact with the Apress © 2003 (1200 pages) incoming HTTP request, the next step is to seewith howatobrief interact with the outgoing HTTP response. In This comprehensive text starts overview of the ASP.NET, the Response property of the Page class provides access to C# language and then quickly moves to key technical andan internal HttpResponse type. for .NET This type definesarchitectural a number ofissues properties thatdevelopers. allow you to format the HTTP response sent back to the client browser. Table 18-8 lists some core properties (many of which should look familiar if you have a classic ASP background). Table of Contents C# and the .NET Platform, of Second Edition Table 18-8: Properties the HttpResponse Type Introduction
System.Web.HttpResponse Meaning Part One - Introducing C# and the .NET Platform
in Life
Property Chapter 1 - The Philosophy of .NET Chapter Cache2
- Building C# Applications
Part Two - The C# Programming Language
Returns the caching semantics of the Web page (e.g., expiration time, privacy, vary clauses)
Chapter 3
- C# Language Fundamentals ContentEncoding Gets Chapter 4 - Object-Oriented Programming with C# or sets the HTTP character set of the output Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections ContentType Chapter 7
stream Gets or sets the HTTP MIME type of the output stream
- Callback Interfaces, Delegates, and Events
Cookies - Advanced C# Type Construction Techniques Gets the HttpCookie collection sent by the current request Part Three - Programming with .NET Assemblies Chapter 8
Chapter 9 - Understanding .NET Assemblies IsClientConnected
Gets a value indicating whether the client is still
Chapter 10 - Processes, AppDomains, Contexts,connected and Threads to the server Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Output
Part Four - Leveraging the .NET Libraries
Enables custom output to the outgoing HTTP content body
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter OutputStream 13 - Building a Better Window (Introducing Enables Windows binaryForms) output to the outgoing HTTP content
body Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
StatusCode
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Gets or sets the HTTP status code of output returned to the client
StatusDescription Gets Part Five - Web Applications and XML Web Services
or sets the HTTP status string of output returned
to the client Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications SuppressContent Chapter 20 - XML Web Services
Gets or sets a value indicating that HTTP content will not be sent to the client
Index List of Figures
Also, consider the methods of the HttpResponse type described in Table 18-9. List of Tables Table 18-9: Methods of the HttpResponse Type
System.Web.HttpResponse Meaning Life C# and the .NET Platform, Secondin Edition Method ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages)
AppendToLog()
Adds custom log information to the IIS log file.
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and output from the buffer Clears all headers and content architectural issues for .NET developers.
Clear()
stream.
Close() Table of Contents C# and the .NET Platform, Second Edition Introduction
End()
Closes the socket connection to a client. This method can be helpful when you wish to terminate further control rendering. Sends all currently buffered output to the client, then closes the socket connection.
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Flush() Chapter 2 - Building C# Applications Part Two - The C# Programming Language
Redirect()
Sends all currently buffered output to the client. Redirects a client to a new URL.
Chapter 3
- C# Language Fundamentals
Write() Chapter 4
Writes - Object-Oriented Programming with C#values to an HTTP output content stream.
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
WriteFile()
Overloaded. Writes a file directly to an HTTP content output stream.
Part Three - Programming with .NET Assemblies
Emitting HTML Content - Understanding .NET Assemblies
Chapter 9
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Perhaps the most well-known aspect of the HttpResponse type is the ability to write content directly to the HTTP output stream. The HttpResponse.Write() method behaves identically to the classic ASP Part Four - Leveraging the .NET Libraries Response.Write() method (simply pass in any HTML tags and/or raw text literals). The Chapter 12 - Object Serialization andtakes the .NET Layer HttpResponse.WriteFile() method this Remoting functionality one step further in that you can specify the name Chapter 13 Building a Better Window (Introducing Windows of a physical file on the Web server whose contents shouldForms) be rendered to the output stream (quite helpful Chapter 14 emit - A Better Paintingof Framework (GDI+) to quickly the contents an existing *.html file): Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 15 - Programming with Windows Forms Controls Chapter 16 -void The System.IO Namespace private SomePageLevelHelperFunction() Chapter 17 - Data Access with ADO.NET { Part Five -Response.Write("My Web Applications and XML Web Services name is:");
Chapter 18 - ASP.NET Web Pages and Web Controls Response.Write(this.ToString()); Chapter 19 - ASP.NET Web Applications Response.Write("Here was your last request:"); Chapter 20 - XML Web Services Response.WriteFile(@"C:\temp\requestDump.txt"); Index } List of Figures List of Tables
The role of this helper function (which you can assume is called by some server-side event handler) is quite simple. The only point of interest is the fact that the HttpResponse.WriteFile() method is now emitting the contents of the *.txt file created previously using the HttpRequest.SaveAs() method (to be safe, of course, you would want to wrap this method invocation within a try/catch statement just in case the requestDump.txt file is missing). Again, while you can always take this "old school" approach and render HTML tags and content using the Write() method, this approach is far less common under ASP.NET than with classic ASP. The reason is (once again) due to the advent of server-side Web controls. For example, if you wish to render a block of textual data to the browser, your task is as simple as assigning a given System.String to the Text property of a Label widget.
Redirecting Users Another aspect of the HttpResponse type is the ability to redirect the user to a new URL:
private void C# PassTheBuck() and the .NET Platform, Second Edition { ISBN:1590590554 by Andrew Troelsen Response.Redirect("http://Intertech-Inc.com"); Apress © 2003 (1200 pages) } This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
If this helper function were called via a server-side event handler, the user would automatically be redirected to the specified URL. Table of Contents
Note The HttpResponse.Redirect() method will always entail a trip back to the client browser. If you simply wish to transfer control to a *.aspx file in the same virtual directory, the Introduction HttpServerUtility.Transfer() method (accessed via the inherited Server property) will be more Part One - Introducing C# and the .NET Platform efficient. C# and the .NET Platform, Second Edition
Chapter 1
- The Philosophy of .NET
Chapter So much 2 for - Building our investigation C# Applications regarding how a given *.aspx file may interact with the incoming HTTP Part request Two -and Theoutgoing C# Programming HTTP response. Language I'll
assume you will check out the remaining members of the HttpRequest and HttpResponse types at your leisure. Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and Platform, Second The Life Cycle ofthean.NET ASP.NET Web Edition Page by Andrew Troelsen
ISBN:1590590554
Like a Windows Forms every ASP.NET Web page has a fixed life cycle. When the ASP.NET Apress application, © 2003 (1200 pages) runtime receives This an incoming request forstarts a given *.aspx file, the associated comprehensive text with a brief overview of the System.Web.UI.Page derived type is allocated into memory using the type's default constructor. After C# language and then quickly moves to key technical andthis point, the framework will issues for developers. automatically firearchitectural three core events: Init,.NET Load, and Unload. By default, a VS .NET-generated code behind page will be prewired to handle the Init event (via the overloaded OnInit() method) as well as the Load event (via the standard C# event syntax and the System.EventHandler delegate): Table of Contents C# and the .NET Platform, Second Edition
public class MainPage: System.Web.UI.Page { Part One - Introducing C# and the .NET Platform private void Page_Load(object sender, System.EventArgs e) Chapter { 1 }- The Philosophy of .NET Chapter // 2 -Override Building C# the Applications base class event handler. Part Twooverride - The C# Programming protectedLanguage void OnInit(EventArgs e) Chapter { 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# InitializeComponent(); Chapter 5 - Exceptions and Object Lifetime base.OnInit(e); Chapter } 6 - Interfaces and Collections void InitializeComponent() Chapter private 7 - Callback Interfaces, Delegates, and Events { Chapter 8 - Advanced C# Type Construction Techniques // Rig-up the Load event! Part Three - Programming with .NET Assemblies this.Load += new System.EventHandler(this.Page_Load); Chapter 9 - Understanding .NET Assemblies Chapter } 10 - Processes, AppDomains, Contexts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Introduction
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Once the Load event has been handled, the next major event to fire is whatever page-specific event handler caused the postback to occur in the first place (such as a Button Click or what have you). Once Chapter 14 - A Betterevent Painting Framework (GDI+) your page-specific handling has completed, the framework will fire the Unload event, which is not Chapter 15 Programming with Windows Forms handled automatically. To do so, you may useControls the VS .NET Properties window (simply select the name of Chapter 16 -Form The System.IO Namespacelist with the designer active) or update InitializeComponent() your Web from the drop-down Chapter 17 Data Access with ADO.NET manually. Chapter 13 - Building a Better Window (Introducing Windows Forms)
Part Five - Web Applications and XML Web Services
Note Init, Load, Unload events are common to all ASP.NET Web controls, given that they are Chapter 18 The - ASP.NET Weband Pages and Web Controls in the base class. Chapter 19 defined - ASP.NET WebSystem.Web.UI.Control Applications Chapter 20 - XML Web Services
Now, although you are aware of the set of key events that fire during a page's lifetime, you are most likely wondering what type of code will end up in each handler. Table 18-10 offers some insights.
Index
List of Figures
List of Tables Table 18-10: The Role of the Init, Load, and Unload Events
Page Event Init
Meaning C# andin theLife .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
The base class' implementation of the OnInit() method is in charge of handling the This comprehensive text starts with a brief overview of the viewC# state for your ASP.NET Web controls (defined later in this chapter). Given this language and then quickly moves to key technical and fact,architectural be very aware thatfor within scope of the overridden Init event handler you issues .NETthe developers. should not add any code that directly interacts with the stateful values of a control (e.g., the value within a TextBox) as you cannot guarantee an accurate read. Typically, this event is of greatest use to WebForm control builders. You can, however, assign Table of Contents values to any non-GUI-centric variables within the scope of OnInit() as well as C# and the .NET Platform, Second Edition establish the event handlers for your page's widgets. Introduction Part One - Introducing C# and the .NET Platform
Load
Chapter 1 Chapter 2
Once the Load event fires, you can safely interact with any Web-widgets on your page.
- The Philosophy of include .NET Common tasks connecting to a database to fill a DataGrid, populating a - Building C# Applications ListBox with entries, and other GUI prep work.
Part Two - The C# Programming Language
Unload When this event fires, your System.Web.UI.Page-derived type is on its way to the Chapter 3 - C# Language Fundamentals Chapter 4
garbage collector. Here you with should - Object-Oriented Programming C# close any page-wide data connections, file
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
handles, and other resources.
The Error Event Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Another9 event that may occur your page's life cycle is Error, which also works in conjunction with Chapter - Understanding .NETduring Assemblies
the System.EventHandler delegate. This event will be fired if a method on the Page-derived type triggered an exception that was not explicitly handled. Assume you have a server-side event handler for a Button Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Click event that attempts to open a file that is nonexistent. Also assume that you failed to test this file Part Four - Leveraging the .NET Libraries manipulation using standard structured exception handling. If you have rigged up the page's Error event, Chapter 12 - Object Serialization and the .NET Remoting Layer you have one final chance to deal with the problem. Ponder the following code: Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
public class MainPage : System.Web.UI.Page { Chapter 16 - The System.IO Namespace protected System.Web.UI.WebControls.Button btnTriggerError; Chapter 17 - Data Access with ADO.NET ... Part Five - Web Applications and XML Web Services private void InitializeComponent() Chapter 18 - ASP.NET Web Pages and Web Controls { Chapter 19 - ASP.NET Web Applications this.btnTriggerError.Click += Chapter 20 - XML Webnew Services System.EventHandler(this.btnTriggerError_Click); Index this.Error += new System.EventHandler(this.MainPage_Error); List of Figures this.Load += new System.EventHandler(this.Page_Load); List of Tables } Chapter 15 - Programming with Windows Forms Controls
private void btnTriggerError_Click(object sender, System.EventArgs e) { // Ack! Unhandled exception here (assume bad path)! Response.WriteFile(@"C:\Foo.bar"); } private void MainPage_Error(object sender, System.EventArgs e) { // Obtain the error and report to user. Exception ex = Server.GetLastError(); Response.Write(ex.Message); Server.ClearError(); } }
C# and the .NET Platform, Second Edition
When the Error event is fired, you are able to obtain the underlying System.Exception using the ISBN:1590590554 by Andrew Troelsen HttpServerUtility.GetLastError() method exposed from the inherited Server property. In this case, I am Apress © 2003 (1200 pages) simply spitting back the error's description to the response stream. Do note, however, that before exiting comprehensive text starts with a brief overview of the this generic errorThis handler, I am explicitly calling HttpServerUtility.ClearError(). This is almost always what C# language and then quickly moves to key technical and you will want to do, as it informs the for runtime that you have dealt with the issue at hand and require no architectural issues .NET developers. further processing. To see the distinction, Figure 18-18 shows the output if you do call HttpServerUtility.ClearError(), while Figure 18-19 shows the result of not calling HttpServerUtility.ClearError(). Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Figure 18-18: The result of calling ClearError()
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List ofFigure Figures18-19: The result of not calling ClearError() List of Tables
Understanding the Role of the IsPostBack Property Closely related to the set of page-level events is a specific inherited property named IsPostBack. As defined at the beginning of this chapter, a postback is the term given to the act of return to a particular Web page while still in session with the server. Given this definition, you are most likely already to determine that the IsPostBack property will return true if the current HTTP request has been sent by a currently logged-on user and false if this is the user's first interaction with the page. Typically, the need to determine whether or not the current HTTP request is indeed a postback is most helpful when you wish to perform a block of code only the first time the user accesses a given page. For example, you may wish to populate an ADO.NET DataSet when the user first accesses an *.aspx file and cache the object for later use. When the caller returns to the page, you can avoid the need to hit the database unnecessarily (of course, some pages may require that the DataSet is always updated upon each request, but that is another issue). We will see this property in action at various points during the
remainder of this chapter, but here is a simple example:
C# and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
private void Page_Load(object sender, System.EventArgs e) Apress © 2003 (1200 pages) { This comprehensive text starts with a brief overview of the // Only C# read the DB the language and then quickly moves to key technical and // very architectural first time the issues for user .NET developers. // comes to this page. if(!IsPostBack) { Table of Contents Populate DataSet and cache it! C# and the .NET// Platform, Second Edition } Introduction Use precached DataSet. Part One// - Introducing C# and the .NET Platform } Chapter 1 - The Philosophy of .NET Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
At this point you should feel quite confident with the architecture of an ASP.NET Page type and the role of - Object-Oriented Programming with C# the System.Web.UI.Page base class. Now that you have such a foundation, we can turn our attention to Chapter 5 Exceptions and controls. Object Lifetime the role of -ASP.NET Web Chapter 4 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# andthe the .NET Platform,Web SecondControls Edition Understanding ASP.NET by Andrew Troelsen
ISBN:1590590554
One major benefit of ASP.NET is the ability to assemble the user interface of your Web pages using the Apress © 2003 (1200 pages) GUI types definedThis in the System.Web.UI.WebControls namespace. These comprehensive text starts with a brief overview of the controls (which go by the names server controls,Web controls, or Web Form controls) are extremely helpful C# language and then quickly moves to key technical and in that they automatically architectural developers. generate the necessary HTMLissues tags for for .NET the requesting browser and expose a set of events that may be processed on the Web server. Furthermore, because each ASP.NET control has a corresponding class in the System.Web.UI.WebControls namespace, it can be programmatically manipulated from your *.aspx file Table of Contents (within a block) as well as within the associated class defined in the code behind file. C# and the .NET Platform, Second Edition
As you would suspect, each of the ASP.NET Web controls are arranged within a class hierarchy, as seen in Introduction Figure Part One18-20. - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Figure 18-20: The ASP.NET Web controls Part Five - Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls Chapter - ASP.NET Web you Applications As you 19 have seen, when configure a given Web control using the VS .NET Properties window, your Chapter 20 XML Web Services edits are written directly to the *.aspx file as a series of name/value pairs. In this regard, Web Form Index development is a bit different from that of Windows Forms development, given that under the Windows List of Figures Forms model, modifications made on the Properties window appear within the InitializeComponent() helper List of Tables method. As you have also seen, like a Windows Forms application, the InitializeComponent() method
defined in your code behind file is still used to rig up events to specific event handlers. To illustrate, if you add a new TextBox widget (named myTextBox) to the designer of a given *.aspx file and change the BorderStyle, BorderWidth, BackColor, and BorderColor properties using VS .NET, the opening tag is modified as follows:
In the code behind file, you will find a member variable whose name is identical to the ID element defined in the *.aspx file. Using this member variable, you are able to interact with the same properties as you would expect:
public class MainPage : System.Web.UI.Page C# and the .NET Platform, Second Edition { ISBN:1590590554 Andrew Troelsen // Note by that the name of the member variable Is identical to Apress © 2003 (1200 pages) // the ID value of the *.aspx declaration. ThisSystem.Web.UI.WebControls.TextBox comprehensive text starts with a brief overview of the protected myTextBox; C# language and then quickly moves to key technical and ... architectural issues for .NET developers. private void SomeHelperFunction() { // Interact with Web widget. Table of Contents myTextBox.BackColor = Color.Red; C# and the .NET Platform, Second Edition Response.Write(String.Format("Border color Is: {0}", Introduction myTextBox.BorderColor.ToString())); Part One - Introducing C# and the .NET Platform } Chapter 1 - The Philosophy of .NET } Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3 in-Figure C# Language Fundamentals As seen 18-20, all of the ASP.NET server-side controls ultimately derive from a common base Chapter 4 - Object-Oriented Programming with C# class named System.Web.UI.WebControls.WebControl. WebControl in turn derives from Chapter System.Web.UI.WebControls.Control 5 - Exceptions and Object Lifetime (which derives from System.Object). Control and WebControl each
define a6 number of properties common to all server-side controls. To help gain an understanding of your Chapter - Interfaces and Collections inherited let's check out the core functionality provided by each of these key base classes. But Chapter 7 functionality, - Callback Interfaces, Delegates, and Events first, let's what means to handleTechniques a server-side event. Chapter 8 formalize - Advanced C# itType Construction Part Three - Programming with .NET Assemblies
- Understanding .NETof Assemblies Qualifying the Role Server-Side Event Handling
Chapter 9
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Given the state of the World Wideand Web, it is impossible to avoid the fundamental nature of Chapter 11 -current Type Reflection, Late Binding, Attribute-Based Programming browser/Web server interaction. Whenever Part Four - Leveraging the .NET Libraries
these two entities communicate, there is always an underlying,
stateless, request-and-response cycle. While ASP.NET server controls do a great deal to shield you Chapter 12 HTTP - Object Serialization and the .NET Remoting Layer from the of the raw HTTP protocol, alwaysWindows remember that treating the Web as an event-driven entity Chapter 13details - Building a Better Window (Introducing Forms) is just a14 magnificent smoke-and-mirror provided by the CLR, and is not semantically identical to a Chapter - A Better Painting Framework show (GDI+) Windows-based user interface.
Chapter 15 - Programming with Windows Forms Controls Chapter 16 -be The System.IO Namespace Given this, aware that although the System.Windows.Forms and System.Web.UI.WebControls Chapter 17 Data Access with ADO.NET namespaces define numerous types with the same simple name (Button, TextBox, and so on), they do not Part Five the - Web Applications and XML Services expose same set of events. For Web example, there
is no way to handle a server-side MouseMove event
Chapter 18 user - ASP.NET Web Controls when the movesWeb the Pages cursorand over a Web Form Button type. Obviously this is a good thing. (Who wants Chapter - ASP.NET Web Applications to post 19 back to the server each time the mouse moves?) When you need to handle such logic, you will Chapter - XMLemit Webthe Services need to20 simply correct client-side JavaScript. Furthermore, many Web widget events expose an Index event that may seem to be identical in nature to the Windows Forms equivalent (such as the Change event
of aofTextBox), List Figures but acts quite differently under the hood. List of Tables
The bottom line is that a given ASP.NET Web control will expose a limited set of events, all of which ultimately correspond to a postback to the Web server. For example, a System.Web.UI.WebControl.Button type exposes a Click event that results in a postback to a specific method on the hosting Page-derived type. The System.Web.WebControl.TextBox type defines a Changed event that will entail a postback when the user tabs off the current control to a new control.
The AutoPostBack Property It is also worth pointing out that many of the ASP.NET Web controls support a property named AutoPostBack (specifically, the CheckBox, RadioButton, and TextBox controls as well as any widget that derives from the abstract ListControl type). By default, this property is set to false, which as you would guess disables the automatic posting of server-side events (even if you have indeed rigged up the event in the code behind file). In many cases, this is the exact behavior you require. However, if you do wish to cause any of these widgets to post back to a server-side event handler, simply set the value of AutoPostBack to true. This technique can be helpful if you wish to have the state of one
widget automatically populate another widget.
C# and the .NET Platform, Second Edition
ISBN:1590590554 by Andrew Troelsen To illustrate, create a Web application that contains a single TextBox and a single ListBox control. Now, Apress © event 2003 (1200 pages) handle the TextChanged of the TextBox, and within the server-side event handler, populate the ListBox with the current value in the TextBox (got that?): This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and architectural issues for .NET developers.
private void txtPostBackBox_TextChanged(object sender, System.EventArgs e) { Table of lstCharacters.Items.Add(txtPostBackBox.Text); Contents } C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
If you run the application as is, you will find that as you type in the TextBox, nothing happens. Furthermore, if
Chapter 1 to - The of .NET you were typePhilosophy in the TextBox and tab to the next control, nothing happens. The reason is that the Chapter 2 Building C# Applications AutoPostBack property of the TextBox is set to false by default. If you set this property to true: Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 6 Interfaces and Collections Chapter 4
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
you will9find that when you .NET tab off the TextBox, the ListBox is automatically populated with the current value Chapter - Understanding Assemblies via the 10 server-side event handler. Beyond the and need to populate the items of one widget based on the value Chapter - Processes, AppDomains, Contexts, Threads of another you will typically not need alter the stateProgramming of a widget's AutoPostBack property. Chapter 11 -widget, Type Reflection, Late Binding, and to Attribute-Based Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and .NET Platform, Second Edition Key Members of the the System.Web.UI.Control Type by Andrew Troelsen
ISBN:1590590554
The System.Web.UI.Control Apress © 2003base (1200 class pages) defines various properties, methods, and events that allow a given page to interact with its set of contained enable disable)ofview This comprehensive textcontrols, starts with a brief(or overview the state, and interact with the event set of a widget's lifetime. Table 18-11 documents some of the key properties, C# language and then quickly moves to key technical and methods, and events to be aware of. architectural issues for .NET developers.
Table 18-11: Select Members of System.Web.UI.Control Interesting Table of Contents Member of
Meaning in Life
C#System.Web.UI.Control and the .NET Platform, Second Edition Introduction
Controls
This property gets a ControlCollection object that represents the child controls for a specified server control in the UI hierarchy.
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
EnableViewState Part Two - The C# Programming Language
This property gets or sets a value indicating whether the server control persists its view state, and the view state of Chapter 3 - C# Language Fundamentals anyC# child controls it contains, to the requesting client. Chapter 4 - Object-Oriented Programming with Chapter 5 ID Chapter 6
- Exceptions and Object Lifetime This property gets or sets the programmatic identifier - Interfaces and Collections assigned to the server control.
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 9 Parent
- Understanding .NET Assemblies This property gets a reference to the server control's parent
Page This property gets a reference to the Page instance that Chapter 8 - Advanced C# Type Construction Techniques contains the server control. Part Three - Programming with .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads control in the page control hierarchy. Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Visible
Part Four - Leveraging the .NET Libraries
This property gets or sets a value that indicates whether a server control is rendered as UI on the page.
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter DataBind() 13 - Building a Better Window (Introducing Binds Windows a data source Forms) to the invoked server control and all its
child controls. Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
HasControls()
Chapter 16 - The System.IO Namespace
DataBinding Chapter 17 - Data Access with ADO.NET
Determines if the server control contains any child controls. This event occurs when the server control binds to a data
source. Part Five - Web Applications and XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls
Init
Chapter 19 - ASP.NET Web Applications
Recall that this event occurs when the server control is initialized, which is the first step in its life cycle.
Chapter 20 - XML Web Services
Load Index List of Figures ListUnload of Tables
Recall that this event occurs when the server control is loaded into the Page object. Recall that this event occurs when the server control is unloaded from memory.
Fun with the Control Base Class: Enumerating Contained Controls The first aspect of System.Web.UI.Control we will examine is the fact that all controls inherit a property named Controls that works in conjunction with the closely related HasControls() method. Much like a Windows Forms application, the Controls property provides access to a strongly typed collection of Web Form control types. Like any collection, you have the ability to add, insert, and remove items dynamically at runtime. To illustrate, assume you have a new ASP.NET Web Application project and an *.aspx file that maintains a Panel type that contains three other types (say, a TextBox, HyperLink, and Button). Here are the widget's declarations: and the .NET Platform, Edition This C# panel contains threeSecond controls
ISBN:1590590554 by Andrew Troelsen Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the HyperLink
C# language and then quickly moves to key technical and architectural issues for .NET developers.
Next, place a Label widget outside the scope of the Panel to hold the page's output. The associated UI can be seen in Figure 18-21.
Table of Contents
C# and the .NET Platform, Second Edition Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8 - 18-21: Advanced C# with Type contained Construction Techniques Figure Panel controls Part Three - Programming with .NET Assemblies
Now, assume in your Page_Load() event, you wish to obtain a list of all the controls contained within the Panel Chapter 9 - Understanding .NET Assemblies (with the of AppDomains, a private helper function) display the results on a Label type. Ponder the following Chapter 10assistance - Processes, Contexts, andand Threads code update: Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
public : System.Web.UI.Page Chapter 12 class - ObjectPanelPage Serialization and the .NET Remoting Layer { Chapter 13 - Building a Better Window (Introducing Windows Forms) ... 14 - A Better Painting Framework (GDI+) Chapter void Page_Load(object sender, System.EventArgs e) Chapter private 15 - Programming with Windows Forms Controls {
Chapter 16 - The System.IO Namespace
// Show the controls on a panel. ListControlsOnPanel();
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
}
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
public void ListControlsOnPanel() { Index string theInfo; List of Figures theInfo = String.Format("Has controls? {0}", List of Tables thePanel.HasControls()); ControlCollection myCtrls = thePanel.Controls; foreach(Control c in myCtrls) { if(c.GetType() != typeof(System.Web.UI.LiteralControl)) { theInfo += "***************************"; theInfo += String.Format("Control Name? {0}", c.ToString()); theInfo += String.Format("ID? {0}", c.ID); theInfo += String.Format("Control Visible? {0}", c.Visible); theInfo += String.Format("ViewState? {0}", c.EnableViewState); } } Chapter 20 - XML Web Services
lblControlInfo.Text = theInfo; C# and the .NET Platform, Second Edition
}
by Andrew Troelsen Apress © 2003 (1200 pages)
... }
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers. Here, the ListControlsOnPanel() helper function iterates over each WebControl maintained on the Panel and
performs a check to see if the current type is a System.Web.UI.LiteralControl. This type is used to represent literal HTML tags and content (such as , text literals, and so on). If you do not make this sanity check, you Table of Contents might be surprised to find a total of seven types in the scope of the panel (given the *.aspx declaration seen C# and the .NET Platform, Second Edition previously). Assuming the type is not literal HTML content, you then print out some various statistics about the Introduction widget.Figure 18-22 shows the output. Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Figure 18-22: Enumerating contained widgets
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Fun with the Control Base Class: Dynamically Adding (and Removing) List Controls of Figures Index
List of Tables
Now, what if you wish to modify the contents of a Panel at runtime? The process should look very familiar to you, given your work with Windows Forms earlier in this text. Let's update the page to support one button that dynamically adds five new TextBox types to the Panel, and another that clears out the entire control set. The Click event handlers for each are shown here: private void btnAddTextBoxes_Click(object sender, System.EventArgs e) { for(int i = 0; i < 5; i++) { // Assign a name so we can get // the text value out later // using the HttpRequest.QueryString() // method. TextBox t = new TextBox(); t.ID = string.Format("newTextBox{0}", i);
thePanel.Controls.Add(t); C# and the .NET Platform, Second Edition } by Andrew Troelsen ListControlsOnPanel();
ISBN:1590590554
Apress © 2003 (1200 pages)
} comprehensive text starts with a brief overview of the private void This btnRemoveAllItems_Click(object sender, System.EventArgs e) C# language and then quickly moves to key technical and { architectural issues for .NET developers. thePanel.Controls.Clear(); ListControlsOnPanel(); } Table of Contents C# and the .NET Platform, Second Edition Introduction Notice that you assign a unique ID to each TextBox (e.g., newTextBox1, newTextBox2, and so on) in order to Part One - Introducing C# and the .NET Platform
obtain their contained text programmatically using the HttpRequest.Form collection (seen momentarily). Given
Chapter - The Philosophy of .NET that you1 dynamically add these items to the Panel, you cannot obtain their values using page-level member Chapter 2 Building C# Applications variables, as they have no formal declaration in the *.aspx file! Part Two - The C# Programming Language
To obtain values within these dynamically generated TextBoxes, update your UI with an additional Button Chapter 3 the - C# Language Fundamentals and Label Within the Click event handler for the Button, loop over each item contained within the Chapter 4 -type. Object-Oriented Programming with C# HttpRequest.NameValueCollection type (accessed via HttpRequest.Form) and concatenate the textual Chapter 5 - Exceptions and Object Lifetime information a locallyand scoped System.String. Once you have exhausted the collection, assign this string to the Chapter 6 - to Interfaces Collections Text property of the new Label widget named lblTextBoxText: - Callback Interfaces, Delegates, and Events
Chapter 7 Chapter 8
- Advanced C# Type Construction Techniques
private void btnGetTextBoxValues_Click(object Part Three - Programming with .NET Assemblies
sender, System.EventArgs e) { Chapter 9 - Understanding .NET Assemblies in case the panel isand empty Chapter // 10 -Just Processes, AppDomains, Contexts, Threads string textBoxValues = ""; Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming for(int i = 0; i < Request.Form.Count; i++) Part Four - Leveraging the .NET Libraries { Chapter 12 - Object Serialization and the .NET Remoting Layer textBoxValues += Chapter 13 - Building a Better Window (Introducing Windows Forms) string.Format("{0}", Request.Form[i]); Chapter 14 - A Better Painting Framework (GDI+) } Chapter 15 - Programming with Windows Forms Controls lblTextBoxText.Text = textBoxValues; Chapter 16 - The System.IO Namespace } Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter When you 18 -run ASP.NET the application, Web Pagesyou andwill Web find Controls that you are able to view the context of each text box, including a
rather long This string contains the view state for each widget on the page and will be Chapter 19 - (unreadable) ASP.NET Web string. Applications examined the Services text. Also, you will notice that once the request has been processed, the ten new text Chapter 20 -later XMLinWeb boxes disappear. Again, the reason has to do with the stateless nature of HTTP. If you wish to maintain these Index dynamically List of Figures created TextBoxes between postbacks, you would need to persist these objects using ASP.NET state programming techniques (examined in the next chapter). List of Tables Note The process of dynamically adding, deleting, and modifying the items in a Panel should drive the point home that one key initiative of ASP.NET was to make the process of building a Web application look and feel much like the process of building a Windows application. Although very intriguing, a simpler approach would be to place all possible widgets in the Panel at design time, and then set the Visible property to false for the items you do not wish to display. In any case, at this point you have seen how all ASP.NET Web controls inherit a Controls property that is used to access internal child controls. Using this collection, you are able to dynamically add, delete, and modify items on the fly. SOURCE CODE
The DynamicCtrls files are included under the Chapter 18 subdirectory.
C# and .NET Platform, Second Edition Key Members of the the System.Web.UI.WebControl Type by Andrew Troelsen
ISBN:1590590554
As you can tell, the Control type provides Apress © 2003 (1200 pages) a number of non-GUI-related behaviors. On the other hand, the WebControl baseThis class provides a polymorphic comprehensivegraphical text starts with a brief interface overview to of all theWeb widgets as suggested in Table 18-12. C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 18-12: Properties of the WebControl Base Class WebControl Table of Contents
Meaning in Life Property C# and the .NET Platform, Second Edition Introduction
BackColor
Gets or sets the background color of the Web control
Part One - Introducing C# and the .NET Platform
BorderColor Chapter 1 - The Philosophy ofGets .NETor sets the border color of the Web control Chapter 2
- Building C# Applications
BorderStyle
Gets or sets the border style of the Web control
Part Two - The C# Programming Language
BorderWidth Gets or sets the border width of the Web control Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Enabled
Gets or sets a value indicating whether the Web control is enabled
CssClass Allows you to assign a cascading style sheet to a Web widget Chapter 6 - Interfaces and Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Font
Gets font information for the Web control
ForeColor Gets sets the foreground Part Three - Programming with .NETor Assemblies
color (typically the color of the text) of the
Web control Chapter 9 - Understanding .NET Assemblies Chapter - Processes, AppDomains, Contexts, and and Threads Height10Width Get or set the height width of the Web control Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
TabIndex Gets or sets Part Four - Leveraging the .NET Libraries
the tab index of the Web control
Chapter andorthe .NET Tool 12 - Object Serialization Gets sets theRemoting tool tip forLayer the Web control to be displayed when the Chapter 13 - Building a Better cursor Windowis(Introducing Windows Forms) over the control Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 -almost Programming with properties Windows Forms Controls I'd bet that all of these are self-explanatory, so rather than drill through the use of all Chapter 16 - The System.IO these properties, let's shift Namespace gears a bit and check out a number of ASP.NET Web Form controls in action. Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the Platform, Second Edition Controls Select Examples of.NET ASP.NET WebForm by Andrew Troelsen
ISBN:1590590554
The types in the System.Web.UI.WebControls can be broken down into four broad categories: Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the
Simple controls C# language and then quickly moves to key technical and architectural issues for .NET developers.
(Feature) Rich controls Data-centric controls
Table of Contents
C# and the validation .NET Platform, Second Edition Input controls Introduction
TheOne simple controls are named because they are Part - Introducing C#so and the .NET Platform
ASP.NET Web controls that map to standard HTML widgets
(buttons, holders, tables, and so forth). Next we have a small set of controls named the Chapter 1 lists, - Thehyperlinks, Philosophyimage of .NET rich controls for which is no direct HTML equivalent (such as the Calendar and AdRotator). The dataChapter 2 - Building C#there Applications centric are widgets thatLanguage are typically populated Part Twocontrols - The C# Programming
via a given data connection. The best (and most complex) example of such a control would be the ASP.NET DataGrid. Other members of this category include Chapter 3 - C# Language Fundamentals "repeater" controls and the lightweight DataList. Finally, the validation controls are server-side widgets that Chapter 4 - Object-Oriented Programming with C# automatically emit client-side JavaScript, for the purpose of form field validation. Chapter 5
- Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections In the pages that follow, I will not walk through each and every member of each and every control within the Chapter 7 Callback Interfaces, Delegates, and Events System.Web.UI.WebControls namespace. Given your work with Windows Forms controls earlier in this book, you Chapter Advanced C# Type Techniques should 8feel- right at home whenConstruction you manipulate these widgets. Just remember that while Windows Forms types Part Three - Programming with .NET Assemblies encapsulate the raw Win32 API from view, Web
Form controls encapsulate the generation of raw HTML tags. If
Chapter 9 to- follow Understanding .NET Assemblies you wish along, create a new ASP.NET Web application named FunWithControls. Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Working with the ListBox Control
Part Four - Leveraging the .NET Libraries
Chapter 12 let's - Object Serialization .NET Remoting Layer These types basically map to a standard HTML To begin, examine some ofand thethe intrinsic simple controls. Chapter 13 Building a Better Window (Introducing Windows Forms) widget counterpart. For example, if you wish to display a static list of items for the end user, you can construct a Chapter ListBox14 type - Ausing Better a Painting set of related Framework ListItems: (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter BMW Part FiveJetta and XML Web Services
Chapter Colt and Web Controls
Value="Grand Am">Grand Am Chapter
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter
Chapter 20 - XML Web Services Index List of Figures List of Tables The and elements are defined as so: C# and the .NET Platform, Second Edition ISBN:1590590554 by Andrew Troelsen soapAction="http://tempuri.org/HelloWorld" This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers. Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part - The C# Programming Language AndTwo finally, there is the element,
Chapter 3
which describes the HelloWS itself:
- C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime Chapter Chapter 7 - Callback Interfaces, and Events Chapter 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
As you 11 can- see, documents tend to beAttribute-Based quite verbose.Programming The good news is that you can lead a productive and Chapter Type WSDL Reflection, Late Binding, and happy life as a .NET XML WebLibraries service Part Four - Leveraging the .NET
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 extremely Chapter 12 - Object Serialization and the .NET Remoting Layer rare. However, having a basic understanding of WSDL will serve you well, especially if you need to tweak the Chapter 13 - Building a Better Window (Introducing Windows Forms) default element definitions emitted by IIS. Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 Recall - Programming with Windows Forms Controls Note that the System.Web.Services.Description namespace contains a plethora of types that allow you Chapter 16 to - The System.IO Namespace programmatically read and manipulate raw WSDL (so check it out if you are so interested). Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, The wsdl.exe Command Line Second UtilityEdition by Andrew Troelsen
ISBN:1590590554
Now that you have a better understanding of WSDL's place in the world, you are ready to check out a Apress © 2003 (1200 pages) command-line tool that ships with the .NET SDK named wsdl.exe. In a nutshell, this tool This comprehensive text starts with a brief(surprise, overview surprise) of the performs two major tasks: C# language and then quickly moves to key technical and architectural issues for .NET developers.
Generates a server-side file that functions as a skeleton for implementing the XML Web service Generates Table of Contentsa client-side file that functions as the proxy to the remote XML Web service C# and the .NET Platform, 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 Part One - Introducing C# and the .NET Platform that each flag supports a shorthand notation as well, which can also be seen via command prompt help). Introduction Chapter 1
- The Philosophy of .NET
Chapter 2 - Building C# Applications Table 20-5: Select Flags of wsdl.exe Part Two - The C# Programming Language
Wsdl.exe Meaning in Life Chapter 3 - C# Language Fundamentals Command-Line Chapter 4 - Object-Oriented Programming with C# Flag5 Chapter
- Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections /appsettingurlkey This option instructs wsdl.exe to build a proxy that does not make use of Chapter 7 - Callback Interfaces, Delegates,URLs. and Events hard-coded Instead, the proxy class will be configured to read the Chapter 8
- Advanced C# Type Construction Techniques URL from a client-side *.config file.
Part Three - Programming with .NET Assemblies
/language Specifies the language to use for the generated proxy class: Chapter 9 - Understanding .NET Assemblies CS (C#;Contexts, default) and Threads Chapter 10 - Processes, AppDomains, Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming VB (Visual Basic .NET) Part Four - Leveraging the .NET Libraries
JS (JScript)
Chapter 12 - Object Serialization and the .NET Remoting Layer
(Visual J#). The Windows default isForms) C#. Chapter 13 - Building a Better VJS Window (Introducing Chapter 14 - A Better Painting Specifies Framework /namespace the(GDI+) namespace for the generated proxy or template. By Chapter 15 - Programming with Windows Controls default yourForms type will not be defined within a namespace definition! Chapter 16 - The System.IO Namespace
/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 with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web /protocol Specifies theControls protocol to use within the proxy code. SOAP is the default. Chapter 19 - ASP.NET Web Applications However, you can also specify HttpGet or HttpPost to create a proxy that
communicates using simple HTTP GET or POST verbs. Chapter 20 - XML Web Services Index
/server
List of Figures List of Tables
Generates an abstract class for an XML Web service based on the WSDL document.
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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
In either case, once wsdl.exe tooltext hasstarts processed elements, Thisthe comprehensive with a the briefWSDL overview of the you will end up with a C# source C# language then quickly moves 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): architectural issues for .NET developers. using System.Diagnostics; Table of Contents using System.Xml.Serialization; using System; Introduction using System.Web.Services.Protocols; Part One - Introducing C# and the .NET Platform using System.ComponentModel; Chapter 1 - The Philosophy of .NET using System.Web.Services; Chapter 2 - Building C# Applications [System.Web.Services.WebServiceBindingAttribute Part Two - The C# Programming Language (Name="HelloClassSoap", Namespace="http://tempuri.org/")] Chapter 3 - C# Language Fundamentals public abstract class HelloClass : System.Web.Services.WebService Chapter 4 - Object-Oriented Programming with C# { Chapter[System.Web.Services.WebMethodAttribute()] 5 - Exceptions and Object Lifetime Chapter[System.Web.Services.Protocols.SoapDocumentMethodAttribute 6 - Interfaces and Collections Chapter("http://tempuri.org/HelloWorld", 7 - Callback Interfaces, Delegates, and Events Chapter RequestNamespace="http://tempuri.org/", 8 - Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies ResponseNamespace="http://tempuri.org/", Chapter Use=System.Web.Services.Description.SoapBindingUse.Literal, 9 - Understanding .NET Assemblies Chapter ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] 10 - Processes, AppDomains, Contexts, and Threads abstract HelloWorld(); Chapterpublic 11 - Type Reflection, string Late Binding, and Attribute-Based Programming } Four - Leveraging the .NET Libraries Part C# and the .NET Platform, Second Edition
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
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 - Programming with Windows Forms Controls defined as abstract entities. Chapter 14 - A Better Painting Framework (GDI+) Chapter 16 - The System.IO Namespace
Chapter 17 this - Data with ADO.NET Although is aAccess very interesting feature of the wsdl.exe utility, the chances are that you would rather have Part Web Applications and XML Services this Five tool -go in the other direction andWeb generate a client-side
proxy type that will communicate with the
Chapter remote18 Web - ASP.NET service.Web You Pages see how andtoWeb do Controls this very thing in just a moment. But first, let's dive a bit deeper into
the wire19protocols. Chapter - ASP.NET Web Applications Chapter 20 - XML Web Services
SOURCE CODE
Index
List of Figures List of Tables
The SimpleHelloWS_WSDL.wsdl and proxy skeleton files can be found under the Chapter 20 subdirectory.
C# and the .NET Platform, Second Edition Revisiting the XML Web Service Wire Protocols by Andrew Troelsen
ISBN:1590590554
As you know, theApress purpose of a(1200 Webpages) service is to return XML-based data to a consumer, using the HTTP © 2003 protocol. Specifically, a Web server bundles this data into the body of This comprehensive text starts with a brief overview of an theHTTP request and transmits it to the consumer using one of three specific techniques (Table 20-6). C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 20-6: Web Service Wire Protocols Transmission Table of Contents
Meaning in Life Protocol C# and the .NET Platform, Second Edition Introduction
HTTP GET
GET submissions append parameters to the query string of the current URL.
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET HTTP2POST POST transmissions embed the data points into the header of the Chapter - Building C# Applications
HTTP message Part Two - The C# Programming Language
rather than appending them to the query string.
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming withthe C#wire using XML. methods across - Exceptions and Object Lifetime
SOAP
Chapter 5
SOAP is a wire protocol that specifies how to submit data and invoke
Chapter 6
- Interfaces and Collections While each leads to the same result (invoking a Web method), your choice of wire protocol Chapter 7 - approach Callback Interfaces, Delegates, and Events
determines types of (and return types) that can be sent between each interested party. Chapter 8 - the Advanced C#parameters Type Construction Techniques TheThree SOAP protocol offers you.NET the greatest form Part - Programming with Assemblies
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 - Understanding .NET Assemblies completion let's check out the role of standard GET and POST. Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
HTTP GET and HTTP POST Messages
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Although and POST verbs may(Introducing be familiar constructs, you must be aware that this method of Chapter 13 GET - Building a Better Window Windows Forms) transportation is not Painting rich enough to represent such complex items as structures or classes. When you use Chapter 14 - A Better Framework (GDI+) GET and verbs, you canWindows only interact Web methods using the types listed in Table 20-7. Chapter 15 POST - Programming with Formswith Controls Chapter 16 - The System.IO Namespace
Table 20-7: Supported POST and GET Data Types
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Supported Meaning inServices Life
Chapter 18 - ASP.NET GET/POST Data Web Pages and Web Controls Chapter Type19 - ASP.NET Web Applications Chapter 20 - XML Web Services
Enumerations
Index
List of Figures 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# and the .NET Platform, Second Edition encodes each complex method using SOAP messages. by Andrew Troelsen
ISBN:1590590554
Apress © 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 comprehensive conceptual container for the information. Second, we have the rules that text starts withrelevant a brief overview of the C# language and then moves to key technical are used to describe the information in quickly said message (placed into theand SOAP body). An optional third architectural issues for .NET developers. section (the SOAP header) may be used to specify general information regarding the message itself such as security or transactional information. Table of Contents
Part One - Introducing C# and the .NET Platform Chapter 1 - The Philosophy of .NET Chapter 2 - Building C# Applications Part Two - The C# Programming Language Chapter 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime C# and the .NET Platform, Second Edition
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8 - aAdvanced Type Construction Techniques Viewing SOAP C# Message Part Three - Programming with .NET Assemblies
Like other of WSDL, you are not required to understand the inner details of SOAP to build XML Chapter 9 -aspects Understanding .NET Assemblies Web services with the .NET platform. However, you use the makeshift client browser, you are able Chapter 10 - Processes, AppDomains, Contexts, andwhen Threads to view 11 the- format of the SOAP for each exposed Web method. For example, if you were to click Chapter Type Reflection, Latemessage Binding, and Attribute-Based Programming the Four link for the Add() method the CalcWebService, Part - Leveraging the .NETof Libraries
you would find the following SOAP request:
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 15 - Programming with Windows Forms Controls Chapter 17 - Data Access with ADO.NET int Part Five - Web Applications and XML Web Services int Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Chapter 16 - The System.IO Namespace
Index List of Figures List of Tables
The corresponding SOAP response looks like this: int
C# and the .NET Platform, Second (Generating Edition Transforming WSDL into C# Code a Proxy) by Andrew Troelsen
ISBN:1590590554
At this point, you Apress are 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 codeof base This comprehensive text starts with a brief overview the that manually requests a WSDL definition and manually parses each XML node to establish a connection C# language and then quickly moves to key technical and to the remote service. A mucharchitectural issues for .NETto developers. preferred approach is to leverage wsdl.exe generate a proxy class that maps to the Web methods defined 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: Table of Contents C# and the .NET Platform, Second Edition
wsdl.exe /out:c:\MyCalcWSProxy.cs http://localhost/CSharpBookSE/CalcWebService/CalcWS.asmx?WSDL
Introduction
Part One - Introducing C# and the .NET Platform
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 Part Two - The C# language, Programming Language alternative .NET make use 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 - Object-Oriented Programming withGET C# or HTTP POST, you may make use of the /protocol flag. Chapter 5
- Exceptions and Object Lifetime
- Interfacesthe and Collections Investigating Proxy Code
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
If you opened up the generated *.cs file, youTechniques would find that you are given a class type that derives from Chapter 8 - Advanced C# Type Construction System.Web.Services.Protocols.SoapHttpClientProtocol. This base class defines a number of helper Part Three - Programming with .NET Assemblies functions that will be leveraged within the implementation of the proxy type. Table 20-8 describes some Chapter 9 - Understanding .NET Assemblies interesting inherited members. Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Table 20-8: Core Members the SoapHttpClientProtocol Part Four - Leveraging the .NETof Libraries
Type
Chapter 12 - Object Serialization and thein .NET Remoting Layer Inherited Meaning Life Chapter 13 - Building a Better Window (Introducing Windows Forms) Member Chapter 14 - A Better Painting Framework (GDI+)
BeginInvoke() Starts an asynchronous invocation of the Web method Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace EndInvoke() Ends an asynchronous invocation of the Web method Chapter 17 - Data Access with ADO.NET
Invoke() invokes Part Five - Web Applications Synchronously and XML Web Services
a method of the Web service
Chapter Webproxy Controls Proxy18 - ASP.NET Web Pages Gets and or sets information for making a Web service request through a Chapter 19 - ASP.NET Web Applications firewall Chapter 20 - XML Web Services
Timeout Index
Gets or sets the timeout (in milliseconds) used for synchronous calls
ListUrl of Figures
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# and the .NET Platform, Second Edition this.Url = "http://localhost/CSharpBookSE/CalcWebService/CalcWS.asmx";
} ... }
by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
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. Table of Contents Asynchronous method inoculations return control to the calling client immediately after sending the invocation C# and the .NET Platform, Second Edition request. When the processing has finished, the runtime makes a callback to the client. Here is the Introduction synchronous implementation of the Add() method which takes two System.Int32 types (recall that we Part One - Introducing C# and the .NET Platform overloaded this 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 - Object-Oriented Programming with C# ResponseNamespace="http://www.intertech-inc.com/WebServices", Chapter 5 - Exceptions and Object Lifetime Use=System.Web.Services.Description.SoapBindingUse.Literal, Chapter 6 - Interfaces and Collections ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] Chapter 7 int - Callback Interfaces, Delegates, public Add(int x, int y) and Events Chapter 8 - Advanced C# Type Construction Techniques { Part Three - Programming with .NET Assemblies object[] results = this.Invoke("Add", Chapter 9 - Understanding new object[] .NET Assemblies {x, y}); ((int)(results[0])); Chapter return 10 - Processes, AppDomains, Contexts, and Threads } Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Two - The C# Programming Language
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
The asynchronous version of this Add() method is represented by the now familiar BeginXXXX() / EndXXX() method pair:
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
public System.IAsyncResult BeginAdd(int x, int y, System.AsyncCallback callback, object asyncState) Chapter 17 - Data Access with ADO.NET { Part Five - Web Applications and XML Web Services return this.BeginInvoke("Add", Chapter 18 - ASP.NET Web Pages and Web Controls new object[] {x, y}, callback, asyncState); Chapter 19 - ASP.NET Web Applications } Chapter 20 - XML Web Services public int EndAdd(System.IAsyncResult asyncResult) Index { List of Figures object[] results = this.EndInvoke(asyncResult); List of Tablesreturn ((int)(results[0])); } Chapter 16 - The System.IO Namespace
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# and MyWayCoolWebCalculator the .NET Platform, Second Edition public class : ISBN:1590590554 by Andrew Troelsen System.Web.Services.Protocols.SoapHttpClientProtocol Apress © 2003 (1200 pages) {...} This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
}
By default, wsdl.exe will not define a specific namespace unless you explicitly specify the /n flag at the command prompt. For example:
Table of Contents
C# and the .NET Platform, Second Edition
wsdl.exe /out:c:\MyCalcWSProxy.cs /n:CalcWSClient http://localhost/CSharpBookSE/CalcWebService/CalcWS.asmx?WSDL
Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
andProxy the .NET(Synchronous Platform, Second Edition LeveragingC# the Invocations) by Andrew Troelsen
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) or Apress © 2003 simply include theThis *.cscomprehensive file directly in text yourstarts clientwith application. In eitherofcase, a brief overview the you need to explicitly set a reference to the System.Web.Services.dll assembly (given that the proxy code makes C# language and then quickly moves to key technical and use of numerous types defined within architectural issues for .NET developers. 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 Table grunge of Contents work of opening an HTTP channel, formatting the SOAP message, and mapping XML to and from .NET
data is handled on Second your behalf. C# andtypes the .NET Platform, Edition Introduction
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:
Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
// Two Don't to set Language a reference Part - Theforget C# Programming
to // System.Web.Services.dll! Chapter 3 - C# Language Fundamentals using System; Chapter 4 - Object-Oriented Programming with C# namespace CalcWSClient Chapter 5 - Exceptions and Object Lifetime { Chapter 6 - Interfaces and Collections class TheClient Chapter 7 - Callback Interfaces, Delegates, and Events { Chapter 8 - Advanced C# Type Construction Techniques static void Main(string[] args) Part Three - Programming with .NET Assemblies { Chapter 9 - Understanding .NET Assemblies // Exercise the proxy! Chapter 10 - Processes, AppDomains, Contexts, and Threads Console.WriteLine("***** The amazing Web Service Client App *****\n"); Chapter 11 - Type MyWayCoolWebCalculator Reflection, Late Binding, and Attribute-Based ws = new Programming MyWayCoolWebCalculator(); Part Four - Leveraging the .NET Libraries Console.WriteLine("2 + 3 = {0}", ws.Add(2, 3)); Chapter 12 - Object Serialization and the .NET Remoting Layer = {0}", ws. Add(23.4F, 33.1F)); Console.WriteLine("23.4 + 33.1 Chapter 13 - Building a Better Window (Introducing Windows Forms) is: {0}", Console.WriteLine("My random number Chapter 14 - A Better Painting ws.GetMyRandomNumber()); Framework (GDI+) Console.WriteLine("Simple value of PI is: {0}", Chapter 15 - Programming with Windows Forms Controls ws.GetSimplePI()); Chapter 16 - The System.IO Namespace Chapter 17 - Data Console.WriteLine(); Access with ADO.NET } Applications and XML Web Services Part Five - Web Chapter}18 - ASP.NET Web Pages and Web Controls } Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index
Regarding Overloaded Web Methods
List of Figures 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 correct 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# and the .NET Platform, Second Edition [System.Web.Services.Protocols.SoapDocumentMethodAttribute ISBN:1590590554 by Andrew Troelsen ("http://www.intertech-inc.com/WebServices/AddFloats", Apress © 2003 (1200 pages) RequestElementName="AddFloats", This comprehensive text starts with a brief overview of the RequestNamespace="http://www.intertech-inc.com/WebServices", C# language and then quickly moves to key technical and ResponseElementName="AddFloatsResponse", architectural issues for .NET developers. ResponseNamespace="http://www.intertech-inc.com/WebServices", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] Table of Contents [return: System.Xml.Serialization.XmlElementAttribute("dddFloatsResult")] C# and the .NET Platform, Second Edition public System.Single Add(System.Single x, System.Single y) Introduction {...} Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
andProxy the .NET(Asynchronous Platform, Second Edition LeveragingC# the Invocations) by Andrew Troelsen
ISBN:1590590554
As you have seenApress at numerous points throughout this text, the .NET platform has native support for © 2003 (1200 pages) asynchronous method invocations. The of with asynchronously invoking This comprehensive texttask starts a brief overview 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 moves to key technicalpattern. and architectural for .NETexposed developers. asynchronously invoke any ofissues the methods by the Calculator XML Web Service, simply leverage the BeginXXX() and EndXXXX() methods. Table Recall of that Contents when you wish to invoke a method asynchronously, the IAsyncResult interface allows you to
gather the.NET method's return valueEdition as well as determine if the call has completed. Thus, you may call Add() C# and the Platform, Second asynchronously as follows: Introduction Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy IAsyncResult result of= .NET ws.BeginAdd(30, 21, null , null); Chapter ... 2 - Building C# Applications Part if(result.IsCompleted) Two - The C# Programming Language
+ 32 = {0}", ws.EndAdd(result)); Chapter Console.WriteLine("30 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
If you would rather have the XML Web service call back to the client-side code base (rather than poll the - Interfaces and Collections method via the IsCompleted property), you can make use of the AsyncCallback delegate:
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
// Three Assume 'ws' is with a static instance Part - Programming .NET Assemblies
of the Calc proxy. AsyncCallback cb = new AsyncCallback(AdditionDone); Chapter 9 - Understanding .NET Assemblies IAsyncResult result = ws.BeginAdd(30, 21, cb, null); Chapter 10 - Processes, AppDomains, Contexts, and Threads ... Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming public static void AdditionDone(IAsyncResult result) Part Four - Leveraging the .NET Libraries { Chapter 12 - Object Serialization and the .NET Remoting Layer Console.WriteLine("30 + 32 = {0}", ws.EndAdd(result)); Chapter 13 - Building a Better Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
SOURCE The CalcWSClient can be Part Five - Web Applications and XML Webproject Services CODE Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
found under the Chapter 20 subdirectory.
C# and the .NET Proxy Platform,Logic Second Edition Avoiding Hard-Coded by Andrew Troelsen
ISBN:1590590554
The default behavior of © wsdl.exe ispages) to hard code the URL of the Web service within the proxy's constructor. The Apress 2003 (1200 obvious drawbackThis to this situation is the URL renamed or relocated, the proxy class must be updated and comprehensive that text if starts with is a brief overview of the recompiled. To build a more flexible proxy type, wsdl.exe provides the /appsettingurlkey flag (which may be C# language and then quickly moves to key technical and architectural for .NET abbreviated to /urlkey). Whenissues you specify thisdevelopers. flag at the command line, the proxy's constructor will contain logic that reads the URL using a key contained within a client-side *.config file. Table To illustrate, of Contents generate a proxy file for the HelloWS Web service created earlier in this chapter (note that HelloURL
is just key that will beEdition placed in the *.config file): C# and an thearbitrary .NET Platform, Second Introduction Part One - Introducing C# and the .NET Platform C:\>wsdl /urlkey:HelloUrl http://localhost/helloWS/helloworldWS.asmx?WSDL
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
If you now check out the default constructor Part Two - The C# Programming Language
of the proxy, you will find the following logic (note that if the correct key cannot be found, the hard-coded URL will be used as a backup): Chapter 3 - C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C# public Chapter 5 HelloClass() - Exceptions and Object Lifetime
{ Chapter 6
- Interfaces and Collections urlSetting = Chapter string 7 - Callback Interfaces, Delegates, and Events
System.Configuration.ConfigurationSettings.AppSettings["HelloUrl"]; - Advanced C# Type Construction Techniques if ((urlSetting null)) Part Three - Programming with!= .NET Assemblies this.Url = urlSetting; Chapter 9 - Understanding .NET Assemblies else Chapter 10 - Processes, AppDomains, Contexts, and Threads this.Url = "http://localhost/helloWS/helloworldWS.asmx"; Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming } Chapter 8
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing The client-side *.config file would look like this: Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures
SOURCE CODE
List of Tables
The HelloWSClient project can be found under the Chapter 20 subdirectory.
the .NET Platform, Second Edition GeneratingC# a and Proxy with VS .NET by Andrew Troelsen
ISBN:1590590554
Although wsdl.exe provides a (1200 number of command-line arguments that give you ultimate control over how Apress © 2003 pages) the resulting proxy class will be generated, VS .NET youoftothe quickly generate a proxy file using This comprehensive text starts with aalso briefallows overview the Add Web Reference dialog. To activate this tool, simply right-click the C# language and then quickly moves to key technical and References folder of the for .NET developers. Solution Explorer.architectural As you canissues see from Figure 20-9, you are able to obtain references to existing XML Web services located at a variety of locales. Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure 20-9: The VS .NET Add Web Reference utility
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Notice that you are not only able to obtain a list of XML Web services on your local development machine,
Chapter - Object Serialization thecatalogs .NET Remoting but you12 may also query variousand UDDI (which Layer we do at the end of this chapter). In any case, once Chapter 13 Building a Better Window (Introducing you type a valid URL that points to a given *.wsdl Windows or *.asmxForms) file, your project will contain a new proxy class. Chapter - Athe Better Painting Framework (GDI+) Do note14that proxy's namespace (which is based on the URL of origin) will be nested within your Chapter - Programming Windows Forms a Controls client's 15 .NET namespace.with Thus, if you added reference to CalcWS (which is located at Chapter http://localhost/CSharpBookSE/CalcWebService/CalcWS.asmx), 16 - The System.IO Namespace you would need to specify Chapter the following 17 - Data C# using Accessdirective: with ADO.NET Part Five - Web Applications and XML Web Services
Chapter - ASP.NET Web Pages and Web Controls using18TheWSClient.localhost; Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the Platform, Second Edition Exposing Arrays of.NET Types from Web Methods by Andrew Troelsen
ISBN:1590590554
So much for MathApress 101. The real power © 2003 (1200 pages)of Web services becomes much more evident when you build Web methods that return complex types. let's create a new XML This comprehensive To textillustrate, starts with a brief overview of theWeb service (named CarSalesInfoWS)C# that is capable of processing arrays, custom UDTs, and ADO.NET DataSets. First, let's language and then quickly moves to key technical and architectural issues for .NET developers. examine how to build Web methods that receive and return arrays of information. Assume you have a Web method named GetSalesTagLines(), which will return an array of strings that Table represent of Contents the current sales for various automobiles. Also assume you have another Web method named
SortCarMakes() that allows the caller C# and the .NET Platform, Second Editionto pass in an array of unsorted strings and obtain a new array of sorted textual information: Introduction Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET namespace CarSalesInfoWS Chapter { 2
- Building C# Applications
Part Two[WebService(Namespace="http://www.intertech-inc.com/webservices", - The C# Programming Language
Web service processes custom types")] Chapter 3 Description="This - C# Language Fundamentals class CarSalesInfoService : System.Web.Services.WebService Chapter public 4 - Object-Oriented Programming with C# Chapter { 5
- Exceptions and Object Lifetime Chapter ... 6 - Interfaces and Collections Chapter 7
[WebMethod(Description="Get - Callback Interfaces, Delegates, and Events current discount blurbs")]
public string[] GetSalesTagLines() { Part Three - Programming with .NET Assemblies string[] currentDeals = {"Colt prices slashed 50%!", Chapter 9 - Understanding .NET Assemblies "All BMWs come with standard 8-track", Chapter 10 - Processes, AppDomains, Contexts, and Threads "Free Pink Caravans...just ask me!"}; Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming return currentDeals; Part Four - Leveraging the .NET Libraries } Chapter 12 - Object Serialization and the .NET Remoting Layer [WebMethod(Description="Sorts a list of car makes")] Chapter 13 - Building a Better Window SortCarMakes(string[] (Introducing Windows Forms) theCarsToSort) public string[] Chapter 14 - A { Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Array.Sort(theCarsToSort); Chapter 16 - The System.IO Namespace return theCarsToSort; Chapter 17 - Data } Access with ADO.NET Part Five}- Web Applications and XML Web Services Chapter } 18 - ASP.NET Web Pages and Web Controls Chapter 8
- Advanced C# Type Construction Techniques
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and theTypes .NET Platform, Exposing Custom fromSecond WebEdition Methods by Andrew Troelsen
ISBN:1590590554
The SOAP protocol is also able to pages) transport XML representations of custom data types (both classes and Apress © 2003 (1200 structures). Interestingly, with the current release of athe .NET platform, you are not required to configure This comprehensive text starts with brief overview of the these custom types in any way to pass or return custom UDTs. To illustrate, add another Web method C# language and then quickly moves to key technical and architectural issues for .NETtakes developers. named GetSalesInfoDetails(). This method no parameters and returns an array of SalesInfoDetails structures: Table of Contents
// Helper struct. public struct SalesInfoDetails Introduction { Part One - Introducing C# and the .NET Platform public string info; Chapter public 1 - The Philosophy .NET DateTimeof dateExpired; Chapter public 2 - Building C# Applications string Url; Part } Two - The C# Programming Language C# and the .NET Platform, Second Edition
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime The implementation GetSalesInfoDetails() returns a populated array of this custom UTD as follows: Chapter 6 - Interfacesofand Collections Chapter 7
- Callback Interfaces, Delegates, and Events
[WebMethod(Description="Get details of current sales")] Chapter 8 - Advanced C# Type Construction Techniques public SalesInfoDetails[] GetSalesInfoDetails() Part Three - Programming with .NET Assemblies { Chapter 9 - Understanding .NET Assemblies theInfo new SalesInfoDetails[3]; Chapter SalesInfoDetails[] 10 - Processes, AppDomains, Contexts,=and Threads theInfo[0].info = "Colt prices slashed 50%!"; Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming theInfo[0].dateExpired = DateTime.Parse("12/02/04"); Part Four - Leveraging the .NET Libraries "http://www.CarsRUs.com"; Chapter theInfo[0].Url= 12 - Object Serialization and the .NET Remoting Layer theInfo[1].info = "All BMWs come with standard 8-track"; Chapter 13 - Building a Better Window (Introducing Windows Forms) theInfo[1].dateExpired = DateTime.Parse("8/11/03"); Chapter 14 - A Better Painting Framework (GDI+) theInfo[1].Url= "http://www.Bmws4U.com"; Chapter 15 - Programming with Windows Forms Controls theInfo[2].info = "Free Pink Caravans...just ask me!"; Chapter 16 - The System.IO Namespace theInfo[2].dateExpired = DateTime.Parse("12/01/09"); Chapter 17 - Data Access with ADO.NET theInfo[2].Url= "http://www.AllPinkVans.com"; Part Five - Web Applications and XML Web Services return theInfo; Chapter 18 - ASP.NET Web Pages and Web Controls } Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the Client .NET Platform, Second Edition A WindowsC# Forms by Andrew Troelsen
ISBN:1590590554
At this point, you Apress can build a client your choosing. Simply compile the XML Web service project, © 2003 (1200 of pages) generate a proxyThis (a lacomprehensive the Add Web References dialog), code away. text starts with a briefand overview of the For example, if you have a Windows Forms client application, you could fill a ListBox when you C# language and then quickly moves to key technical load and the main Form with each tag line architectural issues for .NET developers. as follows: private void mainForm_Load(object sender, System.EventArgs e) { C# and the .NET Platform, Second Edition CarSalesInfoService ws = new CarSalesInfoService(); Introduction string[] tagLines = ws.GetSalesTagLines(); Part One - Introducing C# and the .NET Platform foreach(string s in tagLines) Chapter 1 -lstCarSaleTagLines.Items.Add(s); The Philosophy of .NET Chapter 2 Building C# Applications }
Table of Contents
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals You can get back the array of SalesInfoDetails types in response to a Button Click event as follows: Chapter 4 also - Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6 -void Interfaces and Collections private btnGetAllDetails_Click(object sender, System.EventArgs e) Chapter { 7 - Callback Interfaces, Delegates, and Events
ws = newTechniques CarSalesInfoService(); ChapterCarSalesInfoService 8 - Advanced C# Type Construction SalesInfoDetails[] theSkinny Part Three - Programming with .NET Assemblies=
ws.GetSalesInfoDetails(); foreach(SalesInfoDetails s in theSkinny) Chapter 9 - Understanding .NET Assemblies Chapter{10 - Processes, AppDomains, Contexts, and Threads d = string.Format("Info: {0}\nURL:{1}\nExpiration Date:{2}", Chapter 11 -string Type Reflection, Late Binding, and Attribute-Based Programming s.info, s.Url, s.dateExpired); Part Four - Leveraging the .NET Libraries Chapter 12 -MessageBox.Show(d, Object Serialization and the"Details"); .NET Remoting Layer } Chapter 13 - Building a Better Window (Introducing Windows Forms) } Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and theTypes: .NET Platform, Edition Exposing Custom TheSecond Details by Andrew Troelsen
ISBN:1590590554
As you have seen, the CarsSalesInfoWS Apress © 2003 (1200 pages) application exposes a Web method that returns an array of SalesInfoDetails structures, which was defined in thea server application as so: This comprehensive text starts with brief overview of the C# language and then quickly moves to key technical and issues for .NET developers. public structarchitectural SalesInfoDetails { public string info; Table of Contents public DateTime dateExpired; C# and the .NET Platform, Second Edition public string Url; Introduction } Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2 - Building C# Applications Again, notice that unlike .NET Remoting, you are not required to mark your custom structures/classes with Part - The C# Programming Language the Two [Serializable] attribute. However, if you
wish to be more explicit that the SalesInfoDetails type is
Chapter serialized 3 across - C# Language the wireFundamentals as XML, you could update the structure accordingly: Chapter 4
- Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime [Serializable] public struct SalesInfoDetails Chapter 6 {
- Interfaces and Collections
Chapterpublic 7 - Callback string Interfaces, info;Delegates, and Events
DateTime dateExpired; Chapterpublic 8 - Advanced C# Type Construction Techniques public string with Url;.NET Assemblies Part Three - Programming } Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
One benefit of marking custom types exposed from an XML Web service as serializable is the fact that the same type can be exposed as an MBV type from a .NET Remoting application (where you must mark Chapter 12 - Object Serialization and the .NET Remoting Layer each MBV type with the [Serializable] attribute. Part Four - Leveraging the .NET Libraries
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter - A Better Painting Framework (GDI+) In either14case, however, the .NET runtime will serialize your custom structures and classes using the Chapter 15 - Programming with Windows Forms Controls System.Xml.Serialization.XmlSerializer data type. This type performs the same basic role as the Chapter BinaryFormatter 16 - The System.IO and SoapFormatter Namespacetypes (persist a type's state to some stream), however the
XmlSerializer canAccess only persist public data and/or private data exposed as public properties. Thus, if the Chapter 17 - Data with ADO.NET SalesInfoDetails type was updated follows: Part Five - Web Applications and XML as Web Services Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications [Serializable] public struct SalesInfoDetails Chapter { 20 - XML Web Services Index public string info;
public DateTime dateExpired; List of Figures public string Url; List of Tables private string dealershipName; }
then the dealershipName field would not end up in the resulting XML. Another point of interest regarding the XmlSerializer is the fact that it allows you to have intimate control over how the type is represented. To illustrate, by default the SalesInfoDetails structure is serialized as so: Colt prices slashed 50%! 2004-12-02T00:00:00.0000000-06:00 http://www.CarsRUs.com
As you can see, each public filed/property becomes a subelement of the root element. C# and the .NET Platform, Second Edition If you would rather expose each item of the structure as XML properties, you can mock up the structure ISBN:1590590554 by Andrewfound Troelsen definitions using attributes within the System.Xml.Serialization namespace: Apress © 2003 (1200 pages)
This comprehensive text starts with a brief overview of the
[XmlRoot] C# language and then quickly moves to key technical and public structarchitectural SalesInfoDetails issues for .NET developers. { [XmlAttribute]public string info; [XmlAttribute]public DateTime dateExpired; Table of Contents [XmlAttribute]public string Url; C# and the .NET Platform, Second Edition } Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
which would yield the following XML data representation:
Part Two - The C# Programming Language
Chapter 4 Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter - Callback Interfaces, Delegates, andneed Events For the7most part, you can typically avoid the to adorn your custom types with XML-centric attributes. Chapter 8 this - Advanced C# Type Construction However, can be extremely useful whenTechniques you need to map the names of a type exposed from an XML Part Three - Programming with .NET Assemblies Web service into client-side counterparts. As you would
hope, the attributes found within the
Chapter 9 - Understandingnamespace .NET Assemblies System.Xml.Serialization support various name/value pairs that may be fed into the Chapter 10 - Processes, AppDomains, Threads constructor. If you require such fine Contexts, tuning, I'll and assume you will check out the System.Xml.Serialization Chapter namespace 11 - Type at your Reflection, leisure. Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
and the .NET Platform, Second Edition ConsumingC#Custom Types: The Details by Andrew Troelsen
ISBN:1590590554
When clients set Apress a reference a Web © 2003 to (1200 pages)service that exposes custom types, the proxy class file also contains language definitions for each custom Thus, if you were to examine the client-side This comprehensive text starts public with a type. brief overview of the representation ofC# thislanguage type, youand would find the following C# code: then quickly moves to key technical and architectural issues for .NET developers.
[System.Xml.Serialization.XmlTypeAttribute (Namespace="http://www.intertech-inc.com/webservices")] Table of Contents public class SalesInfoDetails { C# and the .NET Platform, Second Edition public string info; Introduction public System.DateTime dateExpired; Part One - Introducing C# and the .NET Platform public string Url; Chapter 1 - The Philosophy of .NET } Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals Now, understand, of course,Programming that like .NET Remoting, types that are serialized across the wire as XML do Chapter 4 - Object-Oriented with C#
not retain if the SalesInfoDetails structure supported a set of public methods, Chapter 5 implementation - Exceptions andlogic. ObjectThus, Lifetime the proxy will failCollections to account for them (as they are not expressed in the WSDL document in the Chapter 6 generator - Interfaces and first place! However, if you were to distribute a client-side assembly that contained the implementation Chapter 7 -). Callback Interfaces, Delegates, and Events code of8the- client-side type, you would be able to leverage the type-specific logic. Doing so, however, Chapter Advanced C# Type Construction Techniques would require a .NET-aware Part Three - Programming withmachine. .NET Assemblies Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition Updating the CarsSalesInfoWS Project by Andrew Troelsen
ISBN:1590590554
Let's add a final set of Web methods to the CarsSalesInfo application that will illustrate how to leverage Apress © 2003 (1200 pages) CLR types when This constructing an XML Web service. you have created another helper structure comprehensive text starts with aAssume brief overview of the named Car: C# language and then quickly moves to key technical and architectural issues for .NET developers.
public struct Car { Table of Contents public Car(string p, string c, string m) C# and the .NET Platform, Second Edition { Introduction petName = p; Part One - Introducing C# and the .NET Platform carColor = c; Chapter 1 -carMake The Philosophy = m;of .NET Chapter}2 - Building C# Applications Part Two - The C# Programming Language public string petName; Chapterpublic 3 - C# string Language carColor; Fundamentals Chapterpublic 4 - Object-Oriented Programming with C# string carMake; Chapter 5 - Exceptions and Object Lifetime } Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Next, define as privateC# anType ArrayList data member (carList) and fill it with some initial cars in the constructor Chapter 8 - Advanced Construction Techniques of your Web service, as shown here: Part Three - Programming with .NET Assemblies Chapter 9
- Understanding .NET Assemblies public CarSalesInfoService : System.Web.Services.WebService Chapter 10 class - Processes, AppDomains, Contexts, and Threads
{ Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming ArrayList theCars Part Fourprivate - Leveraging the .NET Libraries
= new ArrayList(); public CarSalesInfoService() Chapter 12 - Object Serialization and the .NET Remoting Layer { Chapter 13 - Building a Better Window (Introducing Windows Forms) InitializeComponent(); Chapter 14 - A Better Painting Framework (GDI+) theCars.Add(new Car("Biff", "Green", "Firebird")); Chapter 15 - Programming with Windows Forms Controls theCars.Add(new Car("Bunny", "Pink", "Colt")); Chapter 16 - The System.IO Namespace theCars.Add(new Car("Chuck", "Red", "BWM")); Chapter 17 - Data Access with ADO.NET theCars.Add(new Car("Mary", "Red", "Viper")); Part Five - Web Applications and XML Web Services theCars.Add(new Car("Mandy", "Tan", "Golf")); Chapter } 18 - ASP.NET Web Pages and Web Controls Chapter ... 19 - ASP.NET Web Applications Chapter 20 - XML Web Services } Index List of Figures
Now a method named GetCarList() which returns the entire array of autos. Another method named List of add Tables GetACarFromList() returns a specific car from the array list based on a numerical index. The implementation of each method is simple, as shown here: // Return a given car from the list. [WebMethod(Description = "Get a specific car from ArrayList")] public Car GetACarFromList(int carToGet) { if(carToGet pointer-centricC# operator, 360,364 architectural issues for .NET developers.
!= operator, 378–379 & pointer-centric operator, 360
Table of Contents
* and & parameters, 363
C# and the .NET Platform, Second Edition
* pointer-centric operator, 360 Introduction Part One - Introducing C# and the .NET Platform * wildcard character, 50
Chapter 1
*.aspx file - The Philosophy of .NET
Chapter 2 - Building Applications application cacheC# and, 1041–1043 Part coding, Two - The C# Programming Language 954–958
Chapter 3 - C#structure Language examining of,Fundamentals 964–965 Chapter 4
- Object-Oriented Programming with C#
*.resources (binary) files - Exceptions and Object Lifetime binding into .NET assembly, 736–737 Chapter 6 - Interfaces and Collections building,735–736 Chapter 7 - Callback Interfaces, Delegates, and Events System.Resources namespace and, 733 Chapter 5
Chapter 8
- Advanced C# Type Construction Techniques
*.resx files creating and reading programmatically, 733–735 Chapter 9 - Understanding .NET Assemblies defined by VS .NET IDE, 739 Part Three - Programming with .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
@Page11attributes, 955 Chapter - Type Reflection, Late Binding, and Attribute-Based Programming Part [] pointer-centric Four - Leveraging operator, the .NET 360Libraries
Chapter Object Serialization += and12 –+-operators, 385–386 and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
+ operator, 375
Chapter 14 - A Better Painting Framework (GDI+)
+ token, Chapter 15509 - Programming with Windows Forms Controls , +System.IO operators,Namespace 379–380 Chapter 16and - The Chapter 17 - Data Access with ADO.NET directive, 1066 Part Five - Web Applications and XML Web Services
directive, 955
Chapter 18 - ASP.NET Web Pages and Web Controls
directive, 1066 Chapter 19 - ASP.NET Web Applications directive, 955–956 Chapter 20 - XML Web Services Index == operator, 378–379 List of Figures List of Tables
Index A
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and A Programmer's Guide to ADO.NET in C# (Apress, 2002), 931 architectural issues for .NET developers.
abstract base classes and interface support, 275 Tablevs. of interfaces, Contents 276–277 C# and theclasses, .NET Platform, Second Edition abstract defining, 215–216 Introduction
abstract keyword, 216
Part One - Introducing C# and the .NET Platform
abstract 273 Chapter 1 members, - The Philosophy of .NET Chapter abstract 2 members, - Building defined, C# Applications 22 Part Two -methods, The C# Programming abstract 216–220 Language
Chapter 3
- C# Language Fundamentals
abstract stream class, 818–822 - Object-Oriented Programming with C# BufferedStreams,822 Chapter 5 - Exceptions and Object Lifetime FileStreams, 820 Chapter 6 - Interfaces and Collections members of, 819 Chapter 7 - Callback Interfaces, MemoryStreams, 820–821 Delegates, and Events Chapter 4
Chapter 8
- Advanced C# Type Construction Techniques
Access databases, connecting to, 891
Part Three - Programming with .NET Assemblies
Access,9 Microsoft, 886 Chapter - Understanding .NET Assemblies Chapter - Processes, AppDomains, access10 modifiers, method, 140–143Contexts, and Threads Chapter 11 - Type Reflection, accessibility keywords, 141 Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
accessor methods and object fields, 563
Chapter 12 - Object Serialization and the .NET Remoting Layer
Activate13event, 641–642 Chapter - Building a Better Window (Introducing Windows Forms) Chapter 14 URLs, - A Better activation 571Painting Framework (GDI+) Chapter 15 Programming activator class, 518–520 with Windows Forms Controls Chapter 16 - The System.IO Namespace
Activator.GetObject() method, 571
Chapter 17 - Data Access with ADO.NET
active colors, 692–694 Part Five - Webestablishing, Applications and XML Web Services color members, Chapter 18type - ASP.NET Web693 Pages and Web Controls ColorDialog class,Web 693–694 Chapter 19 - ASP.NET Applications Active Server Pages Chapter 20 - XML Web (ASP) Services Indexbuilding classic, 947–950
page composition, 968–969 List of Figures page derivation, 970–971 List of Tables page life-cycle, 978–982 error events, 979–981 IsPostBack property, 981–982 problems with classic, 950 ad hoc polymorphism, 189–191 Add Class Wizard, 225–228 Add Member Wizard, 228 Add References dialog box, 68,408,449 Add Web Reference, VS .NET utility,1095 wizard,1063 administration utility, .NET, 447–448 ADO.NET, data access with, 843–931
vs. ADO, 843–844 C# and the .NET Platform, Second Edition ADO.NET namespaces, 850–851 by Andrew Troelsen CommandBuilder types and SQL Commands, 912–914 ISBN:1590590554 Apress © 2003 (1200 pages) connected layer of ADO.NET, 888–893 This comprehensive starts with a brief overview of the Access databases, connectingtext to, 891 C# language and then quickly moves to key technical and core OLE DB providers, 889 architectural issues for .NET developers. database schema information, obtaining with, 891–892 defined, 844 type members, 890 Table of OleDbConnection Contents SQL commands, building with OleDbCommand, 892–893 C# and the .NET Platform, Second Edition data providers, 845–850 Introduction IDataAdapter interface, 848 Part One - Introducing C# and the .NET Platform IDataParameter interface, 846–847 Chapter 1 - The Philosophy of .NET IDataReader interface, 848–850 Chapter 2 - Building C# Applications IDataRecord interface, 848–850 Part Two - The C# Programming Language IDbCommand interface, 846–847 Chapter 3 - C# Language Fundamentals IDbConnection and IDbTransaction interfaces, 846 Chapter IDbDataAdapter 4 - Object-Oriented Programming with C# interface, 848 Chapter IDbDataParameter 5 - Exceptions andinterface, Object Lifetime 846–847 Chapter selecting, 6 - Interfaces 887 and Collections Chapter 7 - Callback Interfaces, DataColumn type, 852–858 Delegates, and Events Chapter adding 8 - Advanced C# Type Construction Techniques to DataTable, 855 Part Three - Programming with .NET Assemblies auto-incrementing fields, enabling, 856–857 Chapter building 9 - Understanding a DataColumn, .NET 854–855 Assemblies as primary key constraint, Chapter configuring 10 - Processes, AppDomains, Contexts,855 and Threads configuring, Chapter XML 11 - data Type representation, Reflection, Late Binding, and 857–858 Attribute-Based Programming type,the 879–883 Part DataRelation Four - Leveraging .NET Libraries 880 Chapter properties 12 - Objectof, Serialization and the .NET Remoting Layer tablesanavigation, 880–883 Chapter related 13 - Building Better Window (Introducing Windows Forms) DataRow type, 858–861 Chapter 14 - A Better Painting Framework (GDI+) DataSet type, 874–879 Chapter 15 - Programming with Windows Forms Controls in-memory DataSet, building, 876–879 Chapter 16 - The System.IO Namespace members of, 875–876 Chapter 17 - Data Access with ADO.NET DataSets at design time, 927–931 Part Five - Web Applications and XML Web Services typed DataSets at design time, 928–929 Chapter 18 - ASP.NET Web Pages and Web Controls typed DataSets, defined, 927 Chapter 19 - ASP.NET Web Applications typed DataSets, structure of, 929–931 Chapter untyped 20 - XMLDataSets, Web Services defined, 927 IndexDataTable, building, 863–871 List of Figures filters and sort orders, 867–869 List of Tables rows, deleting, 866–867 rows, updating, 869–871 DataTable type, 861–863 DataView type, 871–873 disconnected layer of ADO.NET, 844,901–905 libraries,844 multitabled DataSets, filling, 916–919 need for ADO.NET, 843–844 OleDbCommand executing stored procedures with, 899–901 inserting, updating and deleting records with, 897–899 OleDbDataAdapter type, 901–905 column names, altering with, 904–905 core members of, 903 DataSets, filling with, 903–904 OleDbDataReader,894–896
Command Behavior, specifying, 895–896 C# and the .NET Platform, Second Edition multiple result sets, obtaining with, 896 ISBN:1590590554 by Andrew Troelsen schema information, obtaining with, 896 Apress © 2003 (1200 pages) simple test database, building, 886 This comprehensive text starts with a brief overview of the SQL Data Provider, 906–912 C# language and then quickly moves to key technical and SqlDataAdapter, inserting records with, 907–910 architectural issues for .NET developers. SqlDataAdapter, updating records with, 910–912 System.Data.SQLTypes namespace, 907 System.Data Table of Contents namespace, 851–852 System.Data.OleDb namespace, 888 C# and the .NET Platform, Second Edition VS .NET wizards. Seewizards Introduction Windows Forms example, 914–916 Part One - Introducing C# and the .NET Platform XML-based DataSets, reading and writing, 883–885 Chapter 1
- The Philosophy of .NET
adornments, member, Chapter 2 - Building C# 22 Applications Part Two - The C# Programming AdRotator control, 996–997 Language
Chapter 3 -.NET C# Language Advanced RemotingFundamentals (Apress, 2002), 560 Chapter 4 - Object-Oriented Programming with C#
alert() method, 945
Chapter 5
- Exceptions and Object Lifetime
al.exe (assembly linker), Chapter 6 - Interfaces and424 Collections Chapter aliases7(C#) - Callback Interfaces, Delegates, and Events
defining Chapter 8 - namespace, Advanced C# 174 Type Construction Techniques data types and, 122–128 Part system Three - Programming with .NET Assemblies numerical members, 125–126 Chapter basic 9 - Understanding .NET Assemblies 125 Chapter experimenting 10 - Processes,with, AppDomains, Contexts, and Threads data,Reflection, parsing values from, 127–128 Chapter string 11 - Type Late Binding, and Attribute-Based Programming System.Boolean 126 Part Four - Leveraging themembers, .NET Libraries members, 127.NET Remoting Layer Chapter System.CharNext 12 - Object Serialization and the anchoring 779–780 Chapter 13 -behavior, Building aconfiguring, Better Window (Introducing Windows Forms) Chapter 14 - A Better AnchorStyles values,Painting 779 Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
apartment structure, COM, 463,479–480
Chapter 16 - The System.IO Namespace
app.config file, 428–429
Chapter 17 - Data Access with ADO.NET
AppDomains 462–468 Part Five - Web(System.AppDomain Applications and XMLtype), Web Services AppDomainManipulator.exe 467–468 Chapter 18 - ASP.NET Web Pages process, and Web Controls basics, Chapter 19 462–463 - ASP.NET Web Applications context, thread relationship to, 474–475 Chapter 20 - process XML Weband Services Indexcreating programmatically, 466–467
events of, 464 interacting programmatically with, 465–466 List of Tables members of, 464 unloading programmatically, 468 List of Figures
AppendText() method, 818 Apple OSX, 16 applications application- and system-level exceptions, 252 application cache, 1037–1043 *.aspx file, modifying, 1041–1043 data caching example, 1038–1040 Application class. SeeSystem.Windows.Forms.Application class application domains, 262,554 application-level exceptions, building custom, 243–247 application roots, 259 application states vs. session states, 1033–1037 application data, modifying, 1036–1037
application-level state data, maintaining, 1033–1036 C# and the .NET Platform, Second Edition Web application shutdown, 1037 ISBN:1590590554 by Andrew Application_Error() eventTroelsen handler, 1031–1032 Apress © 2003 (1200 pages) ApplicationExit event, 619 This method, comprehensive Application.Run() 641 text starts with a brief overview of the C# language and then quickly moves to key technical and Application_Start() event handler, 1038,1040 architectural issues for .NET developers.
, custom Web settings with, 1057 arguments, method, 325
Table of Contents
arrays ArrayList class type, 310,311–312 Introduction jagged, 157 Part One - Introducing C# and the .NET Platform manipulation in C#, 154–159 Chapter 1 - The Philosophy of .NET arrays as parameters and return values, 155–156 Chapter 2 - Building C# Applications multidimensional arrays, 156–157 Part Two - The C# Programming Language System.Array base class, 158–159 Chapter 3 - C# 156 Language Fundamentals rectangular, C# and the .NET Platform, Second Edition
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
as keyword, 278
as operator, 140 Chapter 6 - Interfaces and Collections Chapter ascending 7 -values Callback (font Interfaces, metrics),Delegates, 697 and Events Chapter 8 - Advanced C# Type Construction Techniques aspect-oriented programming, 523 Part Three - Programming with .NET Assemblies
ASP.NET IDE Web Matrix, 90
Chapter 9
- Understanding .NET Assemblies
ASP.NET applications, 1023–1058 Chapter 10 -Web Processes, AppDomains, Contexts, and Threads application cache, 1037–1043 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming *.aspx file, modifying, 1041–1043 Part Four - Leveraging the .NET Libraries
data caching example, 1038–1040 application states vs. session states, 1033–1037 Chapter 13 - Building a Better Window (Introducing Windows Forms) application data, modifying, 1036–1037 Chapter 14 - A Better Painting Framework (GDI+) application-level state data, maintaining, 1033–1036 Chapter 15 - Programming with Windows Forms Controls Web application shutdown, 1037 Chapter 16 - The System.IO Namespace configuration inheritance, 1057–1058 Chapter 17 - Data Access with ADO.NET configuring with web.config file, 1050–1057 Part Fivecustom - Web Applications Web Services1057 Web settingsand withXML , Chapter elements 18 - ASP.NET Web Pages and of web.config, 1052Web Controls Chapter error 19 - ASP.NET Web Applications output, customizing with , 1053–1054 Chapter storing 20 - XML Web Services state with , 1054–1056 Index tracing with , 1052–1053 List of cookies, Figures1047–1050 creating,1047–1049 List of Tables reading incoming data, 1049–1050 Global.asax file, 1030–1032 exception event handler, 1031–1032 HttpApplication base class, 1032 session data, maintaining, 1043–1046 state management, 1023–1026 view state, 1026–1029 custom view state data, 1029 definition and basics, 1026 demonstrating,1027–1029 Chapter 12 - Object Serialization and the .NET Remoting Layer
ASP.NET Web pages, 935–1020 benefits of ASP.NET, 950–951 BetterAspNetCarApp Web application, coding, 966–968 classic Active Server Page building,947–950
problems with, 950 C# and the .NET Platform, Second Edition client-side scripting, 943–946 ISBN:1590590554 Andrew Troelsen default.htmbyform data, 946 Apress © 2003 (1200 pages) example,945–946 This comprehensive text starts with a brief overview of the compilation cycle, 958–961 C# language and then quickly moves to key technical and debugging and tracing, 1020 architectural issues for .NET developers. form data, submitting, 947 GDI+ on Web server, 1016–1019 and POST methods, 947 TableGET of Contents HTML (Hypertext Markup Language) C# and the .NET Platform, Second Edition controls,1014–1016 Introduction document structure, 939–940 Part One - Introducing C# and the .NET Platform form development, 940–943 Chapter 1 - The Philosophy of .NET HTTP requests, interacting with incoming, 971–975 Chapter 2 - Building C# Applications browser statistics, 973 Part Two - The C# Programming Language form data, access to incoming, 975 Chapter 3 - C# Language Fundamentals HttpRequest type members, 972 Chapter server 4 - Object-Oriented Programming variables, access to, 974 with C# Chapter 5 Exceptions and Object Lifetime HTTP responses, interacting with outgoing, 975–978 Chapter HTML 6 - Interfaces and Collections content, emitting, 977 Chapter HttpResponse 7 - Callback Interfaces, Delegates, and Events976 type properties and methods, Chapter redirecting 8 - Advanced C#977–978 Type Construction Techniques users, Part HTTP, Three - role Programming with .NET Assemblies of, 935–936 Chapter namespaces, 9 - Understanding 952–953 .NET Assemblies page Chapter 10composition, - Processes, 968–969 AppDomains, Contexts, and Threads page 970–971Late Binding, and Attribute-Based Programming Chapter 11derivation, - Type Reflection, 978–982 Part page Four -life-cycle, Leveraging the .NET Libraries events,Serialization 979–981 and the .NET Remoting Layer Chapter error 12 - Object property, Chapter IsPostBack 13 - Building a Better 981–982 Window (Introducing Windows Forms) Web application, creating manually, (GDI+) 953–958 Chapter 14 - A Better Painting Framework *.aspx file, coding, 954–958 Chapter 15 - Programming with Windows Forms Controls directive, 955 Chapter 16 - The System.IO Namespace directive, 955–956 Chapter 17 - Data Access with ADO.NET script blocks, 956–957 Part Five - Web Applications and XML Web Services widget declarations, 957–958 Chapter 18 - ASP.NET Web Pages and Web Controls Web application, creating with VS .NET, 961–966 Chapter 19 - ASP.NET Web Applications code behind file, 965–966 Chapter initial 20 - XML Web Services *.aspx file, 964–965 IndexWeb applications and Web servers, 936–938 List of Figures Web controls. SeeWeb controls,ASP.NET List of Tables
aspnet_regiis.exe command line tool, 937 *.aspx file application cache and, 1041–1043 coding,954–958 examining structure of, 964–965 assemblies, .NET assembly- and module- level attributes, 526–527 directive, 1066 assembly manifest, 17–18,397,400,415 assembly metadata, viewing, 37–38 AssemblyInfo.cs file (VS .NET), 527 AssemblyLoad() method, 511–512 AssemblyName type, 513 AssemblyRef #n tokens, 503 binding *.resources file into, 736–737
C# client application, 408–409 CarLibrary C# and the .NET Platform, Second Edition ISBN:1590590554 by Andrew Troelsen manifest,415–417 Apress © 2003 (1200 pages) types,418–419 This comprehensive text starts with a brief overview of the classic COM binaries, problems with, 395–397 C# language and then quickly moves to key technical and COM deployment, 396–397 architectural issues for .NET developers. COM versioning, 396 client,567 Table of Contentselements, 442–444 cross-language inheritance, 411–415 C# and the .NET Platform, Second Edition custom version policies, 440 Introduction delayed signing, 434–435 Part One - Introducing C# and the .NET Platform documenting defining assembly, 502–503 Chapter 1 - The Philosophy of .NET GAC internals, 440–442 Chapter 2 - Building C# Applications machine-wide configuration file, 445–446 Part Two - The C# Programming Language multifile assembly, building, 419–422 Chapter 3 - C# Language Fundamentals airvehicles.dll,422 Chapter ufo.netmodule, 4 - Object-Oriented Programming with C# 421–422 Chapter 5 Exceptions and Object Lifetime multifile assembly, using, 422–424 Chapter 6 Interfaces and Collections .NET administrative tool, 447–448 Chapter 7 - Callback Interfaces, Delegates, and Events ngen.exe utility, 448–449 Chapter 8 - Advanced Type Construction Techniques overview of, 10–11,C# 397–404 Part Three - Programming code reuse, 402 with .NET Assemblies Chapter physical 9 - Understanding and logical .NET views, Assemblies 401–402 context AppDomains, defined, 404 Contexts, and Threads Chapter security 10 - Processes, execution, 404 Chapter side-by-side 11 - Type Reflection, Late Binding, and Attribute-Based Programming single file and multifile 400–401 Part Four - Leveraging the .NETassemblies, Libraries 403 and the .NET Remoting Layer Chapter type 12 - boundaries, Object Serialization self-describing entities, 403 Chapter versionable 13 - Buildingand a Better Window (Introducing Windows Forms) private assemblies Chapter 14 - A Better Painting Framework (GDI+) probing for, 425–426,429–430 Chapter 15 - Programming with Windows Forms Controls understanding, 425 Chapter 16 - The System.IO Namespace and XML configuration files, 426–429 Chapter 17 - Data Access with ADO.NET publisher policy assemblies, 444–445 Part Five - Web Applications and XML Web Services referenced, documenting, 503 Chapter 18 - ASP.NET Web Pages and Web Controls referencing multiple external (csc.exe), 50 Chapter 19 - ASP.NET Web Applications server,567 Chapter 20 -assemblies XML Web Services shared Index building, 432–434 List of Figures installing and removing, 435–436 List of Tables SharedAssembly version 2.0.0.0, 438–439 understanding, 430–431 using,436 versioning,437–438 single file and multifile, 13,400–401 strong names, 431–432 System.Configuration namespace, 446–447 VB .NET client application, 409–411 viewing compiled, 1068–1069 VS .NET Add References dialog box, 449 asynchronous delegates, 341–347 callbacks for, 344–347 invoking methods asynchronously, 343–344 asynchronous IO, 833
asynchronous method invocations, 343–344,1090–1091,1093–1094 C# and the .NET Platform, Second Edition
asynchronous remoting, 603–604 by Andrew Troelsen
ISBN:1590590554
attributed programming, Apress ©520–522 2003 (1200 pages) This comprehensive text starts with a brief overview of the attributes @Page,955 C# language and then quickly moves to key technical and architectural issues for .NET developers. assembly- and module- level, 526–527 assembly-level,527 AttributeUsageAttribute,525 Table of Contents AutoGenerateColumns attribute, 999 C# and the .NET Platform, Second Edition building custom, 523–524 Introduction Inherits attribute, 968 Part One - Introducing C# and the .NET Platform and methods, defined, 179 Chapter 1 - The Philosophy of .NET predefined system, 521 Chapter 2 - Building C# Applications restricting usage, 524–525 Part Two - The C# Programming Language at runtime, 528 Chapter 3 - C#notation, Language Fundamentals shorthand 524 Chapter 4 Object-Oriented Programming with C# [WebMethod] attribute, 1066 Chapter 5 Exceptions and Object Lifetime [WebService] attribute, 1077–1078 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
auto-generating SQL Commands with CommandBuilder types, 912–914
auto-incrementing fields, enabling (DataColumns), 856–857 Chapter 8 - Advanced C# Type Construction Techniques AutoFlush 824 with .NET Assemblies Part Three - property, Programming Chapter 9 - Understanding .NET Assemblies AutoGenerateColumns attribute, 999 Chapter 10 - Processes, AppDomains, Contexts, and Threads
AutoPostBack property, 984–985
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
AutoScroll properties,the 636–637 Part Four - Leveraging .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index B
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
base class creation,203–204 libraries, .NET, 7–8,32,76,197
Table baseofinterfaces, Contents multiple, 287–288 C# andkeyword, the .NET 204, Platform, base 215 Second Edition Introduction
BeginEdit() method (DataTables), 870
Part One - Introducing C# and the .NET Platform
BeginInvoke() 343–345 Chapter 1 - Themethod, Philosophy of .NET Chapter BeginRead() 2 - Building and BeginWrite() C# Applications methods, 833 Part Two - The C# Programming Language BeginTransaction() method, 846
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
\bin directory, 967–968
binaries5 Chapter
- Exceptions and Object Lifetime binary (serialization), 545–547 Chapter 6 formatter - Interfaces and Collections
binary reuse, 402 - Callback Interfaces, Delegates, and Events BinaryReaders and BinaryWriters, 829–831 Chapter 8 - Advanced C# Type Construction Techniques classic COM, 395–397 Part Three - Programming with .NET Assemblies overview of, 11–13 Chapter 7
Chapter 9
- Understanding .NET Assemblies
(WSDL), 1082 Contexts, and Threads Chapter 10 -element Processes, AppDomains, Chapter bitmaps11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Bitmap Four - Leveraging type, 721–723 the .NET Libraries
as brushes, 717Serialization and the .NET Remoting Layer Chapter 12 - Object Chapter 13 programming, - Building a Better black box 192Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
BlinkStyle properties, 778
Chapter 15 - Programming with Windows Forms Controls
BorderStyle property, 781
Chapter 16 - The System.IO Namespace
boxing 17 and- unboxing, 128–132 Chapter Data Access with ADO.NET examples, 129–130 Part (un)boxing Five - Web Applications and XML Web Services (un)boxing customWeb structures, 170–171 Chapter 18 - ASP.NET Pages and Web Controls underlying CIL, 131–132 Chapter 19 - ASP.NET Web Applications Chapter breakpoints, 20 - XML 71 Web Services Index browsers List of Figures property, 973 Browser List of Tables statistics, obtaining, 973
brushes bitmaps as, 717 gradient,719–720 hatch style, 715–717 solid,713–715 textured,717–718 BSD Unix, 16 BufferedStreams,822 bug reports, generating, 52–53 bugs, errors, exceptions defined, 231–232 bundling external resources, 732–733 Button type, 752–755 ButtonBase properties, 753
content position, configuring, 753 default input, C# 767and the .NET Platform, Second Edition by Andrew Troelsen example,754–755 Apress © 2003 (1200 pages) tool bar buttons, 663–664
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index C
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and C# applications, building, 43–90 architectural issues for .NET developers.
bug reports, generating, 52–53 building .NET applications with other IDEs, 89–90 options, 54–55 Tablecompiler of Contents cordbg.exe (command line debugger), 55–57 C# and the .NET Platform, Second Edition with csc.exe Introduction compiling multiple source files, 49–50 Part One - Introducing C# and the .NET Platform output options, 46 Chapter 1 - The Philosophy of .NET referencing external assemblies, 48–50 Chapter 2 - Building C# Applications csc.exe (C# compiler) Part Two - The C# Programming Language configuring, 44–45 Chapter 3 - C# Language Fundamentals configuring other .NET command line tools, 45 Chapter response 4 - Object-Oriented files, 50–52Programming with C# Chapter 5 Exceptions andStudio Object.NET Lifetime debugging with Visual IDE, 70–71 Chapter 6 Interfaces and Collections documenting source code via XML, 76–82 Chapter viewing 7 - Callback Interfaces, Delegates, generated XML file, 79–81 and Events Chapter VS 8 -.NET Advanced C# Type Construction Techniques documentation support, 81–82 Part Three - Programming with .NET Assemblies XML tags, 77 Chapter preprocessor 9 - Understanding directives,.NET 82–88 Assemblies line numbers, 87–88 Contexts, and Threads Chapter altering 10 - Processes, AppDomains, code compilation, 84–86 Chapter conditional 11 - Type Reflection, Late Binding, and Attribute-Based Programming issuing warnings errors, 86 Part Four - Leveraging theand .NET Libraries regions, and 83–84 Chapter specifying 12 - Objectcode Serialization the .NET Remoting Layer System.Environment class, 88–89(Introducing Windows Forms) Chapter 13 - Building a Better Window VS .NET 57–61, 71–76 Chapter 14 - AIDE, Better Painting Framework (GDI+) database manipulation tools, 73–74 Chapter 15 - Programming with Windows Forms Controls debugging applications with, 70–71 Chapter 16 - The System.IO Namespace integrated help, 74–76 Chapter 17 - Data Access with ADO.NET object browser utility, 73 Part Five - Web Applications and XML Web Services project solution, creating, 60–61 Chapter 18 - ASP.NET Web Pages and Web Controls server explorer window, 71–72 Chapter 19 - ASP.NET Web Applications start page, 58–59 Chapter XML-related 20 - XML Web Services editing tools, 72–73 IndexVS .NET test application, building, 61–70 List of Figures adding code, 67 List of Tables configuring a C# project, 64–65 inserting new C# type definitions, 68–69 outlining code via VS .NET, 69–70 properties window, 66 referencing external assemblies via VS .NET, 67–68 solution explorer window, 62–64 C# language, 93–177 array manipulation in C#, 154–159 arrays as parameters and return values, 155–156 multidimensional arrays, 156–157 System.Array base class, 158–159 basic C# class, anatomy of, 93–97 Main() method, variations on, 94–95 processing command line parameters, 95–96 simulating command arguments with VS .NET, 96–97 boxing and unboxing, 128–132
(un)boxing examples, 129–130 and the .NET Platform, Second Edition underlyingC# CIL, 131–132 ISBN:1590590554 by Andrew Troelsen C# type Apress © 2003 (1200 pages) advanced construction techniques. Seeconstruction techniques, advanced C# type comprehensive definitions,This inserting, 68–69 text starts with a brief overview of the C# language and then quickly moves to key technical and class defined, 179–184 architectural issues for .NET developers. method overloading, 181–182 self-reference in C#, 183–184 client application, 408–409 Table of Contents compiler (csc.exe). Seecsc.exe (C# compiler) C# and the .NET Platform, Second Edition compiler options, 54–55 Introduction composition of C# applications, 100–101 Part One - Introducing C# and the .NET Platform configuring a project, 64–65 Chapter 1 - The Philosophy of .NET console class, input and output with, 105–109 Chapter 2 - Building C# Applications formatting textual output, 106–107 Part Two - The C# Programming Language string formatting flags, 107–109 Chapter 3 - C# Language Fundamentals control flow constructs, 137–139 Chapter - Object-Oriented Programming core4 project workspace types, 60–61 with C# Chapter 5 Exceptions and Object Lifetime custom class methods, defining, 140–143 Chapter accessibility 6 - Interfaces and Collections keywords, 141 Chapter method 7 - Callback Interfaces, Delegates, access modifiers, 141–143and Events Chapter 8 - namespaces, Advanced C# Type Construction custom defining, 171–176Techniques Part Three - Programming .NET Assemblies default namespacewith of VS .NET, 175–176 Chapter namespace 9 - Understanding aliases,.NET defining, Assemblies 174 namespaces, 174–175 Chapter nested 10 - Processes, AppDomains, Contexts, and Threads clashes, Chapter resolving 11 - Typename Reflection, Late173–174 Binding, and Attribute-Based Programming assignments scope, 102–104 Part default Four - Leveraging theand .NETvariable Libraries enumerations, Chapter 12 - Object164–168 Serialization and the .NET Remoting Layer enumeration, 164 (Introducing Windows Forms) Chapter EmpType 13 - Building a Better Window System.Enum base class, 166–168 Chapter 14 - A Better Painting Framework (GDI+) features and advantages of, 8–9 Chapter 15 - Programming with Windows Forms Controls indexer from VB .NET, 374–375 Chapter 16 - The System.IO Namespace interfaces, defining with, 273–277 Chapter 17 - Data Access with ADO.NET iteration constructs, 134–137 Part Five - Web Applications and XML Web Services foreach/in loop, 135–136 Chapter 18 - ASP.NET Web Pages and Web Controls for loop, 135 Chapter 19 - ASP.NET Web Applications while and do/while looping constructs, 136–137 Chapter 20 - XML Web Services keywords, summary of, 367–369 Indexmember variable initialization syntax, 104–105 List of Figuresparameter modifiers, 147–154 method List of Tables default parameter passing behavior, 148 out keyword, 148–149 params keyword, 150–151 passing reference types by reference and value, 152–154 ref keyword, 149–150 object construction basics, 97–100 operators,139–140 pointer-centric operators. Seepointer-centric operators program constants, defining, 132–134 snap-in, building, 531 static methods, 143–147 defining,143–145 static data, defining, 145–147 string manipulation in C#, 160–164 escape characters and verbatimstrings,161–162 System.Text.StringBuilder,162–164
structures, defining in C#, 168–171 C# and the .NET Platform, Second Edition system data types and C# aliases, 122–128 ISBN:1590590554 by Andrew Troelsen basic numerical members, 125–126 Apress © 2003 (1200 pages) experimenting with, 125 comprehensive text127–128 starts with a brief overview of the string data,This parsing values from, C# language and then quickly moves to key technical and System.Boolean members, 126 architectural issues for .NET developers. System.CharNext members, 127 System.Object base class, 115–122 behaviors, overriding, 118–119 Table of default Contents Equals(), overriding, 119–120 C# and the .NET Platform, Second Edition GetHashCode(), overriding, 120–122 Introduction static members of, 122 Part One - Introducing C# and the .NET Platform ToString(), overriding, 119 Chapter 1 - The Philosophy of .NET using keyword, 31–32 Chapter 2 - Building C# Applications value-based and reference-based types, 109–114 Part Two - The C# Programming Language comparison of, 113–114 Chapter 3 - C# Language Fundamentals value types containing reference types, 112–113 Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
C/Win32 API programming, 3–4
C++/MFC 409 Chapter 6 -programming, Interfaces and4,Collections Chapter - Callback1037–1043 Interfaces, Delegates, and Events cache, 7application, Chapter *.aspx 8 file, - Advanced modifying, C# 1041–1043 Type Construction Techniques Part data Threecaching - Programming example, with 1038–1040 .NET Assemblies
Chapter - Understanding .NET Assemblies Cache 9class, 1038 Chapter 10 - Processes, AppDomains, Contexts, and Threads
CacheDependency type, 1040
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Calculator XML Web the Service, 1093 Part Four - Leveraging .NET Libraries Chapter CalcWS 12Web - Object methods, Serialization invoking, and1071–1072 the .NET Remoting Layer Chapter 13 control, - Building a Better Window (Introducing Windows Forms) calendar 995–996 Chapter 14 - A Better Painting Framework (GDI+)
callbacks for asynchronous delegates, 344–347 Chapter 16 - The System.IO Namespace functions, defined, 325 Chapter 17 - Data Access ADO.NET instance methods as,with 339–341 Part interfaces, Five - Web321–325 Applications and XML Web Services
Chapter 15 - Programming with Windows Forms Controls
Chapter 18 - ASP.NET Web Pages and Web Controls
CancelEdit() method (DataTables), 870
Chapter 19 - ASP.NET Web Applications
CAO (client-activated objects) Chapter 20 - XML Web Services Indexdefined, 564
understanding, 587–589
List of Figures
CAO/WKO-singleton objects, 589–595 List of Tables client-side lease adjustment, 595 default leasing behavior/characteristics, 590–594 server-side lease adjustment, 594–595 caps, pen, 711–713 Car project Car type, viewing for, 501–502 Car.CarDelegate, multicasting with, 338–339 CarControl,792–796 CarControl type, testing, 797–798 custom events, defining, 794 custom properties, defining, 794–796 CarDelegate, using, 334–337 CarLibrary manifest,415–417 types,418–419
CarLogApp project, 834–837 and the .NET Platform, Second Edition Cars GeneralC# Assembly, building, 583–584 ISBN:1590590554 by Andrew Troelsen Cars Indexer, variation of, 372–373 Apress © 2003 (1200 pages) CarSalesInfoWS project, updating, 1100–1102 This comprehensive text starts with a brief overview of the CarService, installing, 601 C# language and then quickly moves to key technical and
casting architectural issues for .NET developers. between class types, 222–225 determining type of employee, 223–224 Table of numerical Contents casts, 224–225 explicit, 277–278 C# and the .NET Platform, Second Edition Introduction catch statements, generic, 249 Part One - Introducing C# and the .NET Platform
catching exceptions, 236–240 - The Philosophy of .NET HelpLink property, 239–240 Chapter 2 - Building C# Applications StackTrace property, 239 Part Two - The C# Programming Language TargetSite property, 238–239 Chapter 1
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
channels (.NET Remoting), 558
ChannelServices type, and 572–573 Chapter 5 - Exceptions Object Lifetime Chapter 6 - Interfaces CheckBoxes, 755–756and Collections Chapter 7 keyword, - Callback356–358 Interfaces, Delegates, and Events checked Chapter 8
- Advanced C# Type Construction Techniques
CheckedListBox Control, 758–760
Part Three - Programming with .NET Assemblies
child Form, (MDI applications), 668 Chapter 9 - building Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads child windows (MDI applications), 668–669 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming CIL (Common Intermediate Language) Part code, Four -12, Leveraging 397,399 the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer compiling to platform-specific instructions, 18 Chapter 13 keyword, - Building257–259 a Better Window (Introducing Windows Forms) ofnew Chapter - Abenefits Better Painting Framework (GDI+) role14 and of, 13–16 Chapter 15 - manifest, Programming tokens, 417 with Windows Forms Controls Chapter classes16 - The System.IO Namespace Chapter 17 - Data Access with ASP.NET-generated classADO.NET names, 961 Part Class Five - Web Applications and XML Web76 Services Library node of MSDN library,
Chapter 18 Viewer - ASP.NET Pages and38Web Controls Class WebWeb application, Chapter - ASP.NET CTS19class types, Web 19 Applications Chapter 20 - 97, XML Web Services defined, 789 Indexgenerating class definitions with VS .NET, 225–229
Add Class Wizard, 225–228 List of Figures adding members to types, 228–229 List of Tables System.Collections, class types of, 310–314 classic COM binaries, problems with, 395–397 COM deployment, 396–397 COM versioning, 396 classical inheritance, 188 classical polymorphism, 189–191 ClassicAspPage.asp file, 947 CLI (Common Language Infrastructure), 25,40 client applications C#,408–409 VB .NET, 409–411 client area, invalidating (paint sessions), 682 client assembly
building (MBV), 585–587 defined, 567 C# and the .NET Platform, Second Edition by Andrew Troelsen
client, defined, 554 Apress © 2003 (1200 pages)
ISBN:1590590554
client-side *.config files, building, 581–582 This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and client-side lease adjustment, 595 architectural issues for .NET developers.
client-side scripting, 943–946 default.htm form data, 946 945–946 Tableexample, of Contents C# and the .NET Platform, Second Edition ClientValidationFunction property, 1012 Introduction
cloneable objects, building, 297–302
Part One - Introducing C# and the .NET Platform
Close()1method, 895 Chapter - The Philosophy of .NET CloseFigure() method, Chapter 2 - Building C# 730 Applications Part Two -and TheClosed C# Programming Language Closing events, 641–642
Chapter 3
- C# Language Fundamentals
CLR (common language runtime) - Object-Oriented Programming with C# defined, 7 Chapter 5 - Exceptions and Object Lifetime header,397–399 Chapter 6 - Interfaces and Collections system-level exceptions, 240–242 Chapter 7 Callback Interfaces, Delegates, and Events understanding, 25–27 Chapter 4
Chapter 8
- Advanced C# Type Construction Techniques
CLS (Common Language Specification), 23–25 CLSCompliant attribute, 526 Chapter 9 - Understanding .NET Assemblies defined, 7 Chapter 10 - Processes, AppDomains, Contexts, and Threads ensuring compliance, 25 Part Three - Programming with .NET Assemblies
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
code code behind file, examining (Car project), 965–966 Chapter 12 - Object Serialization and the .NET Remoting Layer code behind technique, 935,951,953 Chapter 13 - Building a Better Window (Introducing Windows Forms) elements, 442–444 Chapter 14 - A Better Painting Framework (GDI+) CodeBehind attribute, 965 Chapter 15 - Programming with Windows Forms Controls conditional compilation, 84–86 Chapter 16 - 28 The System.IO Namespace libraries, Chapter 17 Access with ADO.NET outlining Data via VS .NET, 69–70 Part regions, Five - Web Applications and specifying, 83–84 XML Web Services Chapter 18 ASP.NET Web Pages and Web Controls reuse,402 Part Four - Leveraging the .NET Libraries
Chapter 19 - ASP.NET Web Applications
collections.SeeSystem.Collections namespace
Chapter 20 - XML Web Services
Color types, 692–694
Index
ColorDialog List of Figures class, 693–694 List of Tables column names
altering (DataGrids), 998–1000 altering with OleDbDataAdapter type, 904–905 ColumnMapping property, 857 COM (Component Object Model) apartment structure, 463,479–480 binaries, classic, 395–397 callback interfaces and, 321–322 COM AppID, 431 COM+ programming, 471 deployment,396–397 fundamentals of, 5–6 IDispatch reference, 517 IDL (Interface Definition Language), 499–500 interface pointers and, 273
interface using IDL attributes, 520–521 C# and the .NET Platform, Second Edition lollipop notation, 276 versioning,396by Andrew Troelsen
ISBN:1590590554
Apress © 2003 (1200 pages)
Combine(), static, 329,332,339
This comprehensive text starts with a brief overview of the
ComboBoxes andC# ListBoxes, language 761–763 and then quickly moves to key technical and architectural issues for .NET developers.
comma-delimited lists, 50
command arguments, simulating with VS .NET, 96–97 Table of Contents Command Behavior, specifying Data Reader's, 895–896 C# and the .NET Platform, Second Edition
command line debugger (cordbg.exe). Seecordbg.exe (command line debugger)
Introduction
command line parameters, 95–96 Part One - Introducing C# andprocessing, the .NET Platform Chapter CommandBehavior.CloseConnection, 1 - The Philosophy of .NET 896 Chapter 2 - Building C# Applications CommandBuilder types, auto-generating SQL Commands with, 912–914 Part Two - The C# Programming Language
CommandText property, 892
Chapter 3
- C# Language Fundamentals
CommandType property, 892 Chapter 4 - Object-Oriented Programming with C# Chapter Common 5 Intermediate - Exceptions and Language Object Lifetime (CIL). SeeCIL(Common Intermediate Language) Chapter 6 language - Interfaces and Collections common runtime (CLR). SeeCLR (common language runtime) Chapter 7 - Callback Interfaces, Delegates, and Events
Common Language Specification (CLS). SeeCLS(Common Language Specification)
Chapter 8
- Advanced C# Type Construction Techniques
Common Runtimewith Execution Engine, 26 Part Three -Object Programming .NET Assemblies Chapter Common 9 Type - Understanding System (CTS). .NET See Assemblies CTS(Common Type System) Chapter 10 - Processes, AppDomains, Contexts, and Threads CommonSnappableTypes.dll, 530,532 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
comparable objects, building, 302–306 custom properties and sort types, 306 Chapter 12 - Object Serialization and the .NET Remoting Layer multiple sort orders, 304–305 Part Four - Leveraging the .NET Libraries
Chapter 13 - Building a Better Window (Introducing Windows Forms)
CompareTo() method, 302–303
Chapter 14 - A Better Painting Framework (GDI+)
comparison operators, overloading, 379–380 Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The compatibility textSystem.IO string, 403Namespace Chapter 17 - Data Access with ADO.NET
compilation cycle, ASP.NET, 958–961
Part Five - Web Applications and XML Web Services
compilers, .NET-aware, 12–13
Chapter 18 - ASP.NET Web Pages and Web Controls
compliance, CLS, 25Web Applications Chapter 19 - ASP.NET Chapter 20 - XML Web Services components IndexComponent class, 622 List of Component Figures Services utility, 471
defined, List of Tables 790 concurrency and thread synchronization, 475 conditional code compilation, 84–86 conditional operators, 138 configuration files machine-wide,445–446 and VS .NET, 428–429 configuration inheritance, 1057–1058 configuring a C# project, 64–65 connected layer, ADO.NET, 888–893 Access databases, connecting to, 891 core OLE DB providers, 889 database schema information, obtaining with, 891–892 defined, 844
OleDbConnection type members, 890 C# and the .NET Platform, Second Edition SQL commands, building with OleDbCommand, 892–893 by Andrew Troelsen
ConnectionStringApress property, 921–922 © 2003 (1200 pages)
ISBN:1590590554
console class This comprehensive text starts with a brief overview of the Console types, C# 824 language and then quickly moves to key technical and architectural issues for .NET developers. input and output with, 105–109 formatting textual output, 106–107 string formatting flags, 107–109
Table of Contents
const keyword, 200
C# and the .NET Platform, Second Edition
constant data, referencing across types, 134 Introduction Part One - Introducing C# and the .NET Platform constants, defining program, 132–134
Chapter 1
- The Philosophy of .NET construction techniques, advanced C# type, 355–392
Chapter 2 -–+ Building C# Applications += and operators, 385–386
Part C# Twoindexer - The C# Programming Language from VB .NET, 374–375
Chapter 3 - C# Language Fundamentals C# keywords summary, 367–369 Chapter - Object-Oriented Programming with C# Cars4 Indexer variation, 372–373 Chapter 5 - Exceptions and Object Lifetime checked keyword, 356–358 Chapter 6 - conversion Interfaces and Collections custom routines Chapter creating, 7 - Callback 387–390 Interfaces, Delegates, and Events
representation 391–392 Techniques Chapter internal 8 - Advanced C# Typeof, Construction indexer, building, Part custom Three - Programming with370–372 .NET Assemblies custom conversions, 386–387 Chapter 9 - type Understanding .NET Assemblies implicit 390–391 Chapter 10 -conversion Processes, routines, AppDomains, Contexts, and Threads overloadable valid,Binding, 385 and Attribute-Based Programming Chapter 11 - Type operators, Reflection, Late operators Part overloaded Four - Leveraging the .NET Libraries representation 380–383 Chapter internal 12 - Object Serializationof, and the .NET Remoting Layer
from overloaded-operator-challenged languages, 383–385 overloading operators, 375–380 Chapter 14 - A Better Painting Framework (GDI+) comparison operators, 379–380 Chapter 15 - Programming with Windows Forms Controls equality operators, 378–379 Chapter 16 - The System.IO Namespace sizeof keyword, 366–367 Chapter 17 - Data Access with ADO.NET type indexers, 373–374 Part Five - Web Applications and XML Web Services unchecked keyword, 358–359 Chapter 18 - ASP.NET Web 359 Pages and Web Controls underflow conditions, Chapter 19 -code, ASP.NET Web Applications unsafe 359–366 Chapter –> 20 operator, - XML Web Services 364 Index * and & parameters, 363 List of Figures field access via pointers, 364 List of Tables fixed keyword, 365–366 stackalloc keyword, 365 swap function, unsafe and safe, 363–364 unsafe keyword, 361–363 volatile keyword, 366 Chapter 13 - Building a Better Window (Introducing Windows Forms)
constructors calls, forwarding using this,183–184 default, 180 static,198–199 consumers of XML Web services, 1060–1061 contained controls, enumerating, 986–988 ContainerControl class, 637 containing and contained classes, 208 containment/delegation model
ArrayList type and, 318 the .NET Platform, Second Edition programming C# for,and 207–211 by Andrew Troelsen
Contains() method, 677–678,726 Apress © 2003 (1200 pages)
ISBN:1590590554
contexts This comprehensive text starts with a brief overview of the AppDomain, process C# language and thread and then relationship quickly moves to, 474–475 to key technical and architectural issues for .NET developers. attributes, 469–470 boundaries, defined, 468 context 0, 469 Tablecontext-agile of Contents and context-bound types, 469–470 C# and the .NET Platform, Second Edition context-bound objects, creating, 470–471 Introduction Context property, 1073 Part ContextMenu One - Introducing C#649–651 and the .NET Platform class, Chapter 1 The Philosophy of .NET project example, 471–473 Chapter 2
- Building C# Applications controls.See alsoWeb controls,ASP.NET;Windows Forms Controls adding to Forms, 744–747 Chapter 3 - C#996–997 Language Fundamentals AdRotator, Chapter 4 Object-Oriented Programming with C# assigning ToolTips to, 769–770 Chapter 5 Exceptions and Object Lifetime calendar, 995–996 Chapter 6 Interfaces and Collections CheckedListBox, 758–760 Chapter 7 - class Callback Interfaces, Delegates, and Events Control Chapter core 8 - properties Advanced C# of, Type 623 Construction Techniques Part Three example, - Programming 634–635 with .NET Assemblies styles, setting,.NET 624–626 Chapter Form 9 - Understanding Assemblies of, 624 Chapter members 10 - Processes, AppDomains, Contexts, and Threads basics, 635–636 Chapter painting 11 - Type Reflection, Late Binding, and Attribute-Based Programming properties and the methods, 633–634,777 Part Four - Leveraging .NET Libraries Control 627–631 and the .NET Remoting Layer Chapter 12 - events, Object Serialization class example, 627–628 Chapter control 13 - Building a Better Window (Introducing Windows Forms) Mouse events, responding to, 628–631 Chapter 14 - A Better Painting Framework (GDI+) MouseEventArgs type properties, 629 Chapter 15 - Programming with Windows Forms Controls control flow constructs, C#, 137–139 Chapter 16 - The System.IO Namespace Control$ControlCollection type, 745–747 Chapter 17 - Data Access with ADO.NET Controls property, 986 Part Five - Web Applications and XML Web Services data-centric (WebControls), 991,1004–1005 Chapter 18 - ASP.NET Web Pages and Web Controls defined, 789 Chapter 19 - ASP.NET and WebNumericUpDown, Applications DomainUpDown 774–776 Chapter 20 XML Web Services Panel,773 Indextoolbox, HTML, 940 List of Figures 770–772 TrackBar, List of Tables Up/Down, 774–776 Windows Forms Controls. SeeWindows Forms Controls Part Two - The C# Programming Language
conversions among related class types, 387 conversion operators, 389–390 conversion routines creating custom, 387–390 defining implicit, 390–391 internal representation of custom, 391–392 Convert type, 293 numerical,386–387 cookies,1047–1050 cookie data, reading incoming, 1049–1050 creating,1047–1049 coordinate systems, 687–692
default unit of measure, 688–689 and the .NET Platform, Second Edition point of origin,C# 690–692 by Andrew unit of measure, default,Troelsen 689–690
ISBN:1590590554
Apress © 2003 (1200 pages)
CoorSystem application, 691–692
This comprehensive text starts with a brief overview of the
cordbg.exe (command C# language line debugger), and then quickly 55–57 moves to key technical and architectural issues for .NET developers.
CreateText() method, 818,824
cross-language inheritance, 411–415 Table of Contents csc.exe (C# compiler) C# and the .NET Platform, with, Second Edition building applications 43–50 Introduction compiling multiple source files, 49–50 Part Oneconfiguring, - Introducing C# and the .NET Platform 44–45
Chapter output 1 - The Philosophy options, 46 of .NET Chapter referencing 2 - Buildingexternal C# Applications assemblies, 48–50 Part options, Two - The 54–55 C# Programming Language
response files, 50–52 Fundamentals Chapter 3 - C# Language Chapter 4 - Object-Oriented Programming with C# CSharpCalculator Chapter 5 - Exceptions and Object Lifetime applications, 15 Chapter 6 - Interfaces assembly, 17–18 and Collections Chapter 7 property, - Callback997 Interfaces, Delegates, and Events CssStyle Chapter 8
- Advanced C# Type Construction Techniques
CTS (Common Type System) class types, CTS, 19 Chapter 9 - Understanding .NET Assemblies defined, 7 Chapter 10 - Processes, AppDomains, Contexts, and Threads delegate types, 21 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming enumeration types, 21 Part Four - Leveraging the .NET Libraries interface types, 21 Chapter 12 - CTS Object Serialization and the .NET Remoting Layer intrinsic data types, 22–23 Chapter 13 Building a Better Window (Introducing Windows Forms) structure types, 20 Chapter - A Better22 Painting Framework (GDI+) type14 members, Part Three - Programming with .NET Assemblies
Chapter 15 - Programming with Windows Forms Controls
current objects, 183
Chapter 16 - The System.IO Namespace
CurrentThread(),342
Chapter 17 - Data Access with ADO.NET
custom exceptions, 243–247 Part Five application-level - Web Applications and XML Web Services Chapter - ASP.NET Web Pages and Web Controls custom18 attributes Chapter 19 - 523–524 ASP.NET Web Applications building, Chapter 20 - XML reflection andWeb lateServices binding example, 528–534 Index custom class methods, defining, 140–143 List of Figures accessibility keywords, 141 List of Tables method access modifiers, 141–143
custom collections, building, 315–318 custom conversion routines creating,387–390 internal representation of, 391–392 custom dialog boxes, building, 781–787 application example, 782–785 DialogResult property, 785 grabbing data from, 785–787 custom enumerations, 164 custom exceptions and VS .NET, 255–256 custom indexer, building, 370–372 custom properties and sort types, 306 custom serialization example, 552–554
custom snap-in consumer, building, 529–530Second Edition C# and the .NET Platform, custom structures, 170–171 by(un)boxing, Andrew Troelsen
ISBN:1590590554
Apress ©802–803 2003 (1200 pages) custom ToolBox bitmap, This comprehensive text starts with a brief overview of the custom types C# language and then quickly moves to key technical and consuming,1099–1100 architectural issues for .NET developers.
conversions,386–387 exposing,1098–1099 Web methods, exposing, 1096–1097 Tablefrom of Contents C# and the .NET Platform, Second Edition custom UserControl, building, 790–791 Introduction
custom validation, 1010–1012
Part One - Introducing C# and the .NET Platform
custom1version 440 Chapter - The policies, Philosophy of .NET custom2view state data, 1029 Chapter - Building C# Applications Part Two Web - The settings C# Programming Language custom with ,
1057
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
custom Windows Forms Controls, building, 789–790
, 1053–1054 Chapter 5 - Exceptions and Object Lifetime customizing serialization 549–554 Chapter 6 - Interfaces andprocess, Collections Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index D
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and DashStyle enumeration, 710 architectural issues for .NET developers.
data access with ADO.NET. SeeADO.NET, data access with Data Adapters
Tablebuilding of Contents at design time, 922–926 C# and theAdapter .NET Platform, SecondWizard, Edition 922–926 Data Configuration Introduction and design time connections, 926–927 Part using One - Introducing C# and the .NET Platform configured, 926
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
data binding and data-centric controls, 1004–1005
dataTwo caching 1038–1040 Part - The (example), C# Programming Language data-centric controls (WebControls), 991 Chapter 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# Data Providers Chapter 5 - Exceptions ADO.NET, 845–850and Object Lifetime Chapter IDataAdapter 6 - Interfaces and Collections interface, 848 Chapter IDataParameter 7 - Callback Interfaces, interface, Delegates, 846–847and Events
interface, Chapter IDataReader 8 - Advanced C# Type 848–850 Construction Techniques IDataRecord interface, 848–850 Part Three - Programming with .NET Assemblies interface, Chapter IDbCommand 9 - Understanding .NET 846–847 Assemblies IDbTransaction interfaces, 846 Chapter IDbConnection 10 - Processes, and AppDomains, Contexts, and Threads interface, 848 Chapter IDbDataAdapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming IDbDataParameter interface, 846–847 Part Four - Leveraging the .NET Libraries 887 Chapter selecting, 12 - Object Serialization and the .NET Remoting Layer SQL, 906–912 SqlDataAdapter, inserting records with, 907–910 Chapter 14 - A Better Painting Framework (GDI+) SqlDataAdapter, updating records with, 910–912 Chapter 15 - Programming with Windows Forms Controls System.Data.SQLTypes namespace, 907
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 16 - The System.IO Namespace
data types, CTS,with 22–23 Chapter 17 - intrinsic Data Access ADO.NET Part databases Five - Web Applications and XML Web Services
building test, 886 Chapter 18 - simple ASP.NET Web Pages and Web Controls editors, 74 Applications Chapter 19 - integrated, ASP.NET Web manipulation tools,Services 73–74 Chapter 20 - XML Web Indexschema information, 891–892 List DataColumn of Figures type (ADO.NET), 852–858
adding List of Tablesto DataTable, 855 auto-incrementing fields, 856–857 building a DataColumn, 854–855 configuring as primary key constraint, 855 DataColumnCollection type, 858 properties of, 853–854 XML data representation, configuring, 857–858 DataField attribute, 999 DataGrids, ADO.NET, 997–1005 column names, altering, 998–1000 data-centric controls and data binding, 1004–1005 in-place editing, 1001–1004 paging,1000–1001 DataRelation type, 879–883 properties of, 880
related tables navigation, 880–883
C# and the .NET Platform, Second Edition
DataRelationCollection, 874 by Andrew Troelsen
ISBN:1590590554
DataRow type, 858–861 Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the DataRow.GetChildRows() method, 882 C# language and then quickly moves to key technical and
DataRow.RowState property, issues 859–861 architectural for .NET developers. DataSets DataSet type, 874–879 Table of in-memory Contents DataSet, building, 876–879 C# and the .NET Platform, Second Edition members of, 875–876 Introduction at design time, 927–931 Part Onetyped - Introducing C#927–931 and the .NET Platform DataSets, Chapter untyped 1 - TheDataSets, Philosophydefined, of .NET 927 Chapter filling 2 multitabled, - Building C# 916–919 Applications Part filling Two - with The C# OleDbDataAdapter Programming Language type, 903–904 reading and writing XML-based, 883–885 Chapter 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# DataTables Chapter 5 -DataColumn Exceptions and Object Lifetime adding type to, 855 Chapter 6 - 863–871 Interfaces and Collections building, Chapter filters 7 - Callback and sortInterfaces, orders, 867–869 Delegates, and Events
deleting, 866–867 Chapter rows, 8 - Advanced C# Type Construction Techniques rows, updating, 869–871 Part Three - Programming with .NET Assemblies DataTable type, 836,844, 861–863 Chapter 9 - Understanding .NET Assemblies Chapter 10 type, - Processes, AppDomains, Contexts, and Threads DataView 871–873 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
DateTime type, 766–767
Part Four - Leveraging the .NET Libraries
DCOM (Distributed Component Object Model) clients, 1059–1060
Chapter 12 - Object Serialization and the .NET Remoting Layer
DDL (Data commands, 898Windows Forms) Chapter 13 - Definition Building a Language) Better Window (Introducing Chapter 14 - event, A Better Painting Framework (GDI+) Deactivate 641–642 Chapter 15 - Programming with Windows Forms Controls
debugger, command line (cordbg.exe). Seecordbg.exe (command line debugger)
Chapter 16 - The System.IO Namespace
debugging vs. running, 71 Part Five - Web Applications and XML Web Services system exceptions with VS .NET, 253–256 Chapter 18 - ASP.NET Web Pages and Web Controls and tracing ASP.NET pages, 1020 Chapter 17 - Data Access with ADO.NET
Chapter 19 - ASP.NET Web Applications
default 20 assignments variable scope, 102–104 Chapter - XML Web and Services default behaviors, overriding, 118–119 Index List of Figures default constructors, defined, 98–99 List of Tables
default contexts, 469
default input Button, 767 default lease characteristics, altering, 593–594 default leasing behavior, 590–592 default merge system (MDI applications), 666 default namespace of VS .NET, 175–176 default .NET Remoting architecture, 559 default parameter passing behavior, 148 default properties and events, defining, 802 default public interface of a type, 184–186 default remoting layers, extending, 560 default response file (csc.rsp), 51–52
default unit of measure, 688–689
C# and the .NET Platform, Second Edition
default.htm form by data, 946 Andrew Troelsen DefaultWsdlHelpGenerator.aspx, Apress © 2003 (12001066 pages)
ISBN:1590590554
comprehensive text starts with a brief overview of the delayed signing, This 434–435 C# language and then quickly moves to key technical and
delegate types, .NET architectural issues for .NET developers. asynchronous delegates, 341–347 callbacks for, 344–347 methods asynchronously, 343–344 Table of invoking Contents building (example), C# and the .NET Platform,333–341 Second Edition CarDelegate,334–337 Introduction as nested 334Platform Part Onedelegates - Introducing C# andtypes, the .NET delegation code, analyzing, Chapter 1 - The Philosophy of .NET 337–338 methods as callbacks, 339–341 Chapter instance 2 - Building C# Applications multicasting with Car.CarDelegate, Part Two - The C# Programming Language 338–339 example,329–332 Chapter 3 - C# Language Fundamentals multicasting with, 332 Chapter 4 - Object-Oriented Programming with C# System.MulticastDelegate, 328–329 Chapter 5 - Exceptions and Object Lifetime understanding, 325–328 Chapter 6
- Interfaces and Collections
delegates Chapter 7 - Callback Interfaces, Delegates, and Events
CTS types, 21 - Advanced C# Type Construction Techniques defined, 325 Part Three - Programming with .NET Assemblies defining in C#, 326–328 Chapter 9 - Understanding .NET Assemblies delegate keyword Chapter 10 - Processes, AppDomains, Contexts, and Threads to create delegates in C#, 326 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming for declaring a .NET delegate, 330 Part Four - Leveraging the .NET Libraries defined, 321 Chapter 12 - Object Serialization and the .NET Remoting Layer EventHandler,619 Chapter 13 - Building a Better Window (Introducing Windows Forms) multithreaded programming via, 476 Chapter 8
Chapter 14 - A Better Painting Framework (GDI+)
delegation code, analyzing, 337–338 Chapter 16 - The System.IO Namespace defined, 209
Chapter 15 - Programming with Windows Forms Controls Chapter 17 - Data Access with ADO.NET
Delete() Part Five -method Web Applications and XML Web Services DataTables,867 from FileSystem Info type, 808
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
DELETE statements, 848 Chapter 20 SQL - XML Web Services Index deleting records with OleDbCommand, 897–898 List of Figures deploying List of Tables .NET applications, 397
.NET Remoting projects, 566–567 descending values (font metrics), 697 Description property, documenting Web methods with, 1073–1074 description service, XML Web, 1063 deserialization process, 550 Deserialize() method, 545–546 design time connections and Data Adapters, 926–927 functionality,798 GUI, building, 792 destruction methods, building, 264–266 IDisposable interface, 264–265 using keyword, 265–266
dialog boxes, building custom, 781–787 C# and the .NET Platform, Second Edition application example, 782–785 by Andrew Troelsen DialogResult property, 785 © 2003 (1200 pages) grabbing dataApress from, 785–787
ISBN:1590590554
This comprehensive text starts with a brief overview of the
dictionary, defined, C#309 language and then quickly moves to key technical and architectural issues for .NET developers. Directory class, static members of, 812–813 DirectoryInfo and FileInfo types, 806–812 TableDirectoryInfo of Contents type creating subdirectories with, 811–812 C# and the .NET Platform, Second Edition enumerating files with, 810–811 Introduction working with, 808–809 Part One - Introducing C# and the .NET Platform DirectoryInfo.CreateSubdirectory() method, 811–812 Chapter 1 - The Philosophy of .NET FileAttributes enumeration, 809–810 Chapter 2 - Building C# Applications FileSystemInfo base class, 807–808 Part Two - The C# Programming Language
dirty windows 681Fundamentals Chapter 3 - C#(Paint), Language DISCO4(Discovery of Web Services), 1062–1063 Chapter - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime disconnected layer, ADO.NET, 844, 901–905 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
discovery service, XML Web, 1062–1063
dispatcher, defined, 559 Chapter 8 - Advanced C# Type Construction Techniques display names, defined, 512 Part Three - Programming with .NET Assemblies Chapter 9 - and Understanding Assemblies disposable finalizable .NET types, building, 268–269 Chapter 10 - Processes, AppDomains, Contexts, and Threads
Dispose() method creation of, 264–265 Part Four - Leveraging the .NET Libraries GDI+ and, 680 Chapter - Object Windows Serialization and the .NET Remoting Layer role12 in building Forms, 614–615
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 13 - Building a Better Window (Introducing Windows Forms)
distributed applications, building, 568–571 general assembly, 568 Chapter 15 - Programming with Windows Forms Controls server assembly, 569–570 Chapter 16 - The System.IO Namespace SimpleRemoteObjectClient.exe assembly, 570–571 Chapter 14 - A Better Painting Framework (GDI+)
Chapter 17 - Data Access with ADO.NET
Distributed .NET Programming in C# (Apress, 2002), 567,606
Part Five - Web Applications and XML Web Services
DLL hell, Chapter 18 396 - ASP.NET Web Pages and Web Controls Chapter 19and - ASP.NET Web Applications do/while while looping constructs, 136–137 Chapter 20 - XML Web Services
docking behavior, configuring, 780–781
Index
DockStyle values, 780
List of Figures
documentation support, VS .NET, 81 List of Tables DOM (Document Object Model), 944 Domain Name System (DNS), 935–936 DomainUnload event, 468 DomainUpDown control and NumericUpDown Control, 774–776 properties,775 Dotnetfx.exe package (Microsoft), 40 dragging mode (GDI+), 723–725 DraggingImages application, 727 Drawing utility types, 675–680 disposal of, 680 Point(F) type, 675–676 Rectangle(F) type, 677–678
Region class, 678–679 Size(F) types,C# 678and the .NET Platform, Second Edition by Andrew Troelsen
DrawString() method, 675 Apress © 2003 (1200 pages)
ISBN:1590590554
DrawXXXX() methods, 707 This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and dumping architectural issues for .NET developers. CIL instructions to file, 36–37 namespace information to file, 35–36 Dynamic Help Window, 74 Table of Contents C# and theinvocation, .NET Platform, Second Edition dynamic 517–520 Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index E
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the early binding, 517C# language and then quickly moves to key technical and architectural issues for .NET developers.
editing tools, XML-related, 72–73 EJB (Enterprise Java Beans), 1059–1060
Table of Contents
embedded resources, 739–740
C# and the .NET Platform, Second Edition
EmpType enumeration, 164 Introduction Part One - Introducing C# and the831 .NET Platform EnableRaisingEvents property,
Chapter 1
- The Philosophy of .NET EnableSession property, 1075–1077
Chapter 2
- Building C# Applications
EnableViewState property, 1029
Part Two - The C# Programming Language
encapsulation Chapter 3 - C#services, Language191–199 Fundamentals class 193–195 Chapter 4 properties, - Object-Oriented Programming with C# enforcing with accessors and mutators, Chapter 5 - Exceptions and Object Lifetime 192–193 fundamentals of, 187 Chapter 6 - Interfaces and Collections
internal- representation of C# properties, 196–197 Callback Interfaces, Delegates, and Events read-only and write-only properties, 197–198 Chapter 8 - Advanced C# Type Construction Techniques static properties, 198–199 Chapter 7
Part Three - Programming with .NET Assemblies
EndEdit() (DataTables), 870 Chapter 9 method - Understanding .NET Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads EndInvoke() method, 343–346 Chapter 11 - and TypeEndWrite() Reflection, methods, Late Binding, EndRead() 833and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
#endregion and #region tags, 83
Chapter 12 - Object Serialization and the .NET Remoting Layer
EngineState enumeration, for, 500–501 Windows Forms) Chapter 13 - Building a Betterviewing Window (Introducing Chapter 14 -Manager A Better Painting Framework Enterprise (SQL Server), 886 (GDI+) Chapter 15 - Programming with Windows Forms Controls enumerating Chapter 16members, - The System.IO Namespace class 513–514 Chapter 17 - Data Access986–988 with ADO.NET contained controls, Part method Five - Web Applications and XML Web Services parameters, 514–515
Chapter 18 - processes, ASP.NET Web Pages and Web Controls running 456–457 Chapter 19in- referenced ASP.NET Web Applications types assemblies, 513 Chapter 20 - XML WebCTS, Services enumeration types, 21 Index
enumerations, custom, 164
List of Figures
enumerators, building custom, 293–297 List of Tables Enum.Format() method, 167 equality operators, 160,378–379 Equals(),119–120,378 error events, 979–981 error output, customizing with , 1053–1054 ErrorBlinkStyle properties, 778 ErrorProvider type, 776–778 errors, bugs and exceptions defined, 231–232 escape characters and verbatim strings,161–162 Essential Guide to Managed Extensions for C++ (Apress, 2002), 413–414 events event keyword, 347
event sinks, multiple, 349,352 C# and the .NET Platform, Second Edition EventArgs parameter, 619 ISBN:1590590554 Andrew 619 Troelsen EventHandlerby delegate, Apress © 2003 (1200 pages) exception event handler (Global.asax), 1031–1032 text starts with a brief overview of the understandingThis andcomprehensive using, 347–354 C# language and then quickly moves to key technical and events under the hood, 348–350 architectural issues for .NET developers. incoming events, 351–353 objects as event sinks, 353–354 Table exceptions, of Contents 231–256
.NET handling, 232–233 C# and theexception .NET Platform, Second Edition application-level Introduction custom, Part Onebuilding - Introducing C#243–247 and the .NET Platform exceptions, Chapter and 1 -system-level The Philosophy of .NET 252 catching exceptions, 236–240 Chapter 2 - Building C# Applications 239–240 Part TwoHelpLink - The C#property, Programming Language property, 239 Chapter StackTrace 3 - C# Language Fundamentals
TargetSite property, 238–239 - Object-Oriented Programming with C# CLR system-level exceptions, 240–242 Chapter 5 - Exceptions and Object Lifetime debugging system exceptions with VS .NET, 253–256 Chapter 6 - Interfaces and Collections errors, bugs and exceptions defined, 231–232 Chapter 7 - Callback Interfaces, Delegates, and Events exception event handler (Global.asax), 1031–1032 Chapter 8 - Advanced C# Type Construction Techniques finally blocks, 250 Part Three - Programming with .NET Assemblies generic exceptions, throwing, 235–236 Chapter 9 - Understanding .NET Assemblies handling multiple, 247–250 Chapter generic 10 - Processes, AppDomains, catch statements, 249Contexts, and Threads Chapter rethrowing 11 - Type Reflection, Late Binding, and Attribute-Based Programming exceptions, 249–250 Part last Fourchance - Leveraging the .NET Libraries exceptions, 251 Chapter 12 - Object Serialization and234–235 the .NET Remoting Layer System.Exception base class, Chapter 4
Chapter 13 - Building a Better Window (Introducing Windows Forms)
explicit and implicit keywords, 387–389
Chapter 14 - A Better Painting Framework (GDI+)
explicit casting, 223,277–278
Chapter 15 - Programming with Windows Forms Controls
explicit 16 conversion operators, 389–390 Chapter - The System.IO Namespace Chapter - Data implementation, Access with ADO.NET explicit 17 interface 281–284 Part Five - Web Applications and XML Web Services
explicit load request (assemblies), 429
Chapter 18 - ASP.NET Web Pages and Web Controls
ExtendedProperties property, 874–875
Chapter 19 - ASP.NET Web Applications
extendible 529,532–534 Chapter 20 -applications, XML Web Services Index extending default remoting layers, 560 List of Figures Extends metadata tokens, 501 List of Tables
external assemblies referencing, 32,48–49 referencing multiple (csc.exe), 50 referencing via VS .NET, 67–68 external resources, bundling, 732–733
Index F
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and feature-rich controls (WebForms), 995–997 architectural issues for .NET developers.
fields defined, 191 Tablefield of Contents access via pointers, 364 Field tokens, 501 Second Edition C# and the#n .NET Platform, FieldCount property, 895 Introduction 199–201C# and the .NET Platform Part read-only, One - Introducing Chapter 1 dialog - The Philosophy of .NET File Save box, 838–839 Chapter 2
Building C# Applications FileAccess- enumeration values, 816
Part Two - The C# Programming Language
FileAttributes enumeration, 809–810 - C# Language Fundamentals
Chapter 3
FileInfo4and DirectoryInfo types, 806–810with C# Chapter - Object-Oriented Programming DirectoryInfo type, 808–809 Chapter 5 - Exceptions and Object Lifetime FileAttributes enumeration, 809–810 Chapter 6 - Interfaces and Collections FileSystemInfo class, 807–808 Chapter 7 - Callbackbase Interfaces, Delegates, and Events FileInfo8class, 814–818 Chapter - Advanced C# Type Construction Techniques method, Part FileInfo.Create() Three - Programming with 815 .NET Assemblies Open() 815–817 Chapter 9 -method, Understanding .NET Assemblies OpenRead() and OpenWrite() members, Chapter 10 - Processes, AppDomains, Contexts, 817 and Threads OpenText(), AppendText() 817–818 Chapter 11 - TypeCreateText(), Reflection, Late Binding, andmembers, Attribute-Based Programming Part Four - Leveraging the .NET Libraries FileMode enumeration values, 816
Chapter 12 - Object Serialization File.OpenText() method, 826 and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
FileShare enumeration values, 817
Chapter 14 - A Better Painting Framework (GDI+)
FileStreams, 820 Chapter 15 - Programming with Windows Forms Controls Chapter FileStream.Write() 16 - The System.IO method,Namespace 822 Chapter 17 - Data Access with ADO.NET FileSystemEventHandler delegate, 831 Part Five - Web Applications and XML Web Services
FileSystemInfo base class, 807–808
Chapter 18 - ASP.NET Web Pages and Web Controls
FileSystemWatcher 831–833 Chapter 19 - ASP.NET class, Web Applications Chapter Fill() method, 20 - XML 848 Web Services Index filling DataSets with OleDbDataAdapter type, 903–904 List of Figures
FillPath() method, 729
List of Tables
FillXXXX() methods, 707,713 filters and sort orders (DataTables), 867–869 finalizable and disposable types, building, 268–269 finalization reachable tables (freachable), 263 Finalize() method, 260–262 finalizing types, 260–263 finally blocks, 250 firing events, 348 fixed keyword, pinning types via, 365–366 fonts application, building, 698–703 installed fonts, enumerating, 701–703 System.Drawing.Text,701–703
font dialog box, 703 C# and the .NET Platform, Second Edition FontDialog class, 703–704 ISBN:1590590554 by members, Andrew Troelsen FontFamily type 696 Apress © 2003 (1200 pages) FontFamily.Name property, 701 This comprehensive text starts with a brief overview of the FontStyle enumeration, 695 C# language and then quickly moves to key technical and manipulating,695–698 architectural issues for .NET developers. font families, 696–697 font metrics, 697–698 Table for loop, of Contents 135 C# and the .NET foreach/in loop,Platform, 135–136Second Edition Introduction
format characters, XML, 80
Part One - Introducing C# and the .NET Platform
formatters Chapter 1 - The Philosophy of .NET .NET, Chapter 2 559 - Building C# Applications
Part serialization, Two - The C#544–545 Programming Language
formatting string, 107–109 Chapter 3 -flags, C# Language Fundamentals Chapter 4 -textual Object-Oriented Programming with C# formatting output, 106–107 Chapter 5
- Exceptions and Object Lifetime
Forms Interfaces and Collections adding -controls with VS .NET, 747–749 Chapter 7 Callback Interfaces, Delegates, and Events Form class, 637–640 Chapter example, 8 - Advanced C# Type Construction Techniques 639–640 Part Three Programming with .NET Assemblies key- methods of, 638–639 Chapter properties 9 - Understanding of, 638 .NET Assemblies Chapter select 10 - Processes, Contexts, and Threads events of,AppDomains, 639 Chapter 11data - Type Reflection, Late Binding, and Attribute-Based Programming Form Part Four - Leveraging the .NET access to incoming, 975Libraries Chapter submitting, 12 - Object947 Serialization and the .NET Remoting Layer Form Chapter 13inheritance, - Building a 787–789 Better Window (Introducing Windows Forms) Form level events, handling with VS .NET, Chapter 14 - A Better Painting Framework (GDI+)643–644 Form property (HttpRequest), 975 Chapter 15 - Programming with Windows Forms Controls FormBorderStyle properties, 779 Chapter 16 - The System.IO Namespace HTML Form development, 940–943 Chapter 17 - Data Access with ADO.NET 607–608 and XML Web Services Part Web Five -Forms, Web Applications Windows. See Windows Forms;Windows Forms Controls Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 6
freachable reachable table), 263 Chapter 19 - (finalization ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index G
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and GAC (Global Assembly Cache) architectural issues for .NET developers.
internal composition of, 440–442 loading items from, 516–517 assemblies and, 430–431,436 Tableshared of Contents Garage class C# and the .NETdefinition, Platform, 335–336 Second Edition Introduction garbage collection (GC), 257–272
Part basics One - Introducing of, 259–260C# and the .NET Platform
Chapter - Thekeyword, Philosophy of .NET CIL 1of new 257–259 Chapter 2 - Building C# Applications destruction method, building, 264–266 Part TwoIDisposable - The C# Programming Language interface, 264–265
Chapter using 3 - C# keyword, Language reusing, Fundamentals 265–266
finalization process, 263 Programming with C# Chapter 4 - Object-Oriented finalizing types, 260–263 Chapter 5 - Exceptions and Object Lifetime GC.Collect(), 270 and Collections Chapter 6 - Interfaces GC.GetGeneration(), 270 Delegates, and Events Chapter 7 - Callback Interfaces, object 257C# Type Construction Techniques Chapter 8 lifetime, - Advanced of, 267 with .NET Assemblies Part optimizations Three - Programming
System.GC types, 267–272 - Understanding .NET Assemblies finalizable and disposable types, building, 268–269 Chapter 10 - Processes, AppDomains, Contexts, and Threads forcing garbage collections, 270 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming generations, programmatically interacting with, 270–272 Chapter 9
Part Four - Leveraging the .NET Libraries
GDI+ (Graphics Device Interface), Chapter 12 - Object Serialization and 671–742 the .NET Remoting Layer .NET 732–733 Chapter 13resource - Buildingformat, a Better Window (Introducing Windows Forms)
active colors, establishing, 692–694 color type members, 693 Chapter 15 - Programming with Windows Forms Controls ColorDialog class, 693–694 Chapter 16 - The System.IO Namespace coordinate systems, 687–692 Chapter 17 - Data Access with ADO.NET point of origin, 690–692 Part Five - Web Applications and XML Web Services unit of measure, 688–690 Chapter 18 - ASP.NET Web Pages and Web Controls dragging,723–725 Chapter - ASP.NETbuilding, Web Applications font19 application, 698–703 Chapter installed 20 - XMLfonts, Web Services enumerating, 701–703 Index System.Drawing.Text,701–703 List of Figures class, 703–704 FontDialog List of Tables fonts, manipulating, 695–698 families,696–697 metrics,697–698 GDI+ Programming in C# and VB .NET (Apress, 2002), 742 GdiPlusApp,1016 Graphics class, 685–686 hit testing, 723,727–731 images, rendering, 720–723 namespaces overview, 671–772 paint sessions, 680–684 client area, invalidating, 682 obtaining graphics type from Windows Forms controls, 683–684 obtaining graphics type outside paint handler, 682–683 PictureBox control, 723–727 resource configuration with VS .NET, 739–742 ResourceManagers,737–739 Chapter 14 - A Better Painting Framework (GDI+)
ResourceWriters,737 C# and the .NET Platform, Second Edition System.Drawing namespace, 673–675 ISBN:1590590554 by Andrew Troelsen System.Drawing utility types, 675–679 Apress © 2003 (1200 pages) disposal of, 680 This675–676 comprehensive text starts with a brief overview of the Point(F) type, C# language and then quickly moves to key technical and Rectangle(F) type, 677–678 architectural issues for .NET developers. Region class, 678–679 Size(F) types, 678 System.Drawing.Drawing2D namespace overview, 705–720 Table of Contents gradient brushes, 719–720 C# and the .NET Platform, Second Edition hatch style brushes, 715–717 Introduction pen caps, 711–713 Part One - Introducing C# and the .NET Platform pen objects, 707–711 Chapter 1 - The Philosophy of .NET rendering quality, 706–707 Chapter 2 - Building C# Applications solid brushes, 713–715 Part Two - The C# Programming Language textured brushes, 717–718 Chapter 3 - C# Language Fundamentals System.Resources namespace, 733–737 Chapter *.resources 4 - Object-Oriented Programming with C# 736–737 file, binding into .NET assembly, Chapter *.resources 5 - Exceptions and Object Lifetime file, building, 735–736 Chapter *.resx 6 - Interfaces andand Collections file, creating reading, 733–735 Chapter 7 Callback Interfaces, on Web server, 1016–1019 Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques general assembly, building, 568
Part Three - Programming with .NET Assemblies
generations, object - Understanding .NET Assemblies defined, 267 Chapter 10 - Processes, AppDomains, Contexts, and Threads programmatically interacting with, 270–272 Chapter 9
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
generic statements, 249Libraries Part Four catch - Leveraging the .NET Chapter - Object Serialization and the .NET Remoting Layer generic12 class types, 789 Chapter - Building throwing, a Better Window (Introducing Windows Forms) generic13 exceptions, 235–236 Chapter 14 - A Better Painting Framework (GDI+)
GET and POST methods, 947,949–950
Chapter 15 - Programming with Windows Forms Controls
get_ and methods, 196–197 Chapter 16 set_ - The System.IO Namespace Chapter GET messages, 17 - Data HTTP, Access with 1087ADO.NET Part Five - Web method, Applications GetBoolean() 895and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
GetCommandLineArgs(),96
Chapter 19 - ASP.NET Web Applications
GetDateTime() 969 Chapter 20 - XMLmethod, Web Services Index GetFiles() method, 810 List of Figures GetHashCode(), overriding, 120–122 List of Tables
GetInterfaceMap() method, 509 GetObjectData() method, 550
GetOleDbSchemaTable() method, 891–892 GetParentRows() method, 882 GetStringBuilder() method, 826 GetStyle() method, 624 GetTheData() method, 957 GetType() method, 505–506 GetTypeCode() method, 292–293 Global.asax file, 1030–1032 exception event handler, 1031–1032 HttpApplication base class, 1032 gradient brushes, 719–720
graphics C# and the .NET Platform, Second Edition Graphics class ISBN:1590590554 by Andrew Troelsen drawing members of, 707–708 Apress © 2003 (1200 pages) fundamentals of, 685–686 This comprehensive text starts with a brief overview of the graphics type C# language and then quickly moves to key technical and obtaining from Windows Forms 683–684 architectural issues forcontrols, .NET developers. obtaining outside paint handler, 682–683 Graphics.DrawString() method, 695 method, 682–683 TableGraphics.FromHwnd() of Contents Graphics.PageUnit property, 690 C# and the .NET Platform, Second Edition GraphicsPath class, 729–730 Introduction enumeration, 689 Part GraphicsUnit One - Introducing C# and the .NET Platform Chapter 1 - The of .NET GroupBoxes andPhilosophy RadioButtons, 756–760 Chapter 2 - Building Applications GUI (Graphical UserC# Interface) Part of Two - Thepages, C# Programming Language *.aspx 963
Chapter 3 - C# Language namespaces, 607–608Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index H
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and has-a and is-a relationships, 187–189,201–203,207–210 architectural issues for .NET developers.
hatch style brushes, 715–717 HatchStyle enumeration, 715–716
Table of Contents
HeaderText attribute, 999
C# and the .NET Platform, Second Edition
HelloWS WSDL document, viewing, 1082–1084 Introduction Part - Introducing C# 74–76 and the .NET Platform helpOne system, integrated,
Chapter 1
- The Philosophy of .NET HelpLink property, 239–240
Chapter 2
- Building C# Applications
hierarchies building interface, 285–288 Chapter 3 - C# Language Fundamentals System.Collections interfaces, 307
Part Two - The C# Programming Language
Chapter 4
- Object-Oriented Programming with C#
hit testing, 727–731 Chapter 5 -723, Exceptions and Object Lifetime Chapter hosting6remote - Interfaces objects, and 597–598 Collections Chapter 7 - Callback Interfaces, Delegates, and Events HTML (Hypertext Markup Language) Chapter 8 - Advanced C# Type Techniques capturing widget events withConstruction VS .NET, 945 Part content, Three - Programming emitting, 977with .NET Assemblies
Chapter 9 - 1014–1016 Understanding .NET Assemblies controls, Chapter 10 - toolbox, Processes, AppDomains, Contexts, and Threads controls 940 Chapter document 11 - Type structure, Reflection, 939–940 Late Binding, and Attribute-Based Programming Part form Four -development, Leveraging the 940–943 .NET Libraries
GUI12 types, 941 Serialization and the .NET Remoting Layer Chapter - Object HTML-based user interface, building, 941–943Windows Forms) Chapter 13 - Building a Better Window (Introducing tables, Chapter 14 -building, A Better994–995 Painting Framework (GDI+) Chapter 15 - Programming Windows Forms Controls HTTP (Hypertext Transferwith Protocol) Chapter channel, 16 - The defined, System.IO 558 Namespace
fundamentals of, 935–936 Chapter 17 - Data Access with ADO.NET POST messages, 1087 Part GET Five -and WebHTTP Applications and XML Web Services HttpApplication Chapter 18 - ASP.NETbase Webclass, Pages1032 and Web Controls HttpApplication Chapter 19 - ASP.NETtype, Web1050 Applications HttpApplicationState type, 1033–1034,1037–1038 Chapter 20 - XML Web Services IndexHttpContext type, 1073
HttpRequest type members, 972 HttpRequest.Browser property, 944 List of Tables HttpResponse type properties and methods, 976 HttpServerUtility type, 1073 HttpServerUtility.ClearError(), 980–981 HttpServerUtility.GetLastError(), 980 HttpSessionState members, 1045–1046 HttpSessionState type, 1033 requests, interacting with incoming, 971–975 form data access, 975 HttpRequest type members, 972 obtaining browser statistics, 973 server variables, access to, 974 responses, interacting with outgoing, 975–978 HTML content, emitting, 977 HttpResponse type properties and methods, 976 redirecting users, 977–978 List of Figures
hyperthreading, 453
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index I
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and IAsyncResult interface, 1093 architectural issues for .NET developers.
IChannel interface, 558,572–573 ICloneable interface, 297–302
Table of Contents
ICollection interface, 307,308
C# and the .NET Platform, Second Edition
IComparable interface, 302–306 Introduction Part One - Introducing and the .NET Platform IComparer interface, C# 304–307
Chapter 1
- The Philosophy of .NET IComponent interface, 622
Chapter 2
- Building C# Applications
IConvertible interface, 290–293 IConvertible.GetTypeCode(),292–293 Chapter 3 - C# Language Fundamentals IConvertible.ToXXXX() members, 291–292 Chapter 4 - Object-Oriented Programming with C# System.Convert type, 293 Part Two - The C# Programming Language
Chapter 5
- Exceptions and Object Lifetime
IDataAdapter interface, 848 Chapter 6 - Interfaces and Collections IDataParameter interface, 846–847 Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8 - Advanced C# Type IDataParameterCollection, 847Construction Techniques Part Three - Programming with .NET Assemblies
IDataReader interface, 848–850
Chapter 9
- Understanding .NET Assemblies
IDataRecord interface,AppDomains, 848–850 Chapter 10 - Processes, Contexts, and Threads IDbCommand interface, 846–847 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries IDbConnection and IDbTransaction interfaces,
846
Chapter 12 - Object Serialization and the .NET Remoting Layer
IDbDataAdapter interface, 848
Chapter 13 - Building a Better Window (Introducing Windows Forms)
IDbDataParameter 846–847 (GDI+) Chapter 14 - A Betterinterface, Painting Framework identity15 of -private assemblies, Chapter Programming with 426 Windows Forms Controls Chapter 16 - The System.IO Namespace IDEs (Integrated Development Environments), building .NET applications with, 89–90 Chapter 17 - Data Access with ADO.NET
IDictionary interface, 307–309
Part Five - Web Applications and XML Web Services
IDictionaryEnumerator interface, 309Web Controls Chapter 18 - ASP.NET Web Pages and IDispatch 517 Chapter 19 reference - ASP.NET (COM), Web Applications Chapter 20 - XML Web Services IDisposable interface, 264–265 Index
IDL (Interface Definition Language), 16–17,499–500,520–521
List of Figures
IDraw and IDraw3D, 284
List of Tables
IEnumerable and IEnumerator interfaces, 293–297,307,1005 if/else statements, 137–138 IFormatProvider,292 IFormatter and IRemotingFormatter interfaces, 544 IHashCodeProvider interface, 307,309 IIS (Internet Information Server) basics,936–937 hosting remote objects with, 602–603 virtual directories, 938,1066 ildasm.exe assembly metadata, viewing, 37–38 dumping CIL instructions to file, 36–37 dumping namespace info to file, 35–36
tree view icons, 33–35
C# and the .NET Platform, Second Edition
ILease interface, by 591 Andrew Troelsen IList interface, 307, 309–310 Apress © 2003 (1200 pages)
ISBN:1590590554
This (ToolBars), comprehensive text starts with a brief overview of the ImageIndex property 665–666 C# language and then quickly moves to key technical and
images architectural issues for .NET developers. creating,791 hit testing nonrectangular, 729–731 720–723 Tablerendering, of Contents C# and the .NET Platform, IMessage interface, 557 Second Edition Introduction
IMessageFilter interface, 620
Part One - Introducing C# and the .NET Platform
Implement Wizard, Chapter 1 - Interface The Philosophy of 289–290I .NET implicit 2conversion 390–391 Chapter - Buildingroutines, C# Applications Part Two load - Therequest C# Programming Language implicit (assemblies), 429
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
directive, 955–956
Imports5keyword (VB .NET), 410 Lifetime Chapter - Exceptions and Object in-memory 876–879 Chapter 6 - DataSet, Interfacesbuilding, and Collections Chapter - Callback Interfaces, Delegates, and Events in-place7 editing (DataGrids), 1001–1004 Chapter 8
- Advanced C# Type Construction Techniques
incoming events, listening to, 351–353
Part Three - Programming with .NET Assemblies
indexers Chapter 9 - Understanding .NET Assemblies
building custom, 370–373 C# indexer from VB .NET, 374–375 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Cars indexer variation, 372–373 Part Four - Leveraging the .NET Libraries type indexers, 373–374 Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 12 - Object Serialization and the .NET Remoting Layer
informational text string, 403Window (Introducing Windows Forms) Chapter 13 - Building a Better Chapter inheritance 14 - A Better Painting Framework (GDI+)
classical, 188 Chapter 15 - Programming with Windows Forms Controls configuration, 1057–1058 Chapter 16 - The System.IO Namespace cross-language, 411–415 Chapter 17 - Data Access with ADO.NET Part Form, Five - 787–789 Web Applications and XML Web Services
Inheritance PickerWeb (Wizard), Chapter 18 - ASP.NET Pages 788 and Web Controls Inherits Chapter 19 - attribute, ASP.NET 968 Web Applications
is-a and has-a relationships, 187–189 preventing,205–207 Index support, C#, 201–205 List of Figures base class creation, 203–204 List of Tables multiple base classes, 204 Chapter 20 - XML Web Services
Init events, ASP.NET, 978–979 initialization syntax, variable, 104–105 InitializeComponent(), 614–615 INSERT SQL statements, 848 inserting records with OleDbCommand, 897–898 with SqlDataAdapter, 907–910 instance level CTS members, defined, 22 instance methods as callbacks, 339–341 integrated database editors, 74 integrated help system, 74–76 integrated object browser, 73
interface-based event protocol, 324
C# and the .NET Platform, Second Edition
Interface Definition (IDL). SeeIDL(Interface Definition Language) ISBN:1590590554 by Language Andrew Troelsen Apress © 2003 (1200 pages) interface keyword, 273,276–277 This comprehensive text starts with a brief overview of the interfaces.See also interfaces and collections C# language and then quickly moves to key technical and as parameters, 280–281,284–285 architectural issues for .NET developers. callback,321–325 cloneable objects, building, 297–302 Tablecomparable of Contentsobjects, building, 302–306 custom and sort types, 306 C# and the .NETproperties Platform, Second Edition multiple sort orders, 304–305 Introduction 21 Part CTS One -types, Introducing C# and the .NET Platform custom collections, building, 315–318 Chapter 1 - The Philosophy of .NET defining with C#, 273–277 Chapter 2 - Building C# Applications abstract base classes vs. interfaces, 276–277 Part Two - The C# Programming Language implementing with C#, 274–276 Chapter 3 - C# Language Fundamentals enumerators, building custom, 293–297 Chapter 4 - Object-Oriented Programming with C# explicit interface implementation, 281–284 Chapter 5 - Exceptions and Object Lifetime hierarchies, building, 285–288 Chapter 6 - Interfaces Collections HTML-based user, and building, 941–943 Chapter 7 Callback Interfaces, Delegates, and Events IAsyncResult,1093 Chapter 8 - Advanced C# Type Construction Techniques IChannel, 558 Part IChannel Three - Programming with .NET Assemblies definition, 572–573 Chapter 9 - Understanding .NET Assemblies IComponent, 622 Chapter 10 - Processes, AppDomains, IConvertible interface, 290–293 Contexts, and Threads Chapter IConvertible.GetTypeCode(), 11 - Type Reflection, Late Binding, 292–293 and Attribute-Based Programming Part Four IConvertible.ToXXXX() - Leveraging the .NET Libraries members, 291–292 type, 293 Chapter System.Convert 12 - Object Serialization and the .NET Remoting Layer IDataAdapter, 848a Better Window (Introducing Windows Forms) Chapter 13 - Building IDataParameter, Chapter 14 - A Better 846–847 Painting Framework (GDI+) IDataReader, 848–850with Windows Forms Controls Chapter 15 - Programming IDataRecord, 848–850 Namespace Chapter 16 - The System.IO IDbCommand, 846–847 Chapter 17 - Data Access with ADO.NET IDbConnection and IDbTransaction, 846 Part Five - Web Applications and XML Web Services IDbDataAdapter,848 Chapter 18 - ASP.NET Web Pages and Web Controls IDbDataParameter,846–847 Chapter 19 - ASP.NET Web Applications IDisposable, 264–265 Chapter 20 - XML Web Services IEnumerable, 1005 Index ILease,591 List of Figures 557 IMessage, List of Tables IMessageFilter,620 implementing with VS .NET, 288–290 invoking interface members at object level, 277–279 explicit casting, 277–278 is keyword, 279 as keyword, 278 ISerializable, 550–551 ISite, 622 ISponsor,596 multiple base interfaces, 287–288 shapes hierarchy, 279–281 System.Collections interfaces, 306–310 System.ComponentModel.IComponent, 790 System.Data.IDbTransaction, 846
interfaces and collections, 273–306
Interlocked type, 492–493
C# and the .NET Platform, Second Edition
internal and public types, 184–186 by Andrew Troelsen
ISBN:1590590554
internal keyword,Apress 185 © 2003 (1200 pages) This comprehensive text starts with a brief overview of the intrinsic C# operators, 381–383 C# language and then quickly moves to key technical and
intrinsic CTS dataarchitectural types, 22–23 issues for .NET developers. invocations asynchronous,1093–1094 Tablesynchronous, of Contents 1092–1093 C# and the .NET Platform, Second Edition
IPointy interface, 273–274,279,282,284–285
Introduction
is-aOne and-has-a relationships, 187–189, 201–203,207–210,222 Part Introducing C# and the .NET Platform Chapter is keyword, 1 - 223–224, The Philosophy 279 of .NET Chapter 2 - Building C# Applications is operator, 140 Part Two - The C# Programming Language
ISerializable interface, 550–551
Chapter 3
- C# Language Fundamentals
ISite interface, 622 Chapter 4 - Object-Oriented Programming with C# Chapter ISponsor 5 interface, - Exceptions 596and Object Lifetime Chapter 6 - property, Interfaces981–982 and Collections IsPostBack Chapter 7
- Callback Interfaces, Delegates, and Events
iteration constructs, C#, 134–137 Chapter 8 - Advanced C# Type Construction Techniques foreach/in loop, 135–136 Part Three - Programming with .NET Assemblies for loop, 135 Chapter 9 - Understanding .NET Assemblies while and do/while looping constructs, 136–137
Chapter 10 - Processes, AppDomains, Contexts, and Threads
IUnknown interface, 396
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index J
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and jagged arrays, 157 architectural issues for .NET developers.
Java/J2EE programming, 4–5 Java Virtual Machine (JVM), 25
Table of Contents
JavaScript classic ASP and, 950 Introduction for client-side code, 944–945 Part One - Introducing C# and the .NET Platform Http requests and, 1010 C# and the .NET Platform, Second Edition
Chapter 1
- The Philosophy of .NET
JIT (just-in-time) compiler. Seejitter Chapter 2 - Building C# Applications Part jitterTwo (just-in-time - The C# Programming compiler), 18 Language
Chapter - C# Language409, Fundamentals JScript 3.NET language, 944 Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index K
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the language and then quickly moves to key technical and key cryptography,C# public/private, 431 architectural issues for .NET developers.
Keyboard events, 631–633 KeyEventArgs type, 619
Table of Contents
KeyUp event, 631
C# and the .NET Platform, Second Edition
keywords, summary of C#, 367–369 Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index L
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and last chance exceptions, 251 architectural issues for .NET developers.
late binding dynamic invocation, 517–520 Tablereflection of Contents and custom attributes (example), 528–534 technique, 189 C# and the .NET Platform, Second Edition Introduction LayoutMdi() method, 667 Part One - Introducing C# and the .NET Platform
leading values (font metrics), 698
Chapter 1
- The Philosophy of .NET
leasing2 Chapter
- Building C# Applications
behavior, 590–592 Language Part default Two - The C# Programming
lease adjustment - C# Language Fundamentals client-side,595 Chapter 4 - Object-Oriented Programming with C# server-side,594–595 Chapter 5 - Exceptions and Object Lifetime lease characteristics, altering default, 593–594 Chapter 3
Chapter 6
- Interfaces and Collections life-cycle WindowsInterfaces, Form type, 640–643and Events Chapter 7 of - Callback Delegates,
Form lifetime events, 640–641 - Advanced C# Type Construction Techniques Form lifetime example, 642–643 Part Three - Programming with .NET Assemblies Chapter 8
line numbers, altering, 87–88 Chapter 9 - Understanding .NET Assemblies Chapter 10 - Processes,type, AppDomains, LinearGradientBrush 719–720Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
LineCap enumeration, 711–712
Part Four - Leveraging the .NET Libraries
ListBox controls, 992
Chapter 12 - Object Serialization and the .NET Remoting Layer
ListBoxes ComboBoxes, 761–763 Chapter 13 -and Building a Better Window (Introducing Windows Forms) Chapter - A Better Painting Framework (GDI+) listener14 (server) applications, 567 Chapter 15 - Programming with Windows Forms Controls
literals, string, 503–504
Chapter 16 - The System.IO Namespace
Load events, 641–642,978–979
Chapter 17 - Data Access with ADO.NET
LoadFrom() method, 513 and XML Web Services Part Five - Web Applications Chapter ASP.NET methods, Web Pages1037, and Web Lock() 18 and- Unlock() 1043Controls Chapter 19 - ASP.NET Web Applications
lock keyword, 490–492,492
Chapter 20 - XML Web Services
logical and physical views, 401–402
Index
loops List of Figures for, 135 List of Tables foreach/in,135–136 while and do/while looping constructs, 136–137
Index M
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and machine-wide configuration file, 445–446 architectural issues for .NET developers.
machine.config file, 445 Main() method
Tablevariations of Contents on, 94–95 C# and the .NET Platform, Second Edition
Main window, building (Windows Forms), 610–612
Introduction
managed code, defined, 9 the .NET Platform Part One - Introducing C# and Chapter 1 heaps, - The Philosophy managed 257–259 of .NET Chapter 2 Building managed providers.C# SeeApplications Data Providers Part Two - The C# Programming Language
manifests - C# Language Fundamentals assembly,397,400,415 Chapter 4 - Object-Oriented Programming with C# defined, 12 Chapter 5 - Exceptions and Object Lifetime manifest CIL tokens, 417 Chapter 3
Chapter 6
- Interfaces and Collections
MappingType enumeration values, 857 - Callback Interfaces, Delegates, and Events MarshalByRefObject, Chapter 8 - Advanced 622 C# Type Construction Techniques Chapter 7
Part Three - Programming .NET Assemblies marshaling objects. See with alsoMBR; MBV,560–563
Chapter 9
- Understanding .NET Assemblies
MBR (marshal-by-reference) objects activation of, 563–566 Chapter MBR 11 - Type Reflection, Late Binding, configuration options, 566 and Attribute-Based Programming Part Four Leveraging the .NET Libraries WKO types, configuration of, 565 Chapter 12 - Object Serialization and the .NET Remoting Layer configuring, 562–563 Chapter 13 Building a Better Window (Introducing Windows Forms) definition and fundamentals, 560–561 Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 14 - A Better Painting Framework (GDI+)
MBV (marshal-by-value) objects configuring, 561–562 Chapter 16 - The Namespace definition andSystem.IO fundamentals, 560–561 Chapter 17 Data Access with working with, 582–587 ADO.NET Part FiveCars - Web Applications and XML Web583–584 Services general assembly, building, Chapter client 18 - ASP.NET Web Pages and Web assembly, building, 585–587Controls Chapter server 19 - ASP.NET Webbuilding, Applications assembly, 584–585
Chapter 15 - Programming with Windows Forms Controls
Chapter 20 - XML Web Services
MC++
Indexprogramming language, 413–414 List of Figures building, 412–415 subclass, List of Tables
MDI applications, building, 666–669 child Form, 668 child windows, 668–669 parent Form, 666–667 member variable initialization syntax (C#), 104–105 MemberwiseClone() method, 297,299 MemoryStreams,820–821 menus building with VS .NET, 654–655 building with Windows Forms, 644–646 Menu type members, 645 Menu$MenuItemCollection type, 645–646 nested MenuItemCollection type, 646 MenuItem type properties, 645–646,651–653
Menu$MenuItemCollection type, 645–646 and the .NET Platform, Second Edition merging (MDIC# applications), 666 by Andrew Troelsen selection prompts, 659–660 Apress © 2003 (1200 pages) system, building, 646–649
ISBN:1590590554
This comprehensive text starts with a brief overview of the
messages C# language and then quickly moves to key technical and element (WSDL), 1081 architectural issues for .NET developers. message objects, defined, 557 MessageName property, 1074–1075 Tableand of Contents proxies (.NET Remoting), 556–557 C# and the .NET Platform, Second Edition metadata Introduction .NET type, 16–17 Part and One SqlCommandBuilder, - Introducing C# and the .NET Platform 913
Chapter 1397, - The type, 399,Philosophy 499–504 of .NET Chapter 2 - assembly, Building C#37–38 Applications viewing Part Two - The C# Programming Language
metalanguages,16
Chapter 3
- C# Language Fundamentals
method parameters - Object-Oriented Programming with C# enumerating,514–515 Chapter 5 - Exceptions and Object Lifetime modifiers,147–154 Chapter 6 - Interfaces and Collections C#out keyword, 148–149 Chapter 7 - Callback Interfaces, Delegates, and Events C#params keyword, 150–151 Chapter C# 8 ref - Advanced Type Construction Techniques keyword, C# 149–150 Part Three - Programming .NETbehavior, Assemblies default parameter with passing 148 Chapter passing 9 - Understanding .NET by Assemblies reference types reference and value, 152–154 Chapter 4
Chapter 10 - Processes, AppDomains, Contexts, and Threads
methods and attributes, defined, 179,184 Part Four - Leveraging the .NET Libraries invoking asynchronously, 343–344 Chapter 12 - Object Serialization and the .NET Remoting Layer method access modifiers, 141–143 Chapter 13 - hiding, Building220 a Better Window (Introducing Windows Forms) method Chapter 14 - overloading, A Better Painting Framework (GDI+) method 181–182 Chapter 15 - overriding, Programming method 220with Windows Forms Controls Chapter 16 - visibility, The System.IO method 185 Namespace Chapter 17 - Data Access with ADO.NET MethodInfo.GetParameters() method, 514–515 Part parameters. Five - Web Applications XML Web Services Seemethodand parameters
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 18font, - ASP.NET Web Pages and Web Controls metrics, 697–698 Chapter 19 - ASP.NET Web Applications
MFC (Microsoft Foundation Classes), 25
Chapter 20 - XML Web Services
MFC runtime library, 25 Index List Microsoft of Figures Access, 886 List of Tables Mobile Forms, 607–608
mobile .NET development,61 Mobile .NET (Ferguson, Apress), 608 modules defined, 13,400,419 module- and assembly- level attributes, 526–527 module set, 460–461 MonthCalendar Control, 763–766 Mouse events MouseEventArgs parameter, 619 MouseEventArgs type properties, 629 responding to, 628–631 Up, Down, and Move events, 723–728
mscoree.dll assembly, 26–27
C# and the .NET Platform, Second Edition
mscorlib.dll,48,805 by Andrew Troelsen MSDN online help, 76 © 2003 (1200 pages) Apress
ISBN:1590590554
comprehensive text starts with a brief overview of the MulticastDelegateThis type, 328–329 C# language and then quickly moves to key technical and
multicasting architectural issues for .NET developers. with .NET delegates, 332 with Car.CarDelegate (example), 338–339 329 Tabledefined, of Contents C# and the .NET Platform, Edition multidimensional arrays, Second 156–157 Introduction
multifile assemblies building,419–422 Chapter 1 - The Philosophy of .NET airvehicles.dll,422 Chapter ufo.netmodule, 2 - Building C# Applications 421–422 Part and Two single - The C# Programming Language file assemblies, 13 Chapter 3 422–424 - C# Language Fundamentals using,
Part One - Introducing C# and the .NET Platform
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
multiple base classes, 204
multiple6 base interfaces, Chapter - Interfaces and287–288 Collections multiple7 event sinks, Interfaces, 349,352 Delegates, and Events Chapter - Callback Chapter - Advancedhandling, C# Type 247–250 Construction Techniques multiple8 exceptions, Part generic Three - Programming with .NET catch statements, 249 Assemblies
Chapter 9 - Understanding .NET Assemblies rethrowing exceptions, 249–250 Chapter 10 - Processes, AppDomains, Contexts, and Threads
multiple external assemblies, referencing (csc.exe), 50
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
multiple inheritance (MI), 204
Part Four - Leveraging the .NET Libraries
multiple12result sets,Serialization 896 Chapter - Object and the .NET Remoting Layer Chapter - Building a Better Window (Introducing Windows Forms) multiple13sort orders (comparable objects), 304–305 Chapter 14 - A Better Painting Framework (GDI+)
multiple source files, compiling (csc.exe), 49–50
Chapter 15 - Programming with Windows Forms Controls
multitabled DataSets, filling, 916–919
Chapter 16 - The System.IO Namespace
multithreaded programming, 475–476 Chapter 17 - Data Access with ADO.NET Part Five - Web Applications MyPluggableApp.exe, 530 and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
MyThreadSafeObject class type, 471
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index N
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
names clashes, resolving across namespaces, 173–174 method,325 Table namespaces of Contents
*.Binary andPlatform, *.Soap, 544 C# and the .NET Second Edition .NET Remoting, 555 Introduction 850–851 Part ADO.NET, One - Introducing C# and the .NET Platform aliases, 174 of .NET Chapter 1 - defining, The Philosophy ASP.NET Web pages, 952–953 Chapter 2 - Building C# Applications namespace of VS .NET, 175–176 Part default Two - The C# Programming Language defining 171–176 Chapter 3 - custom, C# Language Fundamentals
GDI+ (Graphics Device Interface), 671–772 - Object-Oriented Programming with C# GUI namespaces, 607–608 Chapter 5 - Exceptions and Object Lifetime name clashes, resolving across, 173–174 Chapter 6 - Interfaces and Collections nested,174–175 Chapter 7 - Callback Interfaces, Delegates, and Events nomenclature, increasing, 33–39 Chapter 8 - Advanced C# Type Construction Techniques Class Viewer Web application, 38 Part Three - Programming with .NET Assemblies ildasm.exe, dumping CIL instructions to file, 36–37 Chapter ildasm.exe, 9 - Understanding Assemblies dumping.NET namespace info to file, 35–36 Chapter ildasm.exe 10 - Processes, AppDomains, Contexts, and Threads tree view icons, 33–35 Chapter ildasm.exe, 11 - Type Reflection, Late Binding, and Attribute-Based Programming viewing assembly metadata, 37–38 Part Four Leveraging the .NET Libraries wincv.exe desktop application, 39 Chapter 12 - Object overview, 28–32Serialization and the .NET Remoting Layer Chapter accessing 13 - Building a Better Window (Introducing Windows namespaces programmatically, 30–32 Forms) Chapter referencing 14 - A Better external Paintingassemblies, Framework (GDI+) 32 29–30 with Windows Forms Controls Chapter sampling, 15 - Programming Remoting (.NET), 554–555 Chapter 16 - The System.IO Namespace System.Configuration, 446–447 Chapter 17 - Data Access with ADO.NET 845,850,851–852 Part System.Data, Five - Web Applications and XML Web Services System.Data.Common, 850 and Web Controls Chapter 18 - ASP.NET Web Pages System.Data.Odbc, 851 Chapter 19 - ASP.NET Web Applications System.Data.OleDb, 851,888 Chapter 20 - XML Web Services System.Data.OracleClient, 851 Index System.Data.SqlClient, 851,887 List of Figures System.Data.SqlServerCe,851 List of Tables System.Data.SqlTypes, 851,907 System.Drawing, 673–675 System.IO. See alsoSystem.IO namespace,540 System.Resources,733–737 System.Runtime.Serialization,549 System.Runtime.Serialization.Formatters, 544 System.Web,953 System.Web core types, 1031 System.Web.Services.Description, 1084 System.Web.UI.HtmlControls,941 System.Web.UI.MobileControls, 607 System.Web.UI.WebControls,607,984 System.Windows.Forms, 608,644,693 System.Xml.Serialization,1099 XML Web services, 1064 Chapter 4
naturally dirty windows, 682
C# and the .NET Platform, Second Edition
nested ControlCollection members, 745–746 by Andrew Troelsen
ISBN:1590590554
nested MenuItemCollection type, Apress © 2003 (1200646 pages) This comprehensive text starts with a brief overview of the nested namespaces, 174–175 C# language and then quickly moves to key technical and
nested types architectural issues for .NET developers. definitions of, 211–212 delegates as, 334 Table ofSee Contents .NET. also.NET, philosophy and overview C# and the .NET Platform, Second Edition administrative tool, 447–448
Introduction application domain. SeeAppDomains (System.AppDomain type) Part assemblies. One - Introducing C# and the.NET .NET Platform Seeassemblies,
Chapter 1 class - Thelibraries, Philosophy base 76 of .NET Chapter namespaces 2 - Building C# for distributed Applicationsapplications, 554 Part Twoand - The System C# Programming namespaceLanguage data types,
375 threads safety and, 494 Chapter 3 - C# Language Fundamentals delegate types. Seedelegate types, .NET Chapter 4 - Object-Oriented Programming with C# exception handling. See exceptions Chapter 5 - Exceptions and Object Lifetime Framework, callbacks 325 Chapter 6 - Interfaces and in, Collections namespaces overview, 28–39 Chapter 7 - Callback Interfaces, Delegates, and Events .NET-aware compilers, 12–13 Chapter 8 - Advanced C# Type Construction Techniques .NET-aware programming languages, 10 Part Three - Programming with .NET Assemblies .NET Security (Apress, 2002), 404,1052 Chapter 9 - Understanding .NET Assemblies Remoting layer. Seeserialization and .NET Remoting layer Chapter 10 - Processes, AppDomains, Contexts, and Threads resource format, 732–733 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming running on non-Microsoft OS, 40–41 Part Four - Leveraging the .NET Libraries runtime Chapter 12 - Object Serialization and the .NET Remoting Layer deploying,39–41 Chapter metadata 13 - Building Better Window (Introducing Windows Forms) and,a 499 Chapter 14format - A Better Painting 108–109 Framework (GDI+) string characters, Chapter 15 - Programming with Windows Forms Controls
.NET, philosophy and overview, 3–41 assembly manifest, 17–18 Chapter 17 - Data Access with ADO.NET base class libraries, 7–8 Part Five - Web Applications and XML Web Services building blocks, 7 Chapter - ASP.NET Web Pages and Web Controls CIL,18 13–16, 18 Chapter 1925–27 - ASP.NET Web Applications CLR, Chapter 20 - XML Web Services CLS, 23–25 IndexCTS,18–22 List of Figures class types, 19 List of Tables delegate types, 21 enumeration types, 21 interface types, 21 intrinsic data types, 22–23 structure types, 20 type members, 22 features/advantages of C#, 8–9 features of, 6–7 history of, 3–6 namespace nomenclature, 33–39 Class Viewer Web application, 38 ildasm.exe, dumping CIL instructions to file, 36–37 ildasm.exe, dumping namespace info to file, 35–36 ildasm.exe tree view icons, 33–35 ildasm.exe, viewing assembly metadata, 37–38 wincv.exe desktop application, 39 Chapter 16 - The System.IO Namespace
.NET binaries (assemblies) overview, 11–13 C# and the .NET Platform, Second Edition .NET namespaces overview, 28–32 ISBN:1590590554 Andrew Troelsen accessing by namespaces programmatically, 30–32 Apress © 2003 (1200 pages) referencing external assemblies, 32 This comprehensive text starts with a brief overview of the sampling,29–30 C# language and then quickly moves to key technical and .NET programming languages, 9–11 architectural issues for .NET developers. .NET runtime, deploying, 39–41 .NET type metadata, 16–17 Table new of keyword, Contents 170,221,257–259,505 C# and the .NET Platform, new object pointer, 258 Second Edition Introduction
NextResult() method, 896
Part One - Introducing C# and the .NET Platform
ngen.exe Chapter 1 utility, - The 448–449 Philosophy of .NET Chapter nonrectangular 2 - Building images, C# Applications hit testing, 729–731 Part Two - The C# Programming Language nonstatic (instance) methods, 145
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
numerical casts, 224–225
numerical 386–387 Chapter 5 -conversions, Exceptions and Object Lifetime Chapter numerical 6 -members, Interfaces125–126 and Collections Chapter 7 - Callback Interfaces, Delegates, and Events NumericUpDown properties, 775 Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index O
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and object-oriented programming (OOP) with C#, 179–229 architectural issues for .NET developers.
C# class defined, 179–184 method overloading, 181–182 in C#, 183–184 Table of self-reference Contents C# encapsulation services, 191–199 C# and the .NET Platform, Second Edition class properties, 193–195 Introduction enforcing with accessors and mutators, 192–193 Part One - Introducing C# and the .NET Platform internal representation of C# properties, 196–197 Chapter 1 - The Philosophy of .NET read-only/write-only properties, 197–198 Chapter 2 - Building C# Applications static properties, 198–199 Part Two - The C# Programming Language C# inheritance support, 201–205 Chapter 3 - C# Language Fundamentals base class creation, 203–204 Chapter multiple 4 - Object-Oriented with C# base classes,Programming 204 Chapter 5 Exceptions and Object Lifetime C# polymorphic support, 213–222 Chapter abstract 6 - Interfaces and Collections classes, defining, 215–216 Chapter abstract 7 - Callback Interfaces, Delegates, and Events methods, 216–220 Chapter versioning 8 - Advanced Type Construction classC# members, 220–222 Techniques Part casting Three - Programming .NET Assemblies between classwith types, 222–225 Chapter numerical 9 - Understanding casts, 224–225 .NET Assemblies employee, determining, 223–224 Chapter type 10 - of Processes, AppDomains, Contexts, and Threads class generating VS .NET, 225–229 Chapter 11definitions, - Type Reflection, Latewith Binding, and Attribute-Based Programming Add Class Wizard, 225–228 Part Four - Leveraging the .NET Libraries members to types, 228–229 Chapter adding 12 - Object Serialization and the .NET Remoting Layer default interface a type, 184–186 Chapter 13 -public Building a BetterofWindow (Introducing Windows Forms) nested type definitions, 211–212 Chapter 14 - A Better Painting Framework (GDI+) pillars of, 186–191 Chapter 15 - Programming with Windows Forms Controls encapsulation services, 187 Chapter 16 - The System.IO Namespace inheritance, 187–189 Chapter 17 - Data Access with ADO.NET polymorphism,189–191 Part Five - Web Applications and XML Web Services protected keyword, 205–211 Chapter 18 - ASP.NET Web Pages and Web Controls containment/delegation,207–211 Chapter 19 - ASP.NET Web Applications sealed classes, 205–207 Chapter 20 - XML Web199–201 Services read-only fields, Index
objects configuring for serialization, 541–545 List of Tables construction basics, 97–100 defined, 97 as event sinks, 353–354 generations defined, 267 programmatically interacting with, 270–272 MBR.SeeMBR (marshal-by-reference) objects MBV.SeeMBV (marshal-by-value) objects object browser utility, 73 object fields and accessor methods, 563 object graphs, 260,540–541 object lifetime, 257 Object.Equals() and Object.ReferenceEquals(), 122 persistence in .NET Framework, 540 serialization.Seeserialization and .NET Remoting layer WKO types, 565 List of Figures
OLE/COM Object Viewer utility (Oleview.exe), 38
C# and the .NET Platform, Second Edition
OLE DB providers, by 889 Andrew Troelsen OleDb data provider. Apress See © Data 2003 (1200 Providers pages)
ISBN:1590590554
OleDbCommandThis comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and executing stored procedures with, 899–901 architectural issues for .NET developers. inserting, updating, deleting records with, 897–899 OleDbCommand.ExecuteNonQuery() method, 897–898 method, 895–896 TableOleDbCommand.ExecuteReader() of Contents OleDbConnection types,Second 888–890 C# and the .NET Platform, Edition Introduction OleDbDataAdapter type, 901–905 Part column One - Introducing C# andwith, the .NET Platform names, altering 904–905
Chapter - The Philosophy core1 members of, 903 of .NET Chapter 2 - Building C# Applications DataSets, filling with, 903–904 Part OleDbDataAdapter.Fill() Two - The C# Programming Language method, 901–902
Chapter 3 - C# Language Fundamentals OleDbDataReader, 894–896 Chapter 4 - Object-Oriented Programming with C# Command Behavior, 895–896 Chapter 5 - result Exceptions Objectwith, Lifetime multiple sets,and obtaining 896 Chapter 6 Interfaces and Collections OleDbDataReader.GetTableSchema() method, 896 Chapter 7 - information, Callback Interfaces, Delegates, and Events schema obtaining with, 896 Chapter 8 - Advanced Type Construction Techniques OleDbParameter type,C# 899–901 Part Three - Programming with .NET Assemblies
[OneWayAttribute] type, 604–605
Chapter 9
- Understanding .NET Assemblies OnKeyUp() 631 Chapter 10 - method, Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming OnMouseMove(), 630 Part Four - Leveraging the .NET Libraries
OnMouseUp(),630
Chapter 12 - Object Serialization and the .NET Remoting Layer
OnPaint() virtual method, 680–681,683
Chapter 13 - Building a Better Window (Introducing Windows Forms)
OnStart(), Chapter 14 599 - A Better Painting Framework (GDI+) Chapter 15 599 - Programming with Windows Forms Controls OnStop(), Chapter - The (FileInfo System.IO Namespace Open()16 method class), 815–817 Chapter 17 - Data Access with ADO.NET
OpenRead(), OpenWrite() members (FileInfo class), 817
Part Five - Web Applications and XML Web Services
OpenText(), CreateText(), AppendText() members (FileInfo class), 817–818 Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 systems, - ASP.NETnon-Microsoft, Web Applications operating 40 Chapter 20 XML Web Services operator keyword, 376–377 Index
operator-to-CIL special name roadmap, 381–383
List of Figures
operators List of Tables –>,364 -> pointer-centric operator, 360 !=, 378–379 * and &, 363 +,375 += and –+, 385–386 , +, 379–380 ==,378–379 C# operators, complete set, 139–140 explicit conversion for square type, 389–390 internal representation of overloaded, 380–383 intrinsic C#, 381–383 overloadable,385 overloaded from overloaded-operator-challenged languages, 383–385 overloading,375–380
comparison operators, 379–380 C# and the .NET Platform, Second Edition equality operators, 378–379 Andrew Troelsen pointer-centricbyoperators, 360 Apress385 © 2003 (1200 pages) valid overloadable,
ISBN:1590590554
This comprehensive text starts with a brief overview of the
ORPC (Object Remote Procedure Call), 558 moves to key technical and C# language and then quickly architectural issues for .NET developers. out and ref parameters, 327 out keyword, 148–149 output Table of Contents options, csc.exe, 46 Second Edition C# and the .NET Platform, parameters, 104,148–149 Introduction Part One - and Introducing C# and overflow underflow, 356,the 358.NET Platform
Chapter 1
- The Philosophy of .NET overloadable operators, 385
Chapter 2
- Building C# Applications
overloaded operators C#,329,332,351 Chapter 3 - C# Language Fundamentals from overloaded-operator-challenged languages, 383–385 Part Two - The C# Programming Language
Chapter 4
- Object-Oriented Programming with C#
overloading Chapter 5 - Exceptions and Object Lifetime method, Chapter 6 - 181–182 Interfaces and Collections
operators, 375–380 - Callback Interfaces, Delegates, and Events comparison operators, 379–380 Chapter 8 - Advanced C# Type Construction Techniques equality operators, 378–379 Chapter 7
Part Three - Programming with .NET Assemblies
overriding Chapter 9 - Understanding .NET Assemblies defined, Chapter 10 - 118 Processes, AppDomains, Contexts, and Threads override keyword, 214,218 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index P
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the Page class, 975 C# language and then quickly moves to key technical and architectural issues for .NET developers.
directive, 955 Page type, properties of, 971
Table of Contents
paging, enabling (DataGrids), 1000–1001
C# and the .NET Platform, Second Edition
painting Introduction 635–636 C# and the .NET Platform Part basics, One - Introducing paint 682–683 of .NET Chapter 1 handler, - The Philosophy paint Chapter 2 sessions, - Building680–684 C# Applications
invalidating, Language 682 Part Twoclient - Thearea, C# Programming obtaining graphics type, 682–684 - C# Language Fundamentals PaintEventArgs properties, 635
Chapter 3 Chapter 4
- Object-Oriented Programming with C#
Panel Controls, 773 and Object Lifetime Chapter 5 - Exceptions Chapter - Interfaces panes, 6defined, 655 and Collections Chapter 7 - Callback Interfaces, Delegates, and Events parameters Chapter 8 - Advanced C# Type Construction Techniques interfaces as, 280–281 Part parameter Three - Programming modifiers, with 147 .NET Assemblies
Chapter 9 - Understanding .NET Assemblies parameter passing behavior, 148 Chapter 10 - Processes, AppDomains, parameterized constructors, 20 Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, parameterized queries, 898–899, 908 and Attribute-Based Programming Part params Four - Leveraging the .NET Libraries keyword, 150–151
Chapter taking 12 delegates - Object Serialization as, 334 and the .NET Remoting Layer Chapter - Building a Better Window (Introducing Windows Forms) parent 13 Form, building (MDI applications), 666–667 Chapter 14 - A Better Painting Framework (GDI+)
parsing values from string data, 127–128
Chapter 15 - Programming with Windows Forms Controls
passing16reference types, 152–154 Chapter - The System.IO Namespace pen caps, Chapter 17 -711–713 Data Access with ADO.NET Part - Web707–711 Applications and XML Web Services penFive objects,
Chapter 18 - ASP.NET Web Pages and Web Controls
persistent cookies, defined, 1047
Chapter 19 - ASP.NET Web Applications
physical logical 401–402 Chapter 20and - XML Webviews, Services PictureBox control, 723–727 Index List of Figures PictureBoxSizeMode enumeration, 724 List of Tables
pillars of OOP, 186–191 encapsulation services, 187 inheritance, 187–189 polymorphism,189–191
Point objects, adding and subtracting, 376–377 point of origin, 690–692 pointer-centric operators, 360 pointers field access via, 364 new object, 258 Point(F) type, 675–676 policies custom version, 440 publisher policy, 444–445
polymorphism C# and the .NET Platform, Second Edition C# polymorphic support, 213–222 ISBN:1590590554 by Andrew Troelsen abstract classes, defining, 215–216 Apress © 2003 (1200 pages) abstract methods, 216–220 text starts with a brief overview of the versioning This classcomprehensive members, 220–222 C# language and then quickly moves to key technical and classical and ad hoc, 189–191 architectural issues for .NET developers. enforcing polymorphic activity, 216–220 interfaces as polymorphic agents, 284–285 Table pop-up of Contents menus, creating, 649–651 C# and the .NET Platform, Second Edition element (WSDL), 1081 Introduction
POST and GET methods, 947,949–950
Part One - Introducing C# and the .NET Platform
POST messages, HTTP, 1087 Chapter 1 - The Philosophy of .NET Chapter postbacks, 2 -944, Building 981 C# Applications Part Two -configuration, The C# Programming Language prejitted 448
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
preprocessing messages, 619–621
preprocessor directives, C#, 82–88 Chapter 5 - Exceptions and Object Lifetime altering numbers, Chapter 6 - line Interfaces and87–88 Collections
conditional code compilation, 84–86 - Callback Interfaces, Delegates, and Events issuing warnings and errors, 86 Chapter 8 - Advanced C# Type Construction Techniques specifying code regions, 83–84 Chapter 7
Part Three - Programming with .NET Assemblies
primary9key constraint, 855.NET Assemblies Chapter - Understanding Chapter - Processes, AppDomains, primary10 modules, defined, 13,419 Contexts, and Threads Chapter - Type defined, Reflection, Late Binding, and Attribute-Based Programming primary11 threads, 452 Part Four - Leveraging the .NET Libraries
PrimaryKey property, 864–865
Chapter 12 - Object Serialization and the .NET Remoting Layer
private 13 and- public methods, Chapter Building a Better 142 Window (Introducing Windows Forms) Chapter - A Better 511–515 Painting Framework (GDI+) private 14 assemblies, Chapter enumerating 15 - Programming class members, with Windows 513–514 Forms Controls
enumerating method parameters, Chapter 16 - The System.IO Namespace 514–515 enumerating referenced Chapter 17 - Data types Accessinwith ADO.NETassemblies, 513 of, 425 and XML Web Services Part fundamentals Five - Web Applications identity 426 Web Pages and Web Controls Chapter 18 -of, ASP.NET probing 425–426, Chapter 19 - for, ASP.NET Web 429–430 Applications and20 XML configuration files, 426–429 Chapter - XML Web Services private data fields, 192 Index List of Figures private key, defined, 431 List of Tables
private keyword, 185,191 probing for private assemblies, 425,429–430 process identifiers (PIDs), 451 processes AppDomain,474–475 defined, 451 interaction under .NET, 453–462 enumerating running processes, 456–457 module set, investigating, 460–461 specific process, investigating, 457 starting and killing programmatically, 461–462 System.Diagnostics namespace members, 454–456 thread set, investigating, 458–460 ProcessExit event, 468 Process.GetProcessById() method, 457
Process.GetProcesses() method, 456 C# and the .NET Platform, Second Edition ProcessStartInfo type definition, 462 by type Andrew Troelsen459–460 ProcessThread members, Apress © 2003 pages) and threads under Win32, (1200 451–453
ISBN:1590590554
This comprehensive text starts with a brief overview of the
program constants, C# defining, language 132–134 and then quickly moves to key technical and architectural issues for .NET developers. programming attributed,520–522 languages, .NET, 9–11,944,950 Tablemultithreaded of Contents via delegates, 476 C# and .NET Platform, Second Edition withthe TimerCallbacks, 494–496 Introduction with Windows Forms Controls. SeeWindows Forms Controls, programming with Part One - Introducing C# and the .NET Platform
project solution, creating VS .NET, 60–61
Chapter 1
- The Philosophy of .NET
project-wide symbols, 86 Chapter 2 - Building C#setting, Applications Part properties Two - The C# Programming Language
.NET defining,Fundamentals 193 Chapter 3 classes - C# Language defined, Chapter 4 - 184 Object-Oriented Programming with C# internal 196–197 Chapter 5 - representation Exceptions and of, Object Lifetime properties window, and 66 Collections Chapter 6 - Interfaces Property Builder Wizard, 1000 Chapter 7 - Callback Interfaces, Delegates, and Events
PropertyCollection type, 874 - Advanced C# Type Construction Techniques read-only and write-only, 197–198 Part Three - Programming with .NET Assemblies and sort types, custom, 306 Chapter 9 - Understanding .NET Assemblies static,198–199 Chapter 8
Chapter 10 - Processes, AppDomains, Contexts, and Threads
protected keywords,Late 185,Binding, 191 Chapter 11 internal - Type Reflection, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries protected keyword, 205–211
Chapter containment/delegation, 12 - Object Serialization programming and the .NETfor, Remoting 207–211 Layer
encapsulation enforced 191(Introducing Windows Forms) Chapter 13 - Building a Betterwith, Window sealed Chapter 14 -classes, A Better205–207 Painting Framework (GDI+) visibility and, 185 Chapter 15 - levels Programming with Windows Forms Controls Chapter proxies16 - The System.IO Namespace Chapter basics, 17 1060 - Data Access with ADO.NET Part generating, Five - Web Applications 1089–1091,1095 and XML Web Services
and18 messages (.NET 556–557 Chapter - ASP.NET Web Remoting), Pages and Web Controls proxy 1089–1091 Chapter 19code, - ASP.NET Web Applications proxy 1094 Chapter 20logic, - XMLhard-coded, Web Services Index public and internal types, 184–186 List of Figures public and private methods, 142 List of Tables
public field data, defined, 184 public interface, default, 184–186 public key, defined, 431 public keywords, 94,185,191 publisher policy assemblies,444–445 disabling,445
Index Q
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and Query Analyzer utility (SQL Server), 886 architectural issues for .NET developers.
QueryString property (HttpRequest), 975 Queue class type, 310,312–313
Table of Contents
C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index R
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
RadioButtons and GroupBoxes, 756–760 CheckedListBox Control, 758–760 Table of example, Contents756–758 types, 992–993 C# and the .NET Platform, Second Edition Random.Next() method, 143 Introduction
Part One - Introducing C# and the .NET Platform RangeValidators, 1008–1009
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Read() method, 895
read-only andC# write-only properties, 197–198 Part Two - The Programming Language read-only 199–201Fundamentals Chapter 3 fields, - C# Language Chapter 4 keyword, - Object-Oriented Programming with C# readonly 192,199–200 Chapter 5 - Exceptions and Object Lifetime
ReadOnly member, 835
Chapter 6
- Interfaces and Collections
ReadXml()- method, 884 Callback Interfaces, Delegates, and Events ReadXmlSchema() method, Chapter 8 - Advanced C# Type885 Construction Techniques Chapter 7
Part - Programming with .NET Assemblies realThree proxies, 557
Chapter 9
- Understanding .NET Assemblies
records inserting, updating, deleting with OleDbCommand, 897–898 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming inserting with SqlDataAdapter, 907–910 Part updating Four - Leveraging the .NET Libraries with SqlDataAdapter, 910–912 Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 12 - Object Serialization and the .NET Remoting Layer
Rectangle(F) type, 677–678
Chapter 13 - Building a Better Window (Introducing Windows Forms)
rectangular arrays, Chapter 14 - A Better156 Painting Framework (GDI+) Chapter redirecting 15 - users Programming (HttpResponse.Redirect), with Windows Forms 977–978 Controls Chapter The System.IO Namespace ref and16 out- parameters, 327–328 Chapter 17 - Data Access with ADO.NET
ref keyword, 149–150,364
Part Five - Web Applications and XML Web Services
reference Chapter 18 -books ASP.NET Web Pages and Web Controls Advanced .NET Remoting (Apress, 2002), 560 Chapter 19 - ASP.NET Web Applications
Distributed .NET Programming in C# (Apress, 2002), 567,606 Essential Guide to Managed Extensions for C++ (Apress, 2002), 413–414 Index GDI+ Programming in C# and VB .NET (Apress, 2002), 742 List of Figures Mobile .NET (Ferguson, Apress), 608 List of Tables .NET Security (Apress, 2002), 404,1052 A Programmer's Guide to ADO.NET in C# (Apress, 2002), 931 User Interfaces in C# (Apress, 2002), 802 VB .NET and the .NET Platform (Apress, 2002), 412 Writing Add-Ins for VS .NET (Apress, 2002), 534 Chapter 20 - XML Web Services
references obtaining interface, 277–279 reference-based and value-based types, 109–114 comparison of, 113–114 value types containing reference types, 112–113 reference parameters, 149–150 reference semantics, 118 reference types passing by reference and value, 152–154 and value types, converting between, 128–132
referenced assemblies, 513
C# and the .NET Platform, Second Edition
reflection ISBN:1590590554 by Andrew Troelsen defined, 504 Apress © 2003 (1200 pages) late binding and custom attributes example, 528–534 This comprehensive text starts with a brief overview of the C# snap-in, building, 531 C# language and then quickly moves to key technical and common snappable types, building, architectural issues for .NET530 developers. custom snap-in consumer, building, 529–530 extendible Windows Forms application, building, 532–534 Table of VB Contents .NET snap-in, 531–532 C# and the .NET Platform, Refresh() method, 808 Second Edition Introduction
#region and #endregion tags, 83
Part One - Introducing C# and the .NET Platform
Region1class, 678–679 Chapter - The Philosophy of .NET Chapter RegularExpressionValidator, 2 - Building C# Applications 1008 Part Two tables - The C# Programming Language related navigation, 880–883
Chapter 3
- C# Language Fundamentals
relational and equality operators, 137
Chapter 4
- Object-Oriented Programming with C# Relations 874and Object Lifetime Chapter 5 property, - Exceptions Chapter remote6objects, - Interfaces hosts and for, 597–603 Collections
CarService, installing, 601 Delegates, and Events Chapter 7 - Callback Interfaces, IIS, 602–603 Chapter 8 - Advanced C# Type Construction Techniques ServiceBase derived, 599 Part Main() Three -method, Programming with .NET Assemblies OnStart(), 599 Chapter 9 - Understanding .NET Assemblies OnStop(), 599 Chapter 10 - Processes, AppDomains, Contexts, and Threads service 600–601Late Binding, and Attribute-Based Programming Chapter 11 -installer, Type Reflection, service, the 597–598 Part Windows Four - Leveraging .NET Libraries
RemoteConfiguration type, 573–575 Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better RemoteMessageObject type,Window 577 (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
remoting.See alsoserialization and .NET Remoting layer application Chapter building, 16 - The566–567 System.IO Namespace Chapter testing, 17 - Data 571Access with ADO.NET Part architecture, Five - Web Applications and559 XML Web Services default .NET, Chapter 18 ASP.NET Web Pages and Web Controls asynchronous,603–604 Chapter 19 - ASP.NET Applications configuration files,Web 579–582 Chapter client-side 20 - XML Web Services *.config files, building, 581–582 Index server-side *.config files, building, 580–581 defined, List of Figures554 Framework, .NET, 556–559 List of Tables .NET formatters, 559 channels, 558 extending default remoting layers, 560 proxies and messages, 556–557 terminology, 560 namespaces,554–555,555 remoting layers extending default, 560 and serialization. Seeserialization and .NET Remoting layer Chapter 15 - Programming with Windows Forms Controls
Remove() and RemoveAll() methods, 1046 Remove(), static, 329,339 RenamedEventHandler type, 831 rendering quality, 706–707 resgen.exe utility, 732,736
resources C# and the .NET Platform, Second Edition configuration with VS .NET, 739–742 ISBN:1590590554 Andrew Troelsen format, .NET,by 732–733 Apress © 2003 (1200 pages) ResourceManagers,737–739 This 737 comprehensive text starts with a brief overview of the ResourceWriters, C# language and then quickly moves to key technical and
response file, default (csc.rsp), 51 for .NET developers. architectural issues Response type properties and methods (Http), 975–976 ResXResourceReader type, 733–734 Table of Contents ResXResourceWriter class, 733–734 C# and the .NET Platform, Second Edition Introduction rethrowing exceptions, 249–250 Part One - Introducing C# and the .NET Platform
return values, method, 325
Chapter 1
- The Philosophy of .NET reuse, binary, 402 C# Applications Chapter 2 - Building Part richTwo controls - The(WebControls), C# Programming 991, Language 995–997
Chapter 3 - C# Language RichTextBox class, 752 Fundamentals Chapter 4
- Object-Oriented Programming with C#
roots, application, 259
Chapter 5
- Exceptions and Object Lifetime RowFilter (DataViews), 873 Chapter 6 property - Interfaces and Collections
rows (DataTables) Chapter 7 - Callback Interfaces, Delegates, and Events deleting, Chapter 8 - 866–867 Advanced C# Type Construction Techniques 869–871 Part updating, Three - Programming with .NET Assemblies Chapter 9 - Understanding .NET Assemblies RTTI (Runtime Type Identification), 239 Chapter 10 - Processes, AppDomains, Contexts, and Threads
running processes, 456–457
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
running vs. debugging, 71
Part Four - Leveraging the .NET Libraries
runtime12 - Object Serialization and the .NET Remoting Layer Chapter .NET, Chapter 13 deploying, - Building a39–40 Better Window (Introducing Windows Forms) defined, Chapter 14 - 25 A Better Painting Framework (GDI+) obtaining attributes at, with 528 Windows Forms Controls Chapter 15 - Programming runtime system, .NET (CLR), 26
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index S
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and SAO (server activated object), 564 architectural issues for .NET developers.
SaveFileDialog type, 838–839 schema information
Tabledefined, of Contents 891
C# and the .NET Platform, Second Edition896 obtaining with OleDbDataReader, Introduction
script blocks, 956–957
Part One - Introducing C# and the .NET Platform
scripting, 943–946 Chapter 1 client-side, - The Philosophy of .NET default.htm form C# data, 946 Chapter 2 - Building Applications
Part example, Two - The945–946 C# Programming Language
ScrollableControl class, 636–637 Chapter 3 - C# Language Fundamentals Chapter 4 - Object-Oriented Programming with C# SDI (Single Document Interface), 610 Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
sealed classes, 205–207
sealed keyword, 206 - Callback Interfaces, Delegates, and Events security8 context defined 404 Techniques Chapter - Advanced C#(assemblies), Type Construction Chapter 7
Part Threemethod - Programming with .NET Select() (DataTables), 867,Assemblies 869
Chapter 9
- Understanding .NET Assemblies
SELECT SQL statements, 848
Chapter 10 - Processes, AppDomains, Contexts, and Threads
SelectionMode property, 995–996
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
self-reference in C#, the 183–184 Part Four - Leveraging .NET Libraries Chapter 12 - Object Serialization semicolon-delimited lists, 50 and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
separation of concerns, 100
Chapter 14 - A Better Painting Framework (GDI+)
serialization and .NET Remoting layer, 539–606 asynchronous remoting, 603–604 Chapter 16 - The System.IO Namespace basics,539 Chapter 17 - Data Access with ADO.NET binary formatter, 545–547 Part Five - Web Applications and XML Web Services CAO,587–589 Chapter 18 - ASP.NET Web Pages and Web Controls CAO/WKO-singleton objects, 589–595 Chapter 19 - ASP.NET Web Applications client-side lease adjustment, 595 Chapter default 20 - XML Web Services leasing behavior, 590–594 Index server-side lease adjustment, 594–595 List of Figures ChannelServices type, 572–573 List of Tables choosing formatters, 544–545 configuring objects for, 541–545 customizing serialization process, 549–554 defined, 539–540 deploying server to remote machine, 577 distributed application, building, 568–571 general assembly, 568 server assembly, 569–570 SimpleRemoteObjectClient.exe assembly, 570–571 marshaling objects, 560–563 internal optimizations, 563 MBR objects, configuring, 562–563 MBV objects, configuring, 561–562 MBR object activation, 563–566 MBR configuration options, 566 WKO types, configuration of, 565 Chapter 15 - Programming with Windows Forms Controls
MBV objects, 582–587 C# and the .NET Platform, Second Edition Cars general assembly, building, 583–584 ISBN:1590590554 by Andrew Troelsen client assembly, building, 585–587 Apress © 2003 (1200 pages) server assembly, building, 584–585 This comprehensive text starts with a brief overview of the .NET Remoting framework C# language and then quickly moves to key technical and .NET formatters, 559 architectural issues for .NET developers. application building, 566–567 channels, 558 554 Table of defining, Contents extending default remoting layers, 560 C# and the .NET Platform, Second Edition namespaces,554–555 Introduction proxies and messages, 556–557 Part One - Introducing C# and the .NET Platform terminology, 560 Chapter 1 - The Philosophy of .NET object graphs, 540–541 Chapter 2 - Building C# Applications object persistence in, 540 Part Two - The C# Programming Language [OneWayAttribute] type, 604–605 Chapter 3 - C# Language Fundamentals remote application, testing, 571 Chapter 4 -objects, Object-Oriented remote hosts for,Programming 597–603 with C# Chapter CarService, 5 - Exceptions and Object installing, 601 Lifetime Chapter IIS, 6 602–603 - Interfaces and Collections Chapter Main() 7 - Callback Interfaces, Delegates, and Events method, ServiceBase derived, 599 Chapter OnStart(), 8 - Advanced 599 C# Type Construction Techniques Part Three - Programming with .NET Assemblies OnStop(), 599 Chapter service 9 - Understanding installer, 600–601 .NET Assemblies service, 597–598 Contexts, and Threads Chapter Windows 10 - Processes, AppDomains, RemoteConfiguration type, Chapter 11 - Type Reflection, Late573–575 Binding, and Attribute-Based Programming configuration files,Libraries 579–582 Part remoting Four - Leveraging the .NET files, building, 581–582 Chapter client-side 12 - Object*.config Serialization and the .NET Remoting Layer *.config files, building, 580–581Windows Forms) Chapter server-side 13 - Building a Better Window (Introducing Serialize() method, 545–546 Chapter 14 - A Better Painting Framework (GDI+) server-side/client-side lease sponsorship, 595–597 Chapter 15 - Programming with Windows Forms Controls SOAP formatter, 547 Chapter 16 - The System.IO Namespace TCP channel, 578–579 Chapter 17 - Data Access with ADO.NET WKO types, 576–577 Part Five - Web Applications and XML Web Services XML formatter, 548 Chapter 18 - ASP.NET Web Pages and Web Controls
servers19 - ASP.NET Web Applications Chapter
defined, 554 server assembly Index building,569–570,584–585 List of Figures defined, 567 List of Tables Server Explorer drag and drop in, 926–927 utility,919 window,71–72 Server property, 1073 server-side *.config files, building, 580–581 and client-side lease sponsorship, 590,595–597 event handling, 983–984 lease adjustment, 594–595 scripting languages, 950 variables,974 Web,936–938 Chapter 20 - XML Web Services
element (WSDL), 1082 service installer, 600–601
sessions C# and the .NET Platform, Second Edition cookies, defined, 1048 ISBN:1590590554 by Andrew Troelsen data, maintaining, 1043–1046 Apress © 2003 (1200 pages) defined, 1043 comprehensive text starts1077 with a brief overview of the session state,This configuring with web.config, C# language and then quickly moves to key technical and Session State Server (ASP.NET), 1056 architectural issues for .NET developers. session states vs. application states, 1033–1037 ,1054–1056 Table set_ of and Contents get_ methods, 196–197 C# the .NET Platform, Setand keyword, VB 6.0, 374Second Edition Introduction
SetStyle() method, 624
Part One - Introducing C# and the .NET Platform
Setter/Getter tokens, 502 of .NET Chapter 1 - The Philosophy Chapter severed2 roots, - Building 260 C# Applications Part Two -directories, The C# Programming Language shadow 958
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
shallow copies, 297
shapes5hierarchy (interfaces), 275–276, 279–281 Chapter - Exceptions and Object Lifetime Chapter shared6assemblies - Interfaces and Collections
building, 516–517 Delegates, and Events Chapter 7 - 432–434, Callback Interfaces, fundamentals of, 430–431 Chapter 8 - Advanced C# Type Construction Techniques and removing, 435–436 Part installing Three - Programming with .NET Assemblies SharedAssembly, freezing 438 Chapter 9 - Understanding .NETcurrent, Assemblies SharedAssembly 2.0.0.0,Contexts, 438–439and Threads Chapter 10 - Processes,version AppDomains, using, Chapter 11436 - Type Reflection, Late Binding, and Attribute-Based Programming 437–438 Part versioning, Four - Leveraging the .NET Libraries
SharpDevelop IDE,Serialization 89 Chapter 12 - Object and the .NET Remoting Layer Chapter 13 -notation, Building attribute, a Better Window shorthand 524 (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
side-by-side execution (assemblies), 404
Chapter 15 - Programming with Windows Forms Controls
signing, delayed, 434–435
Chapter 16 - The System.IO Namespace
simple 17 controls 991 Chapter - Data(WebControls), Access with ADO.NET Part Five - Web Applications and XML Services SimpleRemoteObjectClient.exe, 568,Web 570–571
Chapter 18 - ASP.NET Web Pages and Web Controls
SimpleRemoteObjectServer.exe, 568,577
Chapter 19 - ASP.NET Web Applications
SimpleRemotingAsm.dll, 568–570
Chapter 20 - XML Web Services
single file and multifile assemblies, 13,400–401 Index List of Figures single file test assembly, building, 404–408 List of Tables
single-threaded applications, 341 singleton WKO types, 570,576 sinks event sinks, 353–354 multiple event, 352 multiple event sinks, 349 sink objects, 322 Size(F) types, 678 sizeof keyword, 366–367
SmoothingMode enumeration, 706–707 snap-ins,529–532 building C#, 531 building VB .NET, 531–532 snap-in consumer, building, 529–530
snappable types, building, 530 C# and the .NET Platform, Second Edition SnappableAttribute type, 530 by Andrew Troelsen
sn.exe (strong name) utility, 432–433 Apress © 2003 (1200 pages)
ISBN:1590590554
SOAP (Simple Object Access Protocol) This comprehensive text starts with a brief overview of the formatter (serialization), C# language 547, and558 then quickly moves to key technical and architectural issues for .NET developers. messages,1088–1089 SoapHttpClientProtocol members, 1090 soapsuds.exe command line application, 567
Table of Contents
solid C# andbrushes, the .NET713–715 Platform, Second Edition Introduction solution explorer window, 62–64 Part One - Introducing C# and the .NET Platform
Solutions Explorer, 919–921
Chapter 1
- The Philosophy of .NET
Sort() method, 302 - Building C# Applications sortTwo orders, multiple (comparable objects), 304–305 Part - The C# Programming Language Chapter 2
Chapter 3 -and C#properties, Language Fundamentals sort types 306 Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
special names from VB .NET, 384–385
Specialized namespace. SeeSystem.Collections.Specialized namespace - Interfaces and Collections
Chapter 6
spin controls, 774 Interfaces, Delegates, and Events Chapter 7 - Callback Chapter 8 - Advanced C#Language) Type Construction Techniques SQL (Structured Query Part commands Three - Programming with .NET Assemblies
Chapter auto-generating 9 - Understanding Assemblies with.NET CommandBuilder types, 912–914 Chapter building 10 - Processes, with OleDbCommand, AppDomains, Contexts, 892–893 and Threads
connection, 921–922 Chapter 11 - Typecreating, Reflection, Late Binding, and Attribute-Based Programming 906–912 Part Data Four -Provider, Leveraging the .NET Libraries inserting records with, 907–910 Chapter SqlDataAdapter, 12 - Object Serialization and the .NET Remoting Layer updating records with, 910–912 Chapter SqlDataAdapter, 13 - Building a Better Window (Introducing Windows Forms) namespace, 907 Chapter System.Data.SQLTypes 14 - A Better Painting Framework (GDI+) Server, 1056 with Windows Forms Controls Chapter 15 -886–887, Programming Server Query Analyzer, 1056 SqlCommandBuilder, 912–914 Chapter 17 - Data Access with ADO.NET SqlConnectionString attribute, 1056 Part Five - Web Applications and XML Web Services SqlDataAdapter, inserting records with, 907–910 Chapter 18 - ASP.NET Web Pages and Web Controls SqlDataAdapter, updating records with, 910–912 Chapter 16 - The System.IO Namespace
Chapter 19 - ASP.NET Web Applications
square20 brackets ([ ]), Services 532 Chapter - XML Web square type, 389–390 Index List of Figures Stack class type, 310,313–314 List of Tables
stackalloc keyword, 365
StackTrace property, 239 Start() and Kill() methods, 461–462 start page, VS .NET, 58–59 StartFigure() method, 730 state management (Web applications), 1023–1026 stateConnectionString attribute, 1056 stateful Web services, building, 1075–1077 stateless wire protocols, 936 [STAThread] attribute, 67 static Combine() method, 329 static constructors, 198–199
static data, defining, 145–147
C# and the .NET Platform, Second Edition
static functions, 339–340 by Andrew Troelsen static keyword, 94, 199 © 2003 (1200 pages) Apress
ISBN:1590590554
This comprehensive text starts with a brief overview of the static level CTS members, defined, 22 C# language and then quickly moves to key technical and
static members architectural issues for .NET developers. defined, 22 of System.Object base class, 122 Table Contents143–147 staticofmethods, C# and the .NET Platform, Second Edition defining, 143–145 Introduction static data, defining, 145–147 Part One - Introducing C# and the .NET Platform
static properties, 198–199
Chapter 1
- The Philosophy of .NET
static read-only fields, 200–201 - Building C# Applications
Chapter 2
static Remove() 329 Language Part Two - The C# method, Programming Chapter 3 -members, C# Language static type 563Fundamentals Chapter 4
- Object-Oriented Programming with C#
statistics - Exceptions and Object Lifetime basic thread, 478–479 Chapter 6 - Interfaces obtaining browser, and 973 Collections Chapter 5 Chapter 7
- Callback Interfaces, Delegates, and Events
Status bars, 655–660 Chapter 8 - Advanced C# Type Construction Techniques building,656–657 Part Three - Programming with .NET Assemblies menu selection prompts, 659–660 Chapter 9 - Understanding .NET Assemblies select properties of, 655 Chapter 10 - Processes, AppDomains, Contexts, and Threads StatusBarPanel type properties, 656 Chapter 11 type, - Type Reflection, Late Binding, and Attribute-Based Programming Timer 658–659 Part Four - Leveraging the .NET Libraries
stored procedures, 899–901
Chapter 12 - Object Serialization and the .NET Remoting Layer
storing 13 state with , 1054–1056 Chapter - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) streams Chapter abstract. 15 - See Programming abstract stream with Windows class Forms Controls
defined, Chapter 16 - 818 The System.IO Namespace StreamingContextStates members, 551–552 Chapter 17 - Data Access with enumeration ADO.NET class, 136 Part StreamReader Five - Web Applications and XML Web Services StreamReader.Peek() method, Chapter 18 - ASP.NET Web Pages and826 Web Controls StreamWriters and StreamReaders, 822–826 Chapter 19 - ASP.NET Web Applications from, 825–826 Chapter text 20 -files, XMLreading Web Services Index
text files, writing to, 824–825 TextWriter core members, 823–824
List of Figures
strings List of Tables data, parsing values from, 127–128 escape characters, 161–162 formatting flags, 107–109 literals, documenting, 503–504 manipulation in C#, 160–164 escape characters and "verbatim strings", 161–162 System.Text.StringBuilder,162–164 String.Length property, 138 StringReader type, 828–829 StringWriter type, 826–828 strong names, 431–432 structured exception handling (SEH), 233 structures CTS types, 20
defining in C#, 168–171
C# and the .NET Platform, Second Edition
style sheets and tab order, 997 by Andrew Troelsen
ISBN:1590590554
subdirectories, creating, Apress ©811–812 2003 (1200 pages) This comprehensive text starts with a brief overview of the switch statements, 138–139 C# language and then quickly moves to key technical and
synchronization architectural issues for .NET developers. with C# lock keyword, 490–492 using [Synchronized] attribute, 493 System.Threading.Interlocked type, 492–493 Tableusing of Contents using type, 491–492 C# and theSystem.Threading.Monitor .NET Platform, Second Edition Introduction synchronous delegate invocations, 342 Part One - Introducing C# and the .NET Platform
synchronous method invocations, 1090,1092–1093
Chapter 1
- The Philosophy of .NET
syntactic constructs, CTS-defined, 19 - Building C# Applications
Chapter 2
systemPart Two -and Theapplication-level C# Programmingexceptions, Language
252
Chapter - C# Language Fundamentals system3attributes, predefined, 521 Chapter 4
- Object-Oriented Programming with C#
system data types and C# aliases, 122–128 - Exceptions and Object Lifetime basic numerical members, 125–126 Chapter 6 - Interfaces experimenting with,and 125Collections Chapter 7 Callback Interfaces, Delegates, and Events string data, parsing values from, 127–128 Chapter 8 - Advancedmembers, C# Type Construction Techniques System.Boolean 126 Part System.CharNext Three - Programming with .NET Assemblies members, 127 Chapter 5
Chapter 9
- Understanding .NET Assemblies
system exceptions and application exceptions, 244 Chapter 11 - Type Reflection, Binding, and Attribute-Based Programming debugging with VS .NET,Late 253–256 Part defined, Four - Leveraging the .NET Libraries 240 Chapter 12 - 241–242 Object Serialization and the .NET Remoting Layer locating, Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 13 - Building a Better Window (Introducing Windows Forms)
System namespaces (listed), 29–31
Chapter 14 - A Better Painting Framework (GDI+)
system15 types, hierarchy of, 124Windows Forms Controls Chapter - Programming with System.Activator class, 518–519 Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET System.AppDomain type. See AppDomains (System.AppDomain type) Part Five - Web Applications and XML Web Services
System.ApplicationException,243–247
Chapter 18 - ASP.NET Web Pages and Web Controls
System.Array base class, 158–159 Chapter 19 - ASP.NET Web Applications System.Array type, 1005 Chapter 20 - XML Web Services Index System.AsyncCallback,345 List of Figures
System.Boolean members, 126
List of Tables
System.CharNext members, 127 System.Collections namespace, 130,306–315 class types of, 310–314 interfaces of, 306–310 System.Collections.Specialized namespace, 314–315 System.Collections.HashTable type, 121 System.Collections.Specialized.-ListDictionary,372 System.ComponentModel namespace, 798–799 System.ComponentModel.Component,790 System.ComponentModel.IComponent interface, 790 System.Configuration namespace, 446–447 System.Console class. Seeconsole class System.Console type, 824
System.Convert type, 293
C# and the .NET Platform, Second Edition
System.Data namespace, 850–852 by Andrew845, Troelsen
ISBN:1590590554
Apress namespace, © 2003 (1200 pages) System.Data.Common 850 This comprehensive text starts with a brief overview of the System.Data.Common.DataTableMapping type, 905 C# language and then quickly moves to key technical and
System.Data.DataRelation type, 879for .NET developers. architectural issues System.Data.dll assembly, 851 System.Data.IDbTransaction interface, 846 Table of Contents System.Data.Odbc namespace, 851 C# and the .NET Platform, Second Edition Introduction System.Data.OleDb namespace, 851,888 Part One - Introducing C# and the .NET Platform
System.Data.OracleClient namespace, 851
Chapter 1
- The Philosophy of .NET System.Data.OracleClient.dll assembly, 851 Chapter 2 - Building C# Applications Part System.Data.SqlClient Two - The C# Programming namespace, Language 851,887,906
Chapter 3 - C# Language Fundamentals type, 921 System.Data.SqlClient.SqlConnection Chapter 4 - Object-Oriented Programming with C#
System.Data.SqlServerCe namespace, 851
Chapter 5
- Exceptions and Object Lifetime System.Data.Sqlservice.dll assembly, 851 Chapter 6 - Interfaces and Collections
System.Data.SqlTypes namespace, 851,907 Chapter 7 - Callback Interfaces, Delegates, and Events Chapter 8 - Advancednamespace C# Type Construction System.Diagnostics members, Techniques 454–456 Part Three - Programming with .NET Assemblies
System.dll assembly, 609,805
Chapter 9
- Understanding .NET Assemblies
System.Double type, 126 Chapter 10 - Processes, AppDomains, Contexts, and Threads System.Drawing 673–675 Chapter 11 - Type namespace, Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging .NET675–679 Libraries System.Drawing utilitythe types,
Chapter 12 - Object disposal of, 680Serialization and the .NET Remoting Layer Chapter 13 - type, Building a Better Window (Introducing Windows Forms) Point(F) 675–676 Chapter 14 - A Better Painting Framework (GDI+) Rectangle(F) type, 677–678 Chapter Region 15 -class, Programming 678–679with Windows Forms Controls
Size(F) 678 Chapter 16 - types, The System.IO Namespace Chapter 17 - Data Accessstructure, with ADO.NET System.Drawing.Color 692 Part Five - Web Applications and XML Web Services
System.Drawing.dll, 951
Chapter 18 - ASP.NET Web Pages and Web Controls
System.Drawing.Drawing2D namespace overview, 705–720 Chapter 19 - ASP.NET Web Applications gradient brushes, 719–720 hatch style brushes, 715–717 Index pen caps, 711–713 List of Figures pen objects, 707–711 List of Tables rendering quality, 706–707 solid brushes, 713–715 textured brushes, 717–718 Chapter 20 - XML Web Services
System.Drawing.Font type, 695 System.Drawing.Graphics object, 675,685 System.Drawing.Image type, 720 System.Drawing.Text,701–703 System.Enum base class, 21,166–168 System.Environment class, 88–89 System.Exception base class, 234–235 System.Exception.StackTrace property, 239 System.Exception.TargetSite property, 238–239 System.GC types, 267–272
finalizable and disposable types, building, 268–269 C# and the .NET Platform, Second Edition forcing garbage collection, 270 by Andrew with, Troelsen generations, interacting 270–272 Apress © 2003 (1200 pages) members of, 268
ISBN:1590590554
This comprehensive text starts with a brief overview of the
System.Globalization.CultureInfo 292 moves to key technical and C# language and type, then quickly architectural issues for .NET developers. System.IO namespace, 805–841 abstract stream class, 818–822 BufferedStreams,822 Table of FileStreams, Contents 820 C# and the .NET Platform, members of, 819 Second Edition Introduction MemoryStreams,820–821 Part asynchronous One - Introducing IO, C# 833and the .NET Platform Chapter 1 The Philosophy of .NET BinaryReaders and BinaryWriters, 829–831 Chapter 2 Building C# Applications DirectoryInfo and FileInfo types, 806–810 Part TwoDirectoryInfo - The C# Programming Language type, 808–811 Chapter FileAttributes 3 - C# Language enumeration, Fundamentals 809–810 base class, 807–808 Chapter FileSystemInfo 4 - Object-Oriented Programming with C# FileInfo 814–818 Chapter 5 - class, Exceptions and Object Lifetime method,and 815–817 Chapter Open() 6 - Interfaces Collections members, 815–817 Chapter OpenRead(), 7 - Callback OpenWrite() Interfaces, Delegates, and Events OpenText(), CreateText(), AppendText() members, 817–818 Chapter 8 - Advanced C# Type Construction Techniques FileSystemWatcher class, 831–833 Part Three - Programming with .NET Assemblies members of, 806 Chapter 9 - Understanding .NET Assemblies overview of, 805–806 Chapter 10 - Processes, AppDomains, Contexts, and Threads static members of Directory class, 812–813 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming StreamWriters and StreamReaders, 822–826 Part Four - Leveraging the .NET Libraries text files, reading from, 825–826 Chapter 12 - Object Serialization and the .NET Remoting Layer text files, writing to, 824–825 Chapter 13 - Building a Better Window (Introducing Windows Forms) TextWriter core members, 823–824 Chapter 14 - A Better Painting Framework (GDI+) StringReader type, 828–829 Chapter 15 Programming with StringWriter type, 826–828Windows Forms Controls Chapter 16 - The System.IO subdirectories, creating,Namespace 811–812 Chapter 17 Data Access with ADO.NET System.IO.Stream class, 818–819 Part Windows Five - WebForms Applications and XML Web Services Car Logger application, 834–841 Chapter Add 18 - New ASP.NET Web Pages and Car logic, 837–838 Web Controls Chapter serialization 19 - ASP.NET logic, Web 838–840 Applications Chapter 20 - XML Web Services System.MarshalByRefObject Indexbase class, 568 List of Figures 562 members, List of Tables
System.MulticastDelegate, 326,328–329 System.Object base class, 115–122 default behaviors, overriding, 118–119 Equals(), overriding, 119–120 GetHashCode(), overriding, 120–122 static members of, 122 ToString(), overriding, 119 members, 116,563 System.Object.Equals().SeeEquals() System.Object.Finalize() method, 260–263 System.OverflowException type, 357 System.Random type, 143 System.Reflection namespace
dynamic invocation, 517–520 C# and the .NET Platform, Second Edition late binding, 517–520 ISBN:1590590554 by Andrew Troelsen members of, 511 Apress © 2003 (1200 pages) MethodBase defined within, 239 This comprehensive private assemblies and, 511–515text starts with a brief overview of the C# language and then quickly moves to key technical and class members, enumerating, 513–514 architectural issues for .NET developers. method parameters, enumerating, 514–515 referenced assemblies, enumerating types in, 513 shared assemblies, building, 516–517 Table of Contents System.Resources namespace, 733–737 C# and the .NET Platform, Second Edition *.resources file Introduction into .NET 736–737 Part Onebinding - Introducing C# assembly, and the .NET Platform Chapter building, 1 - The735–736 Philosophy of .NET
*.resx creating reading, 733–735 Chapter 2 file, - Building C#and Applications Part Two - The C# Programming 554 Language System.Runtime.Remoting.dll,
Chapter 3 - C# Language Fundamentals System.Runtime.Serialization namespace, 549 Chapter 4 - Object-Oriented Programming with C#
System.Runtime.Serialization.Formatters namespace, 544
Chapter 5
- Exceptions and Object Lifetime
System.Runtime.Serialization.Formatters.-Soap.dll, 547 Chapter 6 - Interfaces and Collections Chapter System.String 7 - Callback members, Interfaces, 160 Delegates, and Events Chapter 8 - Advanced C# Type Construction Techniques System.SystemException, 240–242 Part Three - Programming with .NET Assemblies
System.Text.Encoding object reference, 822
Chapter 9
- Understanding .NET Assemblies
System.Text.StringBuilder, 162–164 Contexts, and Threads Chapter 10 - Processes, AppDomains, Chapter System.Threading 11 - Type Reflection, namespace. Late See Binding, alsoand threads, Attribute-Based 476–480 Programming Part .NET Four -threads Leveraging and the legacy .NETCOM Libraries apartments,
479–480
naming 479 Chapter 12 - threads, Object Serialization and the .NET Remoting Layer select 476–477 Chapter 13 types, - Building a Better Window (Introducing Windows Forms) thread 477–478 Chapter 14 -class, A Better Painting Framework (GDI+) thread level, 480 Chapter 15 -priority Programming with Windows Forms Controls thread 478–479 Chapter 16 -statistics, The System.IO Namespace System.Threading.Interlocked type, 492–493 Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and Web Services System.Threading.Monitor type,XML 491–492
Chapter 18 - ASP.NET Web Pages and Web Controls
System.Threading.Timer type, 495
Chapter 19 - ASP.NET Web Applications
System.Type class, Chapter 20 - XML Web504–510 Services
members of, 505 obtaining type references, 505–506 List of Figures project example, 506–510 Index
List of Tables
System.ValueType,20,125 System.Version,513 System.Void type, 330–331 System.Web namespace, 953,1031 System.Web.Caching.Cache class, 1038 System.Web.HttpApplication type members, 1032 System.Web.HttpCookie type, 1048 System.Web.Services namespace, 1064–1065 System.Web.Services.Description namespace, 1084 System.Web.Services.Protocols.SoapHttp-ClientProtocol, 1089 System.Web.Services.WebMethod type, 1074 System.Web.Services.WebService base class, 1072–1073
System.Web.StateBag type, 1029
C# and the .NET Platform, Second Edition
System.Web.UI.Control type members, 985–990 by Andrew Troelsen adding and removing controls, 988–990 Apress © 2003 (1200 pages) contained controls, 986–988
ISBN:1590590554
This comprehensive text starts with a brief overview of the
System.Web.UI.HtmlControls, C# language and 1014, then 1016 quickly moves to key technical and architectural issues for .NET developers.
System.Web.UI.HtmlControls namespace, 941 System.Web.UI.LiteralControl type, 987
Table of Contents System.Web.UI.MobileControls namespace, 607 C# and the .NET Platform, Second Edition
System.Web.UI.Page base class, 949
Introduction
System.Web.UI.Page.Request 971 Part One - Introducing C# and theproperty, .NET Platform Chapter System.Web.UI.WebControl 1 - The Philosophy of type .NETmembers, 990–991 Chapter 2 - Building C# Applications type, 984 System.Web.UI.WebControl.Button Part Two - The C# Programming Language
System.Web.UI.WebControls namespace, 607,984
Chapter 3
- C# Language Fundamentals
System.Web.UI.WebControls.BaseValidator, Chapter 4 - Object-Oriented Programming with1006 C# Chapter System.Web.WebControl.TextBox 5 - Exceptions and Object Lifetime type, 984 Chapter 6 - Interfaces andnamespace, Collections 608, 644, 693 System.Windows.Forms Chapter 7 - Callback Interfaces, Delegates, and Events
System.Windows.Forms.Application class, 615–621 - Advanced C# Type Construction Techniques Application class example, 617–618 Part Three - Programming with .NET Assemblies ApplicationExit event, 619 Chapter 9 - Understanding .NET Assemblies core properties of, 616–617 Chapter 10 -of, Processes, AppDomains, Contexts, and Threads events 617 Chapter 11 Type Reflection, Late Binding, and Attribute-Based Programming methods,616 Part preprocessing Four - Leveraging the .NET Libraries messages with, 619–621 Chapter 8
Chapter 12 - Object Serialization and the .NET Remoting Layer
System.Windows.Forms.Button type, 752
Chapter 13 - Building a Better Window (Introducing Windows Forms)
System.Windows.Forms.ContainerControl, 637 Chapter 14 - A Better Painting Framework (GDI+) System.Windows.Forms.Control, 623–624, 744Controls Chapter 15 - Programming with Windows Forms Chapter 16 - The System.IO Namespace System.Windows.Forms.dll assembly, 609 Chapter 17 - Data Access with ADO.NET
System.Windows.Forms.Menu,644
Part Five - Web Applications and XML Web Services
System.Windows.Forms.SaveFileDialog type, 838 Chapter 18 - ASP.NET Web Pages and Web Controls System.Windows.Forms.Shortcut enumeration, 647 Chapter 19 - ASP.NET Web Applications Chapter 20 - XMLassembly, Web Services System.Xml.dll 548 Index
System.Xml.Serialization namespace, 1099
List of Figures List of Tables
Index T
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
tab order configuring, 768 and style sheets, 997
Table TableMappings of Contentsproperty, 848, 925 C# and the .NET Platform, Second Edition tables Introduction building HTML, 994–995 Part navigating One - Introducing C#related, and the880–883 .NET Platform between
Chapter 1 -property The Philosophy of .NET Tables (DataSets), 874 Chapter 2
- Building C# Applications TabStop and TabIndex properties, 637
Part Two - The C# Programming Language
tags, XML,- 77 C# Language Fundamentals
Chapter 3
TargetSite 238–239 Chapter 4 -property, Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime TCP channel Chapter 6 - 558 Interfaces and Collections defined, Chapter leveraging, 7 - Callback 578–579 Interfaces, Delegates, and Events Chapter 8 -cookies, Advanced C# Type Construction Techniques temporary defined, 1048 Part Three - Programming with .NET Assemblies
testing,1066–1069 - Understanding .NET Assemblies compiled .NET assembly, 1068–1069 Chapter 10 - Processes, AppDomains, Contexts, and Threads WSDL contract, 1068 Chapter 9
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
textFour files - Leveraging the .NET Libraries Part reading from, 825–826 writing to, 824–825
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Text type, Chapter 14 -701 A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls TextBoxes Chapter creating 16 - scrollable, The System.IO multiline Namespace (WebForms), 993
properties, 750Access with ADO.NET Chapter 17 - Data control, 749–752 Part TextBox Five - Web Applications and XML Web Services TextBoxBase typeWeb members, 749–750 Chapter 18 - ASP.NET Pages and Web Controls Chapter 19 - ASP.NET Web Applications TextReader Chapter - XML Web Services core20members, 825 Indextype, 822 List of Figures textual output, formatting, 106–107 List of Tables
textured brushes, 717–718
TextWriter class,822–824 core members, 823–824 this keyword, 183–184 Thread Local Storage (TLS), 453 threads.See alsoSystem.Threading namespace .NET threads and legacy COM apartments, 479–480 AppDomain,474–475 concurrency and thread synchronization, 475,487–490 defined, 341 multithreaded programming via delegates, 476 naming,479 primary, defined, 452
priority level, setting, 480 and the .NET Platform, Second Edition and processesC# under Win32, 451–453 ISBN:1590590554 by Andrew Troelsen safety and .NET base class libraries, 494 Apress © 2003 (1200 pages) secondary, creating, 481–484 text starts with a brief overview of the foregroundThis andcomprehensive background threads, 482–483 C# language and then quickly moves to key technical and VS .NET threads window, 483–484 architectural issues for .NET developers. select types, 476–477 statistics,478–479 class, 477–478 Tablethread of Contents thread set, 458–460 C# and the .NET Platform, Second Edition thread type, instance level members of, 478 Introduction thread-volatile operations, 475 Part One - Introducing C# and the .NET Platform Thread.CurrentContext property, 475 Chapter 1 - The Philosophy of .NET Thread.GetDomain method, 474 Chapter 2 - Building C# Applications threading example, 484–487 Part Two - The C# Programming Language clogging up primary thread, 485–486 Chapter 3 - C# Language Fundamentals Thread.Sleep() method, 486–487 Chapter 4 - Object-Oriented Programming with C# ThreadStart delegate, 481 Chapter 5 Exceptions and Object Lifetime worker,452–453 Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
throw keyword, 235–236,249–250
time-slice, 453 Chapter 8 -defined, Advanced C# Type Construction Techniques Part TimeOut Three property, - Programming 1046 with .NET Assemblies Chapter 9 - Windows Understanding .NET Assemblies Timer type, Forms, 658–659 Chapter 10 - Processes, AppDomains, Contexts, and Threads
TimerCallbacks, 494–496
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
ToolFour bars Part - Leveraging the .NET Libraries building, Chapter 12 - 660–664 Object Serialization and the .NET Remoting Layer adding images to Tool bar buttons, 663–664 at design time, 664–666 Chapter 14 - A Better Painting Framework (GDI+) ToolBar type properties, 660–661 Chapter 15 - Programming with Windows Forms Controls ToolBarButton type properties, 661
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 16 - The System.IO Namespace
ToolBoxBitmap 802ADO.NET Chapter 17 - Dataattribute, Access with Part ToolTips, Five - 769–770 Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls ToString() Chapter 19 - 826 ASP.NET Web Applications method, Chapter 20 - XML overriding, 119Web Services Index
tracing
List of Figures with , 1052–1053 List of Tables and debugging ASP.NET pages, 1020
TrackBar Control, 770–772 TranslateTransform() method, 688,691 transparent proxies, 556–557 transport protocol, XML Web, 1063 try/catch blocks, 236–237,247–249 type boundaries,403 CTS members, 22 definition,500 indexers,373–374 metadata, 499–504 .NET binary element, 397 documenting defining assembly, 502–503
examples of usage, 399 and the .NET Platform, Second Edition referencedC# assemblies, documenting, 503 ISBN:1590590554 by Andrew Troelsen string literals, documenting, 503–504 Apress © 2003 (1200 pages) typeRef, 502 viewing forThis Carcomprehensive type, 501–502text starts with a brief overview of the C# language and then quickly moves to key technical and viewing for EngineState enumeration, 500–501 architectural issues for .NET developers. references,500,505–506 element (WSDL), 1080 184–186 Tablevisibility, of Contents type ofthe employee, determining, C# and .NET Platform, Second 223–224 Edition Introduction typed DataSets Part defined, One - Introducing C# and the .NET Platform 927
Chapter 1 - The Philosophy at design time, 928–929of .NET Chapter 2 - Building C# Applications structure of, 929–931 Part Two - The C# Programming Language
TypeDef #n tokens, 500
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
TypeDefName tokens, 501
Type.GetCustomAttributes() method, 528 Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces typeof operator, 490 and Collections Chapter 7 502 - Callback Interfaces, Delegates, and Events typeRef, Chapter 8
- Advanced C# Type Construction Techniques
TypeRef #n tokens, 500
Part Three - Programming with .NET Assemblies
types 9 Chapter
- Understanding .NET Assemblies
conversions amongAppDomains, related class, 387 Chapter 10 - Processes, Contexts, and Threads interacting withReflection, WindowsLate Forms, 609–612 Chapter 11 - Type Binding, and Attribute-Based Programming via fixed keyword, Part pinning Four - Leveraging the .NET 365–366 Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index U
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the language and then quickly moves to key technical and UDDI (Discovery C# Service Protocol), 1062,1102–1105 architectural issues for .NET developers.
ufo.netmodule, 421–422 Unadvise() method, 324
Table of Contents
unboxing and boxing. Seeboxing and unboxing
C# and the .NET Platform, Second Edition
unchecked keyword, 358–359 Introduction Part One - Introducing C# and underflow and overflow, 356,the 359.NET Platform
Chapter 1
- The Philosophy of .NET Unicode encoding, 822
Chapter 2
- Building C# Applications
unit of measure default, 688–689 Chapter 3 - C# Language Fundamentals specifying alternative, 689–690
Part Two - The C# Programming Language
Chapter 4
- Object-Oriented Programming with C#
Unload5events, ASP.NET, Chapter - Exceptions and 978–979 Object Lifetime Chapter unloading 6 -AppDomains Interfaces and programmatically, Collections 468 Chapter 7 and - Callback Delegates, Unlock() Lock() Interfaces, methods, 1037, 1043 and Events Chapter 8
- Advanced C# Type Construction Techniques
unmanaged resources, 260
Part Three - Programming with .NET Assemblies
unsafe 9code, 359–366 Chapter - Understanding .NET Assemblies –> operator, 364 AppDomains, Contexts, and Threads Chapter 10 - Processes,
* and & parameters, 363 field access via pointers, 364 Part Four - Leveraging the .NET Libraries fixed keyword, 365–366 Chapter 12 - Object Serialization and the .NET Remoting Layer stackalloc keyword, 365 Chapter 13 - Building a Better Window (Introducing Windows Forms) swap function, unsafe and safe, 363–364 Chapter 14 - A Better Painting Framework (GDI+) unsafe keyword, 361–363
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 15 - Programming with Windows Forms Controls
untyped DataSets, defined, 927
Chapter 16 - The System.IO Namespace
Up/Down 774–776 Chapter 17 Controls, - Data Access with ADO.NET Part Five - Web Applications and XML Web Services Update() method, 848
Chapter 18 - ASP.NET Web Pages and Web Controls
UPDATE SQL statements, 848
Chapter 19 - ASP.NET Web Applications
UpdateGrid() method, 836
Chapter 20 - XML Web Services
updating records Index with OleDbCommand, 897–898 List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and valid overloadable operators, 385 architectural issues for .NET developers.
validation controls, 1005–1014 custom validation, 1010–1012 Tableproject of Contents example, 1006–1010 properties 1006 Second Edition C# and the .NETof, Platform, validation summaries, 1012–1014 Introduction Part One - Introducing C# and the .NET Platform value-based and reference-based types, 109–114
Chapter 1 - The of, Philosophy comparison 113–114of .NET Chapter 2 types - Building C# Applications value containing reference types, 112–113 Part Two - The C# Programming Language
value-based semantics, 119,125,168–169
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
value keyword, 194–195
value semantics, 118 and Object Lifetime Chapter 5 - Exceptions Chapter 6 - Interfaces and Collections value types and reference types, 128–132 Chapter - Callback Interfaces, Delegates, variable7 initialization syntax (C#), 104–105and Events Chapter 8
- Advanced C# Type Construction Techniques
variable scope and default assignments, 102–104
Part Three - Programming with .NET Assemblies
VB .NET Chapter 9 - Understanding .NET Assemblies C# indexer from, 374–375 Chapter 10 - Processes, AppDomains, Contexts, and Threads calculator, 15 Reflection, Late Binding, and Attribute-Based Programming Chapter 11 - Type 409–411 Part client Four -application, Leveraging the .NET Libraries
snap-in, building, 531–532 special names from, 384–385 Chapter 13 - Building a Better Window (Introducing Windows Forms) VB .NET and the .NET Platform (Apress, 2002), 412 Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 14 - A Better Painting Framework (GDI+)
VBCalculator applications, 14–15 Chapter 15 - Programming with Windows Forms Controls Chapter VbNetSnapIn.dll, 16 - The System.IO 530 Namespace Chapter 17944, - Data Access 950 with ADO.NET VBScript, 947–948, Part Five - Web Applications and XML Web Services
verbatim strings and escape characters, 161–162
Chapter 18 - ASP.NET Web Pages and Web Controls
versionable and self-describing entities (assemblies), 403 Chapter 19 - ASP.NET Web Applications Chapter versioning 20 - XML Web Services Indexclass members, 220–222
shared assemblies, 437–438 List of Figures 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# and the .NET Platform, Second Edition runtime module, 25 ISBN:1590590554 VB 6 IDE, 57 by Andrew Troelsen Apress © 2003 (1200 pages) VB 6.0 Object Browser utility, 520 This comprehensive text starts with a brief overview of the VB 6.0 programming, 4 C# language and then quickly moves to key technical and VB 6.0 Set keyword, 374 architectural issues for .NET developers.
volatile keyword, 366 VS .NET
TableAdd of Contents References dialog box, 449 C# and .NET Platform, utility, Second1095 Edition Addthe Web Reference Introduction Add Web Reference wizard, 1063 Part adding One - Introducing and the Platform controls to C# Forms with,.NET 747–749
Chapter 1 - Thestructure, Philosophy application 62of .NET Chapter 2 - Building C# AssemblyInfo.cs file,Applications 527 Part configuration Two - The C# files Programming Language and, 428–429
Chapter debugging 3 - C#system Language exceptions Fundamentals with, 253–256
editing documentsProgramming with, 942 with C# Chapter 4 -HTML Object-Oriented Enterprise edition, 921 Chapter 5 - Exceptions and Object Lifetime handling custom exceptions with, 255–256 Chapter 6 - Interfaces and Collections implementing interfaces with, 288–290and Events Chapter 7 - Callback Interfaces, Delegates, integrated debugger, Chapter 8 - Advanced C# 56 Type Construction Techniques checking, 358 Part overflow Three - Programming with .NET Assemblies
project -workspace, building, 612–615 Understanding .NET Assemblies Dispose() method, 614–615 Chapter 10 - Processes, AppDomains, Contexts, and Threads InitializeComponent(), 614–615 Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming referencing external assemblies via, 67–68 Part Four - Leveraging the .NET Libraries resource configuration with, 739–742 Chapter 12 - Object Serialization and the .NET Remoting Layer test application, building, 61–70 Chapter 13 - Building a Better Window (Introducing Windows Forms) adding code, 67 Chapter configuring 14 - A Better Painting Framework a C# project, 64–65 (GDI+) Chapter inserting 15 - Programming with Windows new C# type definitions,Forms 68–69Controls Chapter outlining 16 - The code, System.IO Namespace 69–70 Chapter properties 17 - Data Access with window, 66 ADO.NET Part Fivereferencing - Web Applications XML Web67–68 Services external and assemblies, Chapter solution 18 - ASP.NET Web Pages and Web explorer window, 62–64 Controls Chapter threads 19 - window, ASP.NET 483 Web Applications UDDI 1103–1105 Chapter 20 interaction - XML Webwith, Services Indexunsafe compilation, 361 VS .NET 2003, 45 List of Figures 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# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
Index W
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and warnings and errors, issuing, 86 architectural issues for .NET developers.
Watcher class (FileSystemWatcher). SeeFileSystemWatcher class Web applications. See alsoASP.NET Web applications
Tablecreating of Contents manually, 953–958 C# and the .NET Platform, Edition *.aspx file, coding,Second 954–958 Introduction directive, 955
Part One - Introducingdirective, C# and the .NET Platform 955–956
Chapter script 1 - The Philosophy of .NET blocks, 956–957 Chapter widget 2 - Building C# Applications declarations, 957–958 Part creating Two - The C# VS Programming Language with .NET, 961–966
Chapter code 3 - C# behind Language file, 965–966 Fundamentals
*.aspx file, 964–965 Chapter initial 4 - Object-Oriented Programming with C# defined, 939 and Object Lifetime Chapter 5 - 936, Exceptions shutdown, 1037 Chapter 6 - Interfaces and Collections and7Web servers,Interfaces, 936–938 Delegates, and Events Chapter - Callback Chapter Web controls, 8 - Advanced ASP.NET C# Type Construction Techniques Part overview Three - Programming of, 982–985 with .NET Assemblies
property, Chapter AutoPostBack 9 - Understanding .NET 984–985 Assemblies event handling, 983–984 Chapter server-side 10 - Processes, AppDomains, Contexts, and Threads System.Web.UI.Control members, Chapter 11 - Type Reflection, type Late Binding, and985–990 Attribute-Based Programming adding and removing controls, Part Four - Leveraging the .NET Libraries988–990 controls, 986–988 Chapter contained 12 - Object Serialization and the .NET Remoting Layer System.Web.UI.WebControl type(Introducing members, 990–991 Chapter 13 - Building a Better Window Windows Forms) toolbox,966 validation controls, 1005–1014 Chapter 15 - Programming with Windows Forms Controls custom validation, 1010–1012 Chapter 16 - The System.IO Namespace project example, 1006–1010 Chapter 17 - Data Access with ADO.NET properties of, 1006 Part Five - Web Applications and XML Web Services validation summaries, 1012–1014 Chapter 18 - ASP.NET Web Pages and Web Controls WebForm controls, examples of, 991–1005 Chapter DataGrids. 19 - ASP.NET Applications SeeWeb DataGrids, ADO.NET Chapter feature-rich 20 - XML Web Services controls, 995–997 Index HTML tables, building, 994–995 List of Figures ListBox controls, 992 List of Tables radio button types, 992–993 scrollable, multiline TextBoxes, 993 Chapter 14 - A Better Painting Framework (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. Web pages C# andSee theASP.NET .NET Platform, Second Edition Web servers ISBN:1590590554 by Andrew Troelsen defined, 936–937 Apress © 2003 (1200 pages) GDI+ on, 1016–1019 This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and Web services, XML. SeeXML Web services architectural issues for .NET developers.
Web sites .NET and non-Microsoft OS, 40–41 Table.NET-aware of Contentsprogramming languages, 10 ASP .NET Web Matrix, C# and the .NETIDE Platform, Second90 Edition C# compiler (csc.exe) download, 43 Introduction support article, 1063 Part DISCO One - Introducing C# and the .NET Platform Dotnetfx.exe package (Microsoft), 40 Chapter 1 - The Philosophy of .NET hyperthreading, 453 Chapter 2 - Building C# Applications IDE, 89 Part SharpDevelop Two - The C# Programming Language WebService behaviors article, 1061 Chapter 3 - C# Language Fundamentals web.config 1050–1057 Programming with C# Chapter 4 - file, Object-Oriented configuring session and stateObject with, Lifetime 1077 Chapter 5 - Exceptions custom settings , 1057 Chapter 6 - Web Interfaces andwith Collections elements of, 1052Interfaces, Delegates, and Events Chapter 7 - Callback
error output with , 1053–1054 - Advanced C# Type Construction Techniques storing state with , 1054–1056 Part Three - Programming with .NET Assemblies tracing with , 1052–1053 Chapter 8 Chapter 9
- Understanding .NET Assemblies
WebControl base classAppDomains, properties, 990–991 Chapter 10 - Processes, Contexts, and Threads Chapter 11 -controls, Type Reflection, Late and Attribute-Based Programming WebForm examples of,Binding, 991–1005 Part DataGrids. Four - Leveraging the .NETADO.NET Libraries SeeDataGrids,
Chapter feature-rich 12 - Object controls, Serialization 995–997 and the .NET Remoting Layer
HTML building, 994–995 Chapter 13 tables, - Building a Better Window (Introducing Windows Forms) ListBox 992 Chapter 14 -controls, A Better Painting Framework (GDI+) radio types, 992–993 Chapter 15button - Programming with Windows Forms Controls scrollable, multiline TextBoxes, 993 Chapter 16 - The System.IO Namespace Chapter [WebService] 17 - Data attribute, Access1077–1078 with ADO.NET Part Five - Web Applications and XML directive, 1066Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
while and do/while looping constructs, 136–137
Chapter 19 - ASP.NET Web Applications
widget 20 declarations, Chapter - XML WebASP.NET, Services 957–958 Index wildcard character (*), 50 List of Figures 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 and the .NET Platform, Second Edition Control class,C# 623–627, 633–636 ISBN:1590590554 by Andrew Troelsen Control class example, 634–635 Apress © 2003 (1200 pages) control methods, 634 This comprehensive Form styles, setting, 624–626 text starts with a brief overview of the C# language and then quickly moves to key technical and members of, 624 architectural issues for .NET developers. painting basics, 635–636 properties of, 623,633 Control events, 627–631 Table of Contents control class example, 627–628 C# and the .NET Platform, Second Edition Mouse events, responding to, 628–631 Introduction MouseEventArgs type properties, 629 Part One - Introducing C# and the .NET Platform controls,683–684 Chapter 1 - The Philosophy of .NET example,914–916 Chapter 2 - Building C# Applications Form class, 637–640 Part Two - The C# Programming Language example,639–640 Chapter 3 - C# Language Fundamentals key methods of, 638–639 Chapter properties 4 - Object-Oriented Programming with C# of, 638 Chapter select 5 - Exceptions and Object Lifetime events of, 639 Chapter 6 Interfaces and Collections Form level events, handling with VS .NET, 643–644 Chapter 7 -anatomy Callback of, Interfaces, Forms, 621–622Delegates, and Events Chapter - Advanced C# Type Construction Techniques GUI8namespaces, 607–608 Part Keyboard Three - Programming with .NETto, Assemblies events, responding 631–633 Chapter MDI9applications, - Understanding building, .NET666–669 Assemblies 668 AppDomains, Contexts, and Threads Chapter child 10 - Form, Processes, 668–669 Chapter child 11 - windows, Type Reflection, Late Binding, and Attribute-Based Programming parent Form, 666–667 Part Four - Leveraging the .NET Libraries menus Chapter 12 - Object Serialization and the .NET Remoting Layer with VS .NET,Window 654–655 Chapter building 13 - Building a Better (Introducing Windows Forms) menu system, building, 646–649 Chapter 14 - A Better Painting Framework (GDI+) MenuItem type properties, 651–653 Chapter 15 - Programming with Windows Forms Controls pop-up, creating, 649–651 Chapter 16 - The System.IO Namespace ScrollableControl class, 636–637 Chapter 17 - Data Access with ADO.NET Status bars, 655–660 Part Five - Web Applications and XML Web Services building,656–657 Chapter 18 - ASP.NET Web Pages and Web Controls menu selection prompts, 659–660 Chapter 19 - ASP.NET Web Applications select properties of, 655 Chapter StatusBarPanel 20 - XML Web Services type properties, 656 Index Timer type, 658–659 List of Figures 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# and the .NET Platform, Second Edition InitializeComponent(), 614–615 ISBN:1590590554 bytype Andrew Troelsen Windows Form life-cycle, 640–643 Apress © 2003 (1200 pages) Form life time events, 640–641 Thisexample, comprehensive text starts with a brief overview of the Form lifetime 642–643 C# language and then quickly moves to key technical and
Windows Forms Controls, 743–803 architectural issues for .NET developers. adding to Forms, 744–747 adding to Forms with VS .NET, 747–749 Tableanchoring of Contents behavior, configuring, 779–780 animation, 796 C# and the .NET Platform, Second Edition assigning ToolTips to, 769–770 Introduction type, 752–755 Part Button One - Introducing C# and the .NET Platform configuring, Chapter content 1 - Theposition, Philosophy of .NET 753 754–755 Chapter example, 2 - Building C# Applications Part CarControl Two - The C# Programming Language defining, 794 Chapter custom 3 - C#events, Language Fundamentals custom properties, defining, 794–796 Chapter 4 - Object-Oriented Programming with C# design time appearance of, 800–803 Chapter 5 - Exceptions and Object Lifetime implementing, 792–796 Chapter 6 - Interfaces and Collections testing,797–798 Chapter 7 - Callback Interfaces, Delegates, and Events CheckBoxes, 755–756 Chapter 8 - Advanced C# Type Construction Techniques custom dialog boxes, building, 781–787 Part Three - Programming with .NET Assemblies application example, 782–785 Chapter DialogResult 9 - Understanding .NET Assemblies property, 785 Chapter grabbing 10 - Processes, AppDomains, data from, 785–787Contexts, and Threads Chapter 11 Type Reflection, Late Binding, and Attribute-Based Programming custom UserControl, building, 790–791 Part custom Four - Leveraging the .NET Libraries Windows Forms Controls, building, 789–790 Chapter 12 - Object DateTime type, Serialization 766–767 and the .NET Remoting Layer Chapter 13 Building a Better default input Button, 767 Window (Introducing Windows Forms) Chapter design 14 -time A Better GUI, Painting building,Framework 792 (GDI+) docking configuring, 780–781 Chapter 15 - behavior, Programming with Windows Forms Controls DomainUpDown and NumericUpDown Controls, 774–776 Chapter 16 - The System.IO Namespace ErrorProvider type, 776–778 Chapter 17 - Data Access with ADO.NET 787–789 Part Form Five - inheritance, Web Applications and XML Web Services hierarchy of, 743–744 Chapter 18 - ASP.NET Web Pages and Web Controls images, 791 Applications Chapter 19 - creating, ASP.NET Web ListBoxes and ComboBoxes, 761–763 Chapter 20 - XML Web Services MonthCalendar Control, 763–766 Index Panel Controls, 773 List of Figures 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 and the .NET Platform, Second Edition Data Adapter C# Configuration, 922–926 ISBN:1590590554 by Andrew Troelsen Data Adapters and design time connections, 926–927 Apress © 2003 (1200 pages) Property Builder, 1000 This comprehensive text starts with a brief overview of the Solutions Explorer, 919–921 C# language and then quickly moves to key technical and SQL connection, 921–922 architectural issues for .NET developers. Tab Order, 768 WKO (Well Known Object) types Tableactivation of Contents mode of, 576–577
CAO/WKO-singleton objects,Edition 589–595 C# and the .NET Platform, Second characteristics of, 587 Introduction of, 565 Part configuration One - Introducing C# and the .NET Platform defined, Chapter 1 - 564 The Philosophy of .NET Chapter 2 - Building C# Applications WM_LBUTTONDOWN message, 619–621 Part Two - The C# Programming Language
WNDCLASSEX structure, 624
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
worker threads, 452–453
write-only read-only properties, 197–198 Chapter 5 and - Exceptions and Object Lifetime Chapter 6 method, - Interfaces WriteTo() 821and Collections Chapter 7 Callback Interfaces, Delegates, and Events WriteXml() method, 883 Chapter 8
- Advanced C# Type Construction Techniques
WriteXmlSchema() method, 885
Part Three - Programming with .NET Assemblies
Writing9Add-Ins for VS .NET (Apress, 2002), 534 Chapter - Understanding .NET Assemblies Chapter - Processes, AppDomains, Contexts, and Threads WSDL 10 (Web Service Description Language) Chapter contract, 11 - Type 1068Reflection, Late Binding, and Attribute-Based Programming Part defined, Four - Leveraging 1063 the .NET Libraries
document format, 1079–1082 Chapter 12 - Object Serialization and the .NET Remoting Layer element, 1082 Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Betterelement, Painting 1081 Framework (GDI+)
element, 1081 Chapter 15 - Programming with Windows Forms Controls element, 1082 Chapter 16 - The System.IO Namespace
element, 1080 fundamentals of, 1078–1079 Part Five - Web Applications and XML Web Services name clashes, 1074–1075 Chapter 18 - ASP.NET Web Pages and Web Controls transforming into C# code, 1089–1091 Chapter 19 - ASP.NET Web Applications proxy code, 1089–1091 Chapter 20 - XML Web Services wrapping proxy type in .NET namespace, 1091 Index wsdl.exe command line utility, 1079,1084–1086 Chapter 17 - Data Access with ADO.NET
List of Figures List of Tables
Index X
C# and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
ISBN:1590590554
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and XML (Extension Markup Language) architectural issues for .NET developers.
configuration files, 426–429 data representation Table of configuring Contents in DataColumns, 857–858 passing information with, 1060 C# and the .NET Platform, Second Edition documenting source code via, 76–79 Introduction files, viewing generated, 79–81 Part One - Introducing C# and the .NET Platform format characters, 80 Chapter 1 - The Philosophy of .NET formatter (serialization), 548 Chapter 2 - Building C# Applications XML-based DataSets, 883–885 Part Two - The C# Programming Language XML-related editing tools, 72–73 Chapter 3
- C# Language Fundamentals
XML Web -services, 1059–1105 Object-Oriented Programming with C# arrays of Web method types, 1096–1097 Chapter 5 - Exceptions and Object Lifetime building manually, 1065–1066 Chapter 6 - Interfaces and Collections building with VS .NET, 1069–1072 Chapter 7 - Callback Interfaces, Delegates, and Events adding functionality, 1071 Chapter 8 - Advanced C# Type Construction Techniques CalcWS Web methods, 1071–1072 Part Three - Programming with .NET Assemblies code behind file (*.asmx.cs), 1070–1071 Chapter 9 - Understanding .NET Assemblies CarSalesInfoWS project, 1100–1102 Chapter 10 Processes, AppDomains, Contexts, and Threads custom types Chapter consuming, 11 - Type Reflection, Late Binding, and Attribute-Based Programming 1099–1100 Part Four Leveraging the .NET Libraries exposing,1098–1099 Chapter 12 - Object Serialization description service, 1063 and the .NET Remoting Layer Chapter 13 Building a Better Window (Introducing Windows Forms) discovery service, 1062–1063 Chapter generating 14 - A Better proxy Painting with VS Framework .NET, 1095(GDI+) hard-coded proxy logic, 1094 Chapter 15 - Programming with Windows Forms Controls HelloWS WSDL document, 1082–1084 Chapter 16 - The System.IO Namespace invocations Chapter 17 - Data Access with ADO.NET 1093–1094 Part Fiveasynchronous, - Web Applications and XML Web Services Chapter synchronous, 18 - ASP.NET1092–1093 Web Pages and Web Controls namespaces, 1064 Chapter 19 - ASP.NET Web Applications overview of, 1059–1061 Chapter 20 - XML Web Services System.Web.Services namespace, 1064–1065 Index System.Web.Services.WebService base class, 1072–1073 List of Figures 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# and the .NET Platform, Second Edition element, 1081 ISBN:1590590554 byelement, Andrew Troelsen 1081 Apress © 2003 (1200 pages) element, 1082 This comprehensive text starts with a brief overview of the element, 1080 C# language and then quickly moves to key technical and WSDL fundamentals, 1078–1079 architectural issues for .NET developers. WSDL, transforming into C# code, 1089–1091 proxy code, 1089–1091 Table of wrapping Contentsproxy type in .NET namespace, 1091 wsdl.exe command line utility, 1084–1086 C# and the .NET Platform, Second Edition XMLSerializer data type, 1098–1099 Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables
C# and the .NET Platform, Second Edition List of Figures by Andrew Troelsen
ISBN:1590590554
Apress © 2003 (1200 pages)
Chapter 1: This Thecomprehensive Philosophy of .NET text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues .NET developers. Figure 1-1: The CLR, CTS, CLSfor base class library relationship
Figure 1-2: All .NET-aware compilers emit IL instructions and metadata. Table of Contents
Figure 1-3: Platform, mscoree.dll in action C# and the .NET Second Edition Introduction
Figure 1-4: The base class libraries
Part One - Introducing C# and the .NET Platform
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 Part Two - The C#Viewing Programming Language Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Figure 1-7: Dumping namespace information to file
Chapter 5 - 1-8: Exceptions andCIL Object Lifetime Figure Dumping to file Chapter 6
- Interfaces and Collections
Figure Viewing type metadata viaand ildasm.exe Chapter 7 - 1-9: Callback Interfaces, Delegates, Events Chapter 8
- Advanced C# Type Construction Techniques
Figure 1-10: Double click here to view the assembly manifest.
Part Three - Programming with .NET Assemblies
Chapter 9 - 1-11: Understanding .NET using Assemblies Figure Viewing types the ClassViewer Web application Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure with wincv.exe Chapter 11 - 1-12: Type Working Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 2: Building C# Applications
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - 2-1: A Better Painting the Framework (GDI+) Figure Establishing path to csc.exe Chapter 15 - Programming with Windows Forms Controls
Figure TestApp in action Chapter 16 - 2-2: The The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Figure 2-3: Your first Windows Forms application
Part Five - Web Applications and XML Web Services
Chapter 18 - 2-4: ASP.NET Webthe Pages andresponse Web Controls Figure Behold, default file Chapter 19 - ASP.NET Web Applications
Figure Chapter 20 - 2-5: XMLDocumenting Web Services the bug Index
Figure 2-6: The entire bug report
List of Figures
List ofFigure Tables2-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# and the .NET Platform, Second Edition
Troelsen dialog box Figure 2-17: by TheAndrew Add References
ISBN:1590590554
Apress © 2003 (1200 pages)
Figure 2-18: This Collapsing the SayHi() comprehensive textmethod starts with a brief overview of the C# language and then quickly moves to key technical and
Figure 2-19: architectural Setting breakpoints issues for .NET developers. Figure 2-20: The Server Explorer window Table of Contents
Figure 2-21: The integrated XML editor
C# and the .NET Platform, Second Edition
Introduction Figure 2-22: The integrated Object Browser Part One - Introducing C# and the .NET Platform
Figure Integratedofdatabase editors Chapter 1 - 2-23: The Philosophy .NET Chapter 2
- Building C# Applications
Figure 2-24: Visual Studio .NET Integrated Help
Part Two - The C# Programming Language
Chapter 3 - 2-25: C# Language Fundamentals Figure Remember, F1 is your friend. Chapter 4 - Object-Oriented Programming with C#
Figure Again,and F1 Object is yourLifetime friend. Chapter 5 - 2-26: Exceptions Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Figure 2-27: Specifying the XML documentation file via VS .NET
Chapter 8 - 2-28: Advanced C# Type Construction Techniques Figure XmlCarDoc.xml Part Three - Programming with .NET Assemblies
Figure Configuration your HTML-based documentation Chapter 9 - 2-29: Understanding .NET of Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure 2-30: The generated XmlCarDoc online documentation
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries Figure 2-31: Regions at work
Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure Configuring debug or release builds Chapter 13 - 2-32: Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Figure 2-33: Setting project-wide symbols
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - 2-34: The System.IO Namespace Figure Viewing line numbers within VS .NET Chapter 17 - Data Access with ADO.NET
Figure 2-35: Obtaining and various Part Five - Web Applications XMLenvironment Web Servicesvariables Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 3: C# Language Fundamentals
Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services
IndexFigure 3-1: Supplying and processing command line arguments List of Figures
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 in action and the System.Object .NET Platform,members Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
Figure 3-13: The hierarchy of System types
ISBN:1590590554
comprehensive text starts with a brief overview of the Figure 3-14: This Random teenager chatter C# language and then quickly moves to key technical and
foramong .NET developers. Figure 3-15: architectural Static data isissues shared like objects.
Figure 3-16: Passing reference types by value locks the reference in place. Table of Contents
Figure 3-17: PassingSecond reference types by reference allows the reference to be redirected. C# and the .NET Platform, Edition Introduction
Figure 3-18: A multidimensional array
Part One - Introducing C# and the .NET Platform
Chapter 1 - 3-19: The Philosophy of .NET Figure Jagged arrays Chapter 2
- Building C# Applications
Figure 3-20: Fun with System.Array Part Two - The C# Programming Language Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Figure 3-21: Configuring the default namespace
Chapter 4: Object-Oriented Programming with C# - Interfaces and Collections
Chapter 6 Chapter 7
- Callback Interfaces, Delegates, and Events
Figure A simple definition Chapter 8 - 4-1: Advanced C# class Type Construction Techniques Part Three - Programming with .NET Assemblies
Figure 4-2: Internal and public types
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - 4-3: Processes, AppDomains, Contexts, and Threads Figure The "is-a" relationship Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 4-4: The "has-a" relationship Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure 4-5: Classical polymorphism
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - 4-6: A Better Painting Framework (GDI+) Figure Ad hoc polymorphism Chapter 15 - Programming with Windows Forms Controls
Figure value of "value" when setting EmpID to 81 Chapter 16 - 4-7: The The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Figure 4-8: Properties map to hidden get_ and set_ methods.
Part Five - Web Applications and XML Web Services
Chapter 18 - 4-9: ASP.NET Web Pageshierarchy and Web Controls Figure The employee Chapter 19 - ASP.NET Web Applications
Figure The Services extended employee hierarchy Chapter 20 - 4-10: XML Web Index
Figure 4-11: The contained Radio in action
List of Figures
List ofFigure Tables4-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# and the .NET Platform, Second Edition
TroelsenWizard Figure 4-22: by TheAndrew Add Member
ISBN:1590590554
Apress © 2003 (1200 pages) comprehensiveand text starts with a brief overview of the Chapter 5: This Exceptions Object Lifetime C# language and then quickly moves to key technical and architectural issues for .NET developers.
Figure 5-1: Dealing with the error using structured exception handling 5-2: Obtaining detailed error information Table Figure of Contents C# and the .NET Platform, Second Edition
Figure 5-3: Identifying the exceptions thrown from a given method
Introduction
Part One - Introducing C# and thesystem .NET Platform Figure 5-4: Application and exceptions
Chapter 1
- The Philosophy of .NET Figure You C# have just entered no-man's land. Chapter 2 - 5-5: Building Applications Part Two - The C# Programming Language
Figure 5-6: Preparing to enable VS .NET exception handling
Chapter 3
- C# Language Fundamentals
Chapter 4 - 5-7: Object-Oriented Programming Figure The CLR exception set with C# Chapter 5
- Exceptions and Object Lifetime Figure Specifying VS .NET exception support for a given exception Chapter 6 - 5-8: Interfaces and Collections Chapter 7
Callback Interfaces, Delegates, and Events Figure- 5-9: Enabling your custom application exceptions via VS .NET
Chapter 8
- Advanced C# Type Construction Techniques
Part Three .NET Assemblies Figure- Programming 5-10: Handlingwith your custom application
Chapter 9
exceptions via VS .NET
- Understanding .NET Assemblies
Figure Reference types are allocated onThreads the managed heap. Chapter 10 - 5-11: Processes, AppDomains, Contexts, and Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 5-12: Finalizers are called automatically upon application shutdown.
Part Four - Leveraging the .NET Libraries
Chapter 12 - 5-13: ObjectThe Serialization and the .NET Remoting Layer Figure interplay of finalization and disposal Chapter 13 - Building a Better Window (Introducing Windows Forms)
Figure Influencing an object's (GDI+) current generation Chapter 14 - 5-14: A Better Painting Framework Chapter 15 - Programming with Windows Forms Controls
Chapter 6: Interfaces and Collections
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Part Five Figure - Web 6-1:Applications The updated and shapes XML Web hierarchy Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Figure 6-2: Dynamically determining implemented interfaces
Chapter 19 - ASP.NET Web Applications
Chapter 20 - 6-3: XMLInterfaces Web Services Figure as parameters Index List ofFigure Figures6-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# and the .NET Platform, Second Edition
Troelsen Figure 6-15: by TheAndrew updated Cars container
ISBN:1590590554
Apress © 2003 (1200 pages) comprehensive text starts with a brief overviewand of theEvents Chapter 7: This Callback Interfaces, Delegates, C# language and then quickly moves to key technical and architectural issues for .NET developers.
Figure 7-1: An interface-based event protocol 7-2: The C# "delegate" keyword represents a sealed type deriving from Table Figure of Contents System.MulticastDelegate.
C# and the .NET Platform, Second Edition Introduction Figure 7-3: Dynamically "pointing to" various methods Part One - Introducing C# and the .NET Platform
Chapter Figure 1 - 7-4: The Remember! Philosophy ofC# .NET delegate types alias System.MulticastDelegate Chapter 2
- Building C# Applications
Figure 7-5: the buck Part Two - The C#Passing Programming Language Chapter 3
C# Language Fundamentals Figure- 7-6: Passing the buck yet again
Chapter 4
- Object-Oriented Programming with C#
Chapter Figure 5 - 7-7: Exceptions Asynchronous and Object invocations Lifetime increase program responsiveness. Chapter 6
- Interfaces and Collections
Figure- 7-8: Asynchronous invocations via callbacks Callback Interfaces, Delegates, and Events
Chapter 7
Chapter 8 - 7-9: Advanced C#into Type Construction Techniques Figure Hooking the engine events Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 8: Advanced C# Type Construction Techniques
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 8-1: Enabling VS .NET overflow checking
Part Four - Leveraging the .NET Libraries
Chapter 12 - 8-2: Object Serialization and unsafe the .NET Remoting Layer Figure Enabling VS .NET compilation Chapter 13 - Building a Better Window (Introducing Windows Forms)
Figure Internal CIL representation of overloaded operators Chapter 14 - 8-3: A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Figure 8-4: CIL representation of user-defined conversion routines
Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Chapter 9: Understanding .NET Assemblies
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Figure Assembly Win32 header file information Chapter 19 - 9-1: ASP.NET Web Applications Chapter 20 - XML Web Services
Figure 9-2: A single file assembly
Index
List ofFigure Figures9-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# and the .NET Platform, Second Edition
ISBN:1590590554 Andrew Troelsen Figure 9-14: by Type metadata for the types within carlibrary.dll
Apress © 2003 (1200 pages)
Figure 9-15: This Yourcomprehensive multifile assembly text starts with a brief overview of the C# language and then quickly moves to key technical and
Figure 9-16: architectural The ufo.netmodule issues for .NET developers.
Figure 9-17: A single module of the multifile assembly Table of Contents
Figure 9-18: *.netmodules are loaded on demand.
C# and the .NET Platform, Second Edition
Introduction Figure 9-19: Relocating CarLibrary.dll into a specific subdirectory Part One - Introducing C# and the .NET Platform
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
Part Two - The C# Programming Language
Chapter 3 - 9-22: C# Language Fundamentals Figure The Global Assembly Cache Chapter 4 - Object-Oriented Programming with C#
Figure Using and sn.exe to generate Chapter 5 - 9-23: Exceptions Object Lifetime the public/private key pair file Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Figure 9-24: A strongly named assembly documents the public key in the manifest.
Chapter 8 - 9-25: Advanced C# Type named, Construction Techniques Figure Our strongly shared assembly (version 1.0.0.0) Part Three - Programming with .NET Assemblies
Figure Freezing .NET the current version of SharedAssembly.dll Chapter 9 - 9-26: Understanding Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure 9-27: Side-by-side execution
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging .NETGAC Libraries Figure 9-28: The the hidden subdirectory
Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure Inside the hidden \SharedAssembly subdirectory Chapter 13 - 9-29: Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Figure 9-30: Behold! The GAC's internal copy of sharedassembly.dll
Chapter 15 - Programming with Windows Forms Controls Chapter 16 - 9-31: The System.IO Namespace Figure Our publisher policy assembly Chapter 17 - Data Access with ADO.NET
Figure 9-32: The .NET and administration utility Part Five - Web Applications XML Web Services Chapter 18 - ASP.NET Web Pages and Web Controls
Figure 9-33: Declaratively building a *.config file
Chapter 19 - ASP.NET Web Applications
Chapter 20 - 9-34: XML Web ServicesCarLibrary.dll to VS .NET developers Figure Suggesting Index
Chapter 10: Processes, AppDomains, Contexts, and Threads
List of Figures 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 object's context and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
Figure 10-11: Your first multithreaded application
ISBN:1590590554
text starts with a brief overview of the Figure 10-12:This Thecomprehensive VS .NET Threads window C# language and then quickly moves to key technical and
issues .NET developers. Figure 10-13:architectural Two threads eachfor performing a unit of work
Figure 10-14: Possible output of the MultiThreadSharedData application Table of Contents
Figure 10-15: Another possible output of the MultiThreadSharedData application C# and the .NET Platform, Second Edition Introduction
Figure 10-16: Consistent output of the MultiThreadSharedData application
Part One - Introducing C# and the .NET Platform
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: The (very useful) console-based Part Two - The C# Programming Language Chapter 3
clock application
- C# Language Fundamentals
- Object-Oriented Programming withLate C# Chapter 11: Type Reflection, Binding, and Attribute-Based Chapter 5 - Exceptions and Object Lifetime Programming Chapter 6 - Interfaces and Collections Chapter 4
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Figure 11-1: Viewing an assembly's metadata
Part Three with Figure- Programming 11-2: Reflecting on.NET FooAssemblies
Chapter 9
- Understanding .NET Assemblies
Figure Reflecting on a private assembly Chapter 10 - 11-3: Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 11-4: Late bound method invocation
Part Four - Leveraging the .NET Libraries
Chapter 12 - 11-5: ObjectAttributes Serialization and the .NET Remoting Layer Figure in action Chapter 13 - Building a Better Window (Introducing Windows Forms)
Figure Attributes via ildasm.exe Chapter 14 - 11-6: A Better Paintingseen Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Figure 11-7: Metadata value
Chapter 16 - The System.IO Namespace Chapter 17 - 11-8: Data Access with ADO.NET Figure Input for a snap-in module Part Five - Web Applications and XML Web Services
Figure Snapping in external assemblies Chapter 18 - 11-9: ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Chapter 12: Object Serialization and the .NET Remoting Layer
Chapter 20 - XML Web Services Index
List ofFigure Figures12-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# and the .NET Platform, Second Edition
Andrew Troelsen Figure 12-12:bySingleton WKOs are shared among remote ISBN:1590590554 clients. Apress © 2003 (1200 pages)
Figure 12-13:This Single call WKOs text maintain one-to-one relationship with their remote clients. comprehensive startsawith a brief overview of the C# language and then quickly moves to key technical and
Figure 12-14:architectural The defaultissues lease for information for CarProvider .NET developers.
Figure 12-15: Altering lease timing via a server-side *.config file Table of Contents
Figure 12-16: Creating a new Windows Service project workspace
C# and the .NET Platform, Second Edition
Introduction Figure 12-17: Including an installer for the custom Windows Service Part One - Introducing C# and the .NET Platform
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)
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4 - 13-1: Object-Oriented Programming with C# Figure The minimal set of assembly references Chapter 5
- Exceptions and Object Lifetime Figure A simple main window a la Windows Forms Chapter 6 - 13-2: Interfaces and Collections Chapter 7
Callback Interfaces, Delegates, and Events Figure- 13-3: Specifying /t—winexe within VS .NET
Chapter 8
- Advanced C# Type Construction Techniques
Part Three with .NET Assemblies Figure- Programming 13-4: The Windows Forms project
Chapter 9
workspace
- Understanding .NET Assemblies
Figure The Form DesignerContexts, and Threads Chapter 10 - 13-5: Processes, AppDomains, Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 13-6: The Properties window provides design time editing support.
Part Four - Leveraging the .NET Libraries
Chapter 12 - 13-7: ObjectReading Serialization and the Remoting Layer Figure attributes via.NET the Application type Chapter 13 - Building a Better Window (Introducing Windows Forms)
Figure ThePainting derivation of a custom Form Chapter 14 - 13-8: A Better Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Figure 13-9: ControlStyles.ResizeRedraw = false
Chapter 16 - The System.IO Namespace
Chapter Figure 17 - 13-10: Data Access ControlStyles.ResizeRedraw with ADO.NET = true Part Five - Web Applications and XML Web Services
Figure Intercepting Chapter 18 - 13-11: ASP.NET Web Pageskey andpresses Web Controls Chapter 19 - ASP.NET Web Applications
Figure 13-12: Scroll Form GUI
Chapter 20 - XML Web Services
IndexFigure 13-13: Form events List of Figures
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 ToolBar buttons and theimages .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
Figure 13-25: The parent window's menu system
ISBN:1590590554
comprehensive text starts with a brief overview of the Figure 13-26:This Spawning child windows C# language and then quickly moves to key technical and architectural issues for .NET developers.
Chapter 14: A Better Painting Framework (GDI+) Table Figure of Contents 14-1: A simple GDI+ application C# and the .NET Platform, Second Edition
Figure 14-2: The default coordinate system of GDI+ Introduction Part One - Introducing C# and the .NET Platform
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 Part Two - The C# Programming Language
Figure The result of applying page offsets Chapter 3 - 14-5: C# Language Fundamentals Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Figure 14-6: Altering coordinate and measurement modes
Chapter 6 - 14-7: Interfaces and Collections Figure The stock .NET color dialog Chapter 7 - Callback Interfaces, Delegates, and Events
Figure Gathering statistics of the Verdana font family Chapter 8 - 14-8: Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Figure 14-9: Font metrics
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - 14-10: Processes, AppDomains, Threads Figure Menu layout of theContexts, FontAppand project Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 14-11: Thethe FontApp application in Part Four - Leveraging .NET Libraries
action
Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure 14-12: The stock .NET Font dialog
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - 14-13: A Better Paintingwith Framework (GDI+) Figure Working Pen types Chapter 15 - Programming with Windows Forms Controls
Figure Working Namespace with pen caps Chapter 16 - 14-14: The System.IO Chapter 17 - Data Access with ADO.NET
Figure 14-15: Working with Brush types
Part Five - Web Applications and XML Web Services
Chapter 18 - 14-16: ASP.NET Web Pages and Web Controls Figure The hatch styles Chapter 19 - ASP.NET Web Applications
Figure Bitmaps as brushes Chapter 20 - 14-17: XML Web Services Index
Figure 14-18: Gradient brushes at work
List of Figures
List ofFigure Tables14-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# and the .NET Platform, Second Edition
Andrew Troelsen Figure 14-29:byThe underlying *.resx file for MainForm.cs
ISBN:1590590554
Apress © 2003 (1200 pages)
Figure 14-30:This Under VS .NET, *.resx files are embedded comprehensive text starts withautomatically a brief overview of the into your assembly. C# language and then quickly moves to key technical and
Figure 14-31:architectural GUI of the ResLoader application issues for .NET developers.
Figure 14-32: Loading resources with the ResourceManager type Table of Contents
Chapter 15: Programming with Windows Forms Controls
C# and the .NET Platform, Second Edition Introduction
Part One - Introducing and theForms .NET Platform Figure 15-1: The C# Windows control hierarchy
Chapter 1
- The Philosophy of .NET
Figure TheC# Form's UI Chapter 2 - 15-2: Building Applications Part Two - The C# Programming Language
Figure 15-3: Interacting with a Form's Controls collection
Chapter 3
- C# Language Fundamentals
Chapter 4 - 15-4: Object-Oriented Programming with C# Figure Design time property configuration Chapter 5
- Exceptions and Object Lifetime
Figure Design time event handling Chapter 6 - 15-5: Interfaces and Collections Chapter 7
Callback Interfaces, Delegates, and Events Figure- 15-6: The many faces of the TextBox type
Chapter 8
- Advanced C# Type Construction Techniques
Part Three with .NETof Assemblies Figure- Programming 15-7: The many faces the Button
Chapter 9
type
- Understanding .NET Assemblies
Figure The initial UI of theContexts, CarConfig Form Chapter 10 - 15-8: Processes, AppDomains, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 15-9: The CheckedListBox type
Part Four - Leveraging the .NET Libraries
Chapter 12 - 15-10: Object Multicolumn Serialization and the .NET Remoting Figure CheckedListBox type Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Figure The ListBox type Chapter 14 - 15-11: A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Figure 15-12: The ComboBox type
Chapter 16 - The System.IO Namespace
Chapter Figure 17 - 15-13: Data Access The MonthCalendar with ADO.NET type Part Five - Web Applications and XML Web Services
Figure Selecting multiple dates Chapter 18 - 15-14: ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Figure 15-15: The VS .NET Tab Order Wizard
Chapter 20 - XML Web Services
IndexFigure 15-16: Associating a ToolTip to a given widget List of Figures
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 the design time GUI and the .NET Platform, Second Edition by Andrew Troelsen Apress © 2003 (1200 pages)
Figure 15-28: The client-side GUI
ISBN:1590590554
comprehensive text with a value brief overview of the Figure 15-29:This Resetting a property tostarts the default C# language and then quickly moves to key technical and
for .NET developers. Figure 15-30:architectural The customissues category
Chapter 16: The System.IO Namespace
Table of Contents
C# and the .NET Platform, Second Edition
Figure 16-1: The File- and Directory-centric types Introduction Part One - Introducing C# and the .NET Platform
Figure 16-2: %windir% directory information
Chapter 1
- The Philosophy of .NET
Chapter 2 - 16-3: Building C# Applications Figure Bitmap file information Part Two - The C# Programming Language
Figure CreatingFundamentals subdirectories Chapter 3 - 16-4: C# Language Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Figure 16-5: Stream-derived types
Chapter 6 - 16-6: Interfaces and and Collections Figure Readers writers Chapter 7
- Callback Interfaces, Delegates, and Events
Figure The contents of your *.txt file Chapter 8 - 16-7: Advanced C# Type Construction Techniques Part Three - Programming with .NET Assemblies
Figure 16-8: Reading from a file
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - 16-9: Processes, AppDomains, Contexts, and Threads Figure Manipulating the StringBuilder Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 16-10: Watching some *.txt files Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure 16-11: The car logger application
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - 16-12: A Better Painting Figure The Add aFramework Car dialog(GDI+) box Chapter 15 - Programming with Windows Forms Controls
Figure The standard File Save dialog box Chapter 16 - 16-13: The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Chapter 17: Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - 17-1: ASP.NET Web Applications Figure ADO.NET data providers provide access to a given DBMS. Chapter 20 - XML Web Services IndexFigure 17-2: Exercising a DataColumn type List of Figures
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# and the .NET Platform, Second Edition
ISBN:1590590554 Andrew multiple Troelsen views for a single DataTable Figure 17-14:byCreating
Apress © 2003 (1200 pages)
Figure 17-15:This Thecomprehensive anatomy of a text DataSet starts with a brief overview of the C# language and then quickly moves to key technical and
Figure 17-16:architectural The Cars database issues for .NET developers. Figure 17-17: Navigating data relations Table of Contents
Figure 17-18: Navigating parent/child relations
C# and the .NET Platform, Second Edition
Introduction Figure 17-19: The Cars database as XML Part One - Introducing C# and the .NET Platform
Figure The finalofGUI update Chapter 1 - 17-20: The Philosophy .NET Chapter 2
- Building C# Applications
Figure 17-21: The Cars XML schema file
Part Two - The C# Programming Language
Chapter 3 - 17-22: C# Language Fundamentals Figure Reading records with the OleDbDataReader Chapter 4 - Object-Oriented Programming with C#
Figure Mapping database column names to unique display names Chapter 5 - 17-23: Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Figure 17-24: Inserting new records using a data adapter
Chapter 8 - 17-25: Advanced C# Type Construction Figure Updating existing recordsTechniques using a data adapter Part Three - Programming with .NET Assemblies
Figure All good.NET things do come ... Chapter 9 - 17-26: Understanding Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure 17-27: Viewing related DataTables
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries Figure 17-28: Adding a new data connection
Chapter 12 - Object Serialization and the .NET Remoting Layer
Figure Configuring the new data connection Chapter 13 - 17-29: Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Figure 17-30: Interacting with the Cars database via VS .NET
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - 17-31: The System.IO Namespace Figure Design time connection configuration Chapter 17 - Data Access with ADO.NET
Figure 17-32: Specifying the connection for the Part Five - Web Applications and XML Web Services
new SqlDataAdapter
Chapter 18 - ASP.NET Web Pages and Web Controls
Figure 17-33: Specifying data store updates
Chapter 19 - ASP.NET Web Applications
Chapter 20 - 17-34: XML Web Services Figure Creating the initial SELECT logic Index List ofFigure Figures17-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# Theand initial crack the default.htm page the .NETatPlatform, Second Edition by Andrew Troelsen
Figure 18-7: Apress Capturing HTML widget events a la VS .NET © 2003 (1200 pages)
ISBN:1590590554
text starts with a brief overview of the Figure 18-8: This The comprehensive dynamically generated HTML C# language and then quickly moves to key technical and
issues for .NET developers. Figure 18-9: architectural Your first ASP.NET Web application
Figure 18-10: The location of the dynamically created assembly Table of Contents
Figure 18-11: *.aspx Second files become C# and the .NET Platform, Editionclasses that extend System.Web.UI.Page. Introduction
Figure 18-12: The ASP.NET compilation cycle
Part One - Introducing C# and the .NET Platform
Chapter 1 - 18-13: The Philosophy Figure Creating of an.NET ASP.NET application project with VS .NET Chapter 2 - Building C# Applications Part Two Figure - The 18-14: C# Programming Your design Language time template
Chapter 3
- C# Language Fundamentals
Figure- 18-15: Initial files of an ASP.NET application Object-Oriented Programming with C#
Chapter 4
Chapter 5 - 18-16: Exceptions Object Web Lifetime Figure The and ASP.NET Controls Toolbox Chapter 6
- Interfaces and Collections
Figure The derivation of an ASP.NET page Chapter 7 - 18-17: Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Figure 18-18: The result of calling ClearError()
Part Three - Programming with .NET Assemblies
Chapter 9 - 18-19: Understanding .NET Figure The result of Assemblies not calling ClearError() Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure The ASP.NET Web controls Chapter 11 - 18-20: Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Figure 18-21: Panel with contained controls
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - 18-22: Building a Better Window (Introducing Figure Enumerating contained widgetsWindows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Figure A dynamically generated HTML table Chapter 15 - 18-23: Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Figure 18-24: A DataGrid with friendly column names
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications anddefault XML Web Services Figure 18-25: A DataGrid paging support
Chapter 18 - ASP.NET Web Pages and Web Controls
Figure AnWeb editable DataGrid Chapter 19 - 18-26: ASP.NET Applications Chapter 20 - XML Web Services
Figure 18-27: The items to be validated
Index
List ofFigure Figures18-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# and the .NET Platform, Second Edition
Troelsen Figure 19-2: by TheAndrew Global.asax designer
ISBN:1590590554
Apress © 2003 (1200 pages)
Figure 19-3: This The comprehensive Application/Session state with distinction text starts a brief overview of the C# language and then quickly moves to key technical and
Figure 19-4: architectural The cache application GUI developers. issues for .NET Figure 19-5: The cache application GUI Table of Contents
Figure 19-6: Cookie data as persisted under Microsoft IE
C# and the .NET Platform, Second Edition
Introduction Figure 19-7: The UI of the CookiesStateApp Part One - Introducing C# and the .NET Platform
Figure The persistent cookie data Chapter 1 - 19-8: The Philosophy of .NET Chapter 2
- Building C# Applications
Figure 19-9: Viewing cookie data
Part Two - The C# Programming Language
Chapter 3 - 19-10: C# Language Fundamentals Figure The Services applet Chapter 4
- Object-Oriented Programming with C#
Figure Configuration Chapter 5 - 19-11: Exceptions and Objectinheritance Lifetime Chapter 6
- Interfaces and Collections
Chapter - Callback 20: XML Interfaces, Web Delegates, Services and Events
Chapter 7 Chapter 8
- Advanced C# Type Construction Techniques
Part Three with .NET Assemblies Figure- Programming 20-1: XML Web services in action
Chapter 9
- Understanding .NET Assemblies Figure Viewing the functionality of the Web service Chapter 10 - 20-2: Processes, AppDomains, Contexts, andHelloWorldWS Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Figure 20-3: Web method return values are expressed in terms of XML.
Part Four - Leveraging the .NET Libraries
Chapter 12 - 20-4: ObjectViewing Serialization and the .NET Figure the compiled .NETRemoting assemblyLayer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Figure Creating a new VS .NET XML Web Service project Chapter 14 - 20-5: A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Figure 20-6: Invoking the Add() Web method
Chapter 16 - The System.IO Namespace
Chapter Figure 17 - 20-7: Data Access Documenting with ADO.NET your Web methods Part Five - Web Applications and XML Web Services
Figure TheWeb dummy value XML namespace is http—//tempuri.org. Chapter 18 - 20-8: ASP.NET Pages and for Webyour Controls Chapter 19 - ASP.NET Web Applications
Figure 20-9: The VS .NET Add Web Reference utility
Chapter 20 - XML Web Services
IndexFigure 20-10: A Windows Forms XML Web Service Client application List of Figures List ofFigure Tables20-11: Interacting with a UDDI catalog
Figure 20-12: Obtaining a list of posted weather-centric Web services
C# and the .NET Platform, Second Edition
by Andrew Troelsen List of Tables
ISBN:1590590554
Apress © 2003 (1200 pages) comprehensive text starts with a brief overview of the Chapter 1: This The Philosophy of moves .NETto key technical and C# language and then quickly architectural issues for .NET developers.
Table 1-1: A Sampling of .NET-Aware Programming Languages 1-2: CTS Class Characteristics Table Table of Contents C# and the .NET Platform, Second Edition
Table 1-3: The Intrinsic CTS Data Types
Introduction
Part One - Introducing C# and the .NET Platform
Table 1-4: A Sampling of .NET Namespaces
Chapter 1
- The Philosophy of .NET Table ildasm.exe Tree View Icons Chapter 2 -1-5: Building C# Applications Part Two - The C# Programming Language
Table -1-6: Select Links to the Platform-Agnostic Nature of .NET C# Language Fundamentals
Chapter 3 Chapter 4
- Object-Oriented Programming with C#
Chapter 2: Building C#Lifetime Applications - Exceptions and Object
Chapter 5 Chapter 6
- Interfaces and Collections
Table Output Options of the C# Compiler Chapter 7 -2-1: Callback Interfaces, Delegates, and Events Chapter 8
- Advanced C# Type Construction Techniques
Table 2-2: Options of the C# Command Line Compiler
Part Three - Programming with .NET Assemblies
Chapter 9 -2-3: Understanding .NET Assemblies Table A Handful of Useful cordbg.exe Flags Chapter 10 - Processes, AppDomains, Contexts, and Threads
Table Core ProjectLate Workspace Chapter 11 -2-4: Type Reflection, Binding, Types and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Table 2-5: The Structure of a VS .NET Console Application
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 -2-6: Building Better Window (Introducing Windows Forms) Table Stocka XML Tags Chapter 14 - A Better Painting Framework (GDI+)
Table XML Format Characters Chapter 15 -2-7: Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Table 2-8: C# Preprocessor Directives
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 3: C# Language Fundamentals
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Table Format Characters Chapter 20 -3-1: XML.NET Web String Services Index
Table 3-2: Value Types and Reference Types Side by Side
List of Figures
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# and the .NET Platform, Second Edition
by Andrew Table 3-13: Select staticTroelsen Members of System.Enum
ISBN:1590590554
Apress © 2003 (1200 pages) comprehensiveand text starts with a brief overview of the Chapter 5: This Exceptions Object Lifetime C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 5-1: Core Members of the System.Exception Type 5-2: Select Members of the System.GC Type Table Table of Contents C# and the .NET Platform, Second Edition
Chapter 6: Interfaces and Collections
Introduction
Part One - Introducing C# and the .NET Platform
Chapter Table 1 -6-1: TheCompareTo() Philosophy of .NET Return Values Chapter 2
- Building C# Applications
Table 6-2:C# Interfaces of System.Collections Part Two - The Programming Language Chapter 3
C# Language Fundamentals Table -6-3: Classes of System.Collections
Chapter 4
- Object-Oriented Programming with C#
Chapter Table 5 -6-4: Exceptions Members and ofObject the Queue Lifetime Type Chapter 6
- Interfaces and Collections
Table -6-5: Types of the System.Collections.Specialized Namespace Callback Interfaces, Delegates, and Events
Chapter 7 Chapter 8
- Advanced C# Type Construction Techniques
Chapter 7: Callback Interfaces, Delegates, and Events
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Table Select Members of System.MultcastDelegate/System.Delegate Chapter 10 -7-1: Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Chapter 8: Advanced C# Type Construction Techniques
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 -8-1: Building a Better Window (Introducing Windows Forms) Table Pointer-Centric C# Operators Chapter 14 - A Better Painting Framework (GDI+)
Table A Summary of Windows C# Keywords Chapter 15 -8-2: Programming with Forms Controls Chapter 16 - The System.IO Namespace
Table 8-3: C#-Operator-to-CIL Special Name Roadmap
Chapter 17 - Data Access with ADO.NET
Part Five - Web and XMLOperators Web Services Table 8-4:Applications Valid Overloadable
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Chapter 9: Understanding .NET Assemblies
Chapter 20 - XML Web Services Index
Table 9-1: Key Elements of an Assembly Manifest
List of Figures
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# and the .NET Platform, Second Edition
by AndrewofTroelsen Table 10-9: Members the Interlocked Type
ISBN:1590590554
Apress © 2003 (1200 pages) comprehensive text starts with a brief overview of the Chapter 11:This Type Reflection, and C# language and then quicklyLate moves Binding, to key technical and Attribute-Based architectural issues for .NET developers. Programming
Table 11-1: Select Members of System.Type
Table of Contents
C# and the .NET Second Edition of the System.Reflection Namespace Table 11-2:Platform, A Sampling of Members Introduction
Table 11-3: A Tiny of Predefined Part One - Introducing C#Sampling and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
System Attributes
Table 11-4: Select Assembly-level Attributes
Part Two - The C# Programming Language
Chapter 12: Object Serialization and the .NET Remoting Layer - C# Language Fundamentals
Chapter 3 Chapter 4
- Object-Oriented Programming with C#
Table BinaryFormatter Chapter 5 -12-1: Exceptions and Object Members Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Table 12-2: System.Runtime.Serialization Namespace Core Types
Chapter 8 -12-3: Advanced C# Type Construction Techniques Members Table StreamingContextStates Enumeration Part Three - Programming with .NET Assemblies
Table The .NET .NET Remoting Namespaces Chapter 9 -12-4: Understanding Assemblies Chapter 10 - Processes, AppDomains, Contexts, and Threads
Table 12-5: Key Members of System.MarshalByRefObject
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries Table 12-6: Configuration Options for
MBR Types
Chapter 12 - Object Serialization and the .NET Remoting Layer
Table Select Members of the ChannelServices Chapter 13 -12-7: Building a Better Window (Introducing Windows Type Forms) Chapter 14 - A Better Painting Framework (GDI+)
Table 12-8: Members of the RemotingConfiguration Type
Chapter 15 - Programming with Windows Forms Controls Chapter 16 -12-9: The System.IO Namespace Table Members of the ILease Interface Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 13: Building a Better Window (Introducing Windows Forms)
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Table 13-1: A Subset of Types Within the System.Windows.Forms Namespace
Chapter 20 - XML Web Services
IndexTable 13-2: Methods of the Application Type List of Figures 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 the ContainerControl and theof.NET Platform, SecondType Edition by Andrew Troelsen
Table 13-14:Apress Properties of the Form Type © 2003 (1200 pages)
ISBN:1590590554
starts with a brief overview of the Table 13-15:This Keycomprehensive Methods of thetext Form Type C# language and then quickly moves to key technical and
issues for .NET developers. Table 13-16:architectural Select Events of the Form Type
Table 13-17: Form Life Time Events Table of Contents
Table 13-18: Members of the Menu Type C# and the .NET Platform, Second Edition Introduction
Table 13-19: The Nested MenuItemCollection Type
Part One - Introducing C# and the .NET Platform
Chapter 1 -13-20: The Philosophy of .NET Table More Details of the MenuItem Type Chapter 2 - Building C# Applications Part Two Table - The 13-21: C# Programming Select StatusBar Language Properties
Chapter 3
- C# Language Fundamentals
Table -13-22: Properties of the StatusBarPanel Type Object-Oriented Programming with C#
Chapter 4
Chapter 5 -13-23: Exceptions and Object Table The Timer TypeLifetime Chapter 6
- Interfaces and Collections
Table Properties of the ToolBarand Type Chapter 7 -13-24: Callback Interfaces, Delegates, Events Chapter 8
- Advanced C# Type Construction Techniques
Table 13-25: Properties of the ToolBarButton Type
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 14: A Better Painting Framework (GDI+)
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Table 14-1: The Core GDI+ Namespaces Part Four - Leveraging the .NET Libraries Chapter 12 - Object Serialization and the .NET Remoting Layer
Table 14-2: Core Types of the System.Drawing Namespace
Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 -14-3: A Better Painting Framework (GDI+) Table Enumerations in the System.Drawing Namespace Chapter 15 - Programming with Windows Forms Controls
Table Key Members of the Point(F) Types Chapter 16 -14-4: The System.IO Namespace Chapter 17 - Data Access with ADO.NET
Table 14-5: Key Members of the Rectangle(F) Types
Part Five - Web Applications and XML Web Services
Chapter 18 -14-6: ASP.NET Web Pagesof and Controls Table Key Members theWeb Size(F) Types Chapter 19 - ASP.NET Web Applications
Table of the Region Class Chapter 20 -14-7: XML Members Web Services Index
Table 14-8: Members of the Graphics Class
List of Figures
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# and the .NET Platform, Second Edition
AndrewMembers Troelsen of the Graphics Class Table 14-19:by Drawing
ISBN:1590590554
Apress © 2003 (1200 pages)
Table 14-20:This Pencomprehensive Properties text starts with a brief overview of the C# language and then quickly moves to key technical and
Table 14-21:architectural Dash Stylesissues for .NET developers. Table 14-22: LineCap Values Table of Contents
Table 14-23: Fill Methods of the Graphics Type
C# and the .NET Platform, Second Edition
Introduction Table 14-24: Values of the HatchStyle Enumeration Part One - Introducing C# and the .NET Platform
Table LinearGradientMode Enumeration Chapter 1 -14-25: The Philosophy of .NET Chapter 2
- Building C# Applications
Table 14-26: Members of the Image Type
Part Two - The C# Programming Language
Chapter 3 -14-27: C# Language Fundamentals Table The PictureBoxSizeMode Enumeration Chapter 4 - Object-Oriented Programming with C#
Table Add-Centric Methods of the GraphicsPath Class Chapter 5 -14-28: Exceptions and Object Lifetime Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Table 14-29: Members of the System.Resources Namespace
Chapter 15: Programming with Windows Forms Controls
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Table NestedAppDomains, ControlCollection Members Chapter 10 -15-1: Processes, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Table 15-2: Members of the TextBoxBase Type
Part Four - Leveraging the .NET Libraries
Chapter 12 -15-3: Object Serialization and the .NET Remoting Layer Table TextBox Properties Chapter 13 - Building a Better Window (Introducing Windows Forms)
Table ButtonBase Properties (GDI+) Chapter 14 -15-4: A Better Painting Framework Chapter 15 - Programming with Windows Forms Controls
Table 15-5: CheckBox Properties
Chapter 16 - The System.IO Namespace
Chapter Table 17 -15-6: Data MonthCalendar Access with ADO.NET Properties Part Five - Web Applications and XML Web Services
Table DateTime Members Chapter 18 -15-7: ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Table 15-8: ToolTip Members
Chapter 20 - XML Web Services
IndexTable 15-9: TrackBar Properties List of Figures
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 and the .NET Platform, Second Edition by Andrew Troelsen
ISBN:1590590554
Table 16-1: Key Members of the System.IO Namespace Apress © 2003 (1200 pages) This comprehensive text starts with a brief overview of the
Table 16-2: FileSystemInfo Properties C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 16-3: Key Members of the DirectoryInfo Type Table 16-4: Select FileAttributes Values
Table of Contents
C# and the .NET Second Edition Table 16-5:Platform, FileInfo Core Members Introduction
Table 16-6: FileMode Enumeration Values Part One - Introducing C# and the .NET Platform Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Table 16-7: FileAccess Enumeration Values
Part Two - The C# FileShare Programming Language Values Table 16-8: Enumeration
Chapter 3
- C# Language Fundamentals
Table Abstract Stream Members Chapter 4 -16-9: Object-Oriented Programming with C# Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Table 16-10: MemoryStream Core Members
Chapter 7 -16-11: Callback Interfaces, Delegates, and Events Table Core Members of TextWriter Chapter 8
- Advanced C# Type Construction Techniques
Table-16-12: TextReader CoreAssemblies Members Part Three Programming with .NET Chapter 9
- Understanding .NET Assemblies
Table 16-13: BinaryWriter Core Members
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 -16-14: Type Reflection, Late Core Binding, and Attribute-Based Programming Table BinaryReader Members Part Four - Leveraging the .NET Libraries
Table Menu Options of .NET the CarLogApp Project Chapter 12 -16-15: ObjectFile Serialization and the Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 17: Data Access with ADO.NET
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls Chapter 16 -17-1: The System.IO Table ADO.NET Namespace Namespaces Chapter 17 - Data Access with ADO.NET
Table 17-2: Key Members theWeb System.Data Part Five - Web Applications and of XML Services
Namespace
Chapter 18 - ASP.NET Web Pages and Web Controls
Table 17-3: Properties of the DataColumn
Chapter 19 - ASP.NET Web Applications
Chapter 20 -17-4: XML Values Web Services Table of the MappingType Enumeration Index
17-5: Key Members of the DataRow Type List ofTable Figures 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# and the .NET Platform, Second Edition
Andrew Troelsen Table 17-16:by Key Members of the OleDbParameter Type ISBN:1590590554 Apress © 2003 (1200 pages)
Table 17-17:This Core Members of the comprehensive textOleDbDataAdapter starts with a brief overview of the C# language and then quickly moves to key technical and
Table 17-18:architectural Core Typesissues of the for System.Data.SqlClient Namespace .NET developers. Table 17-19: Types of the System.Data.SqlTypes Namespace Table of Contents
Chapter 18: ASP.NET Web Pages and Web Controls
C# and the .NET Platform, Second Edition Introduction
Part One - Introducing C# and the .NET Table 18-1: Common HTML GUI Platform Types
Chapter 1
- The Philosophy of .NET
Table ASP.NET Namespaces Chapter 2 -18-2: Building C# Applications Part Two - The C# Programming Language
Table 18-3: Core Types of the System.Web Namespace
Chapter 3
- C# Language Fundamentals
Chapter 4 -18-4: Object-Oriented Programming C# Attributes Table Some (But Not All) of thewith @Page Chapter 5 - Exceptions and Object Lifetime
Table Initial and Project Files Chapter 6 -18-5: Interfaces Collections Chapter 7
Callback Interfaces, Delegates, and Events Table -18-6: Properties of the Page Type
Chapter 8
- Advanced C# Type Construction Techniques
Part Three Programming .NET Assemblies Type Table-18-7: Memberswith of the HttpRequest
Chapter 9
- Understanding .NET Assemblies
Table Properties of the HttpResponse Chapter 10 -18-8: Processes, AppDomains, Contexts, andType Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Table 18-9: Methods of the HttpResponse Type
Part Four - Leveraging the .NET Libraries
Chapter 12 -18-10: ObjectThe Serialization andInit, theLoad, .NET Remoting Layer Table Role of the and Unload Events Chapter 13 - Building a Better Window (Introducing Windows Forms)
Table Select Members of System.Web.UI.Control Chapter 14 -18-11: A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls
Table 18-12: Properties of the WebControl Base Class
Chapter 16 - The System.IO Namespace
Chapter Table 17 -18-13: Data Access Rich WebControl with ADO.NET Widgets Part Five - Web Applications and XML Web Services
Table TheWeb ASP.NET Validation Controls Chapter 18 -18-14: ASP.NET Pages and Web Controls Chapter 19 - ASP.NET Web Applications
Table 18-15: Common Properties of the ASP.NET Validators
Chapter 20 - XML Web Services Index
Chapter 19: ASP.NET Web Applications
List of Figures 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# and the .NET Platform, Second Edition Table 20-4: Key Members of the WebMethodAttribute Type by Andrew Troelsen
ISBN:1590590554
Table 20-5: Select wsdl.exe ApressFlags © 2003 of (1200 pages) This comprehensive text starts with a brief overview of the Table 20-6: Web Service Wire Protocols C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table 20-7: Supported POST and GET Data Types
Table 20-8: Core Members of the SoapHttpClientProtocol Type
Table of Contents
C# and the .NET Platform, Second Edition Introduction Part One - Introducing C# and the .NET Platform
Chapter 1
- The Philosophy of .NET
Chapter 2
- Building C# Applications
Part Two - The C# Programming Language
Chapter 3
- C# Language Fundamentals
Chapter 4
- Object-Oriented Programming with C#
Chapter 5
- Exceptions and Object Lifetime
Chapter 6
- Interfaces and Collections
Chapter 7
- Callback Interfaces, Delegates, and Events
Chapter 8
- Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9
- Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services Index List of Figures List of Tables