Visual C# 2012 IFMG 230
Deitel® Series Page How To Program Series Android How to Program C How to Program, 7/E C++ How to Program, 9/E C++ How to Program, Late Objects Version, 7/E Java™ How to Program, 9/E Java™ How to Program, Late Objects Version, 8/E Internet & World Wide Web How to Program, 5/E Visual Basic® 2012 How to Program Visual C#® 2012 How to Program, 5/E Visual C++® 2008 How to Program, 2/E Small Java™ How to Program, 6/E Small C++ How to Program, 5/E
Simply Series Simply C++: An App-Driven Tutorial Approach Simply Java™ Programming: An App-Driven
Tutorial Approach Simply Visual Basic® 2010, 4/E: An App-Driven
Save your time - order a paper!
Get your paper written from scratch within the tight deadline. Our service is a reliable solution to all your troubles. Place an order on any task and we will take care of it. You won’t have to worry about the quality and deadlines
Order Paper NowTutorial Approach
CourseSmart Web Books www.deitel.com/books/CourseSmart/
C++ How to Program, 7/E, 8/E & 9/E Simply C++: An App-Driven Tutorial Approach Java™ How to Program, 7/E, 8/E & 9/E
Simply Visual Basic 2010: An App-Driven Approach, 4/E
Visual Basic® 2012 How to Program Visual Basic® 2010 How to Program Visual C#® 2012 How to Program, 5/E Visual C#® 2010 How to Program, 4/E
Deitel® Developer Series C++ for Programmers, 2/E Android for Programmers: An App-Driven
Approach C# 2010 for Programmers, 3/E Dive Into® iOS 6: An App-Driven Approach iOS 6 for Programmers: An App-Driven Approach Java™ for Programmers, 2/E JavaScript for Programmers
LiveLessons Video Learning Products www.deitel.com/books/LiveLessons/
Android® App Development Fundamentals C++ Fundamentals C# Fundamentals iOS 6 App Development Fundamentals Java™ Fundamentals JavaScript Fundamentals Visual Basic® Fundamentals
To receive updates on Deitel publications, Resource Centers, training courses, partner offers and more, please register for the free Deitel® Buzz Online e-mail newsletter at:
www.deitel.com/newsletter/subscribe.html
and join the Deitel communities on Twitter®
@deitel
Facebook®
facebook.com/DeitelFan
and Google+ gplus.to/deitel
To communicate with the authors, send e-mail to: deitel@deitel.com
For information on government and corporate Dive-Into® Series on-site seminars offered by Deitel & Associates, Inc. worldwide, visit:
www.deitel.com/training/
or write to deitel@deitel.com
For continuing updates on Prentice Hall/Deitel publications visit: www.deitel.com www.pearsonhighered.com/deitel/
Visit the Deitel Resource Centers that will help you master programming languages, software develop- ment, Android and iPhone/iPad app development, and Internet- and web-related topics:
www.deitel.com/ResourceCenters.html
Paul Deitel Deitel & Associates, Inc.
Harvey Deitel Deitel & Associates, Inc.
Vice President and Editorial Director: Marcia J. Horton Executive Editor: Tracy Johnson Associate Editor: Carole Snyder Director of Marketing: Christy Lesko Marketing Manager: Yezan Alayan Marketing Assistant: Jon Bryant Director of Production: Erin Gregg Managing Editor: Scott Disanno Associate Managing Editor: Robert Engelhardt Operations Specialist: Lisa McDowell Art Director: Anthony Gemmellaro Cover Design: Abbey S. Deitel, Harvey M. Deitel, Anthony Gemmellaro Cover Photo Credit: © Shutterstock/Excellent backgrounds Media Project Manager: Renata Butera
Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on page vi.
The authors and publisher of this book have used their best efforts in preparing this book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and pub- lisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in this book. The authors and publisher shall not be liable in any event for incidental or consequential dam- ages in connection with, or arising out of, the furnishing, performance, or use of these programs.
Copyright © 2014, 2011, 2009 Pearson Education, Inc., publishing as Prentice Hall. All rights reserved. Manufac- tured in the United States of America. This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to 201-236-3290.
Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps.
Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published as part of the services for any purpose. All such documents and related graphics are provided “as is” without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchant- ability, whether express, implied or statutory, fitness for a particular purpose, title and non-infringement. In no event shall Microsoft and/or its respective suppliers be liable for any special, indirect or consequential damages or any dam- ages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of information available from the services.
The documents and related graphics contained herein could include technical inaccuracies or typographical errors. Changes are periodically added to the information herein. Microsoft and/or its respective suppliers may make improve- ments and/or changes in the product(s) and/or the program(s) described herein at any time. Partial screen shots may be viewed in full within the software version specified.
Library of Congress Cataloging-in-Publication Data on file.
10 9 8 7 6 5 4 3 2 1
ISBN-10: 0-13-337933-7
ISBN-13: 978-0-13-337933-4
To our review team
Shay Friedman Octavio Hernandez Stephen Hustedde José Antonio González Seco Shawn Weisfeld
We are grateful for your guidance and expertise.
Paul and Harvey Deitel
Trademarks DEITEL, the double-thumbs-up bug and DIVE INTO are registered trademarks of Deitel and Associates, Inc.
Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation.
UNIX is a registered trademark of The Open Group.
Throughout this book, trademarks are used. Rather than put a trademark symbol in every occurrence of a trademarked name, we state that we are using the names in an editorial fashion only and to the benefit of the trademark owner, with no intention of infringement of the trademark.
Chapters 24–35 and Appendices D–G are PDF documents posted online at the book’s Companion Website (located at www.pearsonhighered.com/deitel/).
Preface xix
Before You Begin xxxv
1 Introduction to Computers, the Internet and Visual C# 1
1.1 Introduction 2 1.2 Hardware and Moore’s Law 2 1.3 Data Hierarchy 3 1.4 Computer Organization 6 1.5 Machine Languages, Assembly Languages and High-Level Languages 7 1.6 Object Technology 8 1.7 Internet and World Wide Web 10 1.8 C# 12
1.8.1 Object-Oriented Programming 12 1.8.2 Event-Driven Programming 12 1.8.3 Visual Programming 12 1.8.4 An International Standard; Other C# Implementations 12 1.8.5 Internet and Web Programming 13 1.8.6 Introducing async/await 13 1.8.7 Other Key Contemporary Programming Languages 13
1.9 Microsoft’s .NET 14 1.9.1 .NET Framework 14 1.9.2 Common Language Runtime 15 1.9.3 Platform Independence 15 1.9.4 Language Interoperability 15
1.10 Microsoft’s Windows® Operating System 16 1.11 Windows Phone 8 for Smartphones 17
1.11.1 Selling Your Apps in the Windows Phone Marketplace 18 1.11.2 Free vs. Paid Apps 18 1.11.3 Testing Your Windows Phone Apps 18
1.12 Windows Azure™ and Cloud Computing 19 1.13 Visual Studio Express 2012 Integrated Development Environment 19
Contents
viii Contents
1.14 Painter Test-Drive in Visual Studio Express 2012 for Windows Desktop 19 1.15 Painter Test-Drive in Visual Studio Express 2012 for Windows 8 23
2 Dive Into® Visual Studio Express 2012 for Windows Desktop 33
2.1 Introduction 34 2.2 Overview of the Visual Studio Express 2012 IDE 34 2.3 Menu Bar and Toolbar 39 2.4 Navigating the Visual Studio IDE 41
2.4.1 Solution Explorer 43 2.4.2 Toolbox 44 2.4.3 Properties Window 44
2.5 Using Help 46 2.6 Using Visual App Development to Create a Simple App that Displays
Text and an Image 47 2.7 Wrap-Up 57 2.8 Web Resources 58
3 Introduction to C# Apps 65 3.1 Introduction 66 3.2 A Simple C# App: Displaying a Line of Text 66 3.3 Creating a Simple App in Visual Studio 72 3.4 Modifying Your Simple C# App 77 3.5 Formatting Text with Console.Write and Console.WriteLine 80 3.6 Another C# App: Adding Integers 81 3.7 Memory Concepts 85 3.8 Arithmetic 86 3.9 Decision Making: Equality and Relational Operators 90 3.10 Wrap-Up 94
4 Introduction to Classes, Objects, Methods and strings 106
4.1 Introduction 107 4.2 Classes, Objects, Methods, Properties and Instance Variables 107 4.3 Declaring a Class with a Method and Instantiating an Object of a Class 108 4.4 Declaring a Method with a Parameter 113 4.5 Instance Variables and Properties 116 4.6 UML Class Diagram with a Property 121 4.7 Software Engineering with Properties and set and get Accessors 121 4.8 Auto-Implemented Properties 123 4.9 Value Types vs. Reference Types 123 4.10 Initializing Objects with Constructors 125 4.11 Floating-Point Numbers and Type decimal 128 4.12 Wrap-Up 134
Contents ix
5 Control Statements: Part 1 142 5.1 Introduction 143 5.2 Algorithms 143 5.3 Pseudocode 144 5.4 Control Structures 144 5.5 if Single-Selection Statement 146 5.6 if…else Double-Selection Statement 148 5.7 while Repetition Statement 152 5.8 Formulating Algorithms: Counter-Controlled Repetition 154 5.9 Formulating Algorithms: Sentinel-Controlled Repetition 158 5.10 Formulating Algorithms: Nested Control Statements 166 5.11 Compound Assignment Operators 171 5.12 Increment and Decrement Operators 171 5.13 Simple Types 174 5.14 Wrap-Up 175
6 Control Statements: Part 2 189 6.1 Introduction 190 6.2 Essentials of Counter-Controlled Repetition 190 6.3 for Repetition Statement 191 6.4 Examples Using the for Statement 195 6.5 do…while Repetition Statement 199 6.6 switch Multiple-Selection Statement 201 6.7 break and continue Statements 209 6.8 Logical Operators 211 6.9 Structured-Programming Summary 216 6.10 Wrap-Up 221
7 Methods: A Deeper Look 231 7.1 Introduction 232 7.2 Packaging Code in C# 232 7.3 static Methods, static Variables and Class Math 234 7.4 Declaring Methods with Multiple Parameters 236 7.5 Notes on Declaring and Using Methods 240 7.6 Method-Call Stack and Activation Records 241 7.7 Argument Promotion and Casting 242 7.8 The .NET Framework Class Library 243 7.9 Case Study: Random-Number Generation 245
7.9.1 Scaling and Shifting Random Numbers 249 7.9.2 Random-Number Repeatability for Testing and Debugging 250
7.10 Case Study: A Game of Chance; Introducing Enumerations 250 7.11 Scope of Declarations 255 7.12 Method Overloading 258 7.13 Optional Parameters 260
x Contents
7.14 Named Parameters 262 7.15 Recursion 263 7.16 Passing Arguments: Pass-by-Value vs. Pass-by-Reference 266 7.17 Wrap-Up 269
8 Arrays; Introduction to Exception Handling 285 8.1 Introduction 286 8.2 Arrays 286 8.3 Declaring and Creating Arrays 288 8.4 Examples Using Arrays 289
8.4.1 Creating and Initializing an Array 289 8.4.2 Using an Array Initializer 290 8.4.3 Calculating a Value to Store in Each Array Element 291 8.4.4 Summing the Elements of an Array 292 8.4.5 Using Bar Charts to Display Array Data Graphically 293 8.4.6 Using the Elements of an Array as Counters 295 8.4.7 Using Arrays to Analyze Survey Results; Introduction to
Exception Handling 296 8.5 Case Study: Card Shuffling and Dealing Simulation 299 8.6 foreach Statement 303 8.7 Passing Arrays and Array Elements to Methods 305 8.8 Passing Arrays by Value and by Reference 307 8.9 Case Study: GradeBook Using an Array to Store Grades 311 8.10 Multidimensional Arrays 316 8.11 Case Study: GradeBook Using a Rectangular Array 321 8.12 Variable-Length Argument Lists 327 8.13 Using Command-Line Arguments 329 8.14 Wrap-Up 331
9 Introduction to LINQ and the List Collection 351 9.1 Introduction 352 9.2 Querying an Array of int Values Using LINQ 353 9.3 Querying an Array of Employee Objects Using LINQ 357 9.4 Introduction to Collections 362 9.5 Querying a Generic Collection Using LINQ 365 9.6 Wrap-Up 367 9.7 Deitel LINQ Resource Center 367
10 Classes and Objects: A Deeper Look 371 10.1 Introduction 372 10.2 Time Class Case Study 372 10.3 Controlling Access to Members 376 10.4 Referring to the Current Object’s Members with the this Reference 377 10.5 Time Class Case Study: Overloaded Constructors 379
Contents xi
10.6 Default and Parameterless Constructors 385 10.7 Composition 386 10.8 Garbage Collection and Destructors 389 10.9 static Class Members 390 10.10 readonly Instance Variables 393 10.11 Data Abstraction and Encapsulation 394 10.12 Class View and Object Browser 396 10.13 Object Initializers 398 10.14 Wrap-Up 398
11 Object-Oriented Programming: Inheritance 405 11.1 Introduction 406 11.2 Base Classes and Derived Classes 407 11.3 protected Members 409 11.4 Relationship between Base Classes and Derived Classes 410
11.4.1 Creating and Using a CommissionEmployee Class 410 11.4.2 Creating a BasePlusCommissionEmployee Class without
Using Inheritance 415 11.4.3 Creating a CommissionEmployee–BasePlusCommissionEmployee
Inheritance Hierarchy 420 11.4.4 CommissionEmployee–BasePlusCommissionEmployee Inheritance
Hierarchy Using protected Instance Variables 423 11.4.5 CommissionEmployee–BasePlusCommissionEmployee Inheritance
Hierarchy Using private Instance Variables 428 11.5 Constructors in Derived Classes 433 11.6 Software Engineering with Inheritance 434 11.7 Class object 434 11.8 Wrap-Up 435
12 OOP: Polymorphism, Interfaces and Operator Overloading 441
12.1 Introduction 442 12.2 Polymorphism Examples 444 12.3 Demonstrating Polymorphic Behavior 445 12.4 Abstract Classes and Methods 448 12.5 Case Study: Payroll System Using Polymorphism 450
12.5.1 Creating Abstract Base Class Employee 451 12.5.2 Creating Concrete Derived Class SalariedEmployee 453 12.5.3 Creating Concrete Derived Class HourlyEmployee 455 12.5.4 Creating Concrete Derived Class CommissionEmployee 457 12.5.5 Creating Indirect Concrete Derived Class
BasePlusCommissionEmployee 458 12.5.6 Polymorphic Processing, Operator is and Downcasting 460
xii Contents
12.5.7 Summary of the Allowed Assignments Between Base-Class and Derived-Class Variables 465
12.6 sealed Methods and Classes 466 12.7 Case Study: Creating and Using Interfaces 466
12.7.1 Developing an IPayable Hierarchy 468 12.7.2 Declaring Interface IPayable 469 12.7.3 Creating Class Invoice 469 12.7.4 Modifying Class Employee to Implement Interface IPayable 471 12.7.5 Modifying Class SalariedEmployee for Use with IPayable 473 12.7.6 Using Interface IPayable to Process Invoices and Employees
Polymorphically 474 12.7.7 Common Interfaces of the .NET Framework Class Library 476
12.8 Operator Overloading 477 12.9 Wrap-Up 480
13 Exception Handling: A Deeper Look 486 13.1 Introduction 487 13.2 Example: Divide by Zero without Exception Handling 488 13.3 Example: Handling DivideByZeroExceptions and FormatExceptions 491
13.3.1 Enclosing Code in a try Block 493 13.3.2 Catching Exceptions 493 13.3.3 Uncaught Exceptions 494 13.3.4 Termination Model of Exception Handling 495 13.3.5 Flow of Control When Exceptions Occur 495
13.4 .NET Exception Hierarchy 496 13.4.1 Class SystemException 496 13.4.2 Determining Which Exceptions a Method Throws 497
13.5 finally Block 497 13.6 The using Statement 504 13.7 Exception Properties 505 13.8 User-Defined Exception Classes 509 13.9 Wrap-Up 513
14 Graphical User Interfaces with Windows Forms: Part 1 518
14.1 Introduction 519 14.2 Windows Forms 520 14.3 Event Handling 522
14.3.1 A Simple Event-Driven GUI 522 14.3.2 Auto-Generated GUI Code 524 14.3.3 Delegates and the Event-Handling Mechanism 526 14.3.4 Another Way to Create Event Handlers 527 14.3.5 Locating Event Information 528
14.4 Control Properties and Layout 529
Contents xiii
14.5 Labels, TextBoxes and Buttons 533 14.6 GroupBoxes and Panels 536 14.7 CheckBoxes and RadioButtons 539 14.8 PictureBoxes 547 14.9 ToolTips 549 14.10 NumericUpDown Control 551 14.11 Mouse-Event Handling 553 14.12 Keyboard-Event Handling 556 14.13 Wrap-Up 559
15 Graphical User Interfaces with Windows Forms: Part 2 569
15.1 Introduction 570 15.2 Menus 570 15.3 MonthCalendar Control 579 15.4 DateTimePicker Control 580 15.5 LinkLabel Control 583 15.6 ListBox Control 587 15.7 CheckedListBox Control 591 15.8 ComboBox Control 594 15.9 TreeView Control 598 15.10 ListView Control 603 15.11 TabControl Control 609 15.12 Multiple Document Interface (MDI) Windows 614 15.13 Visual Inheritance 621 15.14 User-Defined Controls 626 15.15 Wrap-Up 630
16 Strings and Characters: A Deeper Look 638 16.1 Introduction 639 16.2 Fundamentals of Characters and Strings 640 16.3 string Constructors 641 16.4 string Indexer, Length Property and CopyTo Method 642 16.5 Comparing strings 643 16.6 Locating Characters and Substrings in strings 646 16.7 Extracting Substrings from strings 649 16.8 Concatenating strings 650 16.9 Miscellaneous string Methods 651 16.10 Class StringBuilder 652 16.11 Length and Capacity Properties, EnsureCapacity Method and Indexer
of Class StringBuilder 653 16.12 Append and AppendFormat Methods of Class StringBuilder 655 16.13 Insert, Remove and Replace Methods of Class StringBuilder 657 16.14 Char Methods 660
xiv Contents
16.15 (Online) Introduction to Regular Expressions 662 16.16 Wrap-Up 663
17 Files and Streams 669 17.1 Introduction 670 17.2 Data Hierarchy 670 17.3 Files and Streams 672 17.4 Classes File and Directory 673 17.5 Creating a Sequential-Access Text File 682 17.6 Reading Data from a Sequential-Access Text File 691 17.7 Case Study: Credit Inquiry Program 695 17.8 Serialization 701 17.9 Creating a Sequential-Access File Using Object Serialization 702 17.10 Reading and Deserializing Data from a Binary File 706 17.11 Wrap-Up 708
18 Searching and Sorting 715 18.1 Introduction 716 18.2 Searching Algorithms 717
18.2.1 Linear Search 717 18.2.2 Binary Search 721
18.3 Sorting Algorithms 726 18.3.1 Selection Sort 726 18.3.2 Insertion Sort 730 18.3.3 Merge Sort 734
18.4 Summary of the Efficiency of Searching and Sorting Algorithms 740 18.5 Wrap-Up 741
19 Data Structures 746 19.1 Introduction 747 19.2 Simple-Type structs, Boxing and Unboxing 747 19.3 Self-Referential Classes 748 19.4 Linked Lists 749 19.5 Stacks 762 19.6 Queues 766 19.7 Trees 769
19.7.1 Binary Search Tree of Integer Values 770 19.7.2 Binary Search Tree of IComparable Objects 777
19.8 Wrap-Up 782
20 Generics 789 20.1 Introduction 790 20.2 Motivation for Generic Methods 791 20.3 Generic-Method Implementation 793
Contents xv
20.4 Type Constraints 796 20.5 Overloading Generic Methods 798 20.6 Generic Classes 799 20.7 Wrap-Up 808
21 Collections 814 21.1 Introduction 815 21.2 Collections Overview 815 21.3 Class Array and Enumerators 818 21.4 Nongeneric Collections 821
21.4.1 Class ArrayList 821 21.4.2 Class Stack 826 21.4.3 Class Hashtable 828
21.5 Generic Collections 833 21.5.1 Generic Class SortedDictionary 834 21.5.2 Generic Class LinkedList 836
21.6 Covariance and Contravariance for Generic Types 840 21.7 Wrap-Up 843
22 Databases and LINQ 849 22.1 Introduction 850 22.2 Relational Databases 851 22.3 A Books Database 852 22.4 LINQ to Entities and the ADO.NET Entity Framework 856 22.5 Querying a Database with LINQ 857
22.5.1 Creating the ADO.NET Entity Data Model Class Library 858 22.5.2 Creating a Windows Forms Project and Configuring It to
Use the Entity Data Model 862 22.5.3 Data Bindings Between Controls and the Entity Data Model 864
22.6 Dynamically Binding Query Results 869 22.6.1 Creating the Display Query Results GUI 870 22.6.2 Coding the Display Query Results App 871
22.7 Retrieving Data from Multiple Tables with LINQ 874 22.8 Creating a Master/Detail View App 879
22.8.1 Creating the Master/Detail GUI 880 22.8.2 Coding the Master/Detail App 881
22.9 Address Book Case Study 883 22.9.1 Creating the Address Book App’s GUI 884 22.9.2 Coding the Address Book App 885
22.10 Tools and Web Resources 889 22.11 Wrap-Up 889
23 Web App Development with ASP.NET 897 23.1 Introduction 898
xvi Contents
23.2 Web Basics 899 23.3 Multitier App Architecture 900 23.4 Your First Web App 902
23.4.1 Building the WebTime App 904 23.4.2 Examining WebTime.aspx’s Code-Behind File 913
23.5 Standard Web Controls: Designing a Form 914 23.6 Validation Controls 918 23.7 Session Tracking 925
23.7.1 Cookies 926 23.7.2 Session Tracking with HttpSessionState 927 23.7.3 Options.aspx: Selecting a Programming Language 928 23.7.4 Recommendations.aspx: Displaying Recommendations
Based on Session Values 932 23.8 Case Study: Database-Driven ASP.NET Guestbook 933
23.8.1 Building a Web Form that Displays Data from a Database 935 23.8.2 Modifying the Code-Behind File for the Guestbook App 940
23.9 Online Case Study: ASP.NET AJAX 941 23.10 Online Case Study: Password-Protected Books Database App 942 23.11 Wrap-Up 942
Chapters on the Web 949
A Operator Precedence Chart 950
B Simple Types 952
C ASCII Character Set 954
Appendices on the Web 955
Index 957
Chapters 24–35 and Appendices D–G are PDF documents posted online at the book’s Companion Website (located at www.pearsonhighered.com/deitel/).
24 XML and LINQ to XML
25 Windows 8 UI and XAML
26 Windows 8 Graphics and Multimedia
Contents xvii
27 Building a Windows Phone 8 App
28 Asynchronous Programming with async and await
29 Web App Development with ASP.NET: A Deeper Look
30 Web Services
31 Building a Windows Azure™ Cloud Computing App
32 GUI with Windows Presentation Foundation
33 WPF Graphics and Multimedia
34 ATM Case Study, Part 1: Object-Oriented Design with the UML
35 ATM Case Study, Part 2: Implementing an Object- Oriented Design
D Number Systems
E UML 2: Additional Diagram Types
F Unicode®
G Using the Visual C# 2012 Debugger
This page intentionally left blank
Welcome to the Visual C#® 2012 computer programming language and the world of Mi- crosoft® Windows® and Internet and web programming with Microsoft’s .NET platform. Please read the book’s back cover and inside back cover—these concisely capture the book’s essence. In this Preface we provide more details.
This book is appropriate for introductory course sequences based on the curriculum recommendations of two key professional organizations—the ACM and the IEEE. The examples are accessible to computer science, information technology, software engineering and business students in novice-level and intermediate-level C# courses. The book can also be used by professional programmers.
At the heart of the book is the Deitel signature live-code approach—rather than using code snippets, we present concepts in the context of complete working programs followed by sample executions. Read the Before You Begin section after this Preface for instructions on setting up your computer to run the hundreds of code examples. The source code is avail- able at www.deitel.com/books/vcsharp2012htp and www.pearsonhighered.com/deitel. Use the source code we provide to compile and run each program as you study it—this will help you master Visual C# and related Microsoft technologies faster and at a deeper level.
We believe that this book and its supplements for students and instructors will give you an informative, engaging, challenging and entertaining introduction to Visual C#. If you have questions, we’re easy to reach at deitel@deitel.com—we’ll respond promptly. For book updates, visit www.deitel.com/books/vcsharp2012htp, join our social media communities on Facebook (www.deitel.com/DeitelFan), Twitter (@deitel), Google+ (gplus.to/deitel) and LinkedIn (bit.ly/DeitelLinkedIn), and subscribe to the Deitel® Buzz Online newsletter (www.deitel.com/newsletter/subscribe.html).
Visual C#® 2012, the Visual Studio® 2012 IDE, .NET 4.5, Windows® 7 and Windows® 8 The new Visual C# 2012 and its associated technologies motivated us to write Visual C# 2012 How to Program, 5/e. These are some of the key features of this new edition:
• Use with Windows 7, Windows 8 or both. The book is designed so that you can continue to use Windows 7 now and begin to evolve to Windows 8, if you like, or you can move right to Windows 8. All of the code examples in Chapters 1–24 and 28–35 were tested on both Windows 7 and Windows 8. The code examples for the Windows-8-specific chapters—Chapter 25 (Windows 8 UI and XAML), Chapter 26 (Windows 8 Graphics and Multimedia) and Chapter 27 (Building a Windows Phone 8 App)—were tested only on Windows 8.
• C# and Visual C#. The C# language has been standardized internationally by ECMA and ISO (the standards document is available free of charge at bit.ly/ ECMA334). Visual C# 2012 is Microsoft’s implementation of this standard.
Preface
xx Preface
• Modular multi-GUI treatment with Windows Forms, Windows 8 UI and WPF. The printed book features Windows Forms GUI; optional online chapters con- tain treatments of Windows 8 UI (user interface) and WPF GUI. Windows 8 UI apps are called Windows Store apps. In Chapter 25, you’ll learn how to create and test Windows Store apps and upload them to Microsoft’s Windows Store.
• Modular treatment of graphics and multimedia with Windows 8 and WPF. The book features optional online chapters on both Windows 8 Graphics and Multi- media (Chapter 26) and WPF Graphics and Multimedia (Chapter 33).
• Database with LINQ to Entities. In the previous edition of this book, we dis- cussed LINQ (Language Integrated Query) to SQL (Microsoft’s SQL Server da- tabase system). Microsoft stopped further development on LINQ to SQL in 2008 in favor of the newer and more robust LINQ to Entities and the ADO.NET Entity Framework, which we’ve switched to in this edition, keeping the discussion friendly for novices.
• SQL Server database. We use Microsoft’s free SQL Server Express 2012 (which installs with the free Visual Studio Express 2012 for Windows Desktop) to pres- ent the fundamentals of database programming. Chapters 22–23 and 29–30 use database and LINQ capabilities to build an address-book desktop app, a web- based guestbook app, a bookstore app and an airline reservation system app.
• ASP.NET 4.5. Microsoft’s .NET server-side technology, ASP.NET, enables you to create robust, scalable web-based apps. In Chapter 23, you’ll build several apps, including a web-based guestbook that uses ASP.NET and the ADO .NET Entity Framework to store data in a database and display data in a web page. The chapter also discusses the IIS Express web server for testing your web apps on your local computer.
• Building a Windows Phone 8 App. Windows Phone 8 is Microsoft’s latest oper- ating system for smartphones. It features multi-touch support for touchpads and touchscreen devices, enhanced security features and more. In Chapter 27, you’ll build a complete working Windows Phone 8 app and test it on the Windows Phone simulator; we’ll discuss how to upload apps to the Windows Phone Store.
• Building a Windows Azure™ Cloud Computing App. Windows Azure is a cloud computing platform that allows you to develop, manage and distribute your apps in the cloud. Chapter 31 shows you how to build a Windows Azure app that can store data in the cloud.
• Asynchronous programming with async and await. Asynchronous programming is simplified in Visual C# 2012 with the new async and await capabilities. We introduce asynchronous programming with async and await in Chapter 28.
Object-Oriented Programming • Early-objects approach. The book introduces the basic concepts and terminology
of object technology in Chapter 1. In Chapter 2, Dive Into Visual Studio 2012 Ex- press for Windows Desktop, you’ll visually manipulate objects, such as labels and images. In Chapter 3, Introduction to C# Apps, you’ll write Visual C# program code
Complete Code Examples xxi
that manipulates preexisting objects. You’ll develop your first customized classes and objects in Chapter 4. Presenting objects and classes early gets you “thinking about objects” immediately and mastering these concepts more thoroughly.
• Rich coverage of programming fundamentals. Chapters 5 and 6 present a friendly treatment of control statements and problem solving.
• A clear, example-driven presentation of classes, objects, inheritance, polymor- phism and interfaces.
• Optional case study: Using the UML to develop an object-oriented design and Vi- sual C# implementation of an Automated Teller Machine (ATM). The UML™ (Unified Modeling Language™) is the industry-standard graphical language for modeling object-oriented systems. We introduce the UML in the early chapters. Online Chapters 34 and 35 include an optional case study on object-oriented de- sign using the UML. We design and implement the software for a simple automat- ed teller machine. We analyze a typical requirements document that specifies the system to be built. We determine the classes needed to implement that system, the attributes the classes need to have, the behaviors the classes need to exhibit and we specify how the classes must interact with one another to meet the system require- ments. From the design we produce a complete working Visual C# implementa- tion. Students often report a “light bulb moment”—the case study helps them “tie it all together” and truly understand object orientation.
• Three programming paradigms. We discuss structured programming, object-orient- ed programming and generic programming.
Complete Code Examples We include a broad range of example programs selected from computer science, business, simulation, game playing, graphics, multimedia and many other areas (Fig. 1).
Examples
Account class Address book case study Airline reservation web-service Animating the width and
height of a video Applying transforms to a poly-
gon Array initializer ArrayList class BasePlusCommissionEmployee
class Binary search Blackjack game web-service Books database
Card shuffling and dealing CheckedListBox control ComboBox control CommissionEmployee class Common Windows 8 UI con-
trols Common WPF controls Compound interest calcula-
tions Counter-controlled repetition Craps dice game simulation Creating and using a text file Creating custom windows and
using timers
Credit-inquiry program Data binding Date class DateTimePicker control Defining gradients in XAML Dice rolling Directory class Document navigation using XNode
Drawing basic shapes Drawing polylines and poly-
gons Employee class File class
Fig. 1 | A small sample of the book’s hundreds of examples. (Part 1 of 2.)
xxii Preface
Interesting, Entertaining and Challenging Exercises • Extensive self-review exercises and answers are included for self-study.
• Each chapter concludes with a substantial set of exercises, which generally in- cludes simple recall of important terminology and concepts, identifying the errors in code samples, writing individual program statements, writing small portions of Visual C# classes, writing complete programs and implementing major proj- ects. Figure 2 lists a small sampling of the book’s hundreds of exercises, including selections from our Making a Difference exercises set, which encourage you to use computers and the Internet to research and solve significant social problems—we hope you’ll approach these exercises with your own values, politics and beliefs.
Formatting fonts Generic class Stack Generic class List GradeBook class Guestbook app HourlyEmployee class Session tracking in ASP.NET Invoice class IPayable interface Keyboard events LinkLabel control LINQ to Objects with arrays ListBox control Math tutor using web services Menus
NegativeNumberException
NumericUpDown control Object serialization Overloaded constructors PictureBox displaying images Reading sequential-access files Recursive Factorial method REST Web services with
JSON and XML SalariedEmployee class Searching directories with
LINQ Sequential search Sorting an array Stack unwinding
StringBuilder class TabControl
Text-to-speech and speech-to- text
Time class Toolbars TreeView control TV GUI showing GUI
customization Poll analysis Polymorphism demonstration Querying a database with
LINQ to Entities Queue class RadioButton control
Exercises
Airline Reservations System All Possible Three-Letter Words
from a Five-Letter Word Baseball Database App Binary Tree Traversals Blackjack Body Mass Index Calculator Bucket Sort Building Your Own Computer Calendar and Appointments Carbon Footprint Calculator
Card Shuffling and Dealing Car-Pool Savings Calculator Coin Tossing Complex Numbers Computer-Assisted Instruction Computerization of Health
Records Cooking with Healthier
Ingredients Credit Limit Calculator Dice Rolling
Ecofont Eight Queens Employee Class Enforcing Privacy with
Cryptography Enhanced Painter Factorials Fuzzy Dice Order Form Game of Craps Gas Mileage Generic Method Overloading
Fig. 2 | A sampling of the book’s exercises. (Part 1 of 2.)
Examples
Fig. 1 | A small sample of the book’s hundreds of examples. (Part 2 of 2.)
Illustrations and Figures xxiii
Illustrations and Figures Abundant tables, line drawings, UML diagrams, programs and program outputs are in- cluded. A sampling of these is shown in Figs. 3 and 4.
Guess the Number Game Invoice Class Knight’s Tour MDI Text Editor Nutrition Information Palindromes Phishing Scanner Phone-Book Web Service Pig Latin Polymorphic Banking Program
Using Account Hierarchy Pythagorean Triples
Quicksort Quiz App Rational Numbers Restaurant Bill Calculator Salary Calculator Sales Commissions Savings-Account Class Sieve of Eratosthenes Tortoise and Hare Simulation SMS Language Spam Scanner Story Writer
Student Poll Target-Heart-Rate Calculator Tax Plan Alternatives: The
“FairTax” Telephone-Number Word
Generator Tic-Tac-Toe Towers of Hanoi Turtle Graphics Typing Tutor Web-based Address Book World Population Growth
Main text tables, drawings and diagrams
Anchoring demonstration Ajax-enabled web app Binary tree graphical represen-
tation Circular, doubly linked list Circular, singly linked list Client receiving a response
from a web server Client requesting a response
from a web server Creating a web service Collection classes of the .NET
Framework Common built-in commands
from the WPF command library
Components and controls Custom-control creation DatePicker properties/event Doubly linked list Entity-relationship diagram
for the Books database
Escape sequences GroupBox properties HttpSessionState properties Implicit conversions between
simple types Increment and decrement
operators insertAtBack operation repre-
sented graphically insertAtFront operation rep-
resented graphically Interaction between a web-
service client and a SOAP web service
Interfaces of the .NET Frame- work Class Library
Keyboard events and event arguments
Keywords and contextual keywords
Linked list graphical representation
LINQ to XML class hierarchy Master/Detail app Math class methods Mouse events and event
arguments .NET Framework Class
Library namespaces Number of comparisons for
common Big O notations Object methods inherited by
all classes Polymorphic interface for the Employee hierarchy classes
Precedence of arithmetic oper- ators
removeFromBack operation represented graphically
removeFromFront operation represented graphically
Rules of forming structured apps
SDI and MDI forms
Fig. 3 | A sampling of the book’s tables, drawings and diagrams. (Part 1 of 2.)
Exercises
Fig. 2 | A sampling of the book’s exercises. (Part 2 of 2.)
xxiv Preface
Other Features • We use LINQ to query files, databases, XML and collections. The introductory
LINQ to Objects chapter (Chapter 9), is intentionally simple and brief to en- courage instructors to begin covering LINQ technology early. Later in the book, we take a deeper look, using LINQ to Entities (Chapters 22–23 and 29–30) and LINQ to XML (Chapters 24, 30 and 31).
• Local type inference. When you initialize a local variable in its declaration, you can omit the variable’s type—the compiler infers it from the initializer value.
• Object initializers. For new objects, you can use object initializer syntax (similar to array initializer syntax) to assign values to the new object’s public properties and public instance variables.
• We emphasize the IDE’s IntelliSense feature that helps you write code faster and with fewer errors.
• Files and strings.
• Data structures chapter sequence, including searching and sorting, data struc- tures, generics and collections.
Searching and sorting algorithms with Big O values
Single-entry/single-exit sequence, selection and repetition statements
string format specifiers Three-tier architecture Traditional web app reloading
the page for every user interaction
Tree structure for the document article.xml
Validation app enhanced by ASP.NET Ajax
XSL style-sheet elements
Object-oriented design case study drawings and diagrams
Use case diagram for the ATM system from the user’s perspective
Class diagram with an association among classes Class diagram showing composition relationships Class diagram for the ATM system model Classes with attributes State diagram for the ATM Activity diagram for a BalanceInquiry transaction Activity diagram for a Withdrawal transaction Classes in the ATM system with attributes and
operations Communication diagram of the ATM executing
a balance inquiry
Communication diagram for executing a balance inquiry
Sequence diagram that models a Withdrawal exe- cuting
Use case diagram for a modified version of our ATM system that also allows users to transfer money between accounts
Class diagram showing composition relation- ships of a class Car
Class diagram for the ATM system model including class Deposit
Activity diagram for a Deposit transaction Sequence diagram that models a Deposit executing
Fig. 4 | A sampling of the object-oriented design case study drawings and diagrams.
Main text tables, drawings and diagrams
Fig. 3 | A sampling of the book’s tables, drawings and diagrams. (Part 2 of 2.)
Companion Website xxv
• Integrated exception handling. We introduce exception handling early (Chapter 8, Arrays; Introduction to Exception Handling) to ensure that we do not access an array element outside the array’s bounds. Chapter 10, Classes and Objects: A Deeper Look, shows how to indicate an exception when a member function re- ceives an invalid argument. We cover the complete details of exception handling in Chapter 13, Exception Handling: A Deeper Look.
• Visual C# XML capabilities. Extensible Markup Language (XML) is pervasive in the software-development industry, e-business and throughout the .NET platform. In optional online Chapter 24, we introduce XML syntax and programmatically manipulate the elements of an XML document using LINQ to XML. XAML is an XML vocabulary that’s used to describe graphical user interfaces, graphics and mul- timedia. We discuss XAML in optional online Chapters 25–26 and 32–33.
• Web app development with ASP.NET 4.5 and ASP.NET AJAX. Optional online Chapter 29 extends Chapter 23’s ASP.NET discussion with a case study on building a password-protected, web-based bookstore app. Also, we introduce in Chapter 29 ASP.NET AJAX controls and use them to add AJAX functionality to web apps to give them a look and feel similar to that of desktop apps.
• WCF (Windows Communication Foundation) web services. Web services enable you to package app functionality in a manner that turns the web into a library of reusable services. Optional online Chapter 30 includes case studies on building an airline reservation web service, a blackjack web service and a math question gen- erator web service that’s called by a math tutor app.
• WPF (Windows Presentation Foundation) GUI, graphics and multimedia. We extend the core book’s GUI coverage in optional online Chapters 32–33 with an introduction to Windows Presentation Foundation (WPF)—a XAML-based Mi- crosoft framework that preceded Windows 8 UI and integrates GUI, graphics and multimedia capabilities. We implement a painting app, a text editor, a color chooser, a book-cover viewer, a television video player, various animations, and speech synthesis and recognition apps.
Companion Website The printed book contains the core content (Chapters 1–23) for introductory course se- quences. Several optional online chapters are available for advanced courses and profes- sionals. Figure 5 lists the chapters and appendices that are available in searchable PDF format on the book’s password-protected Companion Website at:
See the inside front cover of the book for an access code.
www.pearsonhighered.com/deitel
Online chapters
Chapter 24, XML and LINQ to XML
Chapter 25, Windows 8 UI and XAML
Fig. 5 | Online chapters and appendices in Visual C# 2012 How to Program, 5/e. (Part 1 of 2.)
xxvi Preface
VideoNotes The Companion Website also includes extensive VideoNotes—watch and listen as co-au- thor Paul Deitel discusses key code examples in the core chapters of the book. VideoNotes allow for self-paced instruction with easy navigation, including the ability to select, play, rewind, fast-forward and stop within each video.
We’ve created a jump table that maps each VideoNote to the corresponding figures in the book (www.deitel.com/books/vcsharphtp5/jump_table.pdf). VideoNotes are free with the purchase of a new textbook. If you have a used book you can purchase access to the VideoNotes for this book as follows:
1. Go to www.pearsonhighered.com/deitel/.
2. Scroll to Visual C# 2012 How to Program, 5/e and click Companion Website.
3. Click the Register button.
4. On the registration page, enter your student access code found beneath the scratch-off panel on the inside front cover of this book. Do not type the dashes. You can use lower- or uppercase. The access code can be used only once. This sub- scription is valid for twelve months upon activation and is not transferable. If this access code on your book has already been revealed, it may no longer be valid. If this is the case, click the Website Purchase link and follow the instructions.
5. Once your personal Login Name and Password are confirmed, you can begin us- ing the Visual C# 2012 How to Program, 5/e Companion Website.
Chapter 26, Windows 8 Graphics and Multimedia
Chapter 27, Building a Windows Phone 8 App
Chapter 28, Introduction to Concurrency: async and await
Chapter 29, Web App Development with ASP.NET: A Deeper Look
Chapter 30, Web Services
Chapter 31, Building a Windows Azure™ Cloud Computing App
Chapter 32, GUI with Windows Presentation Foundation
Chapter 33, WPF Graphics and Multimedia
Chapter 34, ATM Case Study, Part 1: Object-Oriented Design with the UML
Chapter 35, ATM Case Study, Part 2: Implementing an Object-Oriented Design
Appendix D, Number Systems
Appendix E, UML 2: Additional Diagram Types
Appendix F, Unicode®
Appendix G, Using the Visual Studio 2012 Debugger
Index (The online index includes the content from the printed book and the online content. The printed book index covers only the printed material.)
Online chapters
Fig. 5 | Online chapters and appendices in Visual C# 2012 How to Program, 5/e. (Part 2 of 2.)
Book Overview and Chapter Dependencies xxvii
Book Overview and Chapter Dependencies This section discusses the book’s modular organization to help instructors plan their syllabi.
Introduction to Visual C# and Visual Studio 2012 Express Chapter 1, Introduction to Computers, the Internet and Visual C#, introduces comput- ing fundamentals and Microsoft’s .NET platform. If you do not need to cover these fun- damentals, you should still cover the Painter app test-drive. The vast majority of the book’s examples will run on Windows 7 and Windows 8 using Visual Studio Express 2012 for Windows Desktop, which we test-drive in Section 1.14. Chapters 25–26 can be run only on Windows 8 using Visual Studio Express 2012 for Windows 8, which we test-drive in Section 1.15. There are other versions of Visual Studio Express 2012 for web development and Windows Phone development—we cover these in the corresponding chapters.
Chapter 2, Dive Into® Visual Studio Express 2012 for Windows Desktop, shows how to develop a simple GUI app that displays text and an image. We’ll look at Visual Studio Express 2012 for Windows 8 in more depth in Chapter 25.
Introduction to Visual C# Fundamentals and Object-Oriented Programming The chapters in this module of the book:
• Chapter 3, Introduction to C# Apps
• Chapter 4, Introduction to Classes, Objects, Methods and strings
• Chapter 5, Control Statements: Part 1
• Chapter 6, Control Statements: Part 2
• Chapter 7, Methods: A Deeper Look
• Chapter 8, Arrays; Introduction to Exception Handling
present C# programming fundamentals (data types, operators, control statements, meth- ods and arrays) and introduce object-oriented programming. These chapters should be covered in order. Chapter 8 introduces exception handling with an example that demon- strates accessing an element outside an array’s bounds.
Object-Oriented Programming: A Deeper Look The chapters in this module of the book:
• Chapter 9, Introduction to LINQ and the List Collection
• Chapter 10, Classes and Objects: A Deeper Look
• Chapter 11, Object-Oriented Programming: Inheritance
• Chapter 12, OOP: Polymorphism, Interfaces and Operator Overloading
• Chapter 13, Exception Handling: A Deeper Look
• Chapter 34, ATM Case Study, Part 1: Object-Oriented Design with the UML
• Chapter 35, ATM Case Study, Part 2: Implementing an Object-Oriented Design
provide a deeper look at object-oriented programming, including classes, objects, inheri- tance, polymorphism, interfaces and exception handling. Chapter 9, Introduction to LINQ and the List Collection, introduces Microsoft’s Language Integrated Query (LINQ) tech- nology, which provides a uniform syntax for manipulating data from various data sources,
xxviii Preface
such as arrays, collections and, as you’ll see in later chapters, XML and databases. This chap- ter can be deferred, but it’s required for one example in Chapter 17 (Fig. 17.6) and many of the later chapters starting with Chapter 22, Databases and LINQ. Online Chapters 34–35 present an optional object-oriented design and implementation case study that requires the C# and object-oriented programming concepts presented in Chapters 3–8 and 10–13.
Windows Forms Graphical User Interfaces (GUIs) There are now three GUI technologies in Windows—Windows Forms (which is a legacy technology), Windows 8 UI (available only on Windows 8) and Windows Presentation Foundation (WPF). We surveyed instructors teaching Visual C# and they still prefer Win- dows Forms for their classes, so we provide a two-chapter introduction to Windows Forms:
• Chapter 14, Graphical User Interfaces with Windows Forms: Part 1
• Chapter 15, Graphical User Interfaces with Windows Forms: Part 2
in the print book, then use Windows Forms GUIs in several other print and online chap- ters. Most examples in Chapters 14–15 can be presented after Chapter 4. For those who wish to present or study Microsoft’s more recent GUI, graphics and multimedia technol- ogies, we provide two-chapter online introductions to Windows 8 UI, graphics and mul- timedia (Chapters 25–26) and WPF GUI, graphics and multimedia (Chapters 32–33).
Strings and Files We introduce strings beginning in Chapter 4 and use them throughout the book. Chapter 16, Strings and Characters: A Deeper Look, investigates strings in more depth. Chapter 17, Files and Streams, introduces text-file processing and object-serialization for input/output of entire objects. Chapter 16 can be presented at any point after Chapter 4. Chapter 17 requires C#, object-oriented programming and Windows Forms concepts pre- sented in Chapters 3–14.
Searching, Sorting and Data Structures The chapters in this module of the book:
• Chapter 18, Searching and Sorting
• Chapter 19, Data Structures
• Chapter 20, Generics
• Chapter 21, Collections
introduce searching, sorting and data structures. Most C# programmers should use .NET’s built-in searching, sorting and collections (prepackaged data structures) capabili- ties, which are discussed in Chapter 21. For instructors who wish to present how to im- plement customized searching, sorting and data structures capabilities, we provide Chapters 18–20, which require the concepts presented in Chapters 3–8 and 10–13.
Databases and an Introduction to Web App Development Chapter 22, Databases and LINQ, introduces database app development using the ADO.NET Entity Framework and LINQ to Entities. The chapter’s examples require C#, object-oriented programming and Windows Forms concepts presented in Chapters 3–14. Chapter 23, Web App Development with ASP.NET, introduces web app development.
Book Overview and Chapter Dependencies xxix
The last example in this chapter requires the LINQ and database techniques presented in Chapter 22.
Extensible Markup Language (XML) Chapter 24, XML and LINQ to XML, introduces XML, which is used in several later chap- ters. The first few sections of this chapter are required to understand the XAML markup that’s used to build Windows 8 GUI, graphics and multimedia apps (Chapters 25–26), Windows Phone 8 apps (Chapter 27) and WPF GUI, graphics and multimedia apps (Chapters 32–33). The remainder of the chapter discusses LINQ to XML, which allows you to manipulate XML using LINQ syntax. These capabilities are used in Chapters 30 and 31.
Windows 8 UI, Graphics and Multimedia; Windows Phone The chapters in this module of the book:
• Chapter 25, Windows 8 UI and XAML
• Chapter 26, Windows 8 Graphics and Multimedia
• Chapter 27, Building a Windows Phone 8 App
present Windows 8 UI, graphics and multimedia, and Windows Phone 8 app develop- ment. These chapters can be used only on computers running Windows 8 and depend on event-handling concepts that are presented in Chapter 14, and the introduction to XML at the beginning of Chapter 24 (see Section 24.1 for details). Developing a Windows Phone 8 app is similar to developing a Windows 8 UI app.
Asynchronous Programming Chapter 28, Asynchronous Programming with async and await, demonstrates .NET’s and Visual C#’s new simplified asynchronous programming capabilities. These are com- monly used in Web app and Web service development (among many other uses).
Web App Development and Web Services The chapters in this module of the book:
• Chapter 29, Web App Development with ASP.NET: A Deeper Look
• Chapter 30, Web Services
• Chapter 31, Building a Windows Azure™ Cloud Computing App
continue our discussion of Web app development from Chapter 23 and introduce web ser- vices, including a case study on cloud computing with Windows Azure. Chapters 30 and 31 depend on the LINQ to XML discussion in Chapter 24.
Windows Presentation Foundation (WPF) GUI, Graphics and Multimedia The chapters in this module of the book
• Chapter 32, GUI with Windows Presentation Foundation
• Chapter 33, WPF Graphics and Multimedia
discuss Windows Presentation Foundation GUI, graphics and multimedia. These chap- ters can be used on computers running Windows 7 or Windows 8 and depend on event- handling concepts that are presented in Chapter 14 and the introduction to XML at the beginning of Chapter 24.
xxx Preface
Teaching Approach Visual C# 2012 How to Program, 5/e contains a rich collection of examples. We concen- trate on building good software and stress program clarity.
Live-Code Approach. The book is loaded with “live-code” examples. Most new concepts are presented in the context of complete working Visual C# apps, followed by one or more executions showing program inputs and outputs. In the few cases where we show a code snippet, to ensure correctness we first tested it in a complete working program then copied the code from the program and pasted it into the book.
Syntax Shading. For readability, we syntax shade the code, similar to the way most inte- grated-development environments and code editors syntax color the code. Our syntax- shading conventions are:
Code Highlighting. We place gray rectangles around each program’s key code segments.
Using Fonts for Emphasis. We place the key terms and the index’s page reference for each defining occurrence in bold text for easy reference. We show on-screen components in the bold Helvetica font (for example, the File menu) and Visual C# program text in the Lucida font (for example, int count = 5). We use italics for emphasis.
Objectives. The chapter objectives preview the topics covered in the chapter.
Programming Tips. We include programming tips to help you focus on important as- pects of program development. These tips and practices represent the best we’ve gleaned from a combined seven decades of programming and teaching experience.
comments appear like this keywords appear like this constants and literal values appear like this all other code appears in black
Good Programming Practice The Good Programming Practices call attention to techniques that will help you pro- duce programs that are clearer, more understandable and more maintainable.
Common Programming Error Pointing out these Common Programming Errors reduces the likelihood that you’ll make them.
Error-Prevention Tip These tips contain suggestions for exposing and removing bugs from your programs; many of the tips describe aspects of Visual C# that prevent bugs from getting into programs.
Performance Tip These tips highlight opportunities for making your programs run faster or minimizing the amount of memory that they occupy.
Portability Tip The Portability Tips help you write code that will run on a variety of platforms.
Obtaining the Software Used in Visual C# How to Program, 5/e xxxi
Summary Bullets. We present a detailed bullet-list summary of each chapter.
Terminology. We include a list of the important terms defined in each chapter.
Index. We’ve included an extensive index for reference. Defining occurrences of key terms in the index are highlighted with a bold page number.
Obtaining the Software Used in Visual C# How to Program, 5/e We wrote the code examples in Visual C# 2012 How to Program, 5/e using Microsoft’s free Visual Studio Express 2012 products, including:
• Visual Studio Express 2012 for Windows Desktop (Chapters 1–24, 28 and 32– 35), which includes Visual C# and other Microsoft development tools. This runs on Windows 7 and 8.
• Visual Studio Express 2012 for Web (Chapters 23 and 29–31)
• Visual Studio Express 2012 for Windows 8 (Chapters 25–26)
• Visual Studio Express 2012 for Windows Phone (Chapter 27)
Each of these is available for download at
Instructor Supplements The following supplements are available to qualified instructors only through Pearson Education’s Instructor Resource Center (www.pearsonhighered.com/irc):
• Solutions Manual contains solutions to most of the end-of-chapter exercises. We’ve added many Making a Difference exercises, most with solutions. Please do not write to us requesting access to the Pearson Instructor’s Resource Center. Access is re- stricted to college instructors teaching from the book. Instructors may obtain ac- cess only through their Pearson representatives. If you’re not a registered faculty member, contact your Pearson representative or visit www.pearsonhighered.com/ educator/replocator/. Exercise Solutions are not provided for “project” exercis- es. Check out our Programming Projects Resource Center for lots of additional ex- ercise and project possibilities:
• Test Item File of multiple-choice questions (approximately two per book section) • Customizable PowerPoint® slides containing all the code and figures in the text,
plus bulleted items that summarize the key points in the text.
Software Engineering Observation The Software Engineering Observations highlight architectural and design issues that affect the construction of software systems, especially large-scale systems.
Look-and-Feel Observation These observations help you design attractive, user-friendly graphical user interfaces that conform to industry norms.
www.microsoft.com/visualstudio/eng/products/ visual-studio-express-products
www.deitel.com/ProgrammingProjects
xxxii Preface
Microsoft DreamSpark™ Professional Developer and Designer Tools for Students Microsoft provides many of its professional developer tools to students for free via a pro- gram called DreamSpark (www.dreamspark.com). See the website for details on verifying your student status so you take advantage of this program.
Acknowledgments We’d like to thank Abbey Deitel and Barbara Deitel of Deitel & Associates, Inc. for long hours devoted to this project. Abbey co-authored this Preface and Chapter 1 and she and Barbara painstakingly researched the new capabilities of Visual C# 2012, .NET 4.5, Win- dows 8, Windows Phone 8, Windows Azure and other key topics.
We’re fortunate to have worked with the dedicated team of publishing professionals at Pearson Higher Education. We appreciate the guidance, wisdom and energy of Tracy Johnson, Executive Editor, Computer Science. Carole Snyder did an extraordinary job recruiting the book’s reviewers and managing the review process. Bob Engelhardt did a wonderful job bringing the book to publication.
Reviewers We wish to acknowledge the efforts of our reviewers. The book was scrutinized by aca- demics teaching C# courses and industry experts. They provided countless suggestions for improving the presentation. Any remaining flaws in the book are our own.
Fifth Edition Reviewers: Shay Friedman (Microsoft Visual C# MVP), Octavio Her- nandez (Microsoft Certified Solutions Developer), Stephen Hustedde (South Mountain College), José Antonio González Seco (Parliament of Andalusia, Spain) and Shawn Weis- feld (Microsoft MVP and President and Founder of UserGroup.tv).
Other recent edition reviewers: Huanhui Hu (Microsoft Corporation), Narges Kasiri (Oklahoma State University), Charles Liu (University of Texas at San Antonio), Dr. Hamid R. Nemati (The University of North Carolina at Greensboro), Jeffrey P. Scott (Blackhawk Technical College), Douglas B. Bock (MCSD.NET, Southern Illinois Uni- versity Edwardsville), Dan Crevier (Microsoft), Amit K. Ghosh (University of Texas at El Paso), Marcelo Guerra Hahn (Microsoft), Kim Hamilton (Software Design Engineer at Microsoft and co-author of Learning UML 2.0), James Edward Keysor (Florida Institute of Technology), Helena Kotas (Microsoft), Chris Lovett (Software Architect at Micro- soft), Bashar Lulu (INETA Country Leader, Arabian Gulf), John McIlhinney (Spatial Intelligence; Microsoft MVP 2008 Visual Developer, Visual Basic), Ged Mead (Microsoft Visual Basic MVP, DevCity.net), Anand Mukundan (Architect, Polaris Software Lab Ltd.), Timothy Ng (Microsoft), Akira Onishi (Microsoft), Joe Stagner (Senior Program Manager, Developer Tools & Platforms), Erick Thompson (Microsoft), Jesús Ubaldo Quevedo-Torrero (University of Wisconsin–Parkside, Department of Computer Science) and Zijiang Yang (Western Michigan University).
As you read the book, we’d sincerely appreciate your comments, criticisms and sug- gestions for improving the text. Please address all correspondence to:
deitel@deitel.com
About the Authors xxxiii
We’ll respond promptly. We really enjoyed writing this book—we hope you enjoy reading it!
Paul Deitel Harvey Deitel
About the Authors Paul Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., is a graduate of MIT, where he studied Information Technology. Through Deitel & Associates, Inc., he has delivered hundreds of programming courses to industry clients, including Cisco, IBM, Siemens, Sun Microsystems, Dell, Fidelity, NASA at the Kennedy Space Center, the National Severe Storm Laboratory, White Sands Missile Range, Rogue Wave Software, Boeing, SunGard Higher Education, Nortel Networks, Puma, iRobot, Invensys and many more. He and his co-author, Dr. Harvey M. Deitel, are the world’s best-selling program- ming-language textbook/professional book/video authors.
Paul was named as a Microsoft® Most Valuable Professional (MVP) for C# in 2012. According to Microsoft, “the Microsoft MVP Award is an annual award that recognizes exceptional technology commu- nity leaders worldwide who actively share their high quality, real world expertise with users and Micro- soft.”
Dr. Harvey Deitel, Chairman and Chief Strategy Officer of Deitel & Associates, Inc., has 50 years of experience in the computer field. Dr. Deitel earned B.S. and M.S. degrees in Electrical Engineering from MIT and a Ph.D. in Mathematics from Boston University. He has extensive college teaching experience, including earning tenure and serving as the Chairman of the Computer Science Department at Boston College before founding Deitel & Associates, Inc., in 1991 with his son, Paul Deitel. The Deitels’ publications have earned international recognition, with translations published in Chinese, Korean, Japa- nese, German, Russian, Spanish, French, Polish, Italian, Portuguese, Greek, Urdu and Turkish. Dr. Deitel has delivered hundreds of programming courses to corporate, aca- demic, government and military clients.
Deitel® Dive-Into® Series Programming Languages Training Deitel & Associates, Inc., founded by Paul Deitel and Harvey Deitel, is an internationally recognized authoring and corporate training organization, specializing in computer pro- gramming languages, object technology, mobile app development and Internet and web software technology. The company’s training clients include many of the world’s largest companies, government agencies, branches of the military, and academic institutions. The company offers instructor-led training courses delivered at client sites worldwide on major programming languages and platforms, including Visual C#®, Visual Basic®, Visual C++®, C++, C, Java™, XML®, Python®, object technology, Internet and web program- ming, Android app development, Objective-C and iPhone app development and a grow- ing list of additional programming and software development courses.
2012 C# MVP
xxxiv Preface
Through its 37-year publishing partnership with Prentice Hall/Pearson, Deitel & Associates, Inc., publishes leading-edge programming college textbooks, professional books and LiveLessons video courses. Deitel & Associates, Inc. and the authors can be reached at:
To learn more about Deitel’s Dive-Into® Series Corporate Training curriculum, visit:
To request a proposal for worldwide on-site, instructor-led training at your organization, e-mail deitel@deitel.com.
Individuals wishing to purchase Deitel books and LiveLessons video training can do so through www.deitel.com. Bulk orders by corporations, the government, the military and academic institutions should be placed directly with Pearson. For more information, visit
deitel@deitel.com
www.deitel.com/training
www.informit.com/store/sales.aspx
This section contains information you should review before using this book and instruc- tions to ensure that your computer is set up properly for use with this book.
Font and Naming Conventions We use fonts to distinguish between features, such as menu names, menu items, and other elements that appear in the program-development environment. Our convention is to em- phasize IDE features in a sans-serif bold Helvetica font (for example, Properties window) and to emphasize program text in a sans-serif Lucida font (for example, bool x = true).
Software This textbook uses the following software:
• Microsoft Visual Studio Express 2012 for Windows Desktop
• Microsoft Visual Studio Express 2012 for Web (Chapters 23 and 29–31)
• Microsoft Visual Studio Express 2012 for Windows 8 (Chapters 25–26)
• Microsoft Visual Studio Express 2012 for Windows Phone (Chapter 27)
Each is available free for download at www.microsoft.com/express. The Express Editions are fully functional, and there’s no time limit for using the software.
Hardware and Software Requirements for the Visual Studio 2012 Express Editions To install and run the Visual Studio 2012 Express Editions, ensure that your system meets the minimum requirements specified at:
Microsoft Visual Studio Express 2012 for Windows 8 works only on Windows 8.
Viewing File Extensions Several screenshots in Visual C# 2012 How to Program, 5/e display file names with file-name extensions (e.g., .txt, .cs or .png). Your system’s settings may need to be adjusted to display file-name extensions. Follow these steps to configure your Windows 7 computer:
1. In the Start menu, select All Programs, then Accessories, then Windows Explorer.
2. Press Alt to display the menu bar, then select Folder Options… from Windows Ex- plorer’s Tools menu.
3. In the dialog that appears, select the View tab.
4. In the Advanced settings: pane, uncheck the box to the left of the text Hide ex- tensions for known file types. [Note: If this item is already unchecked, no action needs to be taken.]
5. Click OK to apply the setting and close the dialog.
www.microsoft.com/visualstudio/eng/products/compatibility
Before You Begin
xxxvi Before You Begin
Follow these steps to configure your Windows 8 computer:
1. On the Start screen, click the Desktop tile to switch to the desktop.
2. On the task bar, click the File Explorer icon to open the File Explorer.
3. Click the View tab, then ensure that the File name extensions checkbox is checked.
Obtaining the Code Examples The examples for Visual C# 2012 How to Program, 5/e are available for download at
If you’re not already registered at our website, go to www.deitel.com and click the Register link below our logo in the upper-left corner of the page. Fill in your information. There’s no charge to register, and we do not share your information with anyone. We send you only account-management e-mails unless you register separately for our free e-mail newsletter at www.deitel.com/newsletter/subscribe.html. You must enter a valid e-mail address. After registering, you’ll receive a confirmation e-mail with your verification code. Click the link in the confirmation email to go to www.deitel.com and sign in.
Next, go to www.deitel.com/books/vcsharp2012htp/. Click the Examples link to download the ZIP archive file to your computer. Write down the location where you save the file—most browsers will save the file into your Downloads folder.
Throughout the book, steps that require you to access our example code on your com- puter assume that you’ve extracted the examples from the ZIP file and placed them at C:\Examples. You can extract them anywhere you like, but if you choose a different loca- tion, you’ll need to update our steps accordingly. You can extract the ZIP archive file’s contents using tools such as WinZip (www.winzip.com), 7-zip (www.7-zip.org) or the built-in capabilities of Windows Explorer on Window 7 or File Explorer on Windows 8.
Visual Studio Theme Visual Studio 2012 has a Dark theme (the default) and a Light theme. The screen captures shown in this book use the Light theme, which is more readable in print. If you’d like to switch to the Light theme, in the TOOLS menu, select Options… to display the Options di- alog. In the left column, select Environment, then select Light under Color theme. Keep the Options dialog open for the next step.
Displaying Line Numbers and Configuring Tabs Next, you’ll change the settings so that your code matches that of this book. To have the IDE display line numbers, expand the Text Editor node in the left pane then select All Lan- guages. On the right, check the Line numbers checkbox. Next, expand the C# node in the left pane and select Tabs. Make sure that the option Insert spaces is selected. Enter 3 for both the Tab size and Indent size fields. Any new code you add will now use three spaces for each level of indentation. Click OK to save your settings.
Miscellaneous Notes • Some people like to change the workspace layout in the development tools. You
can return the tools to their default layouts by selecting Window > Reset Window Layout.
www.deitel.com/books/vcsharp2012htp/
Before You Begin xxxvii
• Many of the menu items we use in the book have corresponding icons shown with each menu item in the menus. Many of the icons also appear on one of the toolbars at the top of the development environment. As you become familiar with these icons, you can use the toolbars to help speed up your development time. Similarly, many of the menu items have keyboard shortcuts (also shown with each menu item in the menus) for accessing commands quickly.
You are now ready to begin your Visual C# studies with Visual C# 2012 How to Pro- gram, 5/e. We hope you enjoy the book!
This page intentionally left blank
1Introduction to Computers,the Internet and Visual C# The chief merit of language is clearness. —Galen
Our life is frittered away with detail. . . . Simplify, simplify. —Henry David Thoreau
Man is still the most extraordinary computer of all. —John F. Kennedy
O b j e c t i v e s In this chapter you’ll learn:
� Basic hardware, software and data concepts.
� The different types of programming languages.
� The history of the Visual C# programming language and the Windows operating system.
� What cloud computing with Windows Azure is.
� Basics of object technology.
� The history of the Internet and the World Wide Web.
� The parts that Windows 8, .NET 4.5, Visual Studio 2012 and Visual C# 2012 play in the Visual C# ecosystem.
� To test-drive a Visual C# 2012 drawing app.
2 Chapter 1 Introduction to Computers, the Internet and Visual C#
1.1 Introduction Welcome to Visual C# 2012 which, from this point forward, we’ll refer to simply as C#.1
C# is a powerful computer programming language that’s appropriate for building substan- tial information systems.
You’re already familiar with the powerful tasks computers perform. Using this text- book, you’ll write instructions commanding computers to perform those kinds of tasks and you’ll prepare yourself to address new challenges.
Computers process data under the control of sequences of instructions called com- puter programs. These programs guide the computer through actions specified by people called computer programmers. The programs that run on a computer are referred to as software. In this book, you’ll learn object-oriented programming—today’s key program- ming methodology that’s enhancing programmer productivity, and reducing software development costs. You’ll create many software objects that model both abstract and real- world things. And you’ll build C# apps for a variety of environments including the desktop—and new to this edition of the book—mobile devices like smartphones and tablets, and even “the cloud.”
1.2 Hardware and Moore’s Law A computer consists of various devices referred to as hardware, such as the keyboard, screen, mouse, hard disks, memory, DVD drives and processing units. Every year or two,
1.1 Introduction 1.2 Hardware and Moore’s Law 1.3 Data Hierarchy 1.4 Computer Organization 1.5 Machine Languages, Assembly
Languages and High-Level Languages 1.6 Object Technology 1.7 Internet and World Wide Web 1.8 C#
1.8.1 Object-Oriented Programming 1.8.2 Event-Driven Programming 1.8.3 Visual Programming 1.8.4 An International Standard; Other C#
Implementations 1.8.5 Internet and Web Programming 1.8.6 Introducing async/await 1.8.7 Other Key Contemporary
Programming Languages 1.9 Microsoft’s .NET
1.9.1 .NET Framework 1.9.2 Common Language Runtime
1.9.3 Platform Independence 1.9.4 Language Interoperability
1.10 Microsoft’s Windows® Operating System
1.11 Windows Phone 8 for Smartphones 1.11.1 Selling Your Apps in the Windows
Phone Marketplace 1.11.2 Free vs. Paid Apps 1.11.3 Testing Your Windows Phone Apps
1.12 Windows Azure™ and Cloud Computing
1.13 Visual Studio Express 2012 Integrated Development Environment
1.14 Painter Test-Drive in Visual Studio Express 2012 for Windows Desktop
1.15 Painter Test-Drive in Visual Studio Express 2012 for Windows 8
Self-Review Exercises | Answers to Self-Review Exercises | Exercises | Making a Difference Exercises
1. The name C#, pronounced “C-sharp,” is based on the musical # notation for “sharp” notes.
1.3 Data Hierarchy 3
the capacities of computer hardware have approximately doubled inexpensively. This re- markable trend often is called Moore’s Law, named for the person who identified it, Gor- don Moore, co-founder of Intel—the leading manufacturer of the processors in today’s computers and embedded systems, such as smartphones, appliances, game controllers, ca- ble set-top boxes and automobiles.
Moore’s Law and related observations apply especially to
• the amount of memory that computers have for running programs and processing data
• the amount of secondary storage (such as hard disk storage) they have to hold programs and data over longer periods of time
• their processor speeds—the speeds at which computers execute their programs (i.e., do their work)
Similar growth has occurred in the communications field, in which costs have plum- meted as enormous demand for communications bandwidth (i.e., information-carrying capacity) has attracted intense competition. We know of no other fields in which tech- nology improves so quickly and costs fall so rapidly. Such phenomenal improvement is truly fostering the Information Revolution and creating significant career opportunities.
As a result of this continuing stream of technological advances, computers already can perform calculations and make logical decisions phenomenally faster than human beings can. Many of today’s personal computers can perform billions of calculations in one second—more than a human can perform in a lifetime. Supercomputers are already per- forming thousands of trillions (quadrillions) of instructions per second! The world’s fastest supercomputer—the Cray Titan—can perform over 17 quadrillion calculations per second—(17.59 petaflops)2—that’s more than 2 million calculations per second for every person on the planet! And—these “upper limits” are expanding quickly!
1.3 Data Hierarchy Data items processed by computers form a data hierarchy that becomes larger and more complex in structure as we progress from the simplest data items (called “bits”) to richer data items, such as characters, fields, and so on. Figure 1.1 illustrates a portion of the data hierarchy.
Bits The smallest data item in a computer can assume the value 0 or the value 1. Such a data item is called a bit (short for “binary digit”—a digit that can assume either of two values). It’s remarkable that the impressive functions performed by computers involve only the simplest manipulations of 0s and 1s—examining a bit’s value, setting a bit’s value and revers- ing a bit’s value (from 1 to 0 or from 0 to 1). We discuss binary numbers (and closely re- lated octal and hexadecimal numbers) in more detail in Appendix D, Number Systems.
Characters It’s tedious for people to work with data in the low-level form of bits. Instead, we prefer to work with decimal digits (0–9), letters (A–Z and a–z), and special symbols (e.g., $, @, %,
2. top500.org/lists/2012/11/.
4 Chapter 1 Introduction to Computers, the Internet and Visual C#
&, *, (, ), –, +, “, :, ? and / ). Digits, letters and special symbols are known as characters. The computer’s character set is the set of all the characters used to write programs and rep- resent data items on that device. Computers process only 1s and 0s, so every character is represented as a pattern of 1s and 0s. The Unicode character set contains characters for many of the world’s languages. C# supports several character sets, including 16-bit Uni- code® characters that are composed of two bytes—each byte is composed of eight bits. See Appendix B for more information on the ASCII (American Standard Code for Informa- tion Interchange) character set—the popular subset of Unicode that represents uppercase and lowercase letters in the English alphabet, digits and some common special characters.
Fields Just as characters are composed of bits, fields are composed of characters or bytes. A field is a group of characters or bytes that conveys meaning. For example, a field consisting of uppercase and lowercase letters could be used to represent a person’s name, and a field con- sisting of decimal digits could represent a person’s age.
Records Several related fields can be used to compose a record. In a payroll system, for example, the record for an employee might consist of the following fields (possible types for these fields are shown in parentheses):
Fig. 1.1 | Data hierarchy.
Tom Blue
Sally Black
Judy Green File
J u d y Field
Byte (ASCII character J)
Record
Iris Orange
Randy Red
01001010
1 Bit
Judy Green
1.3 Data Hierarchy 5
• Employee identification number (a whole number)
• Name (a string of characters)
• Address (a string of characters)
• Hourly pay rate (a number with a decimal point)
• Year-to-date earnings (a number with a decimal point)
• Amount of taxes withheld (a number with a decimal point)
Thus, a record is a group of related fields. In the preceding example, all the fields belong to the same employee. A company might have many employees and a payroll record for each.
Files A file is a group of related records. [Note: More generally, a file contains arbitrary data in arbitrary formats. In some operating systems, a file is viewed simply as a sequence of bytes— any organization of the bytes in a file, such as organizing the data into records, is a view created by the programmer.] It’s not unusual for an organization to have thousands or even millions of files, some containing billions or even trillions of characters of informa- tion. You’ll work with files in Chapter 17.
Database A database is a collection of data that’s organized for easy access and manipulation. The most popular database model is the relational database in which data is stored in simple tables. A table includes records and fields. For example, a table of students might include first name, last name, major, year, student ID number and grade point average fields. The data for each student is a record, and the individual pieces of information in each record are the fields. You can search, sort and otherwise manipulate the data based on its relation- ship to multiple tables or databases. For example, a university might use data from the stu- dent database in combination with data from databases of courses, on-campus housing, meal plans, etc. We discuss databases in Chapter 22.
Big Data The amount of data being produced worldwide is enormous and growing quickly. Accord- ing to IBM, approximately 2.5 quintillion bytes (2.5 exabytes) of data are created daily and 90% of the world’s data was created in just the past two years!3 According to an IDC study, approximately 1.8 zettabytes (equal to 1.8 trillion gigabytes) of data was used world- wide in 2011.4 Figure 1.2 shows relationships between byte measurements.
3. www-01.ibm.com/software/data/bigdata/.
Unit Bytes Which is approximately
1 kilobyte (KB) 1024 bytes 103 (1024 bytes exactly)
1 megabyte (MB) 1024 kilobytes 106 (1,000,000 bytes)
1 gigabyte (GB) 1024 megabytes 109 (1,000,000,000 bytes)
Fig. 1.2 | Byte measurements. (Part 1 of 2.)
4. www.emc.com/collateral/about/news/idc-emc-digital-universe-2011-infographic.pdf.
6 Chapter 1 Introduction to Computers, the Internet and Visual C#
1.4 Computer Organization Regardless of differences in physical appearance, computers can be envisioned as divided into various logical units or sections.
Input Unit This “receiving” section obtains information (data and computer programs) from input devices and places it at the disposal of the other units for processing. Most information is entered into computers through keyboards, touch screens and mouse devices. Other forms of input include receiving voice commands, scanning images and barcodes, reading from secondary storage devices (such as hard drives, DVD drives, Blu-ray Disc™ drives and USB flash drives—also called “thumb drives” or “memory sticks”), receiving video from a webcam or smartphone and having your computer receive information from the Internet (such as when you download videos from YouTube or e-books from Amazon). Newer forms of input include position data from GPS devices, and motion and orientation infor- mation from accelerometers in smartphones or game controllers (such as Microsoft® Ki- nect™, Nintendo’s Wii™ Remote and Sony’s PlayStation® Move).
Output Unit This “shipping” section takes information that the computer has processed and places it on various output devices to make it available for use outside the computer. Most infor- mation that’s output from computers today is displayed on screens; printed on paper (“go- ing green” discourages this); played as audio or video on PCs and media players (such as Apple® iPod®) and giant screens in sports stadiums; transmitted over the Internet or used to control other devices, such as robots, 3D printers and “intelligent” appliances.
Memory Unit This rapid-access, relatively low-capacity “warehouse” section retains information that’s entered through the input unit, making it immediately available for processing when need- ed. The memory unit also retains processed information until it can be placed on output devices by the output unit. Information in the memory unit is volatile—it’s typically lost when the computer’s power is turned off. The memory unit is often called either memory or primary memory—on desktop and notebook computers it commonly contains as much as 16 GB (GB stands for gigabytes; a gigabyte is approximately one billion bytes).
Arithmetic and Logic Unit (ALU) This “manufacturing” section performs calculations, such as addition, subtraction, multi- plication and division. It also contains the decision mechanisms that allow the computer,
1 terabyte (TB) 1024 gigabytes 1012 (1,000,000,000,000 bytes)
1 petabyte (PB) 1024 terabytes 1015 (1,000,000,000,000,000 bytes)
1 exabyte (EB) 1024 petabytes 1018 (1,000,000,000,000,000,000 bytes)
1 zettabyte (ZB) 1024 exabytes 1021 (1,000,000,000,000,000,000,000 bytes)
Unit Bytes Which is approximately
Fig. 1.2 | Byte measurements. (Part 2 of 2.)
1.5 Machine Languages, Assembly Languages and High-Level Languages 7
for example, to compare two items from the memory unit to determine whether they’re equal. In today’s systems, the ALU is usually implemented as part of the next logical unit, the CPU.
Central Processing Unit (CPU) This “administrative” section coordinates and supervises the operation of the other sec- tions. The CPU tells the input unit when information should be read into the memory unit, tells the ALU when information from the memory unit should be used in calculations and tells the output unit when to send information from the memory unit to certain output devices. Many of today’s computers have multiple CPUs and, hence, can perform many operations simultaneously. A multi-core processor implements multiple processors on a single “microchip”—a dual-core processor has two CPUs and a quad-core processor has four CPUs. Many of today’s desktop computers have quad-core processors that can execute bil- lions of instructions per second. In this book you’ll learn how to write programs that can keep all these processors running in parallel to get your computing tasks done faster.
Secondary Storage Unit This is the long-term, high-capacity “warehousing” section. Programs or data not actively being used by the other units normally are placed on secondary storage devices (such as your hard drive) until they’re again needed, possibly hours, days, months or even years lat- er. Information on secondary storage devices is persistent—it’s preserved even when the computer’s power is turned off. Secondary storage data takes much longer to access than information in primary memory, but the cost per unit of secondary storage is much less than that of primary memory. Examples of secondary storage devices include CD drives, DVD drives and flash drives, some of which can hold up to 768 GB. Typical hard drives on desktop and notebook computers can hold up to 2 TB (TB stands for terabytes; a tera- byte is approximately one trillion bytes). New to this edition, you’ll see that storage in “the cloud” can be viewed as additional secondary storage accessible by your C# apps.
1.5 Machine Languages, Assembly Languages and High- Level Languages Programmers write instructions in various programming languages (such as C#), some di- rectly understandable by computers and others requiring intermediate translation steps.
Machine Languages Any computer can directly understand only its own machine language, defined by its hard- ware architecture. Machine languages generally consist of numbers, ultimately reduced to 1s and 0s. Such languages are cumbersome for humans, who prefer words like “add” and “subtract” to indicate the operations to be performed, so the machine language numeric versions of these instructions were referred to as code. The term “code” has become more broadly used and now refers to the program instructions in all levels of language.
Assembly Languages and Assemblers Machine language was simply too slow and tedious to work with. Instead, programmers began using English-like abbreviations to represent elementary operations. These abbrevi- ations form the basis of assembly languages. Translator programs called assemblers convert assembly-language code to machine code quickly. Although assembly-language code is
8 Chapter 1 Introduction to Computers, the Internet and Visual C#
clearer to humans, it’s incomprehensible to computers until translated to machine lan- guage code.
High-Level Languages, Compilers and Interpreters To speed the programming process even further, high-level languages were developed in which single statements could be written to accomplish substantial tasks. High-level lan- guages, such as C#, Visual Basic, C++, C, Objective-C and Java, allow you to write instruc- tions that look almost like everyday English and contain commonly used mathematical expressions. Translator programs called compilers convert high-level language code into machine language code.
The process of compiling a large high-level language program into machine language can take a considerable amount of computer time. Interpreter programs were developed to execute high-level language programs directly (without the need for compilation), although more slowly than compiled programs.
1.6 Object Technology C# is an object-oriented programming language. In this section we’ll introduce the basics of object technology.
Building software quickly, correctly and economically remains an elusive goal at a time when demands for new and more powerful software are soaring. Objects, or more precisely the classes objects come from, are essentially reusable software components. There are date objects, time objects, audio objects, video objects, automobile objects, people objects, etc. Almost any noun can be reasonably represented as a software object in terms of attributes (e.g., name, color and size) and behaviors (e.g., calculating, moving and com- municating). Software developers have discovered that using a modular, object-oriented design and implementation approach can make software-development groups much more productive than was possible with earlier techniques—object-oriented programs are often easier to understand, correct and modify.
The Automobile as an Object Let’s begin with a simple analogy. Suppose you want to drive a car and make it go faster by pressing its accelerator pedal. What must happen before you can do this? Well, before you can drive a car, someone has to design it. A car typically begins as engineering drawings, similar to the blueprints that describe the design of a house. These drawings include the design for an accelerator pedal. The pedal hides from the driver the complex mechanisms that actually make the car go faster, just as the brake pedal hides the mechanisms that slow the car, and the steering wheel hides the mechanisms that turn the car. This enables people with little or no knowledge of how engines, braking and steering mechanisms work to drive a car easily.
Before you can drive a car, it must be built from the engineering drawings that describe it. A completed car has an actual accelerator pedal to make the car go faster, but even that’s not enough—the car won’t accelerate on its own (we hope), so the driver must press the pedal to accelerate the car.
Methods and Classes Let’s use our car example to introduce some key object-oriented programming concepts. Performing a task in a program requires a method. The method houses the program state-
1.6 Object Technology 9
ments that actually perform the task. It hides these statements from its user, just as a car’s accelerator pedal hides from the driver the mechanisms of making the car go faster. In ob- ject-oriented programming languages, we create a program unit called a class to house the set of methods that perform the class’s tasks. For example, a class that represents a bank account might contain one method to deposit money to an account, another to withdraw money from an account and a third to inquire what the account’s current balance is. A class that represents a car might contain methods for accelerating, braking and turning. A class is similar in concept to a car’s engineering drawings, which house the design of an accel- erator pedal, steering wheel, and so on.
Making Objects from Classes Just as someone has to build a car from its engineering drawings before you can actually drive a car, you must build an object from a class before a program can perform the tasks that the class’s methods define. The process of doing this is called instantiation. An object is then referred to as an instance of its class.
Reuse Just as a car’s engineering drawings can be reused many times to build many cars, you can reuse a class many times to build many objects. Reuse of existing classes when building new classes and programs saves time and effort. Reuse also helps you build more reliable and ef- fective systems, because existing classes and components often have gone through extensive testing (to locate problems), debugging (to correct those problems) and performance tuning. Just as the notion of interchangeable parts was crucial to the Industrial Revolution, reusable classes are crucial to the software revolution that’s been spurred by object technology.
Messages and Method Calls When you drive a car, pressing its gas pedal sends a message to the car to perform a task— that is, to go faster. Similarly, you send messages to an object. Each message is implemented as a method call that tells a method of the object to perform its task. For example, a pro- gram might call a particular bank-account object’s deposit method to increase the account’s balance.
Attributes and Instance Variables A car, besides having capabilities to accomplish tasks, also has attributes, such as its color, its number of doors, the amount of gas in its tank, its current speed and its record of total miles driven (i.e., its odometer reading). Like its capabilities, the car’s attributes are repre- sented as part of its design in its engineering diagrams (which, for example, include an odometer and a fuel gauge). As you drive an actual car, these attributes are carried along with the car. Every car maintains its own attributes. For example, each car knows how much gas is in its own gas tank, but not how much is in the tanks of other cars.
An object, similarly, has attributes that it carries along as it’s used in a program. These attributes are specified as part of the object’s class. For example, a bank-account object has a balance attribute that represents the amount of money in the account. Each bank-
Software Engineering Observation 1.1 Use a building-block approach to creating your programs. Avoid reinventing the wheel— use existing pieces wherever possible. This software reuse is a key benefit of object-oriented programming.
10 Chapter 1 Introduction to Computers, the Internet and Visual C#
account object knows the balance in the account it represents, but not the balances of the other accounts in the bank. Attributes are specified by the class’s instance variables.
Encapsulation Classes encapsulate (i.e., wrap) attributes and methods into objects—an object’s attributes and operations are intimately related. Objects may communicate with one another, but they’re normally not allowed to know how other objects are implemented—implementa- tion details are hidden within the objects themselves. This information hiding, as we’ll see, is crucial to good software engineering.
Inheritance A new class of objects can be created quickly and conveniently by inheritance—the new class absorbs the characteristics of an existing class, possibly customizing them and adding unique characteristics of its own. In our car analogy, an object of class “convertible” cer- tainly is an object of the more general class “automobile,” but more specifically, the roof can be raised or lowered.
Object-Oriented Analysis and Design (OOAD) Soon you’ll be writing programs in C#. Perhaps, like many programmers, you’ll simply turn on your computer and start typing. This approach may work for small programs (like the ones we present in the early chapters of this book), but what if you were asked to create a software system to control thousands of automated teller machines for a major bank? Or suppose you were assigned to work on a team of thousands of software developers building the next U.S. air traffic control system? For projects so large and complex, you should not simply sit down and start writing programs.
To create the best solutions, you should follow a detailed analysis process for deter- mining your project’s requirements (i.e., defining what the system is supposed to do) and developing a design that satisfies them (i.e., deciding how the system should do it). Ideally, you’d go through this process and carefully review the design (and have your design reviewed by other software professionals) before writing any code. If this process involves analyzing and designing your system from an object-oriented point of view, it’s called an object-oriented analysis and design (OOAD) process. Languages like C# are object ori- ented. Programming in such a language, called object-oriented programming (OOP), allows you to implement an object-oriented design as a working system.
The UML (Unified Modeling Language) Though many different OOAD processes exist, a single graphical language for communi- cating the results of any OOAD process—known as the Unified Modeling Language (UML)—is now the most widely used graphical scheme for modeling object-oriented sys- tems. We present our first simple UML diagrams in Chapters 4 and 5, then use them in our deeper treatment of object-oriented programming through Chapter 12. In our option- al ATM Software Engineering Case Study in Chapters 34–35 we present a simple subset of the UML’s features as we guide you through a simple object-oriented design experience.
1.7 Internet and World Wide Web In the late 1960s, ARPA—the Advanced Research Projects Agency of the United States De- partment of Defense—rolled out plans to network the main computer systems of approxi-
1.7 Internet and World Wide Web 11
mately a dozen ARPA-funded universities and research institutions. The computers were to be connected with communications lines operating at a then-stunning 56 Kbps (1 Kbps is equal to 1,024 bits per second), at a time when most people (of the few who even had net- working access) were connecting over telephone lines to computers at a rate of 110 bits per second. Academic research was about to take a giant leap forward. ARPA proceeded to im- plement what quickly became known as the ARPAnet, the precursor to today’s Internet.
Things worked out differently from the original plan. Although the ARPAnet enabled researchers to network their computers, its main benefit proved to be the capability for quick and easy communication via what came to be known as electronic mail (e-mail). This is true even on today’s Internet, with e-mail, instant messaging, file transfer and social media such as Facebook and Twitter, enabling billions of people worldwide to communi- cate quickly and easily.
The protocol (set of rules) for communicating over the ARPAnet became known as the Transmission Control Protocol (TCP). TCP ensured that messages, consisting of sequentially numbered pieces called packets, were properly routed from sender to receiver, arrived intact and were assembled in the correct order.
The Internet: A Network of Networks In parallel with the early evolution of the Internet, organizations worldwide were imple- menting their own networks for both intraorganization (that is, within an organization) and interorganization (that is, between organizations) communication. A huge variety of networking hardware and software appeared. One challenge was to enable these different networks to communicate with each other. ARPA accomplished this by developing the In- ternet Protocol (IP), which created a true “network of networks,” the current architecture of the Internet. The combined set of protocols is now called TCP/IP.
Businesses rapidly realized that by using the Internet, they could improve their oper- ations and offer new and better services to their clients. Companies started spending large amounts of money to develop and enhance their Internet presence. This generated fierce competition among communications carriers and hardware and software suppliers to meet the increased infrastructure demand. As a result, bandwidth—the information-carrying capacity of communications lines—on the Internet has increased tremendously, while hardware costs have plummeted.
The World Wide Web: Making the Internet User-Friendly The World Wide Web (simply called “the web”) is a collection of hardware and software associated with the Internet that allows computer users to locate and view multimedia- based documents (documents with various combinations of text, graphics, animations, au- dios and videos) on almost any subject. The introduction of the web was a relatively recent event. In 1989, Tim Berners-Lee of CERN (the European Organization for Nuclear Re- search) began to develop a technology for sharing information via “hyperlinked” text doc- uments. Berners-Lee called his invention the HyperText Markup Language (HTML). He also wrote communication protocols such as HyperText Transfer Protocol (HTTP) to form the backbone of his new hypertext information system, which he referred to as the World Wide Web.
In 1994, Berners-Lee founded an organization, called the World Wide Web Consor- tium (W3C, www.w3.org), devoted to developing web technologies. One of the W3C’s
12 Chapter 1 Introduction to Computers, the Internet and Visual C#
primary goals is to make the web universally accessible to everyone regardless of disabili- ties, language or culture. In this book, you’ll use C# and other Microsoft technologies to build web-based apps.
1.8 C# In 2000, Microsoft announced the C# programming language. C# has roots in the C, C++ and Java programming languages. It has similar capabilities to Java and is appropriate for the most demanding app-development tasks, especially for building today’s large-scale en- terprise apps, and web-based, mobile and “cloud”-based apps.
1.8.1 Object-Oriented Programming C# is object oriented—we’ve discussed the basics of object technology and will present a rich treatment of object-oriented programming throughout the book. C# has access to the powerful .NET Framework Class Library—a vast collection of prebuilt classes that enable you to develop apps quickly (Fig. 1.3). We’ll say more about .NET in Section 1.9.
1.8.2 Event-Driven Programming C# is event driven. You’ll write programs that respond to user-initiated events such as mouse clicks, keystrokes, timer expirations and—new in Visual C# 2012—touches and fin- ger swipes—gestures that are widely used on smartphones and tablets.
1.8.3 Visual Programming Microsoft’s Visual C# is a visual programming language—in addition to writing program statements to build portions of your apps, you’ll also use Visual Studio’s graphical user in- terface (GUI) to conveniently drag and drop predefined objects like buttons and textboxes into place on your screen, and label and resize them. Visual Studio will write much of the GUI code for you.
1.8.4 An International Standard; Other C# Implementations C# has been standardized internationally. This enables other implementations of the lan- guage besides Microsoft’s Visual C#, such as Mono (www.mono-project.com) that runs on
Some key capabilities in the .NET Framework Class Library
Database Debugging
Building web apps Multithreading
Graphics File processing
Input/output Security
Computer networking Web communication
Permissions Graphical user interface
Mobile Data structures
String processing
Fig. 1.3 | Some key capabilities in the .NET Framework Class Library.
1.8 C# 13
Linux systems, iOS (for Apple’s iPhone, iPad and iPod touch), Google’s Android and Windows. You can find the C# standard document at:
1.8.5 Internet and Web Programming Today’s apps can be written with the aim of communicating among the world’s comput- ers. As you’ll see, this is the focus of Microsoft’s .NET strategy. In Chapters 23, 29 and 30, you’ll build web-based apps with C# and Microsoft’s ASP.NET technology.
1.8.6 Introducing async/await In most programming today, each task in a program must finish executing before the next task can begin. This is called synchronous programming and is the style we use for most of this book. C# also allows asynchronous programming in which multiple tasks can be per- formed at the same time. Asynchronous programming can help you make your apps more responsive to user interactions, such as mouse clicks and keystrokes, among many other uses.
Asynchronous programming in previous versions of Visual C# was difficult and error prone. Visual C# 2012’s new async and await capabilities simplify asynchronous program- ming, because the compiler hides much of the associated complexity from the developer. In Chapter 28, we’ll provide a brief introduction to asynchronous programming with async and await.
1.8.7 Other Key Contemporary Programming Languages Figure 1.4 summarizes some popular programming languages with features comparable to those of C#.
www.ecma-international.org/publications/standards/Ecma-334.htm
Programming language Description
C C was implemented in 1972 by Dennis Ritchie at Bell Laborato- ries. It initially became widely known as the UNIX operating sys- tem’s development language. Today, most of the code for general- purpose operating systems is written in C or C++.
C++ C++, an extension of C, was developed by Bjarne Stroustrup in the early 1980s at Bell Laboratories. C++ provides several features that “spruce up” the C language, but more important, it provides capa- bilities for object-oriented programming. It’s often used in apps with stringent performance requirements such as operating systems, real- time systems, embedded systems and communications systems. Visual C++ is Microsoft’s version of the language.
Fig. 1.4 | Other programming languages. (Part 1 of 2.)
14 Chapter 1 Introduction to Computers, the Internet and Visual C#
1.9 Microsoft’s .NET In 2000, Microsoft announced its .NET initiative (www.microsoft.com/net), a broad vi- sion for using the Internet and the web in the development, engineering, distribution and use of software. Rather than forcing you to use a single programming language, .NET per- mits you to create apps in any .NET-compatible language (such as C#, Visual Basic, Visual C++ and many others). Part of the initiative includes Microsoft’s ASP.NET technology.
1.9.1 .NET Framework The .NET Framework executes apps and contains the .NET Framework Class Library, which provides many capabilities that you’ll use to build substantial C# apps quickly and easily. The .NET Framework Class Library has thousands of valuable prebuilt classes that have been tested and tuned to maximize performance. You’ll learn how to create your own
Java In the 1990s, Sun Microsystems (now part of Oracle) developed the C++-based object-oriented programming language called Java. A key goal of Java is to be able to write programs that will run on a great variety of computer systems and computer-control devices— this is sometimes called write once, run anywhere. Java is used to develop large-scale enterprise apps, to enhance the functionality of web servers (the computers that provide the content we see in our web browsers), to provide apps for consumer devices (e.g., smart- phones, tablets, television set-top boxes, appliances, automobiles and more) and for many other purposes. Microsoft developed C# as a competitive language to Java.
Visual Basic Visual Basic evolved from BASIC, developed in the 1960s at Dart- mouth College for introducing novices to fundamental program- ming techniques. When Bill Gates founded Microsoft in the 1970s, he implemented BASIC on several early personal comput- ers. In the late 1980s and the early 1990s, Microsoft developed the Microsoft Windows graphical user interface (GUI)—the visual part of the operating system with which users interact. With the creation of the Windows GUI, the natural evolution of BASIC was to Visual Basic, introduced by Microsoft in 1991 to make pro- gramming Windows apps easier. The latest versions of Visual Basic have capabilities comparable to those of C#.
Objective-C Objective-C is another object-oriented language based on C. It was developed at Stepstone in the early 1980s and later acquired by NeXT, which in turn was acquired by Apple. It has become the key programming language for the Mac OS X desktop operating sys- tem and all iOS-based devices, such as iPods, iPhones and iPads.
Programming language Description
Fig. 1.4 | Other programming languages. (Part 2 of 2.)
1.9 Microsoft’s .NET 15
classes, but you should re-use the .NET Framework classes whenever possible to speed up the software development process, while enhancing the quality and performance of the software you develop.
1.9.2 Common Language Runtime The Common Language Runtime (CLR), another key part of the .NET Framework, ex- ecutes .NET programs and provides functionality to make them easier to develop and de- bug. The CLR is a virtual machine (VM)—software that manages the execution of programs and hides from them the underlying operating system and hardware. The source code for programs that are executed and managed by the CLR is called managed code. The CLR provides various services to managed code, such as integrating software components written in different .NET languages, error handling between such components, enhanced security, automatic memory management and more. Unmanaged-code programs do not have access to the CLR’s services, which makes unmanaged code more difficult to write.5
Managed code is compiled into machine-specific instructions in the following steps:
1. First, the code is compiled into Microsoft Intermediate Language (MSIL). Code converted into MSIL from other languages and sources can be woven together by the CLR—this allows programmers to work in their preferred .NET program- ming language. The MSIL for an app’s components is placed into the app’s exe- cutable file—the file that causes the computer to perform the app’s tasks.
2. When the app executes, another compiler (known as the just-in-time compiler or JIT compiler) in the CLR translates the MSIL in the executable file into ma- chine-language code (for a particular platform).
3. The machine-language code executes on that platform.
1.9.3 Platform Independence If the .NET Framework exists and is installed for a platform, that platform can run any .NET program. The ability of a program to run without modification across multiple plat- forms is known as platform independence. Code written once can be used on another type of computer without modification, saving time and money. In addition, software can tar- get a wider audience. Previously, companies had to decide whether converting their pro- grams to different platformsq—a process called porting—was worth the cost. With .NET, porting programs is no longer an issue, at least once .NET itself has been made available on the platforms.
1.9.4 Language Interoperability The .NET Framework provides a high level of language interoperability. Because soft- ware components written in different .NET languages (such as C# and Visual Basic) are all compiled into MSIL, the components can be combined to create a single unified pro- gram. Thus, MSIL allows the .NET Framework to be language independent.
5. msdn.microsoft.com/en-us/library/8bs2ecf4.aspx.
16 Chapter 1 Introduction to Computers, the Internet and Visual C#
The .NET Framework Class Library can be used by any .NET language. .NET 4.5, which was released in 2012, includes several improvements and new features to make your apps faster and more responsive. It also features .NET for Windows Store Apps—a subset of .NET that’s used to create Windows 8 UI (user interface) style apps.
1.10 Microsoft’s Windows® Operating System Microsoft’s Windows is the most widely used desktop operating system worldwide. Op- erating systems are software systems that make using computers more convenient for us- ers, developers and system administrators. They provide services that allow each app to execute safely, efficiently and concurrently (i.e., in parallel) with other apps. Other popular desktop operating systems include Linux and Mac OS X. Popular mobile operating systems used in smartphones and tablets include Microsoft’s Windows Phone, Google’s Android, Apple’s iOS (for iPhone, iPad and iPod Touch devices) and BlackBerry OS. Figure 1.5 presents the evolution of the Windows operating system.
Version Description
Windows in the 1990s In the mid-1980s, Microsoft developed the Windows operating system based on a graphical user interface with buttons, textboxes, menus and other graphical elements. The various versions released throughout the 1990s were intended for personal computing. Microsoft entered the corporate operating systems market with the 1993 release of Windows NT.
Windows XP and Windows Vista
Windows XP was released in 2001 and combined Microsoft’s cor- porate and consumer operating system lines. It remains popular today—according to a 2012 Netmarketshare study, it’s used on more than 40% of Windows computers (netmarketshare.com/ operating-system-market-share.aspx?qprid=10&qpcustomd=0). Windows Vista, released in 2007, offered the attractive new Aero user interface, many powerful enhancements and new apps and enhanced security. But Vista never caught on—today, it has “only” six percent of the total desktop operating systems market share (that’s still a pretty significant number; netmarketshare.com/ operating-system-market-share.aspx?qprid=10&qpcustomd=0).
Windows 7 Windows 7, now the most widely used version of Windows, includes enhancements to the Aero user interface, faster startup times, further refinement of Vista’s security features, touch-screen with multi-touch support, and more. Windows 7 had a 44% mar- ket share, and overall, Windows (including Windows 7, Windows XP and Windows Vista) had over 90% of the desktop operating system market share worldwide (netmarketshare.com/operating- system-market-share.aspx?qprid=10&qpcustomd=0). The core chapters of this book use Windows 7, Visual Studio 2012 and Visual C# 2012.
Fig. 1.5 | The evolution of the Windows operating system. (Part 1 of 2.)
1.11 Windows Phone 8 for Smartphones 17
Windows Store You can sell Windows 8 UI desktop and tablet apps or offer them for free in the Windows Store. The fee to become a registered Windows Store developer is $49 for individuals and $99 for companies, however the fee is waived for Microsoft DreamSpark program students (see the Preface). For Windows 8 UI apps, Microsoft retains 30% of the purchase price and distributes 70% to you, up to $25,000. If revenues for your app exceed that amount, Microsoft will retain 20% of the purchase price and distribute 80% to you.
The Windows Store offers several business models for monetizing your app. You can charge the full price for your app before download, with prices starting at $1.49. You can also offer a time-limited trial or feature-limited trial that allows users to try the app before purchasing the full version, sell virtual goods (such as additional app features) using in-app purchases and more. To learn more about the Windows Store and monetizing your apps, visit msdn.microsoft.com/en-us/library/windows/apps/br229519.aspx.
1.11 Windows Phone 8 for Smartphones Windows Phone 8 is a pared down version of Windows 8 designed for smartphones. These are resource-constrained devices—they have less memory and processor power than desktop computers, and limited battery life. Windows Phone 8 has the same core operating systems services as Windows 8, including a common file system, security, networking, media and Internet Explorer 10 (IE10) web browser technology. However, Windows Phone 8 has
Windows 8 for Desktops and Tablets
Windows 8, released in 2012 provides a similar platform (the underlying system on which apps run) and user experience across a wide range of devices including personal computers, smartphones, tablets and the Xbox Live online game service. The new look-and- feel features a Start screen with tiles that represent each app, similar to that of Windows Phone—Microsoft’s operating system for smartphones. Windows 8 features multi-touch support for touch- pads and touchscreen devices, enhanced security features and more.
Windows 8 UI (User Interface)
Visual C# 2012 supports the new Windows 8 UI (previously called “Metro”) which has a clean look-and-feel with minimal dis- tractions to the user. Windows 8 apps feature a chromeless win- dow—there’s no longer a border around the window with the typical interface elements such as title bars and menus. These ele- ments are hidden, allowing apps to fill the entire screen, which is particularly helpful on smaller screens such as tablets and smart- phones. The interface elements are displayed in the app bar when the user swipes the top or bottom of the screen by holding down the mouse button, moving the mouse in the swipe direction and releasing the mouse button; this can be done with a finger swipe on a touchscreen device. We discuss Windows 8 and the Windows 8 UI in Chapter 25 and Windows Phone 8 in Chapter 27.
Version Description
Fig. 1.5 | The evolution of the Windows operating system. (Part 2 of 2.)
18 Chapter 1 Introduction to Computers, the Internet and Visual C#
only the features necessary for smartphones, allowing them to run efficiently, minimizing the burden on the device’s resources.
New to this edition of the book, you’ll use Visual C# 2012 to develop your own Win- dows Phone 8 apps. Just as the Objective-C programming language has increased in pop- ularity due to iOS app development for iPhone, iPad and iPod touch, Visual C# 2012 is sure to become even more popular as the demand for Windows Phones increases. Inter- national Data Corporation (IDC) predicts that Windows Phone will have over 19% of the smartphone market share by 2016, second only to Android and ahead of Apple’s iPhone.6
You’ll learn how to develop Windows Phone apps in Chapter 27.
1.11.1 Selling Your Apps in the Windows Phone Marketplace You can sell your own Windows Phone apps in the Windows Phone Marketplace (www.windowsphone.com/marketplace), similar to other app commerce platforms such as Apple’s App Store, Google Play (formerly Android Market), Facebook’s App Center and the Windows Store. You can also earn money by making your apps free for download and selling virtual goods (e.g., additional content, game levels, e-gifts and add-on features) us- ing in-app purchase.
1.11.2 Free vs. Paid Apps A recent study by Gartner found that 89% of all mobile apps are free, and that number is likely to increase to 93% by 2016, at which point in-app purchases will account for over 40% of mobile app revenues. 7 Paid Windows Phone 8 apps range in price from $1.49 (which is higher than the $0.99 starting price for apps in Google Play and Apple’s App Store) to $999.99. The average price for mobile apps is approximately $1.50 to $3, de- pending on the platform. For Windows Phone apps, Microsoft retains 30% of the pur- chase price and distributes 70% to you. At the time of this writing, there were over 100,000 apps in the Windows Phone Marketplace.8
1.11.3 Testing Your Windows Phone Apps You can test your phone apps on the Windows Phone Emulator that Microsoft provides with the Windows Phone 8 SDK (software development kit). To test your apps on a Windows phone and to sell your apps or distribute your free apps through the Windows Phone Marketplace, you’ll need to join the Windows Phone Dev Center. There’s an annual fee of $99; the program is free to DreamSpark students (for more information about DreamSpark, see the Preface) and to MSDN subscribers. The website includes develop- ment tools, sample code, tips for selling your apps, design guidelines and more. To join the Windows Phone Dev Center and submit apps, visit dev.windowsphone.com/en-us/ downloadsdk.
6. www.idc.com/getdoc.jsp?containerId=prUS23523812. 7. techcrunch.com/2012/09/11/free-apps/. 8. windowsteamblog.com/windows_phone/b/windowsphone/archive/2012/06/20/announcing-
windows-phone-8.aspx.
1.12 Windows Azure™ and Cloud Computing 19
1.12 Windows Azure™ and Cloud Computing Cloud computing allows you to use software and data stored in the “cloud”—i.e., accessed on remote computers (or servers) via the Internet and available on demand—rather than having it stored on your desktop, notebook computer or mobile device. Cloud computing gives you the flexibility to increase or decrease computing resources to meet your resource needs at any given time, making it more cost effective than purchasing expensive hardware to ensure that you have enough storage and processing power at their occasional peak levels. Using cloud computing services also saves money by shifting the burden of managing these apps to the service provider. New to this edition of the book, in Chapter 31 you’ll use Mi- crosoft’s Windows Azure—a cloud computing platform that allows you to develop, man- age and distribute your apps in the cloud. With Windows Azure, your apps can store their data in the cloud so that the data is available at all times from any of your desktop computer and mobile devices. Verified DreamSpark students can download Visual Studio 2012 Pro- fessional which includes built-in support for Windows 8 and Windows Azure.9 You can sign up for a free 90-day trial of Windows Azure at www.windowsazure.com/en-us/ pricing/free-trial/.
1.13 Visual Studio Express 2012 Integrated Development Environment C# programs are created using Microsoft’s Visual Studio—a collection of software tools called an Integrated Development Environment (IDE). The Visual Studio 2012 Express IDE enables you to write, run, test and debug C# programs quickly and conveniently. It also supports Microsoft’s Visual Basic, Visual C++ and F# programming languages. Most of this book’s examples were built using Visual Studio Express 2012 for Windows Desktop, which runs on both Windows 7 and Windows 8. The Windows 8 UI and Windows 8 Graphics and Multimedia chapters require Visual Studio Express 2012 for Windows 8.
1.14 Painter Test-Drive in Visual Studio Express 2012 for Windows Desktop [Note: This test-drive can be performed on a computer running either Windows 7 or Win- dows 8. The steps shown here are for Windows 7. We discuss running an app on Windows 8 in Section 1.15.]
You’ll now use Visual Studio Express 2012 for Windows Desktop to “test-drive” an existing app that enables you to draw on the screen using the mouse. The Painter app— which you’ll build in a later chapter—allows you to choose among several brush sizes and colors. The elements and functionality you see in this app are typical of what you’ll learn to program in this text. The following steps walk you through test-driving the app.
Step 1: Checking Your Setup Confirm that you’ve set up your computer and the software properly by reading the book’s Before You Begin section that follows the Preface.
9. www.dreamspark.com/Product/Product.aspx?productid=44.
20 Chapter 1 Introduction to Computers, the Internet and Visual C#
Step 2: Locating the Painter App’s Directory Open a Windows Explorer window and navigate to C:\examples\ch01\win7testdrive. (We assume you placed the examples in the C:\examples folder.) Double click the Paint- er folder to view its contents (Fig. 1.6), then double click the Painter.sln file to open the app’s solution in Visual Studio. An app’s solution contains all of the app’s code files, supporting files (such as images, videos, data files, etc.) and configuration information. We’ll discuss the contents of a solution in more detail in the next chapter.
Depending on your system configuration, Windows Explorer might not display file name extensions. To display them (like .sln in Fig. 1.6):
1. In Windows Explorer, type Alt + t to display the Tools menu, then select Folder options….
2. Select the View tab in the Folder Options dialog.
3. Locate the checkbox Hide extensions for known file types and ensure that it’s un- checked.
4. Click OK to dismiss the Folder Options dialog.
Step 3: Running the Painter App To see the running Painter app, click the Start ( ) button (Fig. 1.7) or press the F5 key. Figure 1.8 shows the executing app.
Figure 1.8 labels several of the app’s graphical elements—called controls. These include GroupBoxes, RadioButtons, Buttons and a Panel. These controls and many others are discussed throughout the text. The app allows you to draw with a Black, Red, Blue or Green brush of Small, Medium or Large size. As you drag the mouse on the white Panel, the app draws circles of the specified color and size at the mouse pointer’s current position. The slower you drag the mouse, the closer the circles will be. Thus, dragging slowly draws a continuous line (as in Fig. 1.9) and dragging quickly draws individual circles with space in between. You can also Undo your previous operation or Clear the drawing to start from scratch by pressing the Buttons below the RadioButtons in the GUI. By using existing con- trols—which are objects—you can create powerful apps much faster than if you had to write all the code yourself. This is a key benefit of software reuse.
Fig. 1.6 | Contents of C:\examples\ch01\win7testdrive\Painter.
Double click Painter.sln to open the project in Visual Studio
1.14 Painter Test-Drive in Visual Studio Express 2012 for Windows Desktop 21
The brush’s properties, selected in the RadioButtons labeled Black and Medium, are default settings—the initial settings you see when you first run the app. Programmers include default settings to provide reasonable choices that the app will use if the user does not change the settings. Default settings also provide visual cues for users to choose their own settings. Now you’ll choose your own settings as a user of this app.
Step 4: Changing the Brush Color Click the RadioButton labeled Red to change the brush color, then click the RadioButton labeled Small to change the brush size. Position the mouse over the white Panel, then drag the mouse to draw with the brush. Draw flower petals, as shown in Fig. 1.9.
Fig. 1.7 | Running the Painter app.
i
Fig. 1.8 | Painter app running in Windows 7.
Press the Start button to begin executing the Painter app
GroupBoxes
RadioButtons
Panel
Buttons
22 Chapter 1 Introduction to Computers, the Internet and Visual C#
Step 5: Changing the Brush Color and Size Click the Green RadioButton to change the brush color. Then, click the Large RadioBut- ton to change the brush size. Draw grass and a flower stem, as shown in Fig. 1.10.
Step 6: Finishing the Drawing Click the Blue and Medium RadioButtons. Draw raindrops, as shown in Fig. 1.11, to com- plete the drawing.
Step 7: Stopping the App When you run an app from Visual Studio, you can terminate it by clicking the stop button ( ) on the Visual Studio toolbar or by clicking the close box ( ) on the running app’s window.
Fig. 1.9 | Drawing flower petals with a small red brush.
Fig. 1.10 | Drawing the flower stem and grass with a large green brush.
1.15 Painter Test-Drive in Visual Studio Express 2012 for Windows 8 23
Now that you’ve completed the test-drive, you’re ready to begin developing C# apps. In Chapter 2, Dive Into® Visual Studio, you’ll use Visual Studio to create your first C# program using visual programming techniques. As you’ll see, Visual Studio will generate for you the code that builds the app’s GUI. In Chapter 3, Introduction to C# Apps, you’ll begin writing C# programs containing conventional program code that you write.
1.15 Painter Test-Drive in Visual Studio Express 2012 for Windows 8 [Note: This test-drive can be performed only on a computer running Windows 8.] You’ll now use Visual Studio to “test-drive” an existing Windows 8 UI app that enables you to draw on the screen using the mouse. The Painter app—which you’ll build in a later chap- ter—allows you to choose among several brush sizes and colors. The elements and func- tionality you see in this app are typical of what you’ll learn to program in this text. The following steps walk you through test-driving the app.
Step 1: Checking Your Setup Confirm that you’ve set up your computer and the software properly by reading the book’s Before You Begin section that follows the Preface.
Step 2: Switching to the Windows 8 Desktop Click the Desktop tile in the Windows 8 Start screen to switch to the desktop.
Step 3: Locating the Painter App’s Directory Click the File Explorer ( ) icon in the task bar to open a File Explorer window, then locate the C:\examples\ch01\win8testdrive folder. (We assume you placed the examples in the C:\examples folder.) Double click the Painter folder to view its contents (Fig. 1.12), then double click the Painter.sln file to open the app’s solution in Visual Studio. An app’s solution contains all of the app’s code files, supporting files (such as images, videos, data
Fig. 1.11 | Drawing rain drops with a medium blue brush.
24 Chapter 1 Introduction to Computers, the Internet and Visual C#
files, etc.) and configuration information. We’ll discuss the contents of a solution in more detail in the next chapter. [Note: Depending on your system configuration, the File Explor- er window might not display file name extensions. To display file name extensions (like .sln in Fig. 1.12), click the View tab in the File Explorer window, then ensure that File name extensions is selected.]
Step 4: Running the Painter App Windows 8 UI apps normally occupy the full screen, though you can also snap apps to a 320-pixel-wide area at the left or right of the screen to see two apps side-by-side. To see the running Painter app, you can install it on the Windows 8 Start screen and execute it by selecting Local Machine (Fig. 1.13) then clicking the Start Debugging ( ) button or pressing the F5 key. Once you install the app on the Start screen, you can also run it by clicking its Start screen tile. Figure 1.14 shows the executing app. Later chapters will dis- cuss the Simulator and Remote Machine options shown in Fig. 1.13 for running apps.
Figure 1.14 labels several of the app’s graphical elements—called controls. These include TextBlocks, RadioButtons, Buttons and a Canvas. These controls and many others are discussed throughout the text. The app allows you to draw with a Black, Red,
Fig. 1.12 | Contents of C:\examples\ch01\win8testdrive\Painter.
Fig. 1.13 | Selecting the Local Machine for running the Painter app.
Double click Painter.sln to open the project in Visual Studio
Select to display file name extensions
1.15 Painter Test-Drive in Visual Studio Express 2012 for Windows 8 25
Blue or Green brush of Small, Medium or Large size. As you drag the mouse on the white Canvas (an object used for drawing), the app draws circles of the specified color and size at the mouse pointer’s current position. The slower you drag the mouse, the closer the cir- cles will be. Thus, dragging slowly draws a continuous line (as in Fig. 1.15) and dragging quickly draws individual circles with space in between (as you can see with some of the rain drops in Fig. 1.17). You can also Undo your previous operation or Clear the drawing to start from scratch by pressing the Buttons below the RadioButtons in the GUI. By using existing controls—which are objects—you can create powerful apps much faster than if you had to write all the code yourself. This is a key benefit of software reuse.
The brush’s properties, selected in the RadioButtons labeled Black and Small, are default settings—the initial settings you see when you first run the app. Programmers include default settings to provide reasonable choices that the app will use if the user does not change the settings. Default settings also provide visual cues for users to choose their own settings. Now you’ll choose your own settings as a user of this app.
Step 5: Changing the Brush Color Click the RadioButton labeled Red to change the brush color. Position the mouse over the white Canvas, then drag the mouse to draw with the brush. Draw flower petals, as shown in Fig. 1.15.
Step 6: Changing the Brush Color and Size Click the RadioButton labeled Green to change the brush color again. Then, click the Ra- dioButton labeled Large to change the brush size. Draw grass and a flower stem, as shown in Fig. 1.16.
i
Fig. 1.14 | Painter app running in Windows 8.
RadioButtons
Canvas
Buttons
TextBlock
26 Chapter 1 Introduction to Computers, the Internet and Visual C#
Fig. 1.15 | Drawing flower petals with a small red brush.
Fig. 1.16 | Drawing the flower stem and grass with a large green brush.
Self-Review Exercises 27
Step 7: Finishing the Drawing Click the Blue and Medium RadioButtons. Draw raindrops, as shown in Fig. 1.17, to com- plete the drawing.
Step 8: Stopping the App When you run an app from Visual Studio, you can terminate it by clicking the stop button ( ) on the Visual Studio toolbar. Typically, when you’re done using a Windows 8 UI app like Painter, you don’t terminate the app. Instead you simply run another app. Windows 8 suspends the execution of the previous app you were running, but keeps it in memory in case you decide to return to the app. Windows may decide to terminate a suspended app to free up memory for executing other apps. To explicitly shut down a Windows 8 UI app, simply drag from the top of the screen to the bottom or press Alt + F4.
Now that you’ve completed the test-drive, you’re ready to begin developing C# apps. In Chapter 2, Dive Into® Visual Studio, you’ll use Visual Studio to create your first C# pro- gram using visual programming techniques. As you’ll see, Visual Studio will generate for you the code that builds the app’s GUI. In Chapter 3, Introduction to C# Apps, you’ll begin writing C# programs containing conventional program code that you write.
Fig. 1.17 | Drawing rain drops with a medium blue brush.
Self-Review Exercises 1.1 Fill in the blanks in each of the following statements:
a) Computers process data under the control of sequences of instructions called .
28 Chapter 1 Introduction to Computers, the Internet and Visual C#
b) A computer consists of various devices referred to as , such as the keyboard, screen, mouse, hard disks, memory, DVD drives and processing units.
c) Data items processed by computers form a(n) that becomes larger and more complex in structure as we progress from the simplest data items (called “bits”) to richer data items, such as characters, fields, and so on.
d) Computers can directly understand only their language, which is composed only of 1s and 0s.
e) The three types of computer programming languages discussed in the chapter are ma- chine languages, and .
f) Programs that translate high-level-language programs into machine language are called .
g) A(n) processor implements several processors on a single “microchip”—a dual-core processor has two CPUs and a quad-core processor has four CPUs.
1.2 Fill in the blanks in each of the following statements: a) Objects, or more precisely the that objects come from, are essentially reusable
software components. b) You send messages to an object. Each message is implemented as a method
that tells a method of the object to perform its task. c) A new class of objects can be created quickly and conveniently by ; the new
class absorbs the characteristics of an existing class, possibly customizing them and add- ing unique characteristics of its own.
d) To create the best solutions, you should follow a detailed analysis process for determin- ing your project’s (i.e., defining what the system is supposed to do) and de- veloping a design that satisfies them (i.e., deciding how the system should do it).
e) Visual C# 2012 is driven. You’ll write programs that respond to mouse clicks, keystrokes, timer expirations and—new in Visual C# 2012—touches and finger swipes.
f) Microsoft’s Visual C# is a(n) programming language—in addition to writing program statements to build portions of your apps, you’ll also use Visual Studio’s graphical user interface (GUI) to conveniently drag and drop predefined objects like buttons and textboxes into place on your screen, and label and resize them.
g) C++ provides several features that “spruce up” the C language, but more important, it provides capabilities for -oriented programming.
h) A key goal of Java is to be able to write programs that will run on a great variety of com- puter systems and computer-control devices. This is sometimes called .
1.3 Fill in the blanks in each of the following statements: a) The executes .NET programs. b) The CLR provides various services to code, such as integrating software com-
ponents written in different .NET languages, error handling between such components, enhanced security and more.
c) The ability of a program to run without modification across multiple platforms is known as platform .
d) Visual Studio is a(n) in which C# programs are developed. e) The new Windows 8 look-and-feel features a Start screen with that represent
each app, is similar to that of Windows Phone—a Microsoft operating system for smart- phones.
f) Windows 8 apps feature a(n) window; there’s no longer a border around the window with the typical interface elements such as title bars and menus.
g) You can sell your own Windows Phone apps in the . h) You can test your phone apps on the Windows Phone that Microsoft provides
with the Windows Phone SDK (software development kit).
Answers to Self-Review Exercises 29
1.4 State whether each of the following is true or false. If false, explain why. a) Software objects model both abstract and real-world things. b) The most popular database model is the relational database in which data is stored in
simple tables. A table includes records and fields. c) A database is a collection of data that’s organized for easy access and manipulation. d) Secondary storage data takes much longer to access than data in primary memory, but
the cost per unit of secondary storage is much higher than that of primary memory. e) High-level languages allow you to write instructions that look almost like everyday Eng-
lish and contain commonly used mathematical expressions. f) An object has attributes that it carries along as it’s used in a program. g) The Transmission Control Protocol (TCP) ensures that messages, consisting of sequen-
tially numbered pieces called bytes, were properly routed from sender to receiver, ar- rived intact and were assembled in the correct order
h) The information-carrying capacity of communications lines on the Internet has in- creased tremendously, while hardware costs have increased.
i) You can build web-based apps with C# and Microsoft’s ASP.NET technology. j) Java has become the key programming language for the Mac OS X desktop operating
system and all iOS-based devices, such as iPods, iPhones and iPads. k) Microsoft’s ASP.WEB technology is used to create web apps. l) Microsoft’s Windows operating system is the most widely used desktop operating sys-
tem worldwide. m) Windows 8 is designed for resource-constrained devices that have less memory and pro-
cessor power than desktop computers, and limited battery life. n) Visual C# 2012 also can be used to develop Windows Phone 8 apps. Visual C# 2012 is
sure to become even more popular as the demand for Windows Phones increases.
1.5 Arrange these byte measurements in order from smallest to largest: terabyte, megabyte, petabyte, gigabyte and kilobyte.
1.6 Describe the two-step translation process for preparing your C# code to execute on your particular computer.
1.7 Why might Windows terminate a suspended app?
Answers to Self-Review Exercises 1.1 a) computer programs. b) hardware. c) data hierarchy. d) machine. e) assembly languages, high-level languages. f) compilers. g) multi-core.
1.2 a) classes. b) call. c) inheritance. d) requirements. e) event. f) visual. g) object. h) write once, run anywhere.
1.3 a) Common Language Runtime (CLR) of the .NET Framework. b) managed. c) indepen- dence. d) IDE. e) tiles. f) chromeless. g) Windows Phone Marketplace. h) Emulator.
1.4 a) True. b) True. c) True. d) False: The cost per unit of secondary storage is much lower than that of primary memory. e) True. f) True. g) False. Packets—not bytes. h) False. Hardware costs have decreased. i) True. j) False. The language is Objective-C, not Java. k) False. It’s ASP.NET technology. l) True. m) False. Windows Phone 8 is designed for resource-constrained devices. n) True.
1.5 kilobyte, megabyte, gigabyte, terabyte, petabyte.
1.6 C# code is first compiled into MSIL and placed in an executable file. When the app exe- cutes, another compiler called the JIT(just-in-time) compiler in the CLR translates the MSIL in the executable file into machine-language code (for a particular platform).
1.7 To free up memory for executing other apps.
30 Chapter 1 Introduction to Computers, the Internet and Visual C#
Exercises 1.8 Fill in the blanks in each of the following statements:
a) The programs that run on a computer are referred to as . b) Systems such as smartphones, appliances, game controllers, cable set-top boxes and au-
tomobiles that contain small computers are called . c) Just as characters are composed of bits, are composed of characters or bytes. d) Information on secondary storage devices is ; it’s preserved even when the
computer’s power is turned off. e) Translator programs called convert high-level language code into machine
language code. f) In object-oriented programming languages, we create a program unit called a(n)
to house the set of methods that perform its tasks. g) Use a building-block approach to creating your programs. Avoid reinventing the
wheel—use existing pieces wherever possible. Such software is a key benefit of object-oriented programming.
1.9 Fill in the blanks in each of the following statements: a) Although many different OOAD processes exist, a single graphical language for com-
municating the results of any OOAD process has come into wide use. This language, known as the , is now the most widely used graphical scheme for modeling ob- ject-oriented systems.
b) Tim Berners-Lee developed the for sharing information via “hyperlinked” text documents on the web.
c) The CLR is a(n) machine. It is software that manages the execution of pro- grams and hides from them the underlying operating system and hardware.
d) Converting a program to run on a different platform from which it was originally in- tended is called .
e) Microsoft’s Windows is a cloud computing platform that allows you to devel- op, manage and distribute your apps in the cloud.
f) By using existing controls—which are objects—you can create powerful apps much faster than if you had to write all the code yourself. This is a key benefit of software
.
1.10 State whether each of the following is true or false. If false, explain why. a) The smallest data item in a computer can assume the value 1 or the value 2. Such a data
item is called a bit (short for “binary digit”—a digit that can assume either of two val- ues).
b) The Unicode character set is a popular subset of ASCII that represents uppercase and lowercase letters, digits and some common special characters.
c) Each of the following is a form of computer output: data displayed on screens, printed on paper, played as audio or video on PCs and media players, used to control other de- vices, such as robots, 3D printers and “intelligent” appliances.
d) Reuse helps you build more reliable and effective systems, because existing classes and components often have gone through extensive testing, debugging and performance tuning.
e) One of the W3C’s primary goals is to make the web universally accessible to everyone regardless of disabilities, language or culture.
f) C# is available only on Microsoft Windows. g) The .NET Framework Class Library has millions of valuable prebuilt classes that have
been tested and tuned to maximize performance. h) .NET programs can run on any platform.
Exercises 31
i) Windows 8, released in 2012, is designed to provide a similar platform (the underlying system on which apps run) and user experience across all of your devices including per- sonal computers, smartphones, tablets and Xbox Live.
j) Most mobile apps are sold for a small fee.
1.11 What is a key advantage of interpreters over compilers? What is a key disadvantage?
1.12 What is the key advantage of using the new Async feature in preference to using old-style multithreading?
1.13 What are operating systems?
1.14 Why is using cloud computing resources sometimes preferable to purchasing all the hard- ware you need for your own computer?
1.15 Categorize each of the following items as either hardware or software: a) CPU b) Compiler c) Input unit d) A word-processor program e) A C# program
1.16 Translator programs, such as assemblers and compilers, convert programs from one lan- guage (referred to as the source language) to another language (referred to as the target language). Determine which of the following statements are true and which are false:
a) An assembler translates source-language programs into machine-language programs. b) High-level languages are generally machine dependent. c) A machine-language program requires translation before it can be run on a computer. d) The C# compiler translates high-level-language programs into SMIL.
1.17 Expand each of the following acronyms: a) W3C b) OOP c) CLR d) MSIL e) UML f) IDE
1.18 What are the key benefits of the .NET Framework and the CLR? What are the drawbacks?
1.19 What are the advantages to using object-oriented techniques?
1.20 You are probably wearing on your wrist one of the world’s most common types of objects— a watch. Discuss how each of the following terms and concepts applies to the notion of a watch: object, attributes and behaviors.
1.21 What was the key reason that Visual Basic was developed as a special version of the BASIC programming language?
1.22 What is the key accomplishment of the UML?
1.23 What did the chief benefit of the early Internet prove to be?
1.24 What is the key capability of the web?
1.25 What is the key vision of Microsoft’s .NET initiative?
1.26 How does the .NET Framework Class Library facilitate the development of .NET apps?
1.27 Besides the obvious benefits of reuse made possible by OOP, what do many organizations report as another key benefit of OOP?
32 Chapter 1 Introduction to Computers, the Internet and Visual C#
Making a Difference Exercises 1.28 (Test Drive: Carbon Footprint Calculator) Some scientists believe that carbon emissions, especially from the burning of fossil fuels, contribute significantly to global warming and that this can be combatted if individuals take steps to limit their use of carbon-based fuels. Organizations and individuals are increasingly concerned about their “carbon footprints.” Websites such as TerraPass
www.terrapass.com/carbon-footprint-calculator/
and Carbon Footprint
www.carbonfootprint.com/calculator.aspx
provide carbon footprint calculators. Test drive these calculators to determine your carbon foot- print. Exercises in later chapters will ask you to program your own carbon footprint calculator. To prepare for this, use the web to research the formulas for calculating carbon footprints.
1.29 (Test Drive: Body Mass Index Calculator) Obesity causes significant increases in illnesses such as diabetes and heart disease. To determine whether a person is overweight or obese, you can use a measure called the body mass index (BMI). The United States Department of Health and Hu- man Services provides a BMI calculator at www.nhlbisupport.com/bmi/. Use it to calculate your own BMI. A forthcoming exercise will ask you to program your own BMI calculator. To prepare for this, use the web to research the formulas for calculating BMI.
1.30 (Attributes of Hybrid Vehicles) In this chapter you learned some basics of classes. Now you’ll “flesh out” aspects of a class called “Hybrid Vehicle.” Hybrid vehicles are becoming increasingly popular, because they often get much better mileage than purely gasoline-powered vehicles. Browse the web and study the features of four or five of today’s popular hybrid cars, then list as many of their hybrid-related attributes as you can. Some common attributes include city-miles-per-gallon and highway-miles-per-gallon. Also list the attributes of the batteries (type, weight, etc.).
1.31 (Gender Neutrality) Many people want to eliminate sexism in all forms of communication. You’ve been asked to create a program that can process a paragraph of text and replace gender-spe- cific words with gender-neutral ones. Assuming that you’ve been given a list of gender-specific words and their gender-neutral replacements (e.g., replace both “wife” and “husband” with “spouse,” “man” and “woman” with “person,” “daughter” and “son” with “child” and so on), ex- plain the procedure you’d use to read through a paragraph of text and manually perform these re- placements. How might your procedure generate a strange term like “woperchild?” You’ll soon learn that a more formal term for “procedure” is “algorithm,” and that an algorithm specifies the steps to be performed and the order in which to perform them.
2Dive Into® Visual StudioExpress 2012 for WindowsDesktop Seeing is believing. —Proverb
Form ever follows function. —Louis Henri Sullivan
O b j e c t i v e s In this chapter you’ll:
� Learn the basics of the Visual Studio Express 2012 for Windows Desktop Integrated Development Environment (IDE) for writing, running and debugging your apps.
� Use Visual Studio’s help features.
� Learn key commands contained in the IDE’s menus and toolbars.
� Understand the purpose of the various kinds of windows in the Visual Studio Express 2012 for Windows Desktop IDE.
� Understand what visual app development is and how it simplifies and speeds app development.
� Use visual app development to create, compile and execute a simple Visual C# app that displays text and an image.
34 Chapter 2 Dive Into® Visual Studio Express 2012 for Windows Desktop
2.1 Introduction Visual Studio 2012 is Microsoft’s Integrated Development Environment (IDE) for creat- ing, running and debugging apps (also called applications) written in various .NET pro- gramming languages. This chapter provides an overview of the Visual Studio 2012 IDE and shows how to create a simple Visual C# app by dragging and dropping predefined building blocks into place—a technique known as visual app development.
2.2 Overview of the Visual Studio Express 2012 IDE There are several versions of Visual Studio available. Most of this book’s examples are based on the Visual Studio Express 2012 for Windows Desktop. See the Before You Be- gin section that follows the Preface for information on installing the software. Our screen captures and discussions focus on Visual Studio Express 2012 for Windows Desktop. The examples will work on full versions of Visual Studio as well—though some options, menus and instructions might differ. From this point forward, we’ll refer to the Visual Studio Ex- press 2012 for Windows Desktop IDE simply as “Visual Studio” or “the IDE.” We assume that you have some familiarity with Windows.
Introduction to Microsoft Visual Studio Express 2012 for Windows Desktop We use the > character to indicate the selection of a menu item from a menu. For example, we use the notation FILE > Open File… to indicate that you should select the Open File… menu item from the FILE menu.
To start the IDE, select Start > All Programs > Microsoft Visual Studio 2012 Express > VS Express for Desktop (on Windows 8, click the VS for Desktop tile on the Start screen. Once the Express Edition begins execution, the Start Page displays (Fig. 2.1). Depending on your version of Visual Studio, your Start Page may look different. The Start Page con- tains a list of links to Visual Studio resources and web-based resources. At any time, you can return to the Start Page by selecting VIEW > Start Page. [Note: Visual Studio supports both a dark theme (with dark window backgrounds and light text) and a light theme (with light window backgrounds and dark text). We use the light theme throughout this book. The Before You Begin section after the Preface explains how to set this option.]
Links on the Start Page The Start Page links are organized into two columns. The left column’s Start section con- tains options that enable you to start building new apps or to continue working on existing
2.1 Introduction 2.2 Overview of the Visual Studio
Express 2012 IDE 2.3 Menu Bar and Toolbar 2.4 Navigating the Visual Studio IDE
2.4.1 Solution Explorer 2.4.2 Toolbox 2.4.3 Properties Window
2.5 Using Help 2.6 Using Visual App Development to
Create a Simple App that Displays Text and an Image
2.7 Wrap-Up 2.8 Web Resources
Summary | Terminology | Self-Review Exercises | Answers to Self-Review Exercises | Exercises
2.2 Overview of the Visual Studio Express 2012 IDE 35
ones. The Recent section contains links to projects you’ve recently created or modified. You can also create new projects or open existing ones by clicking the links in the Start section.
The right column contains two tabs—GET STARTED (selected by default) and LATEST NEWS. The links in the GET STARTED tab provide information about the pro- gramming languages supported by Visual Studio and various learning resources. An Internet connection is required for the IDE to access most of this information.
The LATEST NEWS tab includes an Enable RSS Feed button. Once you click this button, the IDE will display links to the latest Visual Studio developments (such as updates and bug fixes) and to information on advanced app-development topics. To access more extensive information on Visual Studio, you can browse the MSDN (Microsoft Developer Network) Library at
The MSDN site contains articles, downloads and tutorials on technologies of interest to Visual Studio developers. You can also browse the web from the IDE by selecting VIEW > Other Windows > Web Browser. To request a web page, type its URL into the location bar (Fig. 2.2) and press the Enter key—your computer, of course, must be connected to the Internet. The web page that you wish to view appears as another tab in the IDE (Fig. 2.2).
Fig. 2.1 | Start Page in Visual Studio Express 2012 for Windows Desktop.
msdn.microsoft.com/en-us/library/default.aspx
Start Page linksCollapsed Toolbox window
Solution Explorer (no projects open)New Project button Start Page tab
Recent projects will be listed here
Latest News tab
36 Chapter 2 Dive Into® Visual Studio Express 2012 for Windows Desktop
Creating a New Project To begin app development in Visual C#, you must create a new project or open an existing one. You select FILE > New Project… to create a new project or FILE > Open Project… to open an existing one. From the Start Page’s Start section, you can also click the links New Project… or Open Project…. A project is a group of related files, such as the Visual C# code and any images that might make up an app. Visual Studio organizes apps into projects and solutions, which contain one or more projects. Multiple-project solutions are used to cre- ate large-scale apps. Most apps we create in this book consist of a solution containing a single project.
New Project Dialog and Project Templates When you select FILE > New Project… or click the New Project… link on the Start Page, the New Project dialog (Fig. 2.3) displays. Dialogs are windows that facilitate user–com- puter communication.
Visual Studio provides several templates (Fig. 2.3)—the project types users can create in Visual C# and other languages. The templates include Windows Forms apps, WPF apps and others—full versions of Visual Studio provide many additional templates. In this chapter, you’ll build a Windows Forms Application. A Windows Forms app is an app that executes within a Windows operating system (such as Windows 7 or Windows 8) and typ- ically has a graphical user interface (GUI)—users interact with this visual part of the app. Windows apps include Microsoft software products like Microsoft Word, Internet Explorer and Visual Studio, software products created by other vendors, and customized software that you and other app developers create. You’ll create many Windows apps in this text.
By default, Visual Studio assigns the name WindowsFormsApplication1 to a new Win- dows Forms Application project and solution (Fig. 2.3). Select Windows Forms Application, then click OK to display the IDE in Design view (Fig. 2.4), which contains the features that enable you to create an app’s GUI.
Fig. 2.2 | MSDN Library web page in Visual Studio.
Location barWeb browser window tab
2.2 Overview of the Visual Studio Express 2012 IDE 37
Fig. 2.3 | New Project dialog.
Fig. 2.4 | Design view of the IDE.
Visual C# Windows Forms Application (selected)
Default project name (provided by Visual Studio)
Description of selected project (provided by Visual Studio)
Menu in the menu bar Form
Properties window
Solution Explorer window
Active tab (highlighted in blue)
38 Chapter 2 Dive Into® Visual Studio Express 2012 for Windows Desktop
Forms and Controls The rectangle in the Design area titled Form1 (called a Form) represents the main window of the Windows Forms app that you’re creating. Visual C# apps can have multiple Forms (windows)—however, most apps you’ll create in this text will use only one Form. You’ll learn how to customize the Form by adding GUI controls—in this example, you’ll add a Label and a PictureBox (as you’ll see in Fig. 2.20). A Label typically contains descriptive text (for example, “Welcome to Visual C#!”), and a PictureBox displays an image. Visual Studio has many preexisting controls and other components you can use to build and cus- tomize your apps. Many of these controls are discussed and used throughout the book. Other controls are available from third parties.
In this chapter, you’ll work with preexisting controls from the .NET Framework Class Library. As you place controls on the Form, you’ll be able to modify their properties (dis- cussed in Section 2.4). For example, Fig. 2.5 shows where the Form’s title can be modified and Fig. 2.6 shows a dialog in which a control’s font properties can be modified.
Collectively, the Form and controls make up the app’s GUI. Users enter data into the app by typing at the keyboard, by clicking the mouse buttons and in a variety of other ways. Apps use the GUI to display instructions and other information for users to view. For example, the New Project dialog in Fig. 2.3 presents a GUI where the user clicks the mouse button to select a template type, then inputs a project name from the keyboard (the figure is still showing the default project name WindowsFormsApplication1 supplied by Visual Studio).
Each open document’s name is listed on a tab. To view a document when multiple documents are open, click its tab. The active tab (the tab of the currently displayed doc- ument) is highlighted in blue (for example, Form1.cs [Design] in Fig. 2.4).
Fig. 2.5 | Textbox control for modifying a property in the Visual Studio IDE.
Textbox (displaying the text Form1) which can be modified
2.3 Menu Bar and Toolbar 39
2.3 Menu Bar and Toolbar Commands for managing the IDE and for developing, maintaining and executing apps are contained in menus, which are located on the menu bar of the IDE (Fig. 2.7). The set of menus displayed depends on what you’re currently doing in the IDE.
Menus contain groups of related commands (also called menu items) that, when selected, cause the IDE to perform specific actions—for example, open a window, save a file, print a file and execute an app. For example, new projects are created by selecting FILE > New Project…. The menus depicted in Fig. 2.7 are summarized in Fig. 2.8.
Fig. 2.6 | Dialog for modifying a control’s font properties.
Fig. 2.7 | Visual Studio menu bar.
Menu Description
FILE Contains commands for opening, closing, adding and saving projects, as well as printing project data and exiting Visual Studio.
EDIT Contains commands for editing apps, such as cut, copy, paste, undo, redo, delete, find and select.
VIEW Contains commands for displaying IDE windows (for example, Solution Explorer, Toolbox, Properties window) and for adding toolbars to the IDE.
PROJECT Contains commands for managing projects and their files. BUILD Contains options for turning your app into an executable program.
Fig. 2.8 | Summary of Visual Studio menus that are displayed when a Form is in Design view. (Part 1 of 2.)
40 Chapter 2 Dive Into® Visual Studio Express 2012 for Windows Desktop
You can access many common menu commands from the toolbar (Fig. 2.9), which contains icons that graphically represent commands. By default, the standard toolbar is displayed when you run Visual Studio for the first time—it contains icons for the most commonly used commands, such as opening a file, adding an item to a project, saving files and running apps (Fig. 2.9). The icons that appear on the standard toolbar may vary, depending on the version of Visual Studio you’re using. Some commands are initially dis- abled (grayed out or unavailable to use). These commands are enabled by Visual Studio only when they’re necessary. For example, Visual Studio enables the command for saving a file once you begin editing a file.
DEBUG Contains commands for compiling, debugging (that is, identifying and correcting problems in apps) and running apps.
TEAM Allows you to connect to a Team Foundation Server—used by development teams that typically have multiple people working on the same app.
FORMAT Contains commands for arranging and modifying a Form’s controls. The Format menu appears only when a GUI component is selected in Design view.
TOOLS Contains commands for accessing additional IDE tools and options for customiz- ing the IDE.
TEST Contains options for performing various types of autom


