beginning c# object- oriented programming - springer978-1-4302-3531-6/1.pdf · contents iii...

16
Beginning C# Object- Oriented Programming ■ ■ ■ Dan Clark

Upload: dinhkiet

Post on 18-Feb-2019

228 views

Category:

Documents


0 download

TRANSCRIPT

i

Beginning C# Object-Oriented Programming

■ ■ ■

Dan Clark

■ CONTENTS

ii

Beginning C# Object-Oriented Programming

Copyright © 2011 by Dan Clark

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

President and Publisher: Paul Manning Lead Editor: John Osborn Technical Reviewer: Jeff Sanders Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick,

Jonathan Hassell, Michelle Lowman, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh

Coordinating Editor: Corbin Collins Copy Editor: Mary Behr Compositor: Richard Ables Indexer: John Collin Artist: April Milne Cover Designer: Anna Ishchenko

Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com.

For information on translations, please e-mail [email protected], or visit www.apress.com.

Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales.

The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work.

The source code for this book is available to readers at www.apress.com. You will need to answer questions pertaining to this book in order to successfully download the code.

ISBN 978-1-4302-3530-9

ISBN 978-1-4302-3531-6 (eBook)

■ CONTENTS

iii

Contents at a Glance

■ About the Author ........................................................................................................................ xii ■ About the Technical Reviewer ................................................................................................... xiii ■ Acknowledgments..................................................................................................................... xiv ■ Introduction................................................................................................................................ xv ■ Chapter 1: Overview of Object-Oriented Programming ................................................................ 1 ■ Chapter 2: Designing OOP Solutions: Identifying the Class Structure........................................... 7 ■ Chapter 3: Designing OOP Solutions: Modeling the Object Interaction...................................... 29 ■ Chapter 4: Designing OOP Solutions: A Case Study ................................................................... 55 ■ Chapter 5: Introducing the .NET Framework and Visual Studio.................................................. 77 ■ Chapter 6: Creating Classes ..................................................................................................... 101 ■ Chapter 7: Creating Class Hierarchies...................................................................................... 115 ■ Chapter 8: Implementing Object Collaboration......................................................................... 137 ■ Chapter 9: Working with Collections ........................................................................................ 163 ■ Chapter 10: Implementing the Data Access Layer.................................................................... 181 ■ Chapter 11: Developing Windows Applications ........................................................................ 215 ■ Chapter 12: Developing Web Applications................................................................................ 243 ■ Chapter 13: Developing and Consuming WCF Services ............................................................ 265 ■ Chapter 14: Developing the OSO Application ............................................................................ 287 ■ Chapter 15: Wrapping Up.......................................................................................................... 313 ■ Appendix A: Fundamental Programming Concepts .................................................................. 317 ■ Appendix B: Exception Handling in C#...................................................................................... 333 ■ Appendix C: Installing the Required Software .......................................................................... 337

■ Index......................................................................................................................................... 343

■ CONTENTS

iv

Contents

■ About the Author ........................................................................................................................ xii

■ About the Technical Reviewer ................................................................................................... xiii

■ Acknowledgments..................................................................................................................... xiv

■ Introduction................................................................................................................................ xv

■ Chapter 1: Overview of Object-Oriented Programming ................................................................ 1 The History of OOP.............................................................................................................................. 1 Why Use OOP? .................................................................................................................................... 2 The Characteristics of OOP................................................................................................................. 3

Objects ........................................................................................................................................... 3 Abstraction..................................................................................................................................... 3 Encapsulation................................................................................................................................. 4 Polymorphism ................................................................................................................................ 4 Inheritance ..................................................................................................................................... 5 Aggregation.................................................................................................................................... 5

The History of C# ................................................................................................................................ 5 Summary ............................................................................................................................................ 6

■ Chapter 2: Designing OOP Solutions: Identifying the Class Structure........................................... 7 Goals of Software Design ................................................................................................................... 7 Understanding the Unified Modeling Language ................................................................................. 8 Developing a SRS ............................................................................................................................... 9 Introducing Use Cases...................................................................................................................... 10 Understanding Class Diagrams ........................................................................................................ 18 Modeling Object Relationships ......................................................................................................... 19

Association................................................................................................................................... 19 Inheritance ................................................................................................................................... 20 Aggregation.................................................................................................................................. 21 Association Classes ..................................................................................................................... 21

■ CONTENTS

v

Summary .......................................................................................................................................... 26 ■ Chapter 3: Designing OOP Solutions: Modeling the Object Interaction...................................... 29

Understanding Scenarios ................................................................................................................. 29 Introducing Sequence Diagrams ...................................................................................................... 30 Message Types................................................................................................................................. 32 Recursive Messages......................................................................................................................... 33 Message Iteration............................................................................................................................. 34 Message Constraints ........................................................................................................................ 35 Message Branching.......................................................................................................................... 35 Understanding Activity Diagrams ..................................................................................................... 42

Decision Points and Guard Conditions ......................................................................................... 43 Parallel Processing....................................................................................................................... 43 Activity Ownership ....................................................................................................................... 44

Exploring GUI Design ........................................................................................................................ 48 GUI Activity Diagrams................................................................................................................... 49 Interface Prototyping.................................................................................................................... 50 Interface Flow Diagrams.............................................................................................................. 51 Application Prototyping ................................................................................................................ 52

Summary .......................................................................................................................................... 52 ■ Chapter 4: Designing OOP Solutions: A Case Study ................................................................... 55

Developing an OOP Solution ............................................................................................................. 55 Creating the System Requirement Specification ......................................................................... 56 Developing the Use Cases............................................................................................................ 57 Diagramming the Use Cases ........................................................................................................ 59 Developing the Class Model......................................................................................................... 61

Identifying the Classes ............................................................................................................ 61 Adding Attributes to the Classes ............................................................................................. 63 Identifying Class Associations................................................................................................. 65 Modeling the Class Behaviors ................................................................................................. 66 Developing the User Interface Model Design .......................................................................... 70

Avoiding Some Common OOP Design Pitfalls .............................................................................. 74 Summary .......................................................................................................................................... 75

■ Chapter 5: Introducing the .NET Framework and Visual Studio.................................................. 77 Introducing the .NET Framework .................................................................................................... 77

Goals of the .NET Framework....................................................................................................... 77

■ CONTENTS

vi

Support of Industry Standards................................................................................................. 77 Extensibility ............................................................................................................................. 78 Unified Programming Models .................................................................................................. 78 Easier Deployment .................................................................................................................. 78 Improved Memory Management ............................................................................................. 79 Improved Security Model......................................................................................................... 79

Components of the .NET Framework ........................................................................................... 79 Common Language Runtime ................................................................................................... 80 Framework Base Class Library................................................................................................ 80 Data Classes............................................................................................................................ 80 Windows Applications ............................................................................................................. 81 Web Applications..................................................................................................................... 81 Application Services ................................................................................................................ 81

Working with the .NET Framework .............................................................................................. 82 Understanding Assemblies and Manifests .............................................................................. 82 Referencing Assemblies and Namespaces ............................................................................. 82 Compiling and Executing Managed Code ................................................................................ 83

Using the Visual Studio Integrated Development Environment ........................................................ 83 Customizing the IDE ................................................................................................................ 84 Creating a New Project............................................................................................................ 86 Investigating the Solution Explorer and Class View ................................................................ 87 Exploring the Toolbox and Properties Window........................................................................ 91 Building and Executing the Assembly ..................................................................................... 94 Stepping Through Code ........................................................................................................... 95 Setting Conditional Breakpoints .............................................................................................. 97 Locating and Fixing Build Errors.............................................................................................. 99

Summary ........................................................................................................................................ 100 ■ Chapter 6: Creating Classes ..................................................................................................... 101

Introducing Objects and Classes .................................................................................................... 101 Defining Classes............................................................................................................................. 102

Creating Class Properties........................................................................................................... 102 Creating Class Methods ............................................................................................................. 103

Defining the Employee Class................................................................................................. 105 Testing the Employee Class .................................................................................................. 107

Using Constructors ......................................................................................................................... 107 Overloading Methods...................................................................................................................... 108

Creating and Overloading Class Constructors ....................................................................... 110

■ CONTENTS

vii

Testing the Employee Class Constructors ............................................................................. 111 Overloading a Class Method.................................................................................................. 112 Testing the Overloaded Update Method ................................................................................ 113

Summary ........................................................................................................................................ 114 ■ Chapter 7: Creating Class Hierarchies...................................................................................... 115

Understanding Inheritance ............................................................................................................. 115 Creating Base and Derived Classes ........................................................................................... 116 Creating a Sealed Class ............................................................................................................. 117 Creating an Abstract Class......................................................................................................... 117 Using Access Modifiers in Base Classes.................................................................................... 117

Overriding the Methods of a Base Class......................................................................................... 122 Calling a Derived Class Method from a Base Class.................................................................... 123 Calling a Base Class Method from a Derived Class.................................................................... 124

Overloading Methods of a Base Class ............................................................................................ 125 Hiding Base Class Methods ............................................................................................................ 125 Implementing Interfaces ................................................................................................................ 129 Understanding Polymorphism ........................................................................................................ 130 Summary ........................................................................................................................................ 135

■ Chapter 8: Implementing Object Collaboration......................................................................... 137 Communicating Through Messaging.............................................................................................. 137 Defining Method Signatures........................................................................................................... 137 Passing Parameters ....................................................................................................................... 138 Understanding Event-Driven Programming.................................................................................... 139 Understanding Delegation .............................................................................................................. 139 Implementing Events...................................................................................................................... 140 Responding To Events .................................................................................................................... 141 Windows Control Event Handling ................................................................................................... 141 Handling Exceptions in the .NET Framework ................................................................................. 147

Using the Try-Catch Block.......................................................................................................... 147 Adding a Finally Block................................................................................................................ 148 Throwing Exceptions.................................................................................................................. 149 Nesting Exception Handling ....................................................................................................... 149

Static Properties and Methods ....................................................................................................... 150 Using Asynchronous Messaging..................................................................................................... 155 Summary ........................................................................................................................................ 161

■ CONTENTS

viii

■ Chapter 9: Working with Collections ........................................................................................ 163 Introducing the .NET Framework Collection Types......................................................................... 163 Working with Arrays and Array Lists .............................................................................................. 165 Using Generic Collections............................................................................................................... 175 Programming with Stacks and Queues .......................................................................................... 179 Summary ........................................................................................................................................ 180

■ Chapter 10: Implementing the Data Access Layer.................................................................... 181 Introducing ADO.NET ...................................................................................................................... 181 Working with Data Providers.......................................................................................................... 182 Establishing a Connection .............................................................................................................. 183 Executing a Command.................................................................................................................... 184 Using Stored Procedures................................................................................................................ 185 Using the DataReader Object to Retrieve Data............................................................................... 186 Using the DataAdapter to Retrieve Data ......................................................................................... 187 Working with DataTables and DataSets ......................................................................................... 193 Populating a DataTable from a SQL Server Database .................................................................... 194 Populating a DataSet from a SQL Server Database........................................................................ 195 Establishing Relationships between Tables in a DataSet............................................................... 196 Editing Data in the DataSet ............................................................................................................ 197 Working with the Entity Framework ............................................................................................... 204 Querying Entities with LINQ to EF................................................................................................... 206 Updating Entities with the Entity Framework ................................................................................. 207 Summary ........................................................................................................................................ 213

■ Chapter 11: Developing Windows Applications ........................................................................ 215 Windows Fundamentals ................................................................................................................. 215 Introducing XAML ........................................................................................................................... 216 Using Layout Controls..................................................................................................................... 217 Adding Display Controls ................................................................................................................. 218 Using the Visual Studio Designer ................................................................................................... 219 Handling Control Events ................................................................................................................. 220 Creating and Using Dialog Boxes ................................................................................................... 226 Presenting a MessageBox to the User............................................................................................ 227 Creating a Custom Dialog Box ........................................................................................................ 229

■ CONTENTS

ix

Data Binding in Windows-Based GUIs ............................................................................................ 230 Binding Controls Using a DataContext............................................................................................ 230 Creating and Using Control and Data Templates............................................................................ 237 Summary ........................................................................................................................................ 242

■ Chapter 12: Developing Web Applications................................................................................ 243 What Is Silverlight?......................................................................................................................... 243 Creating a Silverlight Application ................................................................................................... 244 Using Layout Controls..................................................................................................................... 245 Adding Display Controls ................................................................................................................. 246 Handling Control Events ................................................................................................................. 247 Data Binding in Silverlight .............................................................................................................. 251 Validating and Converting Data ...................................................................................................... 259 Summary ........................................................................................................................................ 263

■ Chapter 13: Developing and Consuming WCF Services ............................................................ 265 What Are Services? ........................................................................................................................ 265 Creating a WCF Web Service .......................................................................................................... 266 Consuming a WCF Web Service...................................................................................................... 270 Using Data Contracts...................................................................................................................... 272 WCF Data Services ......................................................................................................................... 279 Summary ........................................................................................................................................ 285

■ Chapter 14: Developing the OSO Application ............................................................................ 287 Revisiting Application Design ......................................................................................................... 287 Building the OSO Application’s Data Access and Business Logic Layers....................................... 289 Creating the OSO Application UI ..................................................................................................... 300 Summary ........................................................................................................................................ 312

■ Chapter 15: Wrapping Up.......................................................................................................... 313 Improve Your Object-Oriented Design Skills .................................................................................. 314 Investigate the .NET Framework Namespaces............................................................................... 314 Become Familiar with ADO.NET and the Entity Framework ........................................................... 314 Learn More About WPF and Silverlight........................................................................................... 315 Move Toward Component-Based Development ............................................................................. 315 Find Help ........................................................................................................................................ 315 Join a User Group ........................................................................................................................... 315

■ CONTENTS

x

Please Provide Feedback ............................................................................................................... 316 Thank You and Good Luck .............................................................................................................. 316

■ Appendix A: Fundamental Programming Concepts .................................................................. 317 Working with Variables and Data Types......................................................................................... 317 Understanding Elementary Data Types .......................................................................................... 318

Integral Data Types .................................................................................................................... 318 Non-Integral Data Types ............................................................................................................ 318 Character Data Types................................................................................................................. 319 Boolean Data Type ..................................................................................................................... 319 Date Data Type........................................................................................................................... 319 Object Data Type........................................................................................................................ 319 Nullable Types............................................................................................................................ 320

Introducing Composite Data Types................................................................................................. 320 Structures .................................................................................................................................. 320 Arrays......................................................................................................................................... 320 Classes....................................................................................................................................... 321

Looking at Literals, Constants, and Enumerations ......................................................................... 321 Literals ....................................................................................................................................... 321 Constants ................................................................................................................................... 322 Enumerations ............................................................................................................................. 322

Exploring Variable Scope................................................................................................................ 323 Block-Level Scope ..................................................................................................................... 323 Procedure Scope........................................................................................................................ 323 Module Scope ............................................................................................................................ 324

Understanding Data Type Conversion ............................................................................................ 324 Implicit Conversion..................................................................................................................... 324 Explicit Conversion..................................................................................................................... 325 Widening and Narrowing Conversions ....................................................................................... 325

Working with Operators.................................................................................................................. 325 Arithmetic Operators.................................................................................................................. 325 Comparison Operators ............................................................................................................... 326 Logical Operators ....................................................................................................................... 327 Ternary Operator ........................................................................................................................ 328

Introducing Decision Structures ..................................................................................................... 328 If Statements.............................................................................................................................. 328 Switch Statements..................................................................................................................... 329

■ CONTENTS

xi

Using Loop Structures .................................................................................................................... 330 While Statement......................................................................................................................... 330 Do-While Statement ................................................................................................................... 330 For Statement ............................................................................................................................ 331 For Each Statement.................................................................................................................... 331

Introducing Methods ...................................................................................................................... 331 ■ Appendix B: Exception Handling in C#...................................................................................... 333

Managing Exceptions ..................................................................................................................... 333 Using the .NET Framework Exception Classes ............................................................................... 335

■ Appendix C: Installing the Required Software .......................................................................... 337 Installing the Sample Databases .................................................................................................... 337 Verifying the Database Installs....................................................................................................... 338

■ Index......................................................................................................................................... 383

■ CONTENTS

xii

About the Author

■Dan Clark is a senior IT consultant specializing in .NET and SQL Server technology. He is particularly interested in C# programming and SQL Server Business Intelligence development. Dan is a Microsoft Certified Trainer and a Microsoft Certified Solution Developer. For over a decade, he has been developing applications and training others to develop applications using Microsoft technologies. Dan has published several books and numerous articles on .NET programming. He is a regular speaker at various developer conferences and user group meetings, and he conducts workshops in object-oriented programming and database development. He finds particular satisfaction in turning new developers on to the thrill of developing and designing object-oriented applications. You can reach Dan at [email protected].

■ CONTENTS

xiii

About the Technical Reviewer

■Jeff Sanders is a published author, technical reviewer, and an accomplished technologist. He is currently employed with Avanade in the capacity of Group Manager/Senior Architect.

Jeff has years of professional experience in the field of IT and strategic business consulting, leading both sales and delivery efforts. He regularly contributes to certification and product roadmap development with Microsoft and speaks publicly on Microsoft enterprise technologies. With roots in software development, Jeff’s areas of expertise include operational intelligence, collaboration and content management solutions, digital marketing, distributed component-based application architectures, object-oriented analysis and design, and enterprise integration patterns and designs.

Jeff is also the CTO of DynamicShift, a client-focused organization specializing in Microsoft technologies, specifically SharePoint Server, StreamInsight, Windows Azure, AppFabric, Business Activity Monitoring,

BizTalk Server, Commerce Server, and .NET. He is a Microsoft Certified Trainer, and he leads DynamicShift in both training and consulting efforts.

He enjoys non–work-related travel and spending time with his wife and daughter—and wishes he more time for both. He may be reached at [email protected].

■ CONTENTS

xiv

Acknowledgments

A special thanks to the following people who made this book possible:

• Jonathan Hassell for once again leading the effort to get the project approval.

• Corbin Collins for keeping me on task and for managing the madness.

• Jeff Sanders for the helpful suggestions and making sure this book was technically accurate.

• John Osborn for clarifying my thoughts and increasing the readability of this book.

• The rest of the team at Apress for once again making the process of writing an enjoyable experience.

• And, last but not least, my family for their patience.

■ CONTENTS

xv

Introduction

It has been my experience as a .Net trainer and lead programmer that most people do not have trouble picking up the syntax of the language. What perplexes and frustrates many people are the higher-level concepts of object-oriented programming methodology and design. To compound the problem, most introductory programming books and training classes skim over these concepts or, worse, don’t cover them at all. It is my hope that this book fills this void. My goal in writing this book is twofold. First, to provide you with the information you need to understand the fundamentals of programming in C#. Second and more importantly, to present you with the information required to master the higher-level concepts of object-oriented programming methodology and design.

This book provides the knowledge you need to architect an object-oriented programming solution aimed at solving a business problem. As you work your way through the book, you will learn first how to analyze the business requirements of an application. Next, you will model the objects and relationships involved in the solution design. Finally, you will implement the solution using C#. Along the way, you will learn about the fundamentals of software design, the Unified Modeling Language (UML), object-oriented programming, C#, and the .NET Framework.

Because this is an introductory book, it’s meant to be a starting point for your study of the topics it presents. As such, this book is not designed to make you an expert in object-oriented programming and UML; nor is it an exhaustive discussion of C# and the .NET Framework; nor is it an in-depth study of Visual Studio. It takes considerable time and effort to become proficient in any one of these areas. It is my hope that by reading this book, your first experiences in object-oriented programming will be enjoyable and comprehensible—and that these experiences will instill a desire for further study.

Target Audience The target audience for this book is the beginning C# programmer who wants to gain a foundation in object-oriented programming along with the C# language basics. Programmers transitioning from a procedural-oriented programming model to an object-oriented model will also benefit from this book. In addition, there are many Visual Basic (VB) programmers who want to transition to C#. Before transitioning to C#, it is imperative that you understand the fundamentals of object-oriented programming.

Because the experience level of a “beginner” can vary immensely, I have included a primer in Appendix A that discusses some basic programming concepts and how they are implemented in C#. I would suggest you review these concepts if you are new to programming.

■ INTRODUCTION

xvi

Organization of the Book This book is organized into three parts:

Part 1 delves into object-oriented programming methodology and design—concepts that transcend a particular programming language. The concepts presented are important to the success of an object-oriented programming solution regardless of the implementation language chosen. At the conclusion of this part, a case study walks you through the steps of modeling a real-world application.

Part 2 looks at how object-oriented programming is implemented in C#. You will look at creating class structures, creating hierarchies, and implementing interfaces. This part also introduces object interaction and collaboration. You will see how the object-oriented programming topics discussed in Part 1 are transformed into C# coding constructs.

Part 3 covers creating .NET applications. You will learn how to develop a data access layer using the classes that make up the ADO.NET set of namespaces. You will create a Windows-based user interface, a web-based user interface, and a service-based programmatic interface. At the end of Part 3, you will revisit the case study developed in Part 1 and transform the design into a fully functional C# application. This includes creating a graphical user interface, implementing the business logic, and integrating with a relational database to store data.

Activities and Software Requirements One of the most important aspects of learning is doing. You can’t learn to ride a bike without jumping on a bike, and you can’t learn to program without cranking out code. Any successful training program needs to include both a theory component and a hands-on component.

I have included both components throughout this book. It is my hope that you will take seriously the Activities I have added to each chapter and work through them thoroughly—even repeatedly. Contrary to some students’ perception that these activities are “exercises in typing,” this is where you get a chance to make the theory concrete and where true simulation of the concepts occurs. I also encourage you to play as you work through an Activity. Don’t be afraid to alter some of the code just to see what happens. Some of the best learning experiences occur when students “color outside the lines.”

The UML modeling activities in Part 1 are for someone using UMLet. I chose this program because it’s a good diagramming tool to learn on. It lets you create UML diagrams without adding a lot of advanced features associated with the high-end CASE tools. UMLet is a free open source tool and can be downloaded from www.umlet.com. You can also use another tool such as Visio to complete the activities. However, you don’t even need a tool to complete these activities; paper and pencil will work just fine.

The activities in Part 2 require Visual Studio 2010 Express with C# installed. I encourage you to install the help files and make ample use of them while completing the activities. The activities in Part 3 require Microsoft SQL Server 2008 with the Pubs and Northwind databases installed. Appendix C includes instructions on downloading and installing the sample databases. You can find free Express editions of both Visual Studio 2010 and SQL Server 2008 at www.msdn.microsoft.com.