+ All Categories
Home > Documents > Programming C#

Programming C#

Date post: 10-Nov-2015
Category:
Upload: thabang-elliot-kgasho
View: 656 times
Download: 28 times
Share this document with a friend
Description:
The student is taught the different aspects of an object oriented application, including: implementation of classes, inheritance, basic user interaction and file streaming.
Popular Tags:
261
1 PRG100: C#
Transcript
  • 1

    PRG100: C#

  • 2

  • 3

    CONTENTS

    Part I: Programming Principles ...................................................................................................................................... 9

    Chapters in this section: ...................................................................................................................................... 9

    1. Logic Concepts .............................................................................................................................................. 11

    1.1 Digital Logic ............................................................................................................................................. 11

    1.2 Programming Concepts ........................................................................................................................... 21

    1.3 Flow Charts .............................................................................................................................................. 25

    1.4 PseudoCode ............................................................................................................................................ 35

    1.5 Trace Tables ............................................................................................................................................ 43

    2. Introducing the .NET Platform ...................................................................................................................... 45

    2.1 Application Development Before .NET ................................................................................................... 45

    2.2 Enter.NET ................................................................................................................................................ 46

    2.3 The Building Blocks of .NET ..................................................................................................................... 47

    2.4 A Quick Tour Through Visual Studio 2010 ............................................................................................... 50

    Part II: Core C# ............................................................................................................................................................ 67

    Chapters in this section: .................................................................................................................................... 67

    3. Language Essentials ....................................................................................................................................... 69

    3.1 The Entry Point ........................................................................................................................................ 69

    3.2 The Anatomy of a Console Application ................................................................................................... 69

    3.3 C# Coding Best Practices ......................................................................................................................... 71

    3.4 Keywords ................................................................................................................................................. 75

    3.5 A Primer on Types ................................................................................................................................... 76

    3.6 Variables .................................................................................................................................................. 78

    3.7 Key Terms ................................................................................................................................................ 80

    3.8 Exercises .................................................................................................................................................. 81

    4. Expressions and Operators ........................................................................................................................... 83

    4.1 Expressions .............................................................................................................................................. 83

    4.2 Arity of Operators ................................................................................................................................... 83

    4.3 Binary Arithmetic Operators ................................................................................................................... 84

  • 4

    4.4 String Concatenation ............................................................................................................................... 84

    4.5 Relational Operators ............................................................................................................................... 85

    4.6 Key Terms ................................................................................................................................................ 86

    4.7 Exercises .................................................................................................................................................. 87

    5. Built in Types ................................................................................................................................................. 89

    5.1 Boolean ................................................................................................................................................... 89

    5.2 Numeric Data Types ................................................................................................................................ 90

    5.3 String and StringBuilder .......................................................................................................................... 93

    5.4 Dates ....................................................................................................................................................... 95

    5.5 Enums ...................................................................................................................................................... 95

    5.6 Value Types vs Reference Types ............................................................................................................. 96

    5.7 Null References ....................................................................................................................................... 98

    5.8 Key Terms ................................................................................................................................................ 99

    5.9 Exercises ................................................................................................................................................ 101

    6. Simple Control Flow .................................................................................................................................... 105

    6.1 Blocks .................................................................................................................................................... 106

    6.2 Selection statements ............................................................................................................................. 107

    6.3 Iteration Statements ............................................................................................................................. 108

    6.4 Jump Statements ................................................................................................................................... 109

    7. Decision Making .......................................................................................................................................... 111

    7.1 Using if Statements ............................................................................................................................... 111

    7.2 Nested if Statements ............................................................................................................................. 112

    7.3 Multiple Conditions ............................................................................................................................... 113

    7.4 Compound if Statements ...................................................................................................................... 115

    7.5 Switch Case Statements ........................................................................................................................ 117

    7.6 Key Terms .............................................................................................................................................. 120

    7.7 Exercises ................................................................................................................................................ 121

    8. Loops ........................................................................................................................................................... 125

    8.1 The while Loop ...................................................................................................................................... 125

  • 5

    8.2 The dowhile Loop ............................................................................................................................... 127

    8.3 The for Loop .......................................................................................................................................... 128

    8.4 Nested Loops ......................................................................................................................................... 131

    8.5 Improving Loop Performance ............................................................................................................... 133

    8.6 Key Terms .............................................................................................................................................. 134

    8.7 Exercises ................................................................................................................................................ 135

    9. Arrays .......................................................................................................................................................... 137

    9.1 Intializing Arrays .................................................................................................................................... 137

    9.2 Single Dimension Arrays ........................................................................................................................ 138

    9.3 Accessing Array Elements ..................................................................................................................... 140

    9.4 Multi-Dimension Arrays ........................................................................................................................ 141

    9.5 Loops Revisited: foreach Loops ............................................................................................................ 145

    9.6 Key Terms .............................................................................................................................................. 147

    9.7 Exercises ................................................................................................................................................ 148

    Part III: Methods and Encapsulation ......................................................................................................................... 151

    Chapters in this section: .................................................................................................................................. 151

    10. Methods .................................................................................................................................................... 153

    10.1 Understanding Methods and Implementation Hiding ........................................................................ 153

    10.2 Defining Methods ................................................................................................................................ 153

    10.3 Parameters .......................................................................................................................................... 157

    10.4 Return Values ...................................................................................................................................... 159

    10.5 Passing an Array to a Method ............................................................................................................. 161

    10.6 Overloading Methods ......................................................................................................................... 163

    10.7 Optional Parameters ........................................................................................................................... 166

    10.8 Key Terms ............................................................................................................................................ 167

    10.9 Exercises .............................................................................................................................................. 169

    11. Classes and Objects ................................................................................................................................... 173

    11.1 Creating Classes .................................................................................................................................. 173

    11.2 Fields and Properties ........................................................................................................................... 174

  • 6

    11.3 Creating Class Objects ......................................................................................................................... 179

    11.4 Class Constructors ............................................................................................................................... 180

    11.5 The this Keyword ................................................................................................................................. 181

    11.6 Finalizers/Destructors ......................................................................................................................... 182

    11.7 Object Lifetime .................................................................................................................................... 183

    11.8 Key Terms ............................................................................................................................................ 186

    11.9 Exercises .............................................................................................................................................. 188

    Part IV: Advanced Class Concepts ............................................................................................................................. 193

    Chapters in this Section: ................................................................................................................................. 193

    12. The 3 Pillars of Object Oriented Programming ......................................................................................... 195

    12.1 The Cornerstones of Object Orientation ............................................................................................. 195

    13. Inheritance ................................................................................................................................................ 201

    13.1 What Inheritance Provides for Us ....................................................................................................... 201

    13.2 How Inheritance Works ....................................................................................................................... 203

    13.3 The sealed Keyword ............................................................................................................................ 205

    13.4 Access Modifiers and Inheritance ....................................................................................................... 206

    13.5 Constructors and Inheritance .............................................................................................................. 209

    13.6 Abstract Classes................................................................................................................................... 211

    13.7 Key Terms ............................................................................................................................................ 214

    13.8 Exercises .............................................................................................................................................. 215

    14. Polymorphism ........................................................................................................................................... 219

    14.1 Polymorphism in Action ...................................................................................................................... 219

    14.2 Implementing Polymorphism .............................................................................................................. 220

    14.3 Override Object class methods ........................................................................................................... 221

    14.5 Key Terms ............................................................................................................................................ 224

    14.6 Exercises .............................................................................................................................................. 224

    15. Exception Handling ................................................................................................................................... 227

    15.1 Understanding Exceptions .................................................................................................................. 227

    15.2 Understanding Traditional and Object-Oriented Error-Handling Methods ........................................ 228

  • 7

    15.3 Tracing Exceptions Through the Call Stack .......................................................................................... 233

    15.4 Catching Multiple Exceptions .............................................................................................................. 234

    15.5 The finally Block .................................................................................................................................. 235

    15.6 Key Terms ............................................................................................................................................ 236

    15.7 Exercises .............................................................................................................................................. 237

    Part V: Database Programming ................................................................................................................................. 239

    Chapters in this Section: ................................................................................................................................. 239

    16. File I/O ....................................................................................................................................................... 241

    16.1 Computer Files and the File and Directory Classes ............................................................................. 241

    16.1 Using the File and Directory Classes ................................................................................................... 242

    16.3 Understanding Streams ....................................................................................................................... 244

    16.4 Exercises .............................................................................................................................................. 247

    17. ADO.Net .................................................................................................................................................... 249

    17.1 The Set-up ........................................................................................................................................... 249

    17.2 Connection .......................................................................................................................................... 251

    17.3 Selecting Data ..................................................................................................................................... 253

    17.4 Making a Menu for DataManipulation ................................................................................................ 255

    17.5 Updating Using the Command Builder (OleDbCommandBuilder) ...................................................... 258

    17.6 Update Using the Command (OleDbCommand) ................................................................................. 260

    17.7 Exercises .............................................................................................................................................. 261

  • 8

  • 9

    PART I: PROGRAMMING PRINCIPLES

    CHAPTERS IN THIS SECTION:

    1. LOGIC CONCEPTS

    2. INTRODUCING THE .NET PLATFORM

  • 10

  • 11

    1. LOGIC CONCEPTS

    In the world of programming there is a particular way of thinking necessary in order to understand how to create solutions for problems. In order to learn the needed logical mindset needed we will take a look at the foundation of what high level programming is based on.

    1.1 DIGITAL LOGIC

    Digital logic (also called Binary Logic) is the way of determining what an outcome will be if we send pulses through a circuit with different set ups. In this section we look at how the logic we use in binary will affect our truth table and ultimately our programs we create. In fact, we use the same logic operations when doing decision branches.

    The reason we look at electrical circuits when discussing binary logic is that 0 and 1 are indications of a current being off and on, respectively, in robotics and electrical engineering. We as programmers use the same logic as we work on very similar principles in our own basic forms of application development.

    1.1.1 LOGICAL OPERATIONS We already know that binary variables can be represented by letters of the alphabet such as A, B, C, x, y, z et cetera, and that each variable can only assume the value 0 or 1. We will first look at the three basic binary operators AND, OR, and NOT, indicating relationships between binary variables. They can be defined as follows:

    AND OPERATOR

    This operator is indicated by a period (), or by the absence of an operator. For example, we write AB=L or AB=L, which is read as "A AND B is equal to L". What value shall we now assign to L? Let's simulate this operation using a circuit containing two switches that are linked serially:

    We are now going to compile a truth table for this circuit. A truth table is a table containing all possible combinations of the input variables, A and B in this case, as well as the result of one or more logical operations on the input variables.

  • 12

    We can now allocate a value of 1 to A if it is closed and a value of 0 to A if it is open. Do the same for B. Let L=1 if the light is on and let L=0 if the light is off.

    The truth table is as follows:

    OR OPERATOR

    This operator is indicated by a plus sign (+). For the same variables as before, we write A+B=L. We read this as "A OR B is equal to L". What value is now assigned to L? Again we use a circuit with two switches, but this time linked in parallel:

    The truth table for the circuit:

    Truth table for OR operator:

    NOT OPERATOR This operator is indicated by a prime (sometimes by a small horizontal line as in ). We therefore write: A=C or =C, which is read: "A complement is equal to C". This means that A is not equal to C, or that C is what A is not! In other words, if A=1, then C=0 and if A=0, then C=1.

  • 13

    Truth table for NOT operator:

    A variety of notation symbols are commonly used for the AND, OR and NOT operators. For example, logicians like to use v, and . Electronic engineers, on the other hand, prefer , +, and . We are going to keep to the latter convention since our next topic has to do with circuit design.

    1.1.2 SWITCHING CIRCUITS AND BINARY LOGIC

    As we have seen, we can describe simple circuits using binary logic. The two circuits in the previous section can be expressed as follows in terms of binary logic:

    L = AB (for serial switches) - AND operator

    L = A+B (for parallel switches) OR operator

    1.1.3 LOGIC GATES

    An electronic circuit that performs a function similar to the logical operators AND, OR or NOT, is called a logic gate or logic circuit. A circuit of this kind has one or more inputs, each of which may be equal to either 0 or 1. There are one or more outputs, depending on the function of the circuit. The outputs can be equal to either 1 or 0.

    NOT GATE

    Consider the following elementary circuit:

    This circuit is designed in such a way that the output is 0 if the input is 1, and the output is 1 if the input is a 0. This circuit implements the function of the NOT operator discussed earlier and is called an inverter or a NOT gate. The following is a symbolic representation of the NOT gate:

  • 14

    We can describe the behavior of this gate with the aid of a truth table (which is the same as that for the NOT operator).

    AND GATE

    The logic circuit which performs the same function as the AND operator is called the AND gate and is symbolically represented in the following way:

    The truth table is the same as that of the AND operator:

    Consider the following circuit with three switches:

    The light will only burn if all three switches are closed. The truth table is as follows:

    Note that the total number of value combinations of the three variables A, B and C, (which can only be 0 or 1), is equal to 23 = 8.

    It should now be clear that the output of an AND gate (with any number of inputs) can only be a 1 if all the inputs are equal to 1.

  • 15

    OR GATE

    The logic circuit that performs the same function as the OR operator is called the OR gate and is represented symbolically in the following way:

    The truth table is the same as that of the OR operator:

    We again draw an electrical circuit to determine what the output of the OR gate will be if there are more than two inputs.

    The light will burn if any of these switches are closed, in other words if A=1 or B=1 or C=1 or D=1. The light will only be off if all the switches are open. Thus: X = A + B + C + D = 0 only if A=0 and B=0 and C=0 and D=0

    For all other combinations of A, B, C and D, X will be equal to 1.

    NAND GATE

    The NAND gate is equivalent to an AND gate followed by an inverter.

    We represent the NAND gate symbolically as follows:

  • 16

    The truth table for a NAND gate can be derived as follows:

    Note that the output of a NAND gate is 0 only in the case when all inputs are equal to 1. For all other combinations of input values the output will be equal to 1.

    NOR GATE The NOR gate is the equivalent of an OR gate followed by an inverter as illustrated in the first figure below and the NOR gate is represented symbolically as in the second figure below:

    Equivalent representation of a NOR gate

    Symbolic representation of a NOR gate

    The truth table is as follows:

    XOR GATE (EXCLUSIVE OR)

    We use the XOR gate; where a combination of one input being true and one being false produces a true; for the expression A.B + A.B. The XOR gate can be represented symbolically as in figure below:

  • 17

    The truth table is as follows:

    1.1.4 HIERARCHY OF OPERATIONS

    The logical operators have a hierarchy, or precedence, that stipulates the order in which their operations will take place.

    Order Operations 1 () Reorders the hierarchy; all operations are completed within the

    parentheses using the same hierarchy. 2 NOT 3 AND 4 OR

    1.5 BOOLEAN EXPRESSIONS

    Prove the following using a truth table:

    (x + y) + z = x + (y + z)

    Truth Table:

    x y z (x + y) (y + z) (x + y) + z x + (y + z) 0 0 0 0 0 0 0 0 0 1 0 1 1 1 0 1 0 1 1 1 1 0 1 1 1 1 1 1 1 0 0 1 0 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1

  • 18

    1.1.6 SUMMARY

    Gate Graphic symbol Function Truth table AND

    F = xy

    x y F 0 0 0 0 1 0 1 0 0 1 1 1

    OR

    F = x + y

    x y F 0 0 0 0 1 1 1 0 1 1 1 1

    Inverter

    F = x

    x F 0 1 1 0

    Buffer

    F = x

    x F 0 0 1 1

    NAND

    F = (xy)

    x y F 0 0 1 0 1 1 1 0 1 1 1 0

    NOR

    F = (x+y)

    x y F 0 0 1 0 1 0 1 0 0 1 1 0

    XOR (Exclusive OR)

    F = xy + xy

    = xy

    x y F 0 0 0 0 1 1 1 0 1 1 1 0

  • 19

    1.1.7 EXERCISES

    1. x+0 = x

    2. x x = x

    3. (x ) = x

    4. x x = 0

    5. x+y = y+x

    6. (x+y) + z = x + (y+z)

    7. x (y+z) = x y + x z

    8. x+xy = x

    9. xy + xy = x

    10. (x+y)(x+y) = x

    11. A + AB = A + B

    12. A + AB = A + B

    13. A + AB = A + B

    14. A + AB = A + B

  • 20

  • 21

    1.2 PROGRAMMING CONCEPTS

    A computer is only as good as its hardware, the software running on it, and the people that use the computer. Computers need a set of instructions, the solution, in order to process data in the correct sequence and reach the desired results. The programmer or user has to be able to easily read and interpret the solution. The solution will be most effective if the programmer follows certain steps and rules. The solution becomes a program when it is coded into a computer language during the final stages of programming.

    1.2.1 COMMUNICATING WITH COMPUTERS

    Computers cannot speak English, thus you have to learn its system of communication. This system of communication requires instructions that are governed by specific rules. If the instructions you write are incorrect, the computer will give an error message, the wrong answer or no answer at all.

    The meaning of an instruction is essentially the same in all programming languages. They only differ in how they are set up. Syntax refers to the rules governing the computer operating system, the language and the application. An error is called a bug, and most bugs are found through a process called debugging. Many errors are due to syntax errors, but some are logical errors.

    1.2.2 ORGANIZING AND SOLVING PROBLEMS

    Before learning a programming language, it is helpful to establish some context for the productive part of the entire programming effort. This context comprises the understanding and agreement that there are four fundamental and discrete steps involved in solving a problem on a computer.

    The four steps are:

    1) State, analyze, and define the problem 2) Develop program logic and prepare an algorithm and a diagram 3) Code the program, prepare the code in machine-readable form, prepare data, and perform

    debug and test runs. 4) Complete the documentation and prepare operator for implementation and production.

    Programming can be complicated, and advance preparation is required before you can actually start to write or code the program. The first two steps, problem understanding and making a diagram, fall into the advance planning phase of programming. This is very important to develop correct habits and procedures, since this will prevent later difficulties.

    1.2.3 ANALYSING THE PROBLEM

    Whether you are working with a systems analyst, a customer, or solving a problem of your own, it is extremely important that you have a thorough understanding of the problem.

  • 22

    Every aspect of the problem must be defined:

    What is the problem? What information (or data) is needed? Where and how will the information be obtained? What is the desired output?

    Starting with only a portion of the information, or an incomplete definition, will result in having to constantly alter what has been done to accommodate the additional facts as they become available. It is easier and more efficient to begin programming after all of the necessary information is understood. Once you have a thorough understanding of the problem, the next step is flowcharting.

    1.2.4 DRAWING THE FLOWCHART

    A flowchart is a graphic representation of the algorithm or set of instructions. Flowcharts are drawn using a set of symbols to represent the different processes.

    Flowcharts use different shaped symbols connected by one-way arrows to represent operations, data, flow, equipment, and so forth.

    A flowchart is constructed by the programmer to represent the sequence of operations the computer is to perform to solve a specific problem. It graphically describes what is to take place in the program. It displays specific operations and decisions, and their sequence within the program. For instance, if we had an algorithm that required us to get the name and age of a user and then we had to print that name and age. The flowchart for that algorithm would be:

    Drawing flowcharts will be discussed in more detail in the next section.

    1.2.5 CODING A PROGRAM

    Regardless of the language used, there are strict rules the programmer must adhere to with regard to punctuation and statement structure when coding any program.

    Once coding is completed, the program must be debugged and tested prior to implementation.

  • 23

    1.2.6 DEBUGGING

    Errors caused by faulty logic and coding mistakes are referred to as "bugs." Finding and correcting these mistakes and errors that prevent the program from running and producing correct output is called "debugging." Rarely do complex programs run to completion on the first attempt. Often, time spent debugging and testing equals or exceeds the time spent in program coding. This is particularly true if insufficient time was spent on problem definition and logic development. Some common mistakes which cause program bugs are: mistakes in coding punctuation, incorrect operation codes, transposed characters, keying errors and failure to provide a sequence of instructions (a program path) needed to process certain conditions. To reduce the number of errors, you will want to carefully check the coding sheets before they are turned in for keying. This process is known as "desk-checking" and should include an examination for program completeness.

    Typical input data should be manually traced through the program processing paths to identify possible errors. In effect, you will be attempting to play the role of the computer. After the program has been desk-checked for accuracy, the program is ready to be assembled or compiled. Assembly and compiler programs prepare your program (source program) to be executed by the computer and they have error diagnostic features, which detect certain types of mistakes in your program. These mistakes must be corrected. Even when an error-free pass of the program through the assembly or compiler program is accomplished, this does not mean your program is perfected. However, it usually means the program is ready for testing.

    1.2.7 TESTING

    Once a program reaches the testing stage, generally, it has proven it will run and produce output. The purpose of testing is to determine that all data can reprocessed correctly and that the output is correct. The testing process involves processing input test data that will produce known results.

    1.2.8 DOCUMENTATION

    Documentation is a continuous process, beginning with the problem definition. Documentation involves collecting, organizing, storing, and other-wise maintaining a complete record of the programs and other documents associated with the data processing system.

    Local minimum documentation requirements are usually established by the head of the data processing department/division. At most, commands from this function are delegated to the project manager. The key to the minimum amount of documentation required by local commands should be the amount that is required for replacement personnel to understand input, processing, and output for each program or system for which they will be responsible. A documentation package should include:

  • 24

    1. A definition of the problem. Why was the program written? What were the objectives? Who requested the program, and who approved it? These are the types of questions that should be answered.

    2. A description of the system. The system environment (hardware, software, and organization) in which the program functions should be described (including systems flowcharts). General systems specifications outlining the scope of the problem, the form and type of input data to be used, and the form and type of output required should be clearly defined.

    3. A description of the program. Programming flowcharts, program listings, program controls, test data and test results, storage dumpsthese and other documents that describe the program and give a historical record of problems and/or changes should be included.

    4. Operator instructions. Items that should be included are computer switch settings, loading and unloading procedures, and starting, running, and termination procedures.

  • 25

    1.3 FLOW CHARTS

    A flowchart is a method of graphically representing an algorithm or a procedural solution to a problem before attempting to enter it into a computer. The algorithms and the flowcharts are the final steps in organizing a solution before writing the computer program. Using a flowchart, a programmer can detect bugs and go on to code the problem in a computer language. A flowchart will show errors in logic not readily visible in other charts. The Figure below illustrates some of the commonly used flowchart symbols.

    1.3.1 SYMBOLS

  • 26

    1.3.2 EXAMPLES USING FLOWCHARTS

    A flowchart shows the flow of the processing from the beginning to the end of a solution. Each block in a flowchart represents one instruction from an algorithm. Most blocks have one or more entrances, flow lines directing the flow of data into the block. Most blocks have only one exit, flow lines directing the data out of the block, since data can flow to only one other block. The exception to this rule is a block representing a decision instruction, an instruction that enables the computer to make one of two choices. A decision block has two exits, one for each choice. The following is an example of an algorithm and flowcharts for a payroll system; this is to illustrate how a process is incorporated into a module.

  • 27

    FUNCTIONS

  • 28

    SEQUENCE CONTROL STRUCTURES

  • 29

    SELECTION CONTROL STRUCTURES

  • 30

    CONTROL LOGIC

    Straight-through logic means that all the decisions are processed sequentially, one after the other. There is no ELSE part of the instructions; the FALSE branch always goes to the next decision, and the TRUE branch goes to the next decision after the instructions for the TRUE branch have been processed.

    The following problem will be used to illustrate the different types of decision logic.

    You need to determine the amount a person will be charged for a movie ticket depending on his/her age. When the person is under 16, the charge is R10; when the person is 65 or over, the charge is R7; all others are charged R20. The conditions are the following:

    Age Charge AGE < 16 R10 AGE >= 16 AND AGE < 65 R20 AGE >= 65 R7

    Example of straight-through logic

    On the contrary, not all positive logic instructions are processed. Positive logic allows the flow of the processing to continue through the module instead of processing succeeding decisions, once the resultant of a decision is TRUE. Whenever the resultant is FALSE, another decision in the sequence is processed until the resultant is TRUE, or there are no more decisions to process. At that time, the FALSE ranch processes the remaining instructions.

  • 31

    Example of positive logic

    Negative logic is similar to positive logic except that the flow of the processing continues through the module when a resultant of a decision is FALSE. Whenever the resultant is TRUE, another decision is processed until the resultant is FALSE, or there are no more decisions to process. At that time, the TRUE branch processes the remaining instructions.

    Example of negative logic

  • 32

    ITERATION (REPETITION) CONTROL STRUCTURES

  • 33

  • 34

    1.3.3 EXERCISES

    1. Draw a flowchart to read an input record containing two numbers and print out the larger of the two numbers.

    2. At Belgium Campus, a student is enrolled in a course in which the final grade is either a P or an

    F. The grade is determined by adding the scores obtained on three tests: T1, T2, & T3. If the sum of the test scores is greater than 225, a grade of P to be printed, otherwise, an F is printed. Draw a flowchart to read an input record containing three test scores and print an appropriate grade.

    3. Draw a flowchart to read a file of records, print a heading at the top of each page, print the data

    records, but print no more than 60 data lines per page.

    4. Read a file of 45 students enrolled in Pretoria Art Class. Draw a flowchart to print the names of the students, and then the number of males and females enrolled in the class

    5. Draw the flowchart for the following scenario: The 84 pupils of a small school often get gifts of

    fruit. The headmaster wants to divide the fruit amongst all children. The remainder, if any, will be given to the local hospital. You first need to prompt the user for the number of fruit. The number each child and the hospital gets should then be displayed on the screen. Use a loop to repeat the process until 0 is entered for the number of fruit.

    6. Draw a flowchart to display the following:

    XXXXXXXX XXXXXXX XXXXXX XXXXX XXXX XXX XX X

  • 35

    1.4 PSEUDOCODE

    We have looked at algorithms and transferring those algorithms into a visual flow of how a process is planned to execute. Now we take a look at pseudocode. Pseudocode is a compact and informal description of the execution of a computer program. It uses the structural conventions of a programming language, but is intended for human reading rather than machine reading. It typically omits details that are not needed for human understanding of the algorithm, such as variable declarations, system-specific code and some subroutines. The programming language is augmented with natural language description details, where convenient, or with compact mathematical notation. The purpose of using pseudocode is that it is easier for people to understand than conventional programming language code, and that it is an efficient and environment-independent description of the key principles of an algorithm. It is commonly used in textbooks and scientific publications that are documenting various algorithms, and also in planning of computer program development, for sketching out the structure of the program before the actual coding takes place. We are going to show how using pseudocode makes creating a program easier for us, as programmers.

    We start by taking a simple algorithm, and converting it into pseudocode, which we will later create a program out of. Given this algorithm for example:

    GET NAME FROM USER GET SURNAME FROM USER PRINT SURNAME, NAME

    We can create the pseudocode that would look like this:

    Print Please input your name: Read name from user Print Please input your surname: Read surname from user Print Hello, + user name + + user surname

    The pseudocode looks similar to actual programming code as we will use it as a human readable reference to what we want to accomplish in code. This allows us to concentrate on creating the program logic without having to worry about language syntax etc. Once we are able to see the logic we want in the program then we can translate this into actual code for whatever language we are working in. We also talk about pseudocode as if it is interchangeable with actual code by talking about it as if it is actual code.

    The first thing to note is that pseudocode is written as if we are creating a procedure driven program. For object-oriented programming these procedures will still be valid for use but it is wise to remember that execution can, at times, be unpredictable as far as how users interact with your program. This means that every procedure we create in pseudocode will translate into a method in our code.

    1.4.1 INPUT/OUTPUT

    When creating programs we understand that we must, and always will, depend on user input in order to create a useful program. In the same way a program is only as good as its output. The

  • 36

    processes in between input and output are inconsequential to anyone who cant see and interact with them. So, we must first look at representing getting and sending information in our pseudocode.

    The more astute of you would have figured that the word Print was used for output in our earlier example. Print represents exactly what it says; print a message on the relevant output device. In 9 out of 10 cases this will be the screen. So if we say:

    Print This is a message we are printing

    Then it is safe to assume that we are going to translate that into the C# equivalent of displaying that message on the screen.

    On the other hand if we need to get information from the user; be it name, surname, age, marks, etc.; we use Read. In this case we can assign whatever we read into some kind of representation or variable, and we will worry about declaration in code. E.g.:

    Read name from user Read age from user

    These are examples of assigning the name and age we get from the user to a variable. This allows us to work with the inputs from the user even without knowing what possible values we may get. As an example let us assume we are writing the pseudocode for a simple adding calculator:

    Print Please input your first number: Read numA from user Print Please input your second number: Read numb from user answer = numA + NumB Print answer

    Here we read input into numA and numB variables and we are free to add them and assign that to a variable called answer which we print. Unlike in actual programming we dont worry about data types or actually declaring the variable. This will all be done when we create the program itself from the design. The pseudocode is the rough draft of our end product, in a sense. This allows us to use the variables as we see fit, without having to worry about conversion code, etc.

    1.4.2 DECISION MAKING

    Like in flow charts we will need to make decisions in our pseudocode and control how our branches behave. As in flowcharts we have the if and case statements for this. This gives us flexibility dependent on what we expect from the user. For instance, we want to expand our adding machine to subtract. But the user needs to decide what they want the machine to perform. So we write this:

    Print Please input your first number: Read numA from user Print Please input your second number: Read numB from user Print Please select A for adding or S for subtracting: Read op from user If op = A answer = numA + numB Else answer = numA - numB EndIf Print answer

  • 37

    Here we use an if statement to show us how processing will work when we add a branch. Here we ask the user to decide on addition or subtraction of the two numbers that are input. Important to note is the indentation of the if statements relevant instructions. This defines visually what will execute in the if statement. In this case when the user inputs A to add we add the numbers together. If they dont input A and we check the op variable then we will execute a subtraction.

    If we wanted to extend the program to be able to do most basic arithmetic we could create something like this:

    Print Please input your first number: Read numA from user Print Please input your second number: Read numB from user Print Please select an operation: Print A Addition Print S Subtraction Print M Multiplication Print D Division Read op from user If op = A answer = numA + numB ElseIf op = S answer = numA - numB ElseIf op = M answer = numA * numB Else answer = numA / numB EndIf Print answer

    In the case of doing this we could create a very long list of if statements, include large processes for each valid if statement, or even have nested if statements within any, or all, of the if statements we would have to sift through. To solve this problem we use a case statement instead of multiple ifs.

    Print Please input your first number: Read numA from user Print Please input your second number: Read numB from user Print Please select an operation: Print A Addition Print S Subtraction Print M Multiplication Print D Division Read op from user Case op A answer = numA + numB S answer = numA - numB M answer = numA * numB D answer = numA / numB Default Print Invalid selection EndCase Print answer

  • 38

    Here we can see a cleaner, easier to read solution. The Case does exactly the same processing as the if statements, however the conditional statements are altered to show us what we are Casing and what values we are looking for. This alteration may seem impractical or just semantic but we lower the complexity level of the code without removing its ability to process data.

    1.4.3 ITERATION

    If we need to design repetitive actions within our program then we have, at our disposal, two tools. The While loop and the For loop. The For loop is used to execute a list of instructions a set number of times. Lets say, for example, that we want to display a message on screen 5 times. The logic for that would look like this:

    For x starts at 0, x < 5, increment x Print "Are we having fun?" Endfor

    The first line in this pseudocode defines a variable called x which starts at 0 and after reaching the EndFor, if it is smaller than 5, increases by 1. If it then equals or is larger than 5 the for loop exits. If implemented into code we can assume the program would display this:

    Are we having fun? Are we having fun? Are we having fun? Are we having fun? Are we having fun?

    This is the reason we call these statements loops, as they repeatedly execute the same section of code. This can be altered in order to extend or shorten the amount of loops that execute.

    Alternatively we could have a loop that needs to execute without knowing exactly how many times we need it to execute but know that when a condition is met then the loop has executed the necessary number of times.

    count assigned zero While count < 5 Display "Oh Yeah!!!" Increment count Endwhile

    This prints 5 times similarly to the above example, except that we increment within the execution instructions. This is important to note as the while loop can create infinite loops when implemented incorrectly. In this case we use a counter and loop until the condition to exit the loop is met.

    1.4.4 ARRAYS

    At times when creating programs we come across a point when we need to hold a list of information; names, for instance; and creating a single variable for each one of those items would be problematic. The solution to this issue is to use arrays. To indicate we are using an array in our pseudocode we would write this:

    Names = Array[4] Names[0] = Steve Names[1] = John Names[2] = Mandy Names[3] = Sue

  • 39

    Here we see that we use a zero based array; meaning the first item in the array is numbered as 0 and not 1, therefore every item is numbered one lower than their position; and we add the names into the index we want. We assign Names as an array of size 4 and then we assign the values into the array. This is one of the few times we will create a variable in pseudocode, in order to give the array size.

    In practical use we can combine arrays and loops to get the user to input names and we can display them with another loop. E.g.:

    Name = Array[4] For x starts at 0, x < 4, increment x Print "Please insert Name number " + (x+1) + : Read Name[x] from User Endfor Print Names received. Print Would you like to display these names? y/n Read disp from User If disp = y For y starts at 0, y < 4, increment y Print Name[y] EndFor EndIf

    This seemingly confusing piece of pseudocode will, when implemented into code, create a program that takes in 4 names and displays them as such:

    Please insert Name number 1 Stan Please insert Name number 2 John Please insert Name number 3 Hanna Please insert Name number 4 Sam Names received. Would you like to display these names? y/n y Stan John Hanna Sam Processing Finished.

    This output shows how we can use loops to not only input information into these lists, but get information out too. As most of you may have noticed we have statements within one another. This brings us to our next topic.

    1.4.5 NESTING STATEMENTS

    As with flowcharts and actual programming we can nest all combinations of control statements within one another as needed. There is no maximum nesting point for any statements as far as restrictions go, however the more complex we design our logic the longer and more difficult it could become to implement into code. So if we want to create a loop that sorts an array or we want to loop through an array conditionally and display only specific elements of it then we would need to

  • 40

    nest ifs, fors, etc. in order for the output to be of value. For instance, a bubble sort; the most common sorting method for arrays; would be written in pseudocode as follows:

    Numbers = Array[20] while stillGoing = yes stillGoing = no For i starts at 0, i < 20 1, increment i one = Numbers[i]; two = Numbers[i + 1]; If one > two Numbers [i] = two; Numbers [i + 1] = one; stillGoing = yes; EndIf EndFor EndWhile For y starts at 0, y < 20, increment y Print Numbers[y] EndFor

    This sorts our Numbers array from smallest to largest then prints the arrays values. Assuming we have 20 random numbers in the array and would like to sort them from largest to smallest then if we implement this into code we might have an output similar to this:

    0 5 14 22 22 28 30 33 37 48 64 65 67 72 80 82 86 88 93

    If we would like to sort the numbers from largest to smallest we would just change the if statement where we compare one to two from this:

    If one > two

    To this:

    If one < two

    This bubble sort is a good example of combining different programming elements to create valuable solutions for programming.

  • 41

    1.4.6 IN CLOSING

    This brings us to the end of the chapter on pseudocode. As we have seen we can create a written example of what our actual code will look like without us having to worry about the syntax or compilation issues involved with straight coding. We can take the pseudocode and write the code in the equivalent language after we have been able to make the logic work outside of a strict programming environment.

    1.4.7 EXERCISES

    1. Design pseudocode for the following tasks: Leaving the classroom. Knocking a set of nails into a block of wood. Making a sandwidge (choice of ham or cheese) Making sandwidges from a loaf. Adding up a set of numbers. Calculating the average of a set of numbers. Finding the largest of a set of numbers. Finding the middle on of 3 numbers. Printing out results for a class of students.

    o

  • 42

    7. Design a program to create a graduation list given an input file of graduates including name and

    GPA for each graduate. Any graduate with a GPA that is greater or equal to 3.8 should have "Dean's List" written next to his/her name. All others should have Graduate written next to his/her name. Finally print End of Graduation List -2011.

    8. Suppose that you, a wolf, a goat, and cabbage are on one riverbank. You have a boat that can

    carry you and one of your three companions. You need to get to the other side of the river using the boat. Write pseudocode that describes how you are going to do it. Your solution should avoid both of the following situations:

    a. Leaving the goat and the cabbage alone on the same riverbank. This will cause the goat to eat the cabbage.

    b. Leaving the wolf and the goat alone on the same riverbank. That will cause the wolf to eat the goat.

    9. Consider the following game. We wrote pseudocode for it in class. Supose the user knows a

    secret number between 1 and 100. The player wants to guess that randomnumber. Write pseudocode for a players strategy, where the player knows the smallest and the largest possible values of the secret number. The user input is now one of guess lower, guess higher, and you are right instead of numeric guesses, and the inputs should be entered after the algorithm produces a guess for the secret number. What is the best strategy a player can adopt? In other words, what strategy leads to finding the secret number in the smallest number of guesses possible? Can you write pseudocode for it?

  • 43

    1.5 TRACE TABLES Trace tables allow developers to test their algorithms in order to make sure there are no logic errors. To see how this works, an algorithm is required. As well, a set of test data must be created that will test all aspects of the algorithm. For the purpose of demonstration, the guessing game algorithm will be used. As well, each line of the algorithm, written in pseudocode for this demonstration, will be numbered.

    1.5.1 PROGRAM

    1 Secret assigned to 5 2 Get the word the user guesses 3 While Guess Secret 4 If Guess < Secret Then 5 Display "Too low" 6 Else 7 Display "Too High" 8 EndIf 9 Get the word the user guesses 10 EndWhile 11 Display "You guessed it"

    1.5.2 DATA

    Set 1 - Secret = 5; Guess = 2, 9, 5

    Set 2 - Secret = 5; Guess = 5

    1.5.3 TRACE TABLE

    Within the trace table, each variable, conditional test and output must be listed. In this case, the variable Secret and Guess are listed. As well, the results of the conditions Guess Secret (not equals) and Guess < Secret are determined.

    SET 1

    Line # Secret Guess Guess Secret Guess < Secret Output 1 5 2 2 3 True 4 True 5 Too Low 9 9 3 True 4 False 7 Too High 9 5 3 False

    11 You guessed it

  • 44

    SET 2

    Line # Secret Guess Guess Secret Guess < Secret Output 1 5 2 5 3 False

    11 You guessed it

    The data used in this example ensures that each line of the algorithm is tested. As well, the Test First loop block is tested to ensure the possibility that the loop may not necessarily be entered on the first test.

    1.5.4 EXERCISES Create trace tables for the following programs: 1. Vowels

    1) Assign curr to 1 2) Assign last to number of letters on the page 3) Assign count to 0 4) Read letter at curr 5) If letter is vowel Then 6) increment count 7) EndIf 8) Increment curr 9) If curr

  • 45

    2. INTRODUCING THE .NET PLATFORM

    For developers to be successful in the jungle of software engineering today, we need solid tools and basic building blocks we can leverage to build up the solutions our customers dream of. The .NET platform is such an environment adapted to the needs of the modern software developer. In this chapter, we explore the .NET platform in all its breadth, covering its execution environment, the support for various programming languages, the libraries it comes with, and the tooling support available to develop on it. In addition, we talk about the role of C# in this picture.

    2.1 APPLICATION DEVELOPMENT BEFORE .NET

    Before we had the .NET platform there were obvious solutions to the computer using public for their problems. However, through the evolution of each platform there have arisen certain complexities. Here we take a look at the history of application development.

    2.1.1 C

    One of the common and still most used pre-.NET languages, that C# is a descendant of, is C. As a C/Win32 Developer involved using a very terse, unforgiving language. C is considered the first high level language, and as such, needs manual memory management, pointer arithmetic, and complex, ugly syntax constructs. C is also a structured, not Object Oriented, language. And, although C is the programming language used for all our current operating systems and many robotics, development with the API was complex. When you combine the thousands of global functions and data types defined by the Win32 API to an already formidable language, it is little wonder that there are so many buggy applications floating around today.

    2.1.2 C++

    The next step in the world of major application development, specifically in the C family, was C++. In many ways, C++ can be thought of as an object-oriented layer on top of C. Many games and applications have been and still are created in C++, even though it is a heavy and complex language. But, even though C++ programmers benefit from the famed pillars of OOP (encapsulation, inheritance, and polymorphism), they are still at the mercy of the painful aspects of the C language (e.g., manual memory management, pointer arithmetic, and ugly syntactical constructs). And the bottom line is that C++ programming remains a difficult and error-prone experience, given its historical roots in C.

    2.1.3 VISUAL BASIC

    In a desire to make things simpler for programmers to develop applications Visual Basic was created. The pre-.NET versions of Visual Basic (up until VB6) were popular due to its ability to build complex user interfaces, code libraries (e.g., COM servers), and data access logic with minimal fuss and bother. The major downfall was that it is not a fully object-oriented language; rather, it is object aware. Moreover, VB didnt provide the ability to build multithreaded applications unless you are willing to drop down to low-level Win32 API calls (which is complex at best and dangerous at worst).

  • 46

    2.1.4 JAVA

    Enter Java. Java is an object-oriented programming language that has its syntactic roots in C++. Java (as a language) cleans up many unsavory syntactical aspects of C++. Java (as a platform) provides programmers with a large number of predefined packages that contain various type definitions. Using these types, Java programmers are able to build 100% Pure Java applications complete with database connectivity, messaging support, web-enabled front ends, and a rich desktop user interface.

    Although Java is a very elegant language, one potential problem is that using Java typically means that you must use Java front-to-back during the development cycle. In effect, Java offers little hope of language integration, as this goes against the grain of Javas primary goal (a single programming language for every need). In reality, however, there are millions of lines of existing code out there in the world that would ideally like to commingle with newer Java code. Sadly, Java makes this task problematic. While Java does provide a limited ability to access non-Java APIs, there is little support for true cross-language integration.

    2.1.5 COM

    To realize the dream of cross-language support in one application Microsoft created COM. The Component Object Model (COM) was Microsofts previous application development framework. COM is an architecture that says in effect, If you build your classes in accordance with the rules of COM, you end up with a block of reusable binary code. The beauty of a binary COM server is that it can be accessed in a language-independent manner. Thus, C++ programmers can build COM classes that can be used by VB6. Delphi programmers can use COM classes built using C, and so forth. However, the platform was complex and made deployment a nightmare when critical registries failed and class libraries would be missing. The hidden COM support needed for applications was frustrating to decipher and deployment issues made COM difficult.

    2.2 ENTER.NET

    So life as a Windows application developer has been tough. The .NET Framework is a rather radical and brute-force approach to making our lives easier. The solution proposed by .NET is Change everything. The .NET Framework is a completely new model for building systems on the Windows family of operating systems, as well as on numerous non-Microsoft operating systems such as Mac OS X and various Unix/Linux distributions. To set the stage, here is a quick rundown of some core features provided courtesy of .NET:

    Comprehensive interoperability with existing code: This is (of course) a good thing. Existing COM binaries can commingle (i.e., interop) with newer .NET binaries and vice versa. Also, PlatformInvocation Services (PInvoke) allows you to call C-based libraries (including the underlying API of the operating system) from .NET code.

    Complete and total language integration: .NET supports cross-language inheritance, crosslanguage exception handling, and cross-language debugging of code.

  • 47

    A common runtime engine shared by all .NET-aware languages: One aspect of this engine is a well-defined set of types that each .NET-aware language understands.

    A comprehensive base class library: This library provides shelter from the complexities of raw API calls and offers a consistent object model used by all .NET-aware languages.

    No more COM plumbing: IClassFactory, IUnknown, IDispatch, IDL code, and the evil variantcompliant data types (BSTR, SAFEARRAY, and so forth) have no place in a .NET binary.

    A truly simplified deployment model: Under .NET, there is no need to register a binary unit into the system registry. Furthermore, .NET allows multiple versions of the same *.dll to exist in harmony on a single machine.

    As you can most likely gather from the previous bullet points, the .NET platform has nothing to do with COM (beyond the fact that both frameworks originated from Microsoft). In fact, the only way .NET and COM types can interact with each other is using the interoperability layer.

    2.3 THE BUILDING BLOCKS OF .NET

    Now that you know some of the benefits provided by .NET, lets preview three key (and interrelated) entities that make it all possible: the CLR, CTS, and CLS. From a programmers point of view, .NET can be understood as a runtime environment and a comprehensive base class library. The runtime layer is properly referred to as the common language runtime, or CLR. The primary role of the CLR is to locate, load, and manage .NET types on your behalf. The CLR also takes care of a number of low-level details such as memory management; creating application domains, threads, and object context boundaries; and performing various security checks.

    Another building block of the .NET platform is the Common Type System, or CTS. The CTS specification fully describes all possible data types and programming constructs supported by the runtime, specifies how these entities can interact with each other, and details how they are represented in the .NET metadata format.

    Understand that a given .NET-aware language might not support each and every feature defined by the CTS. The Common Language Specification (CLS) is a related specification that defines a subset of common types and programming constructs that all .NET programming languages can agree on. Thus, if you build .NET types that only expose CLS-compliant features, you can rest assured that all .NET-aware languages can consume them. Conversely, if you make use of a data type or programming construct that is outside of the bounds of the CLS, you cannot guarantee that every .NET programming language can interact with your .NET code library.

    THE ROLE OF THE BASE CLASS LIBRARIES

    In addition to the CLR and CTS/CLS specifications, the .NET platform provides a base class library that is available to all .NET programming languages. Not only does this base class library encapsulate various primitives such as threads, file input/output (I/O), graphical rendering, and interaction with various external hardware devices, but it also provides support for a number of services required by most real-world applications.

  • 48

    For example, the base class libraries define types that facilitate database access, manipulation of XML documents, programmatic security, and the construction of web-enabled (as well as traditional desktop and console-based) front ends. From a high level, you can visualize the relationship between the CLR, CTS, CLS, and the base class library, as shown the figure below.

    WHAT C# BRINGS TO THE TABLE

    Given that .NET is such a radical departure from previous technologies, Microsoft crafted a new programming language, C# (pronounced see sharp), specifically for this new platform. C# is a programming language whose core syntax looks very similar to the syntax of Java. However, to call C# a Java rip-off is inaccurate. Both C# and Java are members of the C family of programming languages (C, Objective C, C++, etc.) and therefore share a similar syntax. Just as Java is in many ways a cleaned-up version of C++, C# can be viewed as a cleaned-up version of Java.

    The truth of the matter is that many of C#s syntactic constructs are modeled after various aspects of Visual Basic 6.0 and C++. For example, like VB6, C# supports the notion of formal type properties (as opposed to traditional getter and setter methods) and the ability to declare methods taking a varying number of arguments (via parameter arrays). Like C++, C# allows you to overload operators, as well as to create structures, enumerations, and callback functions (via delegates).

    Due to the fact that C# is a hybrid of numerous languages, the result is a product that is as syntactically cleanif not cleanerthan Java, is about as simple as VB6, and provides just about as much power and flexibility as C++ (without the associated ugly bits). Here is a partial list of core C# features that are found in all versions of the language:

    No pointers required! C# programs typically have no need for direct pointer manipulation (although you are free to drop down to that level if absolutely necessary).

    Automatic memory management through garbage collection. Given this, C# does not support a delete keyword.

    Formal syntactic constructs for classes, interfaces, structures, enumerations, and delegates.

  • 49

    The C++-like ability to overload operators for a custom type, without the complexity (e.g., making sure to return *this to allow chaining is not your problem).

    Support for attribute-based programming. This brand of development allows you to annotate types and their members to further qualify their behavior.

    With the release of .NET 2.0 (circa 2005), the C# programming language was updated to support numerous new bells and whistles, most notably the following:

    The ability to build generic types and generic members. Using generics, you are able to build very efficient and type-safe code that defines numerous placeholders specified at the time you interact with the generic item.

    Support for anonymous methods, which allow you to supply an inline function anywhere a delegate type is required.

    Numerous simplifications to the delegate/event model, including covariance, contravariance, and method group conversion.

    The ability to define a single type across multiple code files (or if necessary, as an in-memory representation) using the partial keyword.

    As you might guess, .NET 3.5 adds even more functionality to the C# programming language

    (C# 2008, to be exact), including the following features:

    Support for strongly typed queries (a la LINQ, or Language Integrated Query) used to interact with various forms of data

    Support for anonymous types, which allow you to model the shape of a type rather than its behavior

    The ability to extend the functionality of an existing type using extension methods

    Inclusion of a lambda operator (=>), which even further simplifies working with .NET delegate types

    A new object initialization syntax, which allows you to set property values at the time of object creation

    Perhaps the most important point to understand about the C# language is that it can only produce code that can execute within the .NET runtime (you could never use C# to build a native COM server or an unmanaged Win32 API application). Officially speaking, the term used to describe the code targeting the .NET runtime is managed code. The binary unit that contains the managed code is termed an assembly (more details on assemblies in just a bit in the section An Overview of .NET Assemblies). Conversely, code that cannot be directly hosted by the .NET runtime is termed unmanaged code.

  • 50

    2.4 A QUICK TOUR THROUGH VISUAL STUDIO 2010

    With Visual Studio 2010 installed, lets take a quick tour through the IDE youll be spending a lot of your time as a developer in.

    SPLASH SCREEN AND START PAGE

    The Visual Studio 2010 splash screen is shown above. Prior to Visual Studio 2010, the splash screen used to show the different extensibility packages that were installed. Now this information is available from the Help, About menu. New and notable packages in Visual Studio 2010 are the built-in Silverlight projects and out-of-the-box support for the F# language.

    The first thing youll see in Visual Studio is the Start page shown below. It provides links to various tasks (for example, to reload recently used projects).

  • 51

    CORE UI ELEMENTS

    The menu and toolbar contain a wealth of features. (Well only cover the essential ones.)Make sure to explore the menu a bit for things that catch your eye. Because we havent loaded a project yet, various toolbars are not visible yet. Various collapsible panels are docked on the borders. There are several of those, but only a few are visible at this point: Toolbox, Solution Explorer, and Error List are the ones well interact with regularly. More panels can be enabled through the View menu, but most panels have a contextual nature and will appear spontaneously when invoking certain actions (for example, while debugging). The screenshot below shows how panels can be docked at various spots in the editor. The little pushpin button on the title bar of a panel can be used to prevent it from collapsing. As you get more familiar with the editor, youll start rearranging things quite bit to adapt to your needs.

    INTEGRATION WITH WPF

    If youve used earlier releases of Visual Studio, you no doubt have noticed the different look and feel of the IDE in the 2010 version. Starting with Visual Studio 2010, large portions of the user interface have been redesigned to use WPF technology.

    This has several advantages in both the short and long term, and today were seeing just the tip of the iceberg of capabilities this unlocks. For example, by having the code editor in WPF, whole new sets of visualizations become possible. To name just one example, imagine what itd be like to have code comments with rich diagrams in it to illustrate some data flow or architectural design.

    Its worth pointing out explicitly that Visual Studio is a hybrid managed and native (mostly for historical reasons) code application. An increasing number of components are written using managed code, and new extensibility APIs are added using the new Managed Extensibility Framework (MEF).

    YOUR FIRST APPLICATION

    To continue our tour through Visual Studio 2010, lets make things a bit more concrete and create a program in the IDE.

  • 52

    NEW PROJECT DIALOG

    The starting point to create a new application is the New Project dialog, which can be found through File, New, Project or invoked by Ctrl+Shift+N. A link is available from the Projects tab on the Start Page, too. A whole load of different project types are available, also depending on the edition used and the installation options selected. Actually, the number of available project templates has grown so much over the years that the dialog was redesigned in Visual Studio 2010 to include features such as search.

    Because Ive selected Visual C# as my preferred language at the first start of Visual Studio 2010, the C# templates are shown immediately. (For other languages, scroll down to the Other Languages entry on the left.) Subcategories are used to organize the various templates. Lets go over a few commonly used types of projects:

    Console Application is used to create command-line application executables. This is what well use for our Hello application.

    Class Library provides a way to build assemblies with a .dll extension that can be used from various other applications (for example, to provide APIs).

    Windows Forms Application creates a project for a GUI-driven application based on the Windows Forms technology.

    WPF Application is another template for GUI applications but based on the new and more powerful WPF framework.

    ASP.NET Web Application provides a way to create web applications and deploy them to an ASP.NET-capable web server.

  • 53

    Well cover other types of templates, too, but for now those are the most important ones to be aware of. The figure above shows the New Project dialog, where you pick the project type of your choice.

    Notice the NET Framework 4.0 drop-down. This is where the multi-targeting support of Visual Studio comes in. In this list, you can select to target older versions of the framework, all the way back to 2.0. Give it a try and select the 2.0 version of the framework to see how the dialog filters out project types that are not supported on that version of the framework. Recall that things like WPF and WCF were added in the .NET Framework 3.0 (WinFX) timeframe, so those wont show up when .NET Framework 2.0 is selected.

    For now, keep .NET Framework 4.0 selected, mark the Console Application template, and specify Hello as the name for the project. Notice the Create Directory for Solution check box. Stay tuned. Well get to the concept of projects and solutions in a while. Just leave it as is for now. The result of creating the new project is shown in the following Figure:

    Once the project has been created, it is loaded, and the first (and in this case, only) relevant file of the project shows up. In our little console application, this is the Program.cs file containing the managed code entry point.

    Notice how an additional toolbar (known as the Text Editor toolbar), extra toolbar items (mainly for debugging), and menus have been made visible based on the context were in now.

  • 54

    SOLUTION EXPLORER

    With the new project created and loaded, make the Solution Explorer (typically docked on the right side) visible, as shown in the above figure. Slightly simplified, Solution Explorer is a mini file explorer that shows all the files that are part of the project. In this case, thats just Program.cs. Besides the files in the project, other nodes are shown as well:

    Properties provides access to the project-level settings (see later) and reveals a code file called AssemblyInfo.cs that contains assembly-level attributes

    References is a collection of assemblies the application depends on. Notice that by default quite a few references to commonly used class libraries are added to the project, also depending on the project type.

    So, whats the relation between a solution and a project? Fairly simple: Solutions are containers for one or more projects. In our little example, we have just a single Console Application project within its own solution. The goal of solutions is to be able to express relationships between dependent projects. For example, a Class Library project might be referred to by a Console Application in the same solution. Having them in the same solution makes it possible to build the whole set of projects all at once.

    PROJECT PROPERTIES

    Although we dont need to reconfigure project properties at this point, lets take a quick look at the project configuration system. Double-click the Properties node for our Hello project in Solution Explorer (or right-click and select Properties from the context menu). The figure below shows the Build tab in the project settings.

  • 55

    As a concrete example of some settings, Ive selected the Build tab on the left, but feel free to explore the other tabs at this point. The reason Im highlighting the Build configuration at this point is to stress the relationship between projects and build support, as will be detailed later on.

    CODE EDITOR

    Time to take a look at the center of our development activities: writing code. Switch back to Program.cs and take a look at the skeleton code that has been provided:

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hello { class Program { static void Main(string[] args) { } } }

  • 56

    First of all, namespaces with commonly used types have been imported by means of using directives. Second, a namespace declaration is generated to contain the Program class. Well talk about namespaces in more detail in the next chapters, so dont worry about this for now. Finally, the Main entry point has a different signature: Instead of not taking in any arguments, it now does take in a string array that will be populated with command-line arguments passed to the resulting executable. Because we dont really want to use command-line arguments, this doesnt matter much to us. We discuss the possible signatures for the managed code entry point in The Entry Point in Chapter 3. Lets write the code for our application now. Let us input these three lines:

    static void Main(string[] args) { Console.Write(Enter your name: ); string name = Console.ReadLine(); Console.WriteLine(Hello + name); }

    As you enter this code in the editor, youll observe a couple of things. One little feature is auto-indentation, which positions the cursor inside the Main method indented a bit more to the right than the opening curly brace of the method body. This enforces good indentation practices (the behavior of which you can control through the Tools, Options dialog).

    More visible is the presence of IntelliSense. As soon as you type the member lookup dot operator after the Console type name, a list of available members appears that filters out as you type. The above Figure shows IntelliSense in action.

    Once youve selected the Write method from the list (note you can press Enter or the spacebar as soon as the desired member is selected in the list to complete it further) and you type the left parenthesis to supply the arguments to the method call, IntelliSense pops up again showing all the available overloads of the method. You learn about overloading in Chapter 11, Methods, so just type the Enter your name: string.

  • 57

    IntelliSense will help you with the next two lines of code in a similar way as it did for the first. As you type, notice different tokens get colorized differently. Built-in language keywords are marked with blue, type names (like Console) have an aqua color, and string literals are colored with a red-brown color. Actually, all those colors can be changed through the Tools, Options dialog.

    Another great feature about the code editor is its background compilation support. As you type, a special C# compiler is running constantly in the background to spot code defects early. Suppose we have a typo when referring to the name variable; it will show up almost immediately, marked by red squiggles, as shown in the this figure:

    If youre wondering what the yellow border on the left side means, it simply indicates the lines of code youve changed since the file was opened and last saved. If you press Ctrl+S to save the file now, youll see the lines marked green. This feature helps you find code youve touched in a file during a coding session by providing a visual clue, which is quite handy if youre dealing with large code files.

    BUILD SUPPORT

    As software complexity grows, so does the build process: Besides the use of large numbers of source files, extra tools are used to generate code during a build, references to dependencies need to be taken care of, resulting assemblies must be signed, and so on. You probably dont need further convincing that having integrated build support right inside the IDE is a great thing.

    In Visual Studio, build is integrated tightly with the project system because thats ultimately the place where source files live, references are added, and properties are set. To invoke a build process, either use the Build menu (see left figure) or right-click the solution or a specific project node in Solution Explorer. A shortcut to invoke a build for the entire solution is F6.

    Behind the scenes, this build process figures out which files need to compile, which additional tasks need to be run, and so on. Ultimately, calls are made to various tools such as the C# compiler. This is not a one-way process: Warnings and errors produced by the underlying tools are bubbled up through the build system into the IDE, allowing for a truly interactive development experience.

  • 58

    Starting with Visual Studio 2005, the build system is based on a .NET Framework technology known as MSBuild. One of the rationales for this integration is to decouple the concept of project files from exclusive use in Visual Studio. To accomplish this, the project file (for C#, that is a file with a .csproj extension) serves two goals: Its natively recognized by MSBuild to drive build processes for the project, and Visual Studio uses it to keep track of the project configuration and all the files contained in it.

    DEBUGGING SUPPORT

    One of the first features that found a home under the big umbrella of the IDE concept was integrated debugging support on top of the editor. This is obviously no different in Visual Studio 2010, with fabulous debugging support facilities that youll live and breathe on a day-to-day basis as a professional developer on the .NET Framework.

    The most commonly used debugging technique is to run the code with breakpoints set at various places of interest, as shown in the figure above. Doing so right inside a source code file is easy by putting the cursor on the line of interest and pressing F9. Alternative approaches include clicking in the gray margin on the left or using any of the toolbar or menu item options to set breakpoints.

    To start a debugging session, press F5 or click the button with the VCR Play icon. Code will run until a breakpoint is encountered, at which point youll break in the debugger. This is illustrated in this figure:

  • 59

    Notice a couple of


Recommended