Fundamentals of Corporate Finance 4th Ed by Brealy Meyers Net
Programming Fundamentals Using Visual C#.Net: A Business...
Transcript of Programming Fundamentals Using Visual C#.Net: A Business...
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 1
Getting Started Draft, Not for General Distribution
OK, so what is programming? Programming (or coding) is just writing a set of instructions for a computer
(or phone or website) to follow on its own. That set of instructions is then called a program. Of course,
these instructions must be written in a way that the computer can understand what is to be done, how,
etc. That is, since the computer does not speak English (or Chinese or whatever other language we speak),
we need to write those instructions in a language the computer does understand, i.e., in a type of code.
Hence, writing instructions for a computer is also called coding.
An underlying theme of this book is that we can address programming fundamentals from a multi-
platform – desktop, web, and mobile – perspective. That is, much, if not all, of the coding for the
applications software* (or apps) at which we will be looking can be done in a manner that the coding will
work for apps that are to run on essentially any of those major three platforms. By “desktop” we mean
both standard laptop/notebook computers and traditional desktop computers running MS Windows
operating systems. The “web” app versions of the programs we will be developing should run in just
about web browser on any computer, regardless of operating system (including any mobile device that
includes a web browser). Finally, the “mobile” app versions of the programs we write are limited to
current Windows mobile devices (i.e., smartphone or tablet). However, the procedures involved in
developing mobile apps for Windows devices are generally analogous to procedures used in building apps
for Apple and Android devices. The important thing to keep in mind is the programming fundamentals,
which are universal even though syntax will vary somewhat from language to language and platform to
platform.
Of the three applications platforms, building the user interface (UI) – also referred to often as a graphical
user interface, or GUI -- is probably simplest for the desktop. We will therefore, for the most part, look
first at these apps as desktop apps and then address them as web and mobile apps.
[*Computer programs, or software, can be classified as either systems software or applications software.
In general, applications programs are software with which end-users interact directly, e.g., a weather app,
Microsoft Excel, a payroll processing program, etc. On the other hand, systems software (e.g., an
operating system such as Microsoft Windows) consists of programs that make it possible for applications
programs to interact with the computer and its resources, e.g., printers, files, etc. While the programming
fundamentals we will be addressing apply to both types of software, our primary concern will be
applications software.]
An Example Program (for Humans)
Now, without getting involved right away with coding (we will get to that soon enough), let’s consider a
set of instructions for a human to follow. When I was growing up, I would get home from school both
thirsty and hungry. However, my parents (who were still at work) had no snacks around and would not
let us kids cook anything. Somehow my brother and I figured that chocolate milk would hit the spot, but
we had no instant flavoring or chocolate syrup available, just unsweetened cocoa, sugar, and milk. (By
the way, you cannot simply put cocoa and sugar into milk and make chocolate milk, as these ingredients
simply do not blend.) Nevertheless, with a little experimenting, we did manage to come up with the
following recipe for chocolate milk:
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 2
1. Get a 12 ounce glass
2. Add 1 tbsp of cocoa
3. Add 1 tbsp of sugar
4. Stir once
5. Add 1 tbsp of hot water
6. Stir once
a. If consistent, proceed to next step
b. Otherwise, stir again
7. Add cold milk
8. Stir and repeat until consistent
9. Drink and enjoy
These instructions therefore constitute a program for humans to follow. Computer programs are actually
quite similar to this, both in form and in concept; they are simply recipes for computers to follow.
Now, note that any human (my brother, for example) would ordinarily execute (i.e., follow) the above
instructions one at a time, one after another in sequence. However, that sequence is interrupted twice,
once at step 6(a) and again at step 8. At step 6(a), a decision must be made so that the appropriate path
can be selected. That is, one instruction or another must be executed, depending upon whether the mix
is consistent, and must select a path. Then at step 8 the instruction there is repeated over and over until
the chocolate milk is completely mixed.
Well, a computer works in the same manner, executing instructions in sequence until it encounters a “fork
in the road” and/or must repeat one or more instructions in a set. Note, therefore, that essentially all
programming logic consists of sequence, selection, and looping constructs. This applies to any application,
whether making chocolate milk or determining someone’s net pay for example. In addition, we can also
consider a fourth type of construct, call it jumping for lack of a better term. Suppose in the chocolate milk
example that we replace steps 2 through 6 with the following.
2*. Put 2 tbsp of chocolate syrup into the glass
This replaces several steps in the process by relying upon an ingredient someone else has already
prepared, chocolate syrup. We do this in computer programming by making references to (i.e., calling)
small programs that have already been written, usually for use in a variety of other programs. Typically
these small programs (which are often not really that small) are called methods. Obviously, for this to
occur, the method must exist, just as using chocolate syrup requires that the syrup is available.
In summary, programming (just as recipe writing) involves specifying instructions that are by default
executed in the sequence provided. That sequence is then altered when one or more of those instructions
is a selection, looping, or jumping construct. Let’s therefore take a look (finally) at a computer program,
first written in English, then in a computer language, C#. However, do not worry at this point that the C#
code may not be very understandable, as it will be addressed in detail later on.
Another Example Program (for Computers)
Consider a process that is near and dear to almost all of us: determining how much we are to be paid.
Let’s therefore take a look at a weekly payroll app (short for applications program), where any work
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 3
beyond 40 hours is paid at the typical rate of time-and-a-half. Suppose the program is to start by
displaying a form for an employee to enter her hourly wage. The employee can then click on a button
that will cause the computer (or phone or website) to proceed with determining her total pay for the
week. Below is a screenshot of a web app version of this simplified payroll app, and you can also try out
a working version, available through the following link PayRoll App Version A.
For the computer to do this payroll processing, we must instruct the computer first to read the hourly
wage from the form. Then the computer must ask the employee how many hours she has worked on
each assignment completed over the past week. Based upon this information, the computer can then
calculate gross pay for the week and display that result for the employee. The instructions then to be
executed essentially as if a human (e.g., payroll clerk) were doing the processing manually are as follows.
1. Get the hourly wage from the form
2. Get the hours worked on the first assignment:
a. Ask the end user for the hours worked on the first assignment
b. Convert to numeric (the computer is picky about data types)
c. Set total hours worked to the amount worked on the first assignment
3. Get the hours worked on the remaining assignments:
a. Ask the end user for the hours worked on the current assignment
b. Convert to numeric (the computer is picky about data types)
c. Add those hours worked to the total hours worked
d. Repeat until no more assignments are to be recorded
4. If total hours worked is no more than 40, then:
a. Calculate total gross pay: multiply hourly wage by total hours
b. Otherwise:
i. Calculate regular wages: multiply hourly wage by 40
ii. Calculate overtime wages: Multiply hourly wage by 1.5 by amount of hours
worked greater than 40
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 4
iii. Add regular wages and overtime wages to get total gross pay
5. Write total gross pay in the appropriate place on the form
As indicated earlier, these instructions must be written in code (i.e., a language) so that the computer can
understand and execute them. Those coded instructions are referred to as source code (or just code)*.
Written in the C# language, the code for this payroll app is as follows.
double.TryParse(wageBox.Text, out hourlyWage); // 1 strHours = Interaction.InputBox(inputQuestion, inputTitle); // 2(a) int.TryParse(strHours, out hoursWorked); // 2(b) totalHoursWorked += hoursWorked; // 2(c) while (hoursWorked != 0) { // 3 strHours = Interaction.InputBox(inputQuestion, inputTitle); // 3(a) int.TryParse(strHours, out hoursWorked); // 3(b) totalHoursWorked += hoursWorked; // 3(c) } if (totalHoursWorked<=40) { // 4 totalGrossPay = hourlyWage * totalHoursWorked; // 4(a) } else { // 4(b) regularWages = hourlyWage * 40; // 4(b)(i) overtimeWages = hourlyWage * 1.5 * (totalHoursWorked - 40); // 4(b)(ii) totalGrossPay = regularWages + overtimeWages; // 4(b)(iii) } resultLabel.Text = outputPrefix + totalGrossPay.ToString("c2"); // 5
[*Actually, the source code is a sort of intermediate step, between instructions we as humans can
understand and the actual instructions a computer can understand. This latter type of instructions is
referred to as machine code. Therefore, the source code for an app must be compiled (i.e., translated)
into machine code before the computer can execute the instructions. This translation requires a compiler,
which is itself a type of computer program, which in general is transparent to the programmer, as you will
see shortly. Source code can be written in various languages, among which C# is a powerful and popular
option. While source code is written using English-like characters (and words), machine code is stored as
ones and zeros, i.e., in binary format, which is why machine code is also called binary code.]
Please do not be overwhelmed with the code above, as we will deal later with the language syntax and
features, as well as the actual meaning of the various code elements. At that time, what that code is
telling the computer should become much clearer. In the meantime, you should nevertheless be able to
see that each line of code corresponds to a line in the human language instructions. You may even be
starting to see how we might begin writing C# code to accomplish simple task like those above.
Most importantly, notice the four fundamental programming constructs: sequence, selection, looping,
and jumping. Lines 1 through 2(c) are a sequence of instructions (i.e., statements) to be executed one
after another. Lines 3(a) through 3(c) are a set of statements executed over and over within a “while”
loop until the employee indicates 0 hours on an assignment, as specified in line 3. Lines 4 through 4(b)(iii)
specify a selection construct with two alternatives, depending upon whether or not the employee worked
a total of more than 40 hours. Finally, the concept of jumping is illustrated in the following locations:
lines 1, 2(b), and 3(b), which all use TryParse() method; lines 2(a) and 3(a), both of which use the InputBox()
method; and line 5, which uses the ToString() method. Although these methods seem to be buried among
other cryptic language, they represent calls to other pre-written programs. We will look at these (and
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 5
many other) methods in detail later. For now, however, just note that the TryParse() method converts
text to numeric values, the InputBox() method displays a popup requesting information, and the ToString()
method converts numeric values to text.
Notice also that many of the items being worked with have names, rather than actual values. For example,
the value for total hours worked is referred to as totalHoursWorked. Another example is the prompt
asking the employee about time spent on an assignment; that prompt is referred to as inputQuestion,
which corresponds to the text string “Hours spent on this assignment (0 when done)”. These are called
variables, and we will discuss the concept of variables later as well.
Finally, you may have noticed some other items with names, wageBox and resultLabel. These are just
names given to elements that are part of the form displayed for the computer to interact with the
employee. There are quite a few such elements, and we will soon get started building apps with forms
that contain these elements.
Of course, this is an overly simplified version of a payroll app, but we will get to something much more
realistic later on. However, by now you should have at least a basic idea of what programming (or at least
the coding part of it) is. Next you will get the chance to start doing your own coding, as well as building a
UI that allows the end user to interact with the programming code. . . .
Note that you have so far been exposed to a number of fundamental programming concepts (e.g., control
structures, variables, methods, etc.) without much explanation about the details of those concepts. . . .
An Introductory Exercise
Enough talk about programming, now it’s time to do some programming. That is, we are going to develop
a simple app, starting with building a UI and followed up with the writing the actual code that makes that
interface functional. Note that essentially all apps can be considered to consist of three components, or
building blocks: an interface, a database, and a backend. (Although you may find other terms used, these
should suit our purposes.) The simplest applications, however, such as what we will be looking at for the
most part, often do not include the database component.
As indicated previously we will address this first as a desktop app and then a little later take a look at what
needs to be done to build web and mobile app versions. Our app is based upon the following scenario.
A ticket sales app
Treasure Island Tickets is a national broker for sales of vouchers providing access to entertainment events,
such as concerts, wrestling matches, Broadway plays, etc. You are to develop an app that will ultimately
greet a customer, find out how many tickets she wants, and then display the total cost for those tickets.
However, we will start small and just build the app initially so that it greets the customer. After that we
will enhance the app as described by the following phases. (Click* on the links to see working examples
of each phase as a web app.)
Phase 1: greets the customer
Phase 2: gets the customer’s name and greets her personally
Phase 3: also gets the number of tickets and displays total cost
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 6
[*Unless otherwise specified, “click” in the instructions in this book will always mean a single-click using
the left mouse button.]
For each of these phases we will describe the app in terms of its outputs, inputs, and processing, as well
as in terms of the features of its interface. This is in fact how the design stage of the applications
development procedure is done for essentially any app. That is, once the end user requirements have
been identified and understood, the developer should first specify the outputs to be generated by the
app. Then the developer should determine what inputs need to be provided and how. After that, the
developer must determine the processing needed to convert those inputs into the required outputs. Once
the design stage is completed for an app, it is time to go ahead and build the UI and write the code
Using Visual Studio
We will soon get started working on each of the phases of the ticket sales app one at a time, but first we
need to deal with a technology issue. That is, we need to get to know the integrated development
environment (IDE) that makes is much easier to build apps of all types. Essentially, an IDE is itself a
computer program that provides the equivalent of a “one-stop shopping” experience for applications
development. A number of IDEs are available for this purpose – Eclipse, NetBeans, Xcode, and more – but
we will be using Microsoft’s Visual Studio (VS). In particular, the examples and exercises we will be
working on use the Community 2017 edition of VS, as that is available without charge from Microsoft.
(You are welcome to use a more current version of VS, because most, if not all, of the procedures should
be the same.)
If you are not currently using a computer with VS installed, refer to Appendix I and follow the instructions
for installing VS. Other recent versions of VS should also work, so, if your computer has VS, but not
Community Edition 2017, already installed, that should be sufficient.
Note that building applications using the C# language does not strictly require the use of an IDE.
Programming code – for both the UI and the backend – can be written using any text editor (e.g., NotePad),
and that code can then be processed so that the app runs as intended. However, there are many tasks
involved in making this happen, and an IDE takes care of most of those, and much of this is done through
a visual, relatively intuitive, interface.
Building Phase 1 of the Treasure Island Tickets App
Design:
The backend can be summarized as follows.
o Outputs: the actual greeting
o Inputs: phrase to be used for the greeting
o Processing: get the greeting phrase and place it on the computer screen
The UI needs to have the following features.
o Form or screen to contain the following components
Button to click in order to start the processing
Place (also known as a label) to display the greeting
Construction:
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 7
Start VS (may take a while to get completely started). Once VS has settled down, start a new
project by doing the following.
1. Click on File and then New
2. Select Project, and this will open up the New Project window,
3. In the New Project window, click on the following in sequence from the left-hand panel
a. Installed
b. Templates
c. Visual C#
d. Windows
4. In the center panel click on Windows Forms Application
5. In the bottom section provide a Project name and a Solution name; these names are ordinarily
your choice, but for now use the following.
a. Project: treasureIsland2017a1_proj
b. Solution: treasureIsland2017a1_soln
c. Note that recommended naming conventions, such as these, will be explained a little
later.*
6. Then click on the OK button and wait for VS to create the project framework
7. Once VS has finished loading the new project, maximize the VS window so that you have
plenty of space to work.
8. We will soon examine the anatomy of VS more thoroughly, but for now notice the following.
a. The right panel, where the Solution Explorer and Properties Window are located
b. To the left is what we will refer to as the center panel, which is where most of the our
work will be done (currently containing a small window with the title Form1, although
possibly empty)
c. The Output Window, at the bottom of the center panel
d. The left panel, where the Toolbox is located (currently empty if Form1 is not displayed
in the center panel)
A project created as a Windows Forms Application is intended to run as a conventional Windows
desktop app. That means the resulting application should be capable of running on Windows XP
and Windows 7, as well as when using Desktop mode on Windows 8 and Windows 10.
When the project is created, a default UI (referred to as a form) is also created at that time. This
interface is initially empty, and the form serves as a container for various features (e.g., Buttons)
that interact with the end user of the app. Note that these UI “features” are more formally called
controls, which is how we refer to them from here on.
[*Although most aspects of project, folder, and file naming are essentially arbitrary (subject to a
few rules) some guidelines are provided as we encounter various naming options. For example,
the solution (i.e., overall folder containing the project and all related files) and project (i.e., the
main set of files within a solution) naming herein uses the scheme a|b|x|d|e (e.g.,
treasureIsland2017a1_proj), where: a is some word or words providing a descriptive name (i.e.,
treasureIsland); b is the current year (i.e., 2017); x is a letter (i.e., a) corresponding to the platform
(a for desktop, b for web, c for mobile); d indicates the stage of sophistication (i.e., 1); and e is a
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 8
value of either _soln or _proj and indicates whether it is the solution folder or the project folder,
respectively .]
Let’s now finish building the interface for Phase 1 by performing the following steps.
1. In the Solution Explorer locate Form1.cs.
a. Rename the file; typically optional, but for now do the following.
i. Right-click on it and select Rename.
ii. Type the name ticketForm.cs and press the Enter key.
iii. Accept the offer to change the names of related items.
b. Double-click on ticketForm.cs.
c. The empty form should then display in the center panel, if it was not there previously.
d. The Toolbox (in the left panel) should no longer be empty.
i. Click on the Common Controls item in the Toolbox.
ii. A list of typical UI features (i.e., form controls) displays
2. From the Toolbox drag the following controls to the form
a. Button: somewhere near the center of the form
b. Label: below the Button and slightly off-center to the left
3. Assign values to properties of the controls (i.e., UI features); names are typically arbitrary, but
for now use the ones provided (including upper/lower case as indicated).
a. Properties to be assigned
i. Form: Name (TicketForm); Text (“Treasure Island Tickets”)
ii. Button: Name (startButton); Text (“Get Started”)
iii. Label: Name (greetingLabel); Text (“Hello”)
b. Use the Properties Window to do this, as follows
i. Select a control by clicking on it (once, not twice).
ii. In the Properties Window find the name of the property to be assigned a value:
First, sort the properties alphabetically by clicking on the A/Z button.
Then scroll down (or up) the list until you find the desired property name.
iii. To the right of that property name, type (or otherwise designate) the value for
the property.
iv. Press the Enter key (or just click on any other control)
c. Your interface should now look like the following.
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 9
4. Test the app
a. On the Menubar click on Debug and then select Start Debugging.
b. After a few seconds a new window, containing the ticket app, will pop up.
c. You can click on the button (startButton), but nothing will happen, since we have not
written any of the code that is needed to make the app functional.
d. You can, however, click on the red X button, and the app (like essentially any other
Windows application) will close.
e. When done examining this essentially non-functional app, go ahead and end the
testing:
i. Either click on the red X button on the app
ii. Or, on the Menubar, click on Debug and then select Stop Debugging
f. Note that this “testing” process is more formally known in the VS context as
debugging. In addition to allowing the programmer to test apps, debugging causes
VS to perform the following chores.
i. Save all files, so there is generally no need to save your work explicitly; these
files include:
C# source code
The interface design (also stored as C# code)
Other files that may be associated with app
ii. Check the syntax of the source code; i.e., makes sure the code is written
according to the C# “grammar” rules
iii. If the syntax is correct, then
Compile all source code associated with the app
Link all internal and external files required for the app
5. Now, let’s refer to the processing portion of the design outline above and finally write some
code.
a. First, note that there are two main views of the app:
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 10
i. The designer view and the code view.
ii. We have been working so far with the designer view and now we need to work
with the code view.
b. In addition, the app needs to respond to the customer’s clicking on the button
(startButton)
i. To write the code to accomplish this, we double-click on the button.
ii. This will then open up (or switch over to) the code view for the app.
iii. Note that a considerable amount of code already exists, but we will ignore most
of that for now and focus on what goes into the startButton_Click() method.
iv. Recall that a method is a semi-independent program that can be called or
accessed from another program.
In this case, the startButton_Click() method is intended to be called in
the event that the customer clicks on the button.
The startButton_Click() method is therefore referred as an event-
handler (or event-handling method).
c. We can switch most easily between the design and code views by clicking on the
appropriate tab at the top of the middle panel of the VS interface.
d. Now, enter the following code below the “{“ just under the opening line for the
startButton_Click() method.
string strGreeting = "Welcome!"; greetingLabel.Text = strGreeting;
e. Be careful to type the lines above exactly as shown; computers are very stupid and
do exactly what you tell them and only what you tell them! They therefore can’t
guess at what you meant if you, for example, leave out a semi-colon or use lowercase
one time and uppercase another.
f. The complete code for the startButton_Click() method is indicated below.
g. Test the app again by using the debugging feature of VS and click on the “Get Started”
button once the app is running.
h. Here is what happens when this code is executed.
i. Clicking the button tells the computer to run the startButton_Click() method.
ii. The first line in the method specifies a variable (strGreeting) and assigns a value
to it.
iii. Note the keyword “string” that precedes the rest of the first statement; this is
telling the computer the type of data (in this case, string data, i.e., text) that
will be stored in the variable being specified. We will elaborate on this concept
later, but you should at this point be able to get a general idea about the
purpose of this and other preceding keywords.
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 11
iv. The second line tells the computer to get the value for strGreeting and to assign
that value to the Text property of the greetingLabel.
There is clearly not much to this app, nor to the UI and the coding for the app’s backend. You
should nevertheless see that the only programming construct we have worked with is the
sequence construct. In addition, however, the jumping construct is employed when the customer
clicks the button (startButton), at which the startButton_Click() method executes.
We can now move on to a somewhat more interesting version of the ticket app, Phase 2.
Building Phase 2 of the Treasure Island Tickets app
Design:
The backend can be summarized as follows.
o Outputs: greeting customized with the customer’s name
o Inputs:
Phrase to be used for the greeting
Customer’s name
o Processing:
Get the greeting phrase
Get the customer’s name
Combine the greeting phrase with the customer’s name
Place the customized greeting on the computer screen
The UI needs to have the following features.
o Form or screen to contain the following components
Place (also known as a TextBox) where the customer can enter her name
Label for identifying the customer name TextBox
Button to click in order to start the processing
Label for displaying the greeting
Construction:
Starting with the work you completed for Phase 1 (if you have closed it, then open it), modify the
interface and code slightly.
1. Interface modifications
a. From the Toolbox add two controls: a Label and a TextBox
i. Drag a Label control to a location above the button (startButton) and off-
center to the left.
ii. Drag a TextBox control to a position just to the right of the Label you just
added.
b. Assign values to properties of those controls as follows.
i. Label: Text (“Your name:”)
ii. TextBox: Name (nameBox)
c. Your interface should now look like the following.
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 12
2. Code modifications (within the startButton_Click() method)
a. Change the first line to the following
string strGreeting = "Welcome, ";
b. Insert the following lines between the two lines you wrote previously.
string strName = nameBox.Text; strGreeting = strGreeting + strName + "!";
c. Test the app again by using the debugging feature of VS and click on the “Get Started”
button once the app is running.
d. The complete code for the revised startButton_Click() method is indicated below.
e. Here is what happens when this new code is executed.
i. The first of these two new lines specifies a variable (strName) and assigns it
the value of the Text property from the nameBox control.
ii. The other new line tells the computer to get the value for strGreeting, to
append (i.e., concatenate) the value for strName (i.e., the customer’s name),
then to concatenate an exclamation point, and finally to assign the result to
the greeting (strGreeting), replacing the old value.
Of course, this is not much of an improvement in the app, but at least you now have an app that
gets information from the customer, processes that information, and then displays a result back
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 13
to the customer. Again, the only programming construct we have worked with is the sequence
construct.
Now, let’s wrap up this exercise by incorporating some additional processing.
Building Phase 3 of the Treasure Island Tickets app
Design:
The backend can be summarized as follows.
Outputs:
o Greeting customized with the customer’s name
o Total price of tickets desired
Inputs:
o Phrase to be used for the greeting
o Phrase to be used for the total cost
o Price per ticket
o Customer’s name
o Number of tickets desired
Processing:
o Get the greeting phrase
o Get the total cost phrase
o Get the price per ticket
o Get the customer’s name
o Get the number of tickets desired
o Combine the greeting phrase with the customer’s name
o Calculate the total price of the tickets
o Combine the total cost phrase with the total cost amount
o Place the customized greeting on the computer screen
o Place the total cost phrase and price on the computer screen
The UI needs to have the following features.
Form or screen to contain the following components
o TextBox for the customer to enter her name
o Label for identifying the customer name TextBox
o TextBox for the customer to enter the number of tickets desired
o Label for identifying the TextBox for the number of tickets
o Button to click in order to start the processing
o Label for displaying the greeting
o Label for displaying the total ticket price
Construction:
This time starting with the work you completed for Phase 2 (if you have closed it, then open it),
modify the UI and code as follows.
1. UI modifications
a. From the Toolbox add three controls: two Labels and a TextBox
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 14
i. Drag a Label control to a location above the button (startButton), below the
label for the customer name, and off-center to the left.
ii. Drag a TextBox control to a position above the button (startButton), below
the TextBox (nameBox) for the customer name, and just to the right of the
Label you just added.
iii. Drag a Label control to a location directly below the Label (greetingLabel) that
contains the greeting.
b. Assign values to properties of those controls as follows.
i. First new Label: Text (“# Tickets:”)
ii. New TextBox: Name (numberBox)
iii. Second new Label: Name (costLabel); Text (“ ----- “)
c. Your interface should now look like the following.
2. Code modifications (within the startButton_Click() method)
a. Insert the following after the first line of code within the method.
string strTotal = "Total price: "; double dblUnitPrice = 50;
b. Leave the next line unchanged and then insert the following code after that.
string strQuantity = numberBox.Text;
double dblQuantity;
double.TryParse(strQuantity, out dblQuantity);
c. Leave the next line unchanged and insert the following code after that.
double dblTotalPrice = dblQuantity * dblUnitPrice;
strTotal = strTotal + dblTotalPrice.ToString("c2");
d. Add the following code as the last line of the method.
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 15
costLabel.Text = strTotal;
e. Test the app again by using the debugging feature of VS and click on the “Get Started”
button once the app is running.
f. The complete code for the completed startButton_Click() method is indicated below.
g. Here is what happens when this new code is executed.
i. The first new line specifies a variable (strTotal) and assigns an initial phrase
to it.
ii. The next new line specifies a variable (dblUnitPrice) containing the price per
ticket, which in this case is $50.
iii. After the name is read from the form the next new line specifies a variable
(strNumber) and assigns it the value of the Text property from the numberBox
control.
iv. The line after that specifies a variable that will hold the number of tickets
requested, but no value is assigned yet. (Notice that the type of data
contained in this variable is “double”, which we will discuss later along with
other datatypes.)
v. After that is an example of the jumping construct. The code calls for the
TryParse() method (an external program) to convert the text (i.e., string data)
in strNumber to numeric and store it in the dblNumber variable.
vi. The next new line specifies a variable (dblTotalPrice), calculates the result of
multiplying the number of tickets (dblNumber) by the price per ticket
(dblPrice), and assigns the result to be the value for dblTotalPrice.
vii. After that, the computer is instructed to
1. Convert the value of dblTotalPrice (which has a numeric datatype) to
a string value,
2. Concatenate (i.e., append) that to the value of strTotal, and
3. Use that combined value to replace the initial value of strTotal.
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 16
4. Again, the jumping construct is used, this time when the ToString()
method is called; the “c2” tells the computer to format the converted
value to a standard currency format.
viii. Finally, the last line assigns the value of strTotal to the Text property of the
total cost label (costLabel), which causes the total cost of the tickets to be
displayed.
You may or may not have found this example to be challenging. Regardless, you should at least
have an idea of what programming is, as well as how the app development process works. In the
chapters that follow we will address all of the above in more detail and we will work with more
realistic (and challenging) examples. Therefore, if you are like most people and do not understand
all of what we have just done, take heart. These things are about to be explained. On the other
hand, if you have grasped everything addressed so far, you can also be encouraged by the fact
that we will be working with apps that go well beyond this one.
Summary
By now you should have a basic understanding of what is meant by programming (aka coding). It is just
writing instructions for a computer to follow and doing so in a manner that computer can understand
those instructions. Of course, just writing code is only part of programming, as it is necessary to
understand the problem being addressed with the application we are developing. The application
development procedure can then be summarized by the following outline, which will serve as our model
throughout this book.
Identify user requirements (i.e., understand the problem)
Determine
o Outputs desired
o Inputs available
o Processing needed to convert inputs to outputs
Develop the user interface
o Design it (specify objects needed)
o Build it (e.g., using VS)
Develop the code
o Summarize the processing in plain English (or Chinese or French or . . . )
o Write the code corresponding to that processing
Test the app, revise, and repeat as appropriate
If you will look back over the discussion of the Treasure Island example, you should recognize that we
have essentially followed that procedure. Of course, this model is not intended to be rigid, so we will
deviate from the model from time to time as appropriate.
Now you may be thinking at this point, “OK, so I can see the basic idea about creating apps for a traditional
computer, but I am really more interested in building apps for phones or websites.” Well, do not go away
yet, as we will look at how we would do the same things for mobile and/or web apps.
Programming Fundamentals Using Visual C#.Net: A Business Context©
©John Seydel 2017 Getting Started, Page 17