Programming Fundamentals Using Visual C#.Net: A Business...

18
Programming Fundamentals Using Visual C#.Net: A Business Context © ©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 1 Chapter 1: Nuts & Bolts Draft, Not for General Distribution Now that we have taken a quick look at what programming is about, let’s examine things more closely. That is, let’s look at the details, the why, and the wherefore associated with the examples in the previous chapter. In addition, we will look more closely at the UI (user interface) controls in those examples and discuss the concepts behind object-oriented programming (OOP). For these things, we will be referring to, and examining more closely, the Treasure Island Tickets app from the previous chapter. In addition, we will still be working again with app development for a desktop platform. The concepts, procedures, and techniques, all apply, equally well to desktop, web, and mobile apps, however. We will therefore use the next chapter to address implementing the Treasure Island application as a web app and a mobile app. Review of the Treasure Island Example As a prelude to our discussion of OOP concepts, let’s start with an overview of the interface controls (i.e., features) you have worked with so far. As we do this, notice in particular the use of the terms property, method, and event. In a desktop (i.e., traditional computing) environment, the foundation for an app is the Form control, which serves as a container for other UI elements. The form control in a desktop environment corresponds to a web page when it is a web app that is being developed. Similarly, the Page element (i.e., control) serves as the fundamental container for other controls in a mobile app. Recall that, for the Treasure Island desktop app, you specified values for two properties of the Form: the Name property and the Text property. In addition, values were assigned by default to other properties when VS initially created the form. For example, the Width property was assigned a value of 300 pixels, as was the Height property. You also worked with the Label, TextBox, and Button controls. You specified values for the Name property for two of the Label controls and for both of the TextBox controls, as well as for the Button control. In addition, you specified values for the Text property for all of the Label controls, as well as for the Button control. Finally, you wrote a method corresponding to the Button control. In addition, you used two other methods, which were not associated with any of the controls. (More on these a little later.) (Note that you accepted the default values for some of the Label controls. Since these controls were not addressed in the code, there was no need to provide meaningful names for those controls.) In summary, all of the controls have properties, which describe the various attributes of those controls. In addition, controls can have methods associated with them, as does the Button control. A method corresponding to a control is essentially a behavior associated with that control. Many such methods that are associated with form controls respond to events. An example is when the customer in the Treasure Island example clicks on the startButton. The Click event triggers the processing of the code in the startButton_Click() method. This type of method is therefore often called an event handler. Many methods, however, are not event handlers and are executed when called upon in the code. One such method is the ToString() method, which converts a numeric object such as dblTotalPrice into text. As you can see, there is no interface control involved here, so no particular event is used to trigger the conversion. Instead, a line of program code calls upon the ToString() method. Object-Oriented Programming Concepts

Transcript of Programming Fundamentals Using Visual C#.Net: A Business...

Page 1: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 1

Chapter 1: Nuts & Bolts Draft, Not for General Distribution

Now that we have taken a quick look at what programming is about, let’s examine things more closely.

That is, let’s look at the details, the why, and the wherefore associated with the examples in the previous

chapter. In addition, we will look more closely at the UI (user interface) controls in those examples and

discuss the concepts behind object-oriented programming (OOP). For these things, we will be referring

to, and examining more closely, the Treasure Island Tickets app from the previous chapter. In addition,

we will still be working again with app development for a desktop platform. The concepts, procedures,

and techniques, all apply, equally well to desktop, web, and mobile apps, however. We will therefore use

the next chapter to address implementing the Treasure Island application as a web app and a mobile app.

Review of the Treasure Island Example

As a prelude to our discussion of OOP concepts, let’s start with an overview of the interface controls (i.e.,

features) you have worked with so far. As we do this, notice in particular the use of the terms property,

method, and event. In a desktop (i.e., traditional computing) environment, the foundation for an app is

the Form control, which serves as a container for other UI elements. The form control in a desktop

environment corresponds to a web page when it is a web app that is being developed. Similarly, the Page

element (i.e., control) serves as the fundamental container for other controls in a mobile app. Recall that,

for the Treasure Island desktop app, you specified values for two properties of the Form: the Name

property and the Text property. In addition, values were assigned by default to other properties when VS

initially created the form. For example, the Width property was assigned a value of 300 pixels, as was the

Height property.

You also worked with the Label, TextBox, and Button controls. You specified values for the Name property

for two of the Label controls and for both of the TextBox controls, as well as for the Button control. In

addition, you specified values for the Text property for all of the Label controls, as well as for the Button

control. Finally, you wrote a method corresponding to the Button control. In addition, you used two other

methods, which were not associated with any of the controls. (More on these a little later.)

(Note that you accepted the default values for some of the Label controls. Since these controls were not

addressed in the code, there was no need to provide meaningful names for those controls.)

In summary, all of the controls have properties, which describe the various attributes of those controls.

In addition, controls can have methods associated with them, as does the Button control. A method

corresponding to a control is essentially a behavior associated with that control. Many such methods that

are associated with form controls respond to events. An example is when the customer in the Treasure

Island example clicks on the startButton. The Click event triggers the processing of the code in the

startButton_Click() method. This type of method is therefore often called an event handler.

Many methods, however, are not event handlers and are executed when called upon in the code. One

such method is the ToString() method, which converts a numeric object such as dblTotalPrice into text.

As you can see, there is no interface control involved here, so no particular event is used to trigger the

conversion. Instead, a line of program code calls upon the ToString() method.

Object-Oriented Programming Concepts

Page 2: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 2

Now, we can more formally discuss the concepts underlying OOP. First, an object can be just about

anything, such as a customer, a sales transaction, etc. Each of the controls contained in the UI for an app

is an object. Each object, such as a customer, or an interface control (like a Button), will commonly have

one or more properties, for example the Name property. Properties describe the characteristics or

attributes of the object. In addition, an object will typically have one or more methods associated with it,

and these methods are behaviors or operations that the object can perform. Recall that a method is

essentially a small program that can be called by other programs.

To be more exact, each of the controls comprising the UI is an instance of some type of object, and that

“type” is referred to as a class. For example, the startButton is an instance of the Button class. In addition,

dblTotalPrice can be considered an instance of the Double class (which we will address later). An object

is then created (i.e., instantiated) from a class, which serves essentially as the design (or working drawing)

for a type of object. In actuality, a class is just a prepackaged collection of program code.

OOP relies upon a large number of classes having already been written and stored in libraries that are

readily available to the programmer. Then, when, for example, a particular UI feature such as a Button is

needed, we can reference its class in our code. In VS, this is done by dragging the Button control from the

Toolbox onto the Form, and this creates an instance of the Button class. (Note that, behind the scenes, a

file containing additional program code is simultaneously being created. While we build the form in

Designer view, references to the various control objects are being made in that code. We will discuss

more about this later.) For other objects (i.e., those that are not controls) we instantiate those objects

through declarations in the main code, as in the following code from the Treasure Island example.

double dblQuantity;

We will soon look at this statement more closely. For now, you can simply think of the “double” keyword

as telling the computer to create an instance of a double datatype (essentially a form of object). You

have seen this “object” used in conjunction with the ToString() method associated with all Double objects,

i.e., in the following code.

strTotal = strTotal + dblTotalPrice.ToString("c2");

OOP is based upon the concept of code reusability. That means, for example, that someone has already

written the code that will allow a Button to be incorporated into a UI. Since that code can be packaged

and made available to other programmers, it makes no sense for them to write the code from scratch.

As indicated above, various classes are typically stored in libraries to make them available to programmers.

Since we are using C# we are therefore using Microsoft’s .NET Framework and the class library available

through that. Within that library are a number of namespaces, which are in turn essentially collections of

classes with related functionality. We as programmers benefit greatly as a result, because we need not

rewrite that code or even know details of the code that makes up those classes. We simply need to know

(or be able to find out) the specifications for using them and the results generated.

A fundamental concept in OOP is that of dot notation. You have seen this used several times in the code

for the Treasure Island Tickets app. The basic syntax of dot notation is objectName.property and

objectName.method(). In our app, examples of these are in the statements referring to nameBox.Text

and dblTotalPrice.ToString(“c2”), respectively. Since “child” objects are often created from “parent”

objects, the dot notation provides a way to deal with this in the general syntax of

parentObjectName.childObjectName.property. This reflects the inheritance associated with parent and

Page 3: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 3

child objects. While a deeper examination of the inheritance concept is beyond our scope, it is important

that you nevertheless have a grasp of the basic idea.

In summary, the types of apps we are developing for the examples and exercises in this book are generally

referred to as object-oriented event-driven applications. This means that C#, the language we are using,

is an object-oriented language, while the apps are designed to be event-driven. We will therefore be using

many of the various object classes, their properties, and their methods that are available through the .NET

Framework. In addition, we will write methods that correspond to various events that take place as a

person uses the apps we develop. Now we will take another look at the controls included so far on the

user Treasure Island interface.

More about UI Controls

As you should recall, you have worked so far with four controls: Form, Button, Label, and TextBox. For

the most part you have accepted the default values for the properties associated with these classes. You

accepted the default size of 300 pixels by 300 pixels for the Form for example. However, you must admit

that a different-sized interface would be more appropriate, and possibly different sizes, locations, and

fonts are in order for the other controls. Let’s explore the more common properties for these controls

and also introduce methods that might be used as event handlers. To do this you will be working through

a demonstration exercise and referencing a new version of the Treasure Island application. No difference

in the app’s functionality is involved, but a revised UI with a somewhat different look will be employed.

We will refer to this as Phase 4 of the app, and the interface should look like that in the following figure.

Beginning the exercise

Start with a copy of your completed solution for Phase 3 (referred to from here on as Version 3) of the

Treasure Island Tickets app you developed in the “Getting Started” chapter.* To do this, make a copy of

that solution folder (treasureIsland2017a1_soln) and use a different name for the copy, something like

treasureIsland2017a4_soln. Open the copy and make the interface modifications as indicated below.

Recall from the “Getting Started” chapter that this name indicates the 4th level of sophistication of the

Treasure Island desktop app. (Since you modified the original a1 solution in phases without creating new

VS solutions, no a2 or a3 solutions exist.) We will refer to the current exercise as Version 4.

Page 4: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 4

[*Alternatively (e.g., you do not have a working version for Version 3), download, extract, and open the

solution folder available through this link Link to completed version of Phase 3]

As you will soon realize (if you have not already done so), many ways typically exist for accomplishing

various tasks will be doing through our examples in this book. We will generally, however, look at only

one or two ways, but you should feel free to explore other alternatives. In addition, the actual sizes of

the controls we include in your UIs is platform dependent. For example, a form just wide enough to

contain the “Treasure Island Tickets” title on one computer might be 270 pixels, whereas another

computer may require a form width of 300 pixels. Sizing for many of the controls is therefore specified in

a relative manner for the most part, since absolute sizing will vary.

The Form control

Although the text for the UI is readable, it could stand to be a little larger. In addition, you can make the

interface a little more attractive by changing the font style for that text. Therefore, you will now modify

the font properties for the form. In addition, you do not need such a large interface, so you will also resize

the form.

In the Designer view of VS click on the title bar of the form (TicketForm). This selects the Form object so

that its properties can be modified. Now take a look at the Properties window. You should see the name

of the Form just under the title of the Properties window. Click on the A/Z button below TicketForm and

then scroll down until you see the Font property. Click on the current property value (set as Microsoft

Sans Serif by default) and you should see an ellipsis (…) button. Now click on that button, which will cause

the Font dialog box to display. Use that dialog box to set the “Font” property to Comic Sans MS and the

“Size” property to 10, and click on the OK button when done.

(As you may have realized to select a control, you simply need to move the mouse pointer anywhere over

the control and click on it using the left mouse button. However, click only once on the control; i.e., do

not double-click. Double-clicking will cause VS to create an event-handler method for that control, as it

did for the Button control (startButton) and also switch to the Code View. Nevertheless, if you do/did

that, for now just switch back to design view and ignore the empty method that was created. Later we

will address this further.)

Notice now that the size of the form has changed, having become substantially larger than the default

size, which was already too large for our purposes. You will therefore resize the form, but first let’s move

the controls within the form to a more appropriate location. Do this by selecting all of those controls at

once and then moving the collection by dragging them as a single unit to a temporary location. To select

all of the controls at once, click the mouse pointer above and to the left of the top label control (label1),

hold the mouse button, drag it below and to the right of the bottom label (costLabel), and release. Now,

by using the arrow keys on your keyboard, move that collection of controls so that (a) the top edge of the

collection is near the form’s title bar and (b) the collection is somewhat centered on the form. Click any

empty area on the form to unselect the controls.

You will now modify the form’s size visually initially and then possibly fine-tune the size by using the

Properties window. Comparing what you see in the Designer window to the diagram above, try to make

your form about the same width as that in the diagram. To do this, move the mouse pointer over the

sizing handle on the right edge of the form so that the pointer becomes a double arrow. Click, hold, and

Page 5: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 5

drag the pointer, along with the right edge of the form. Release the mouse when the form is just a little

wider than it needs to be for “Treasure Island Tickets” to display completely in the title bar. In the same

manner, modify the height of the form by dragging the bottom up until it is a little below the bottom label

(i.e., costLabel).

Now, with the form still selected, use the Properties window to “fine tune” Size property. In the Properties

window, scroll to the Size property. If a plus (+) sign is to the left, click it to expand the size options so

that Width and Height show. Select the value for Width and change its value to the nearest multiple of

10 that is at least 5 pixels larger than the current setting. Do likewise for the Height property. After you

have done this, press the Enter key to make the change take effect. This should provide plenty of room

for accommodating the functionality of the UI, although the primary purpose here was to provide you

with some experience fine tuning the controls.

This would be a good time to test the application. Notice on the VS Toolbar (just below the Menubar)

that there is a Debug button, with a green triangle pointing to the right. This button provides a shortcut

for starting the debugging process, so click the Debug button and see how the UI looks during run-time.*

You can (and should) at the same time make sure that the app still functions as needed. Recall that clicking

on the Debug button not only starts the application but also checks syntax, compiles the source code,

links related files to the app, saves all files associated with the application. You are now done with

modifying the Form control, so let’s move on to working with the properties of the Label, TextBox, and

Button controls.

[*As far as the programmer is concerned, there are two stages to the actual construction of an app: design-

time and run-time. The former applies to the building of the basic UI, as well as the writing of the source

code. On the other hand, run-time (as implied by the name) refers to the actual running of the app.

Although VS is a WYSIWYG (what you see is what you get) development environment, an application’s

interface may nevertheless look different during run-time than it does at design-time. In addition, the

source code may call for properties of the controls on the UI to be modified during run-time. For example,

as you have seen, the value of the greetingLabel control’s Text property changes from “Hello” to

“Welcome . . . !” during run-time, depending upon the name provided by the customer.]

The Label control

For both label1 and label2 you will set the TextAlign property to “TopRight”, and you will align the right

edges of those controls. Start by selecting label1 and then, in the Properties window, find the TextAlign

property, click on the value there (typically TopLeft by default), and then on the dropdown button. In the

selector table that appears select the top right cell, and this will set the alignment of text in that control

to TopRight. Do the same for label2.

Adjust the position of label1 by selecting the control and then using the arrow keys to move it to whatever

position looks more appropriate. If you move the control so that it overlaps that of another control (e.g.,

one of the TextBox controls), do not worry, as you can move that other control in the same manner. When

done with label1, rather than using the arrow keys to position label2, you will simply do this with the

mouse and also take advantage of the positioning rulers in VS. Click on label2, hold down the mouse

button, and drag the control left or right, until a blue vertical line appears through the right edge of the

control, as well as that of label1. This blue positioning ruler indicates that the right edges of these two

controls are aligned. Release the mouse button, but with label2 still selected, use the arrow keys to move

Page 6: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 6

it up or down as desired. (If you wish, you can also do some fine-tuning by changing the values of the

Position property, but that should not be necessary for our purposes here.)

Once again, test the app so as to view the application in run-time, save all related files, and ensure the

functionality has not been altered.

The remaining labels, greetingLabel and costLabel, will also need to be repositioned, but their locations

depend upon those of the other controls on the form. Therefore, setting the Location property for

greetingLabel and costLabel is addressed later. Instead, you will now make some modifications to the

properties of the TextBox controls.

The TextBox control

Select the nameBox control with the mouse, drag the control up or down until you see a red (or purple)

horizontal line, and release the mouse button. When the red positioning ruler displays, you know that

the text in the current control is aligned vertically with that of the nearby control. With nameBox still

selected, use the arrow keys to move that control so that it is adjacent to, but not overlapping, the label1

control. You will likely need to alternate between selecting label1 and nameBox in order to see where

their right and left edges are, respectively.

Once you have the nameBox control where it needs to be, use the mouse to select the numberBox control

and drag it so that the left edge is aligned horizontally with that of the nameBox control. At the same

time, numberBox vertically so that its text is aligned with the text in the label2 control. (Refer

simultaneously to the red and blue positioning rulers in order to do this.)

Finally, note that it is unlikely that any customer will be buying even as many as 1,000 tickets. Hence, the

size of the numberBox control is considerably larger than needed, so you should resize it. Do this as you

would most other controls; i.e., select the control, move the mouse pointer over the right sizing handle,

click, and drag the handle to the left. Alternatively, you can select the control and use the Properties

window to set the value of control’s Width property to a value such as 50 pixels.

Test the app again by clicking the Debug button on the VS Toolbar. Now, let’s take a look at modifying

properties for the Button control.

The Button control

You will modify the Width and Location properties for the startButton control. Note that, depending

upon your platform, the width of startButton may not be sufficient to contain all the text (“Get Started”).

You can set the AutoSize property to “True” for this control, and the button will be resized automatically.

To do this, scroll to AutoSize in the Properties window and then double-click where property value of

“False” is indicated. The width of the button will then adjust if needed to accommodate the text contained.

(Double-clicking on a true/false property value will toggle that value back and forth.)

It makes sense that the Button control for this app should be centered horizontally on the form, so let’s

adjust the horizontal Location property (i.e., the X value) for startButton. You could use the mouse to

drag the button to what appears to be a desired location. Alternatively, you could experiment with various

values for the X property. However, probably the easiest way to center any control is to use the Format

option on the Menubar. Therefore, with startButton selected, click Format and then select Center in Form

and choose Horizontal. As you probably noticed, you can also use the Format menu items for several

Page 7: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 7

other ways of aligning controls. In addition, you can select a group of controls and apply formatting the

group as a whole.

Remaining controls

The controls greetingLabel and costLabel are different from the other Label controls in that new values of

the Text property of greetingLabel and costLabel are assigned during run-time. Since the rest of the

controls have now been somewhat permanently located, these final Label controls can be repositioned

to more suitable locations.

Horizontal alignment can be done using the Format option on the Menubar, but first some temporary text

will need to be assigned to greetingLabel and costLabel. It is difficult at design-time to know exactly how

much space to plan for either label, since that is determined at run-time. You can nevertheless get a

pretty good idea, given the greeting phrase that is used (“Welcome”) and an average length sample name,

such as “Jojo Beanstalk”. (Yes, you could write some code that would determine sizing requirements at

run-time, but that is beyond our scope for now.) Similarly, you know that the first part of the text assigned

at run-time to the costLabel control is “Total price: “. In addition, a reasonable estimate for the text

containing the cost might be something around “$5,000.00” (100 tickets at $50.00).

Therefore, temporarily set the Text properties for greetingLabel and costLabel to “Welcome, Jojo

Beanstalk!” and “Total price: $5,000.00”, respectively. Now, select both these controls by using the

mouse and dragging from the top left to the bottom right, as you did previously with the TextBox controls

and the other labels. Then use the Format option from the Menubar to specify horizontal alignment for

the selected block. While the controls are still selected, use the arrow keys to position the controls

vertically, a little below the startButton control. Finally, replace the temporary values of the Text property

for these controls with the originals once the alignment has been completed. (There is a much better,

and fairly simple, way of dealing with those initial values for the Text property of these two labels.

However, that is a little beyond our scope at present, and we will take a look in the next chapter.)

Now, you can finish this exercise by resizing the form so that there is not so much space below the

greetingLabel and costLabel controls. Do this by using the mouse to select the form and then dragging

the lower sizing handle up until the bottom form border is a little below the lower edge of the costLabel

control. Fine tune, if desired, by changing the value of the Height property in the Properties window.

Summary: Working with the UI

By now you should be getting the idea about the various properties associated with different controls, as

well as about how to set/modify the values of those properties at design-time. You have used several

means of setting those values, starting by using the mouse to select a control or set of controls.

Properties window

Visually

o Using the mouse; drag and drop, taking advantage of

Sizing handles

Positioning rulers

o Using the arrow keys

Using the Format option on the Menubar

Page 8: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 8

In addition, the control properties you have modified include the following.

Size (Width, Height)

Location

o X (distance to the left edge of the control, in pixels)

o Y (distance to the top edge of the control, in pixels)

Font (Font, Size)

TextAlign (e.g., TopRight, MiddleCenter, etc.)

AutoSize (True/False toggle)

Not all of these properties apply to every control, but many controls have the same properties (as well as

value options) available.

While you have been doing this, you should also have noticed a number of other UI development features

of the VS environment. For example, while using the Format option on the Menubar, you probably saw

that alignment, sizing, spacing, etc. can be done quickly with this tool.

The Code behind the UI

Recall that an app can be considered as consisting of three fundamental building blocks: an interface, a

database, and a backend. The backend then is where the code that provides the application’s functionality

resides.* We took a quick look at the code for the backend of the Treasure Island Tickets app in the

“Getting Started” chapter. We will now look more closely at that code, slightly enhanced as shown in the

following figure.

[*Yes, programming code is also used to specify the UI. However, for the most part that code is

automatically generated as you drag and drop controls into the app.]

Comment statements

Page 9: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 9

Before we proceed, let’s quickly address a difference you likely noticed. We will refer to the above

as belonging to Version 5, which has the exact same UI and functionality as Version 4. However,

while there is no difference in functionality, the code above includes comment statements which

are nonexecutable and are therefore ignored by the computer.

A comment provides documentation to any humans who may be trying to understand the code,

which is often written by programmers they do not even know. This is necessary for a couple of

reasons: code maintenance and team-based programming. A good app will need to be

maintained, since conditions driving the design of the application will likely evolve over its lifetime.

Thus maintenance will be required in order for the app to continue to meet the needs of its end-

users. In addition, most (if not all) programming for apps is done by multiple people, generally

working as teams. Self-documentation of the code through comments makes it for one person to

understand better and more quickly what a teammate has done. This is often helpful in the

debugging process, where another pair of eyes can spot logic flaws the original programmer is too

close to see.

Three fundamental concepts

It is important to understand three important concepts demonstrated in the Treasure Island

Tickets code, as well as that in the rest of this book: data, variables, and operations. In addition,

the code for most apps can be summarized as consisting of one or more input/processing/output

patterns. This means something is being supplied as input to the application, that “something” is

being processed, and the results of that processing are the desired outputs. The figure below

summarizes this model.

Now, referring to the basic input/processing/output model, note that data are what are being

input, processed, and output. Strictly speaking, “data” is the plural of “datum”, which means

some sort of fact. We can then think of data (the plural) as a collection of pieces of information.

More formally, “information” is data that have been processed and organized into some useful

form. Outputs are therefore a form of data, so it can be said that computing is all about data (or

information) processing

Data currently being processed are stored in various locations (like mailboxes) in the computer’s

memory, and each location is either a variable or some object’s property value. Variables in turn

are assigned names so that the code can refer to the values in memory. The Treasure Island

Tickets code above uses seven variables, such as dblQuantity. In general, a variable name should

be descriptive, must be comprised of letters and numbers, must start with a letter, and should

not contain any punctuation or other special characters other than the _ or – characters. In the

Appendix you will find some other guidelines for naming variables.

An operation is just something the code tells the computer to do. The first operator in the code

above is referred to as the assignment operator, and you use an equals sign (=) to indicate this.

This may seem to behave the same way the arithmetic equals sign works (i.e., stating that each

side of the sign is equivalent to the other. However, there is a substantial fundamental difference.

Page 10: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 10

In programming, this operator is telling the computer to take whatever is on the right side of the

operator and to assign it to the memory location indicated on the left side. Therefore, the first

line of code above is telling the computer to assign the text “Welcome, ” to the memory location

known as strGreeting. Although most code will involve a number of operators, the only other

operator in the Treasure Island Tickets code is the plus sign (+), which serves a dual purpose.

When the plus sign comes between two numeric values, it acts as an addition operator, the same

as it does when you are doing basic arithmetic. On the other hand, the plus sign specifies a

concatenation operator when it is between two text values, such as “Jojo” and “Beans”. The result

in this case would be “JojoBeans”.

What is happening in the code

Now let’s go through the code line-by-line to see what is happening and to address concepts you

will see over and over as you work with code. Note several things about the first four lines

(including the comment statement), which represent what is called a declarations section. First,

each line is a statement and is essentially an instruction to the computer. A statement can begin

anywhere on a line (whitespace is ignored) and does not end until a semi-colon (;) is reached. (A

comment statement is an exception and does not require a semicolon at the end.) Therefore, a

statement can span multiple lines of code, although none of the code in the current version of the

app does that. Similarly, multiple statements can be included on the same line of code, but this

makes the code much more difficult to read and is therefore discouraged.

Declaring variables

Computers are picky about how we direct them to treat the data. In fact, with most languages

(including C#) we need to tell the computer (i.e., declare) the type of the data being processed

(referred to herein as datatype). In a declaration statement, the programmer is telling the

computer to reserve some space in memory, what kind of data will be stored at that location, and

what to call that location. Here in the Treasure Island Tickets code you are declaring variables,

which you should recall are names that you assign to memory locations. Multiple variables can

be declared in a single statement, as long as they are all of the same datatype. Optionally, the

programmer can specify an initial value to be stored in that location; doing this is called

initialization. Declarations can be done anywhere in the code prior to the use of the variables

being declared. It is nevertheless wise to try to keep declarations for a block of code together in

a section near the beginning of that block.

In the Treasure Island Tickets app, three variables are declared in the declarations section, each

in a single statement. Two of the variables are also initialized here and are of the string datatype,

while the third variable is of the double datatype. When actual text (known as a string literal) is

assigned to a string variable (as is done in the first two declarations), the text is quoted. However,

quotes are not used around numeric literals (where actual numbers are used), such as that being

assigned to the dblUnitPrice variable.

Datatypes in C#

Before going further, we need to take a quick look at the major datatypes you will be using, and

these are summarized in the table below. In general, you can think of data as being either numeric

Page 11: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 11

or nonnumeric. The major difference is of course that ordinary arithmetic can be performed on

numeric data. Numeric datatypes include the int (short for “integer”), double (short for “double

precision”), and decimal types, listed in order of the memory/storage required for each. While

there is a similarity among the numeric datatypes, about the only thing that the nonnumeric types

have in common is that they are not numeric. Note also that, when a literal value is to be assigned

to, or used with, a decimal variable, the literal value must have an “m” appended. (More will be

said about this later.) In the next chapter you will start using the bool (short for “Boolean”)

datatype. Later you will work also with the DateTime type (which is actually a specific object class

and not truly a datatype). As you likely have already figured out, the string datatype is for use

with text data, meaning letters, numerals, punctuation, etc.

Data Type Storage Size Prefix Possible Values

bool 2 bytes bln True or False

DateTime 8 bytes dat Dates between 1/1/0001 and

12/31/9999

int 4 bytes int Positive and negative whole

numbers between –

2,147,483,648 and 2,147,483,647

double 8 bytes dbl A number with at most 14 digits

to the right of the decimal point

decimal 16 bytes dec Very small to very large!

string 1 byte per

character

str Character string of up to about 2

billion characters

The table above contains only a few of the datatypes available to C#, although they are the most

common. Various other datatypes can be very useful but are beyond our scope.

Variable naming

Notice also the “Prefix” column in the table above. While variable names are largely arbitrary, it

is helpful to adhere to certain conventions, such as starting variable names with prefixes indicating

the associated datatypes. This is an optional practice, as the computer does not care about what

the actual variable names are, as long as they meet a few requirements. These requirements are

summarized below, along with recommended conventions for good variable naming.

Rules for variable names (must be followed)

o First character must be one of either a-z or A-Z, or an underscore (_)

Page 12: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 12

o Following characters must be from a-z, A-Z, 0-9, or an underscore

o No spaces are allowed

o Do not use any C# keywords* (e.g., dec, private, namespace, etc.)

Conventions being used in this book for variable names (recommended but optional)

o Use names that are self-documenting

Name describes what the variable represents

Name starts with a prefix indicating the variable’s datatype

o Use camel case: variable name starts with a lowercase letter, and the first

character in each successive word is capitalized; called “camel” case because of

the “humps” formed by the internal uppercase letters

[*Keywords are words reserved for special purposes. For a table of C# keywords, refer to the

Microsoft Developer Network page at https://msdn.microsoft.com/en-us/library/x53a06bb.aspx]

Choosing the appropriate datatype

Generally, it is recommended that the smallest feasible datatype (in terms of storage required)

be used for declaring variables. Therefore, if a numeric variable will need to store only values that

are whole numbers (i.e., integers), an int datatype should be used. On the other hand, the

decimal datatype is generally used for monetary values, since the high level of precision helps

preclude internal roundoff errors.* Previously in the Treasure Island Tickets code you have used

only the double datatype in order to make the code for this introductory app as simple as possible.

A slightly better version of the same code is indicated below, and we will refer to this as Version

6a. (The “a” corresponds to the desktop platform, and Versions 6b and 6c correspond to web and

mobile platforms, respectively. Versions 6b and 6c, along with concepts and procedures

associated with developing them, are the subject of the next chapter.)

Page 13: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 13

The revised code is “better” in that it follows the guidelines provided above (a) to minimize

storage required and (b) to use the decimal datatype for monetary values. (Note also that

additional comments, some end-of-line comments, provide additional documentation about

what is happening with the processing.) With such a limited app, this does not really matter, since

very little memory (i.e., temporary storage used during processing) is involved. In addition, the

amount and type of processing (e.g., calculations) are minimal, so roundoff error is also not a

concern. Attention to storage efficiency and accuracy become very important in nearly all

practical applications, especially as computing devices get smaller and smaller (e.g., wearable

technologies).

That said, for our purposes here, either version will suffice for the discussion that follows. Since

the code in the latter listing is “better”, we will nevertheless be referring to that code. Accordingly,

the declaration for the order quantity variable has been changed so that an int variable is being

created. In addition, the variable’s name has been changed such that its prefix indicates the

variable’s datatype.

[*Computers use the binary number system (commonly values of 0 and 1), whereas we as humans

typically use the decimal number system (values from 0 through 9). That means values we need

processed by a computer must be converted from decimal to binary for processing and then back

to decimal for display or use by humans. Whenever non-integer values are involved, this means

there may not be an exact conversion, so rounding must take place, leading to roundoff error.

That “error” may or may not be substantial, depending upon the application and the amount of

calculation involved.]

Input section: Getting data to work with

Following the declarations section are three statements that can be considered an “inputs”

section. Here data needed for processing are assigned as literal constants or are read from what

the end-user has entered onto the form. (Most programming languages, including C#, provide

for a better way to handle literal constants, and you will incorporate that approach later.)

By now you should have noticed that multiple operations can take place in a single statement.

The statements in the “inputs” section of the code demonstrate this. Here the declarations

process is combined with the assignment process. In addition, by using the dot notation in the

form of object.property in a statement, we can refer to the given property of an object. Hence,

as an example, the statement

string strName = nameBox.Text;

tells the computer to

1. Set aside memory for a variable containing string data,

2. assign a name of strName to that memory location,

3. find the value of the Text property for the nameBox control, and

4. store that value in the memory located at the strName address

Processing section: Working with the data

Page 14: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 14

As demonstrated by this small application, processing often can be consist of this pattern: (a)

convert the input data; (b) manipulate the data, i.e., do the calculations and such; and (c) convert

the results so they can be displayed. This pattern might exist as a single instance, as in the

Treasure Island Tickets app, but also might be executed multiple times during the processing stage

of an application.

Converting the data

One statement in your code converts data from string (i.e., text) to numeric. All data

collected from a form or other graphical interface (e.g., mobile phone) are initially of the

string datatype. Consider a number such as how many tickets are being purchased (as

provided on the form by the end-user). If that number is to be used in calculations, it

must be converted to a numeric datatype. Conversely, the results of calculations, as well

as other numeric data, must then be converted to text in order to be displayed through

an interface.

For the former (converting data from text to numeric) several approaches are available,

but the TryParse() method is preferred. Although more than one version of TryParse() is

available, for now you will use the simplest version and address other versions in

subsequent chapters. The general syntax is

outputDatatype.TryParse(inputText, out numericOutputVariable)

where

inputText is the string variable (or literal) to be converted,

numericOutputVariable is the output variable, and

outputDataType is the datatype of numericOutputVariable.

If the value of inputText cannot be converted to the specified datatype (outputDataType),

the output variable (numericOutputVariable) will be assigned a value of zero. Otherwise,

the numeric value corresponding to inputText will be assigned to numericOutputVariable.

Hence the statement

int.TryParse(strQuantity, out intQuantity);

does the following.

1. Calls the TryParse() method that belongs to the int datatype.

2. This version of the method instructs the computer to convert the value stored in

the memory location designated by the variable strQuantity to an integer.

3. The result of the conversion is then stored in the memory location designated by

the variable intQuantity.

a. If the conversion is successful, the value stored will by the numeric

integer equivalent of whatever value was entered into the TextBox

named numberBox.

b. Otherwise, the value stored will be a zero.

Page 15: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 15

The other conversion taking place in the Treasure Island Tickets code uses the ToString()

method to convert a given numeric value (of any datatype) to text. (While it could be said

that this method is universal in that it works with any numeric, more correctly, each

numeric datatype has its own ToString() method. However, they all work in essentially

the same manner.) The general syntax is

numericValue.ToString(“formatString”)

where

numericValue is a numeric variable or numeric literal constant, and

formatString indicates the manner in which the number is to be displayed (e.g.,

number of decimal places)

This method returns a string (i.e., text value), formatted as specified. * The formatString

values consist of a letter plus a number indicating how many decimal places are desired

in the output string. The most common letter values are summarized in the following

table. (See https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx for

further discussion of format strings.)

C or c Currency

F or f Fixed-point

N or n Number

P or p Percent

In your code, for example, if decTotalPrice has been calculated to be a value of 1234.567,

then

decTotalPrice.ToString("c2")

returns a value of “1,234.58” (where the quotation marks are intended to indicate this

result has a datatype of string. As you can see, the appropriate rounding takes place and

a comma separating thousands is entered.

[*A “return” value for a method is a data value that results when the code in the method

is processed. The concept of methods and their return values will be addressed in more

detail later on.]

Manipulating the data

Two types of operations – one for string data and the other for numeric data – are

illustrated in the Treasure Island Tickets code. Concatenation does for string data more

or less what addition does for numeric data. It therefore seems appropriate that the same

operator – the plus sign (+) – is used for both. As indicated in the previous chapter,

concatenation simply joins two or more strings, which is being done in the code here. The

values of strGreeting, strName, and an exclamation point (!) are being joined.

Page 16: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 16

In addition to working with the string data by using a concatenation operation, this

section of code also does a numeric calculation for the value for decTotalPrice. In the

single statement

decimal decTotalPrice = intQuantity * decUnitPrice;

the following takes place.

1. The variable decTotalPrice is declared, which means

a. memory is set aside for a variable containing decimal data and

b. a name of decTotalPrice is designated for that memory location,

2. intQuantity is multiplied times decUnitPrice, and

3. the result is stored in the memory address associated with decTotalPrice.

This may seem to be an excessive explanation of what that statement is doing. However,

it can be helpful to break down the process in order to see this in a manner similar to how

the computer sees it.

Output section: displaying the results

The final two lines of code display the results of the processing (i.e., the concatenation, the

calculation, and the data conversions). This is done by assigning values to the Text properties for

the output controls. Hence, the statement

greetingLabel.Text = strGreeting;

takes whatever value is contained in the memory location designated by the variable strGreeting

and assigns it to the Text property of greetingLabel. The final line of code works the same way.

Notice, by the way, a major difference between TextBox controls and Label controls.

A TextBox is primarily (if not exclusively) for input

A Label is essentially for output

Even though these controls can be configured (i.e., have appropriate property values specified)

similarly, it is important not to confuse the purposes of these controls.

Summary

In the previous chapter, “Getting Started”, you were introduced through a couple of examples to what

programming is. In the current chapter we have used one of those examples, the Treasure Valley Tickets

app, to discuss and demonstrate the fundamental concepts of app development. In other words, you

were initially exposed briefly to those concepts and in this chapter those concepts have been explained.

You should therefore now have an understanding of the essentials of programming and maybe even be

able to develop your own simple desktop app by putting that understanding to work.

At this point, you should be able to identify the object classes you have used, work with the most common

properties and methods associated with those classes, use VS to develop and/or modify UIs for simple

desktop apps, organize code for applications according to the input/processing/output model, recognize

the datatypes for the data involved, and write the code that makes UIs functional.

Page 17: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 17

In writing code for any type of app you should be able to declare variables appropriately for the datatypes

involved, get data from TextBox controls on a form, convert data from text to numeric and vice versa,

assign values to variables, concatenate text strings, perform basic addition, and assign values to Label

controls on a form.

In Chapter 2 you will use VS to assist us in developing and implementing the Treasure Island Tickets app

for web and mobile platforms.

Page 18: Programming Fundamentals Using Visual C#.Net: A Business ...cit2033/handouts/cSharpChapter01_2017a.pdfProgramming Fundamentals Using Visual C#.Net: A Business Context ©John Seydel

Programming Fundamentals Using Visual C#.Net: A Business Context©

©John Seydel 2017 Chapter 1: Nuts & Bolts, Page 18