Introduction

Microsoft Visual C# is a powerful but simple language aimed primarily at developers creating applications by using the Microsoft .NET Framework. It inherits many of the best features of C++ and Microsoft Visual Basic, but few of the inconsistencies and anachronisms, resulting in a cleaner and more logical language. C# 1.0 made its public debut in 2001. The advent of C# 2.0 with Visual Studio 2005 saw several important new features added to the language, including generics, iterators, and anonymous methods. C# 3.0, which was released with Visual Studio 2008, added extension methods, lambda expressions, and most famously of all, the Language-Integrated Query facility, or LINQ. C# 4.0, released in 2010, provided further enhancements that improve its interoperability with other languages and technologies. These features included support for named and optional arguments, and the dynamic type, which indicates that the language runtime should implement late binding for an object. An important addition in the .NET Framework released concurrently with C# 4.0 was the classes and types that constitute the Task Parallel Library (TPL). Using the TPL, you can build highly scalable applications that can take full advantage of multicore processors quickly and easily. C# 5.0 adds native support for asynchronous task-based processing through the async method modifier and the await operator.

Another key event for Microsoft has been the launch of Windows 8. This new version of Windows supports highly interactive applications that can share data and collaborate with each other as well as connect to services running in the cloud. The development environment provided by Microsoft Visual Studio 2012 made all these powerful features easy to use, and the many new wizards and enhancements included in Visual Studio 2012 can greatly improve your productivity as a developer.

After listening to feedback from developers, Microsoft modified some aspects of the way in which the user interface works and released a technical preview of Windows 8.1 containing these changes. At the same time, Microsoft released a preview edition of Visual Studio 2013, containing incremental changes to Visual Studio 2012 and adding new features that help to further improve programmer productivity. Although many of the updates to Visual Studio are small, and there have been no changes to the C# language in this release, we felt that the modifications to the way in which Windows 8.1 handles the user interface would make it beneficial to perform a similar incremental update to this book. The result is this volume.

Note

This book is based on the Technical Preview of Visual Studio 2013. Consequently, some features of the IDE might change in the final release of the software.

Who should read this book

This book assumes that you are a developer who wants to learn the fundamentals of programming with C# by using Visual Studio 2013 and the .NET Framework version 4.5.1. By the time you complete this book, you will have a thorough understanding of C# and will have used it to build responsive and scalable applications that can run by using the Windows operating system.

You can build and run C# 5.0 applications on Windows 7, Windows 8, and Windows 8.1, although the user interfaces provided by Windows 7 and Windows 8 have some significant differences. Additionally, Windows 8.1 has modified some parts of the user interface model, and applications designed to take advantage of these changes might not run on Windows 8. Consequently, Part I Part II Part III of this book provide exercises and working examples that run using Windows 7, Windows 8, and Windows 8.1. Part IV focuses on the application development model used by Windows 8.1, and the material in this section provides an introduction to building interactive applications for this new platform.

Who should not read this book

This book is aimed at developers new to C#, but not completely new to programming. As such, it concentrates primarily on the C# language. This book is not intended to provide detailed coverage of the multitude of technologies available for building enterprise-level applications for Windows, such as ADO.NET, ASP.NET, Windows Communication Foundation, or Workflow Foundation. If you require more information on any of these items, you might consider reading some of the other titles in the Step by Step for Developers series available from Microsoft Press, such as Microsoft ASP.NET 4 Step by Step by George Shepherd, Microsoft ADO.NET 4 Step By Step by Tim Patrick, and Microsoft Windows Communication Foundation 4 Step By Step by John Sharp.

Organization of this book

This book is divided into four sections:

  • Part I provides an introduction to the core syntax of the C# language and the Visual Studio programming environment.

  • Part II goes into detail on how to create and manage new types by using C#, and how to manage the resources referenced by these types.

  • Part III includes extended coverage of the elements that C# provides for building types that you can reuse across multiple applications.

  • Part IV describes the Windows 8.1 programming model, and how you can use C# to build interactive applications for this new model.

Note

Although Part IV is aimed at Windows 8.1, many of the concepts described in Chapter 23 and Chapter 24 are also applicable to Windows 8 and Windows 7 applications.

Finding your best starting point in this book

This book is designed to help you build skills in a number of essential areas. You can use this book if you are new to programming or if you are switching from another programming language such as C, C++, Java, or Visual Basic. Use the following table to find your best starting point.

If you are

Follow these steps

New to object-oriented programming

  1. Install the practice files as described in the upcoming section, Code samples.

  2. Work through the chapters in Part I, Part II, and Part III sequentially.

  3. Complete Part IV as your level of experience and interest dictates.

Familiar with procedural programming languages such as C but new to C#

  1. Install the practice files as described in the upcoming section, Code samples. Skim the first five chapters to get an overview of C# and Visual Studio 2013, and then concentrate on Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 Chapter 21 Chapter 22.

  2. Complete Part IV as your level of experience and interest dictates.

Migrating from an object-oriented language such as C++ or Java

  1. Install the practice files as described in the upcoming section, Code samples.

  2. Skim the first seven chapters to get an overview of C# and Visual Studio 2013, and then concentrate on Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 Chapter 21 Chapter 22.

  3. For information about building scalable Windows 8.1 applications, read Part IV.

Switching from Visual Basic to C#

  1. Install the practice files as described in the upcoming section, Code samples.

  2. Work through the chapters in Part I, Part II, and Part III sequentially.

  3. For information about building Windows 8.1 applications, read Part IV.

  4. Read the Quick Reference sections at the end of the chapters for information about specific C# and Visual Studio 2013 constructs.

Referencing the book after working through the exercises

  1. Use the index or the table of contents to find information about particular subjects.

  2. Read the Quick Reference sections at the end of each chapter to find a brief review of the syntax and techniques presented in the chapter.

Most of the book’s chapters include hands-on samples that let you try out the concepts just learned. No matter which sections you choose to focus on, be sure to download and install the sample applications on your system.

Conventions and features in this book

This book presents information by using conventions designed to make the information readable and easy to follow.

  • Each exercise consists of a series of tasks, presented as numbered steps (1, 2, and so on) listing each action you must take to complete the exercise.

  • Boxed elements with labels such as “Note” provide additional information or alternative methods for completing a step successfully.

  • Text that you type (apart from code blocks) appears in bold.

  • A plus sign (+) between two key names means that you must press those keys at the same time. For example, “Press Alt+Tab” means that you hold down the Alt key while you press the Tab key.

  • A vertical bar between two or more menu items (for example, File | Close) means that you should select the first menu or menu item, then the next, and so on.

System requirements

You will need the following hardware and software to complete the practice exercises in this book:

  • Windows 7 (x86 and x64), Windows 8 (x86 and x64), Windows 8.1 (x86 and x64), Windows Server 2008 R2 SP1 (x64), Windows Server 2012 (x64), or Windows Server 2012 R2 (x64).

    Important

    The Windows Store templates for Visual Studio 2013 are not available on Windows 8, Windows 7, Windows Server 2012, or Windows Server 2008 R2. If you want to use these templates or perform the exercises that build Windows Store apps, you must be running Windows 8.1 or Windows Server 2012 R2.

  • Visual Studio 2013 (any edition except Visual Studio Express for Windows 8.1).

    Important

    You can use Visual Studio Express 2013 for Windows Desktop, but you can only perform the Windows 7 version of the exercises in this book by using this software. You cannot use this software to perform the exercises in Part IV of this book.

  • Computer that has a 1.6 GHz or faster processor (2 GHz recommended).

  • 1 GB (32-bit) or 2 GB (64-bit) RAM (add 512 MB if running in a virtual machine).

  • 10 GB of available hard disk space.

  • 5400 RPM hard disk drive.

  • DirectX 9 capable video card running at 1024 × 768 or higher resolution display; If you are using Windows 8.1, a resolution of 1366 × 768 or greater is recommended.

  • DVD-ROM drive (if installing Visual Studio from a DVD).

  • Internet connection to download software or chapter examples.

Depending on your Windows configuration, you might require Local Administrator rights to install or configure Visual Studio 2013.

Code samples

Most of the chapters in this book include exercises with which you can interactively try out new material learned in the main text. You can download all sample projects, in both their pre-exercise and postexercise formats, from the following page:

http://aka.ms/VC2013SbS/files

Follow the instructions to download the C#_SBS.zip file.

Note

In addition to the code samples, your system should have Visual Studio 2013 installed. If available, install the latest service packs for Windows and Visual Studio.

Installing the code samples

Follow these steps to install the code samples on your computer so that you can use them with the exercises in this book.

  1. Unzip the C#_SBS.zip file that you downloaded from the book’s website into your Documents folder.

  2. If prompted, review the displayed end user license agreement. If you accept the terms, select the accept option, and then click Next.

Note

If the license agreement doesn’t appear, you can access it from the same webpage from which you downloaded the C#_SBS.zip file.

Using the code samples

Each chapter in this book explains when and how to use any code samples for that chapter. When it’s time to use a code sample, the book will list the instructions for how to open the files.

For those of you who like to know all the details, here’s a list of the code sample Visual Studio 2013 projects and solutions, grouped by the folders where you can find them. In many cases, the exercises provide starter files and completed versions of the same projects that you can use as a reference. The code samples provide versions of the code for Window 7 and Windows 8.1, and the exercise instructions call out any differences in the tasks that you need to perform or the code that you need to write for these two operating systems. The completed projects for each chapter are stored in folders with the suffix “- Complete”.

Important

If you are using Windows 8, Windows Server 2012 or Windows Server 2008 R2, follow the instructions for Windows 7. If you are using Windows Server 2012 R2, follow the instructions for Windows 8.1.

Project

Description

Chapter 1

 

TextHello

This project gets you started. It steps through the creation of a simple program that displays a text-based greeting.

WPFHello

This project displays the greeting in a window by using Windows Presentation Foundation (WPF).

Chapter 2

 

PrimitiveDataTypes

This project demonstrates how to declare variables by using each of the primitive types, how to assign values to these variables, and how to display their values in a window.

MathsOperators

This program introduces the arithmetic operators (+ – * / %).

Chapter 3

 

Methods

In this project, you’ll re-examine the code in the previous project and investigate how it uses methods to structure the code.

DailyRate

This project walks you through writing your own methods, running the methods, and stepping through the method calls by using the Visual Studio 2013 debugger.

DailyRate Using Optional Parameters

This project shows you how to define a method that takes optional parameters and call the method by using named arguments.

Chapter 4

 

Selection

This project shows you how to use a cascading if statement to implement complex logic, such as comparing the equivalence of two dates.

SwitchStatement

This simple program uses a switch statement to convert characters into their XML representations.

Chapter 5

 

WhileStatement

This project demonstrates a while statement that reads the contents of a source file one line at a time and displays each line in a text box on a form.

DoStatement

This project uses a do statement to convert a decimal number to its octal representation.

Chapter 6

 

MathsOperators

This project revisits the MathsOperators project from Chapter 2 and shows how various unhandled exceptions can make the program fail. The try and catch keywords then make the application more robust so that it no longer fails.

Chapter 7

 

Classes

This project covers the basics of defining your own classes, complete with public constructors, methods, and private fields. It also shows how to create class instances by using the new keyword and how to define static methods and fields.

Chapter 8

 

Parameters

This program investigates the difference between value parameters and reference parameters. It demonstrates how to use the ref and out keywords.

Chapter 9

 

StructsAndEnums

This project defines a struct type to represent a calendar date.

Chapter 10

 

Cards

This project shows how to use arrays to model hands of cards in a card game.

Chapter 11

 

ParamsArrays

This project demonstrates how to use the params keyword to create a single method that can accept any number of int arguments.

Chapter 12

 

Vehicles

This project creates a simple hierarchy of vehicle classes by using inheritance. It also demonstrates how to define a virtual method.

ExtensionMethod

This project shows how to create an extension method for the int type, providing a method that converts an integer value from base 10 to a different number base.

Chapter 13

 

Drawing Using Interfaces

This project implements part of a graphical drawing package. The project uses interfaces to define the methods that drawing shapes expose and implement.

Drawing Using Abstract Classes

This project extends the Drawing Using Interfaces project to factor common functionality for shape objects into abstract classes.

Chapter 14

 

GarbageCollectionDemo

This project shows how to implement exception-safe disposal of resources by using the Dispose pattern.

Chapter 15

 

Drawing Using Properties

This project extends the application in the Drawing Using Abstract Classes project developed in Chapter 13 to encapsulate data in a class by using properties.

AutomaticProperties

This project shows how to create automatic properties for a class and use them to initialize instances of the class.

Chapter 16

 

Indexers

This project uses two indexers: one to look up a person’s phone number when given a name and the other to look up a person’s name when given a phone number.

Chapter 17

 

BinaryTree

This solution shows you how to use generics to build a typesafe structure that can contain elements of any type.

BuildTree

This project demonstrates how to use generics to implement a typesafe method that can take parameters of any type.

Chapter 18

 

Cards

This project updates the code from Chapter 10 to show how to use collections to model hands of cards in a card game.

Chapter 19

 

BinaryTree

This project shows you how to implement the generic IEnumerator<T> interface to create an enumerator for the generic Tree class.

IteratorBinaryTree

This solution uses an iterator to generate an enumerator for the generic Tree class.

Chapter 20

 

Delegates

This project shows how to decouple a method from the application logic that invokes it by using a delegate.

Delegates With Event

This project shows how to use an event to alert an object to a significant occurrence, and how to catch an event and perform any processing required.

Chapter 21

 

QueryBinaryTree

This project shows how to use LINQ queries to retrieve data from a binary tree object.

Chapter 22

 

ComplexNumbers

This project defines a new type that models complex numbers and implements common operators for this type.

Chapter 23

 

GraphDemo

This project generates and displays a complex graph on a WPF form. It uses a single thread to perform the calculations.

GraphDemo With Tasks

This version of the GraphDemo project creates multiple tasks to perform the calculations for the graph in parallel.

Parallel GraphDemo

This version of the GraphDemo project uses the Parallel class to abstract out the process of creating and managing tasks.

GraphDemo With Cancellation

This project shows how to implement cancellation to halt tasks in a controlled manner before they have completed.

ParallelLoop

This application provides an example showing when you should not use the Parallel class to create and run tasks.

Chapter 24

 

GraphDemo

This is a version of the GraphDemo project from Chapter 23 that uses the async keyword and the await operator to perform the calculations that generate the graph data asynchronously.

PLINQ

This project shows some examples of using PLINQ to query data by using parallel tasks.

CalculatePI

This project uses a statistical sampling algorithm to calculate an approximation for pi. It uses parallel tasks.

Chapter 25

 

Customers Without Scalable UI

This project uses the default Grid control to lay out the user interface for the Adventure Works Customers application. The user interface uses absolute positioning for the controls and does not scale to different screen resolutions and form factors.

Customers With Scalable UI

This project uses nested Grid controls with row and column definitions to enable relative positioning of controls. This version of the user interface scales to different screen resolutions and form factors, but it does not adapt well to Snapped view.

Customers With Adaptive UI

This project extends the version with the scalable user interface. It uses the Visual State Manager to detect whether the application is running in Snapped view, and it changes the layout of the controls accordingly.

Customers With Styles

This version of the Customers project uses XAML styling to change the font and background image displayed by the application.

Chapter 26

 

DataBinding

This project uses data-binding to display customer information retrieved from a data source in the user interface. It also shows how to implement the INotifyPropertyChanged interface so that the user interface can update customer information and send these changes back to the data source.

ViewModel

This version of the Customers project separates the user interface from the logic that accesses the data source by implementing the Model-View-ViewModel pattern.

Search

This project implements the Windows 8.1 Search contract. A user can search for customers by first name or last name.

Chapter 27

 

Web Service

This solution includes a web application that provides an ASP.NET Web API web service that the Customers application uses to retrieve customer data from a SQL Server database. The web service uses an entity model created by using the Entity Framework to access the database.

Updatable ViewModel

The Customers project in this solution contains an extended ViewModel with commands that enable the user interface to insert and update customer information by using the WCF Data Service.

Acknowledgments

Despite the fact that my name is on the cover, authoring a book such is this is far from a one-man project. I’d like to thank the following people who have provided unstinting support and assistance throughout this rather protracted exercise.

First, Russell Jones, who first alerted me to the impending release of the Windows 8.1 and Visual Studio 2013 technical previews. He managed to expedite the entire process of getting this edition of the book ready to go to print. Without his efforts you might have been reading this edition just as the next edition of Windows emerged.

Next, Mike Sumsion and Paul Barnes, my esteemed colleagues at Content Master, who performed sterling work reviewing the material for the original versions of each chapter, testing my code, and pointing out the numerous mistakes that I had made! I think I have now caught them all, but of course any errors that remain are entirely my responsibility.

Also, John Mueller, who has done a remarkable job in performing a very swift technical review of this edition. His writing experience and understanding of the technologies covered herein have been extremely helpful, and this book has been enriched by his efforts.

Of course, like many programmers, I might understand the technology but my prose is not always as fluent or clear as it could be. I would like to thank the editors for correcting my grammar, fixing my spelling, and generally making my material much easier to understand.

Finally, I would like to thank my wife and cricketing companion, Diana, for not frowning too much when I said I was about to start work on an updated edition of this book. She has now become used to my cranky mutterings while I debug code, and the numerous “d’ohs” that I emit when I realize the crass mistakes I have made.

Errata and book support

We’ve made every effort to ensure the accuracy of this book and its companion content. Any errors that have been reported since this book was published are listed on our Microsoft Press site at oreilly.com:

http://aka.ms/VC2013SbS/errata

If you find an error that is not already listed, you can report it to us through the same page.

If you need additional support, email Microsoft Press Book Support at .

Please note that product support for Microsoft software is not offered through the addresses above.

We want to hear from you

At Microsoft Press, your satisfaction is our top priority, and your feedback is our most valuable asset. Please tell us what you think of this book at:

http://www.microsoft.com/learning/booksurvey

The survey is short, and we read every one of your comments and ideas. Thanks in advance for your input!

Stay in touch

Let’s keep the conversation going! We’re on Twitter: http://twitter.com/MicrosoftPress

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.183.210