5.1 Relational and Logical Operators 192 Relational Operators ...

1 FINAL CHAPTER Web Applications WEB PROGRAMS The programs in this chapter require the use of either Visual Web Developer 2010 (packaged with this textbook) or the complete version of Visual Studio 2010. We assume that you are using one of these two software products. 2

CREATING A WEB PROGRAM Click on New Web Site in the File menu. Select Visual Basic in the left pane. Select ASP.NET Web Site in the middle pane. Select File System as the Web location. Give a name and path for the program. Click on the OK button. 3 CREATING A WEB PROGRAM (CONTINUED)

enter name click on OK 4 WEB PAGE (VWD EQUIVALENT OF THE FORM DESIGNER) Web page tab Main Content region 5 WEB PAGE TAB The Web page tab is titled Default.aspx

instead of Form1. vb [Design] The Web page is referred to as Default.aspx in the Solution Explorer window 6 TOOLBOX The common controls, such as button, text box, and list box are contained in the Standard group of the Toolbox. 7

DESIGNING THE WEB PAGE Begin by clearing the Main Content region Permanent text (called static text) can be typed into the page and formatted directly without the use of labels Text boxes and buttons can be placed at the cursor position (called the insertion point) by

double-clicking on them in the Toolbox 8 SAMPLE WEB PAGE 9 PROPERTIES WINDOW The name of a control is specified by the ID property instead of the Name property 10

CODE EDITOR The Code Editor tab reads Default.aspx.vb instead of Form1.vb The code in the editor is referred to as the code behind. 11 SUMMARY THUS FAR

12 SAMPLE CODE Protected Sub btnCalculate_Click(...) Handles _ btnCalculate.Click Dim cost As Double = CDbl(txtCost.Text) Dim percent As Double = CDbl(txtPercent.Text) / 100 txtTip.Text = FormatCurrency(percent * cost) End Sub Notice that Sub is proceeded by Protected instead of Private. 13

RUNNING A PROGRAM Press Ctrl+F5 to run program without debugging Program runs in the computers Web browser To terminate the program, close the browser by clicking on , the Close button

Close program by clicking on Close Project in the File menu. 14 A RUN OF THE SAMPLE PROGRAM 15 TABLES A table control can be used to improve the

layout of a Web page Tables are created with the Insert Table command from the Table menu in the Toolbar 16 SAMPLE TABLE cell This table has 5 rows and 2 columns. Each subdivision is called a cell.

17 CELLS Text and controls can be placed into cells The alignment (such as right, left, or center) of the contents of a cell can be specified with the Align property from the Properties window

Commands from the Table menu allow you to insert and delete rows and columns, and to merge cells 18 MANAGING TABLES Assorted arrows can be used to highlight groups of cells and resize tables Dragging of the cursor also can be used to

highlight groups of cells 19 TEXT FILES Normally placed in the Solution Explorers App_Data folder A text file can be read into an array with a statement of the form

Dim strArrayName() As String = IO.File.ReadAllLines(MapPath("App_Data\" & filename)) 20 HOW TO OPEN AN EXISTING WEB PROGRAM first click here Then navigate to the programs folder and click on the Open button.

21 HOW TO ADD AN ADDITIONAL WEB PAGE TO A PROGRAM Click on an existing Web page to make sure it has the focus Click on Add New Item in the Website menu. (An Add New Item dialog box will appear.)

Select Web Form in the center pane, type a name into the Name box, and click on the Add button. 22 HOW TO ADD AN ADDITIONAL WEB PAGE TO A PROGRAM (CONT.) select change

name click on Add button 23 HYPERLINK CONTROL Found in the General group of the Toolbox Appears on a page as underlined text

Used to navigate to another page NavigateUrl property specifies the page to navigate to 24 SAMPLE WEB PAGE hyperlink control

25 VALIDATION CONTROLS Used to validate user input The RequiredFieldValidator control checks that data has been entered into a text box or that an item of a list box has been selected

The RangeValidator control checks that the entry in a text box falls within a specified range of values. 26 SAMPLE WEB PAGE RequiredFieldValidator RangeValidator Validation controls are not visible at run time. Only appear when input is missing or invalid.

27 REQUIREDFIELDVALIDATOR CONTROL The key properties are ControlToVerify and ErrorMessage The ErrorMessage setting is the text that appears when input into the specified control does not meet the given criteria

28 RANGEVALIDATOR CONTROL The key properties are ControlToVerify, ErrorMessage, Type, MinimumValue, and MaximumValue Possible settings for Type are String, Integer, Double, Date, and Currency

The entry in the text box must lie between the MinimumValue and the MaximumValue 29 POSTBACK A postback occurs when the contents of a Web page are sent to the server for processing. Afterwards, the server sends a new page back to the browser

When a validation control is triggered, the matter is handled entirely by the browserno postback occurs 30 PROGRAMMING MODEL THE PAGE LOAD EVENT Raised when a Web page is first loaded and

every time it is reloaded after a postback The IsPostBack property can be used to guarantee that the page load event is raised only once if Not Page.IsPostBack Then End if 32 CLASS-LEVEL VARIABLES

In VWD, class-level variables are of limited value since they do not retain their values after postbacks Devices known as cookies or session variables can be used to retain values 33 RADIOBUTTONLIST CONTROL rblAges

rfvAge VWD does not have a group box control. The radio-button list control is the counterpart of the 34 VB group box containing a set of radio buttons. RADIOBUTTONLIST CONTROL (CONTINUED) The radio-button list control is populated via a ListItem Collection Editor that is invoked from the Tasks button In the previous slide, the control rfvAge, a RequiredFieldValidator, guarantees that a radio button has been selected before the

button is clicked on. 35 CHECK BOX CONTROL Example 5 of Section 4.4. In regular VB clicking on a check-box can cause code to run

VWD does not do this To convert this VB program to a VWD program, the AutoPostBack property of each check box must be set to True 36 38 REVIEW Chapter 1

COMMUNICATING WITH THE COMPUTER Machine language low level, hard for humans to understand Visual Basic high level, understood by humans, consists of instructions such as Click, If, Do Usable in other applications (Word, Excel) 39

COMPUTERS AND COMPLICATED TASKS Tasks are broken down into instructions that can be expressed by a computer language A program is a sequence of instructions Programs can be only a few instructions or millions of lines of instructions 40 PERFORMING A TASK ON THE COMPUTER Determine Output

Identify Input Determine process necessary to turn given Input into desired Output 41 PROBLEM-SOLVING: APPROACH LIKE ALGEBRA CLASS How fast is a car traveling if it goes 50 miles in 2 hours? Output: Input: Process:

42 PROGRAM DEVELOPMENT CYCLE 1. 2. 3. 4. 5. 6. Analyze: Define the problem. Design: Plan the solution to the problem.

Choose the interface: Select the objects (text boxes, buttons, etc.). Code: Translate the algorithm into a programming language. Test and debug: Locate and remove any errors in the program. Complete the documentation: Organize all the materials that describe the program. 43 PROGRAMMING TOOLS

Three tools are used to convert algorithms into computer programs: Flowchart - Graphically depicts the logical steps to carry out a task and shows how the steps relate to each other Pseudocode - Uses English-like phrases with some Visual Basic terms to outline the program

Hierarchy chart - Shows how the different parts of a program relate to each other 44 FLOWCHART EXAMPLE Chapter 1 45 PSEUDOCODE EXAMPLE Determine the proper number of stamps for a letter

Read Sheets (input) Set the number of stamps to Sheets / 5 (processing) Round the number of stamps up to the next whole number (processing) Display the number of stamps (output) 46 HIERARCHY CHARTS EXAMPLE Chapter 1 47 DECISION FLOW CHART

Chapter 1 48 LOOPING FLOW CHART 49 50 REVIEW Chapter 2&3 CONTROL NAME PREFIXES Control

Prefix Example button btn btnCompute label lbl

lblAddress text box txt txtAddress list box lst lstOutput Chapter 2

51 EVENT An event is an action, such as the user clicking on a button Usually, nothing happens in a Visual Basic program until the user does something and generates an event. What happens is determined by statements. 52 THREE TYPES OF ERRORS

Syntax error Run-time error Logic error 53 SOME TYPES OF SYNTAX ERRORS Misspellings lstBox.Itms.Add(3) Omissions lstBox.Items.Add(2 + ) Incorrect punctuation Dim m; n As Integer

Displayed as blue underline in VS 54 SYNTAX ERROR The following is NOT a valid way to test if n falls between 2 and 5: (2 < n < 5 ) 55 A TYPE OF RUN-TIME ERROR Dim numVar As Integer = 1000000 numVar = numVar * numVar

Whats wrong with the above? 56 A LOGICAL ERROR Dim average As Double Dim m As Double = 5 Dim n As Double = 10 average = m + n / 2 Whats wrong with the above? Value of average will be 10. Should be 7.5. 57 COMMON ERROR IN BOOLEAN

EXPRESSIONS A common error is to replace the condition Not ( 2 < 3 ) with the condition ( 2 > 3 ) 58 DATA CONVERSION Because the contents of a text box is always a string, sometimes you must convert the input or output.

dblVar = CDbl(txtBox.Text) Converts a String to a Double txtBox.Text = CStr(numVar) 59 Converts a number to a string STRING PROPERTIES AND METHODS "Visual".ToUpper is VISUAL. .ToUpper makes everything upper case. Varname = blah Varname.ToUpper BLAH

60 STRING PROPERTIES AND METHODS "a" & " bcd ".Trim & "efg" is abcdefg .trim removes leading/trailing spaces Varname = Varname.trim blah blah 61

SUBSTRING METHOD Let str be a string. str.Substring(m, n) is the substring of length n, beginning at position m in str. Visual Basic.Substring(2, 3) is sua Visual Basic.Substring(0, 1) is V 62 CHR FUNCTION For n between 0 and 255, Chr(n) is the string consisting of the character with

ASCII value n. EXAMPLES: Chr(65) is "A" Chr(162) is "" 63 ASC FUNCTION For a string str, Asc(str) is ASCII value of the first character of str. EXAMPLES: Asc("A") is 65 Asc("25") is 162 64

SCOPE The scope of a variable is the portion of the program that can refer to it Variables declared inside an event procedure are said to have local scope and are only available in the event procedure in which they are declared 65

SCOPE Variables declared outside an event procedure are said to have class-level scope and are available to every event procedure Usually declared after Public Class formName (Declarations section of Code Editor.) 66

67 REVIEW Chapter 4 LOGICAL OPERATORS Used with Boolean expressions Not makes a False expression True and vice versa

And will yield a True if and only if both expressions are True Or will yield a True if at least one of both expressions are True 68 EXAMPLE 4.3 n = 4, answ = Y Are the following expressions true or false?

1) 2) 3) 4) Not (n < 6) (answ = "Y") Or (answ = "y") (answ = "Y") And (answ = "y") Not(answ = "y") 69 IF BLOCK The program will take a course of action based on whether a condition is true.

If condition Then action1 Else action2 End If Will be executed if condition is true Will be executed if condition is false 70 ANOTHER EXAMPLE IF BLOCK If condition Then

action1 End If Statement2 Statement3 Regardless of whether the condition in the If statement is true or alse, these statements will be executed 71 PSEUDOCODE AND FLOWCHART

Chapter 4 - VB 2008 by Schneider 72 ELSEIF CLAUSE If condition1 Then action1 ElseIf condition2 Then action2 ElseIf condition3 Then action3 Else action4 End If 73

SELECT CASE SYNTAX The general form of the Select Case block is Select Case selector Case valueList1 action1 Case valueList2 action2 Case Else action of last resort End Select 74 CASE

75 FLOWCHART FOR SELECT CASE (not in book, but equivalent) 76 77 REVIEW Chapter 5

DEVICES FOR MODULARITY Visual Basic has two devices for breaking problems into smaller pieces: Sub procedures Function procedures 78 SUB PROCEDURES Perform one or more related tasks General syntax

Sub ProcedureName() statements End Sub 79 ARGUMENTS AND PARAMETERS Sum(2, 3) arguments parameters Sub Sum(ByVal num1 As Double, ByVal num2 As Double)

displayed automatically 80 FUNCTION PROCEDURES Function procedures (aka user-defined functions) always return one value Syntax: Function FunctionName(ByVal var1 As Type1, _ ByVal var2 As Type2, _ ) As dataType statement(s)

Return expression End Function 81 FUNCTIONS VS. PROCEDURES Both can perform similar tasks Both can call other subs and functions Use a function when you want to return one and only one value 82

EXAMPLE: NUM Public Sub btnOne_Click (...) Handles _ btnOne.Click Dim num As Double = 4 Triple(num) txtBox.Text = CStr(num) End Sub Sub Triple(ByVal num As Double) num = 3 * num End Sub Output: 4 83 EXAMPLE Public Sub btnOne_Click (...) Handles _

btnOne.Click Dim num As Double = 4 Triple(num) txtBox.Text = CStr(num) End Sub Sub Triple(ByRef num As Double) num = 3 * num End Sub Output: 12 84 85 REVIEW Chapter 6

DO LOOP SYNTAX Do While condition statement(s) Loop Condition is tested, If it is true, the loop is run. If it is false, the statements following the Loop statement are executed.

These statements are inside the body of the loop and are run if the condition above is true. 86 POST TEST LOOP Do statement(s) Loop Until condition Loop is executed once and then the condition is tested. If it is false, the loop is run again.

If it is frue, the statements following the Loop statement are executed. 87 WHATS THE DIFF? Do statement(s) Loop Until condition Whats the difference between a Do Until

Do While condition statement(s) Loop and Do While? 88 PSEUDOCODE AND FLOWCHART 89 EXAMPLE 1: DISPLAY THE

TOTAL CONTENTS OF A FILE Dim sr As IO.StreamReader = _ IO.File.OpenText("PHONE.TXT") lstNumbers.Items.Clear() Do While sr.Peek <> -1 name = sr.ReadLine phoneNum = sr.ReadLine lstNumbers.Items.Add(name & " " _ & phoneNum) Loop sr.Close() 90 FORNEXT LOOP SYNTAX

Chapter 6 91 EXAMPLE 2 Control variable Data type Start value

Stop value Amount to add to i For i As Integer = 0 To n Step s lstValues.Items.Add(i) Next 92 COMMENTS

The value of the control variable should not be altered within the body of the loop (For ... Next). To skip an iteration in a For .. Next loop: Continue For To skip an iteration in a Do .. While loop: Continue Do 93

COMMENTS For i As Integer = 1 To 5 (some statements) Continue For (some statements) Next What will happen? 94 COMMENTS To break out of a For .. Next loop: Exit For To break out of a Do .. While loop:

Exit Do 95 96 REVIEW Chapter 7 SIMPLE AND ARRAY VARIABLES A variable (or simple variable) is a name to which Visual Basic can assign a single value

An array variable is a collection of simple variables of the same type to which Visual Basic can efficiently assign a list of values 97 INITIALIZING ARRAYS Arrays may be initialized when they are created:

Dim arrayName() As varType = {value0, _ value1, value2, ..., valueN} For Ex: Dim Students() As String = {"Jack", "John", "Julie", "Jimmy", "Janet"} 98 INITIALIZING ARRAYS Arrays may be initialized when they are created:

Dim arrayName() As varType = IO.File.ReadAllLines(filespec) Opens filespec, reads all lines from it, and stores it in arrayName Each line in filespec is stored in one location of arrayName 99 EXAMPLE Dim Grades() As integer = {70, 75, 80, 85, 90} Grades.Average 80 Grades.Count 5 Grades.Min 70

Grades.Max 90 Grades.Sum 400 100 PRESERVE KEYWORD ReDim arrayName(m) resets all values to their default. This can be prevented with the keyword Preserve. ReDim Preserve arrayName(m) resizes the array and retains as many values as possible.

101 SET OPERATIONS Concat Contains elements of array1 and array2 Duplication is OK Dim States1() As String = {"A", "B", "C", "D"} Dim States2() As String = {"E", "F", "G", "H"} Dim States3() As String = _ States1.Concat(States2).ToArray()

102 SET OPERATIONS Union Contains elements of array1 and array2 No Duplication Dim States1() As String = {"A", "B", "C", "D"} Dim States2() As String = {"E", "F", "G", "H"} Dim States3() As String = _ States1.Union(States2).ToArray()

103 SET OPERATIONS Intersect Contains elements from array1 and array2 which exist in both array1 and array2 Dim States1() As String = {"A", "B", "C", "D"} Dim States2() As String = {"E", "F", "G", "H"} Dim States3() As String = _ States1.Intersect(States2).ToArray()

104 SET OPERATIONS Except Contains elements from array1 which do not exist in array2 Dim States1() As String = {"A", "B", "C", "D"} Dim States2() As String = {"E", "F", "G", "H"} Dim States3() As String = _

States1.Except(States2).ToArray() 105 STRUCTURES A way of grouping heterogeneous data together Also called a UDT (User Defined Type) Sample structure definition: Structure College Dim name As String Dim state As String Dim yearFounded As Integer

End Structure 106 EXAMPLE 4 Structure FullName Dim firstName As String Dim lastName As String End Structure Structure Student Dim name As FullName Dim credits() As Integer End Structure Structure "FullName"

contained, or nested, inside Student 107 SORTING Sorting is an algorithm for ordering an array. We discuss two sorting algorithms: bubble sort

Shell sort Both use the swap algorithm: temp = varl varl = var2 var2 = temp 108 BUBBLE SORT ALGORITHM: N ITEMS 1. 2. 3.

4. 5. 6. Compare the first and second items. If they are out of order, swap them. Compare the second and third items. If they are out of order, swap them. Repeat this pattern for all remaining pairs. The final comparison and possible swap are between the next-to-last and last items. The last item will be at its proper place. Do another pass through first n 1 items. Repeat this process with one less item for each pass until a pass uses only the first

and second items. 109 SHELL SORT ALGORITHM 1. 2. 3. 4. 5. Begin with a gap of g = Int(n/2) Compare items 0 and g, 1 and 1 + g, . . ., n - g and n. Swap any pairs that

are out of order. Repeat Step 2 until no swaps are made for gap g. Halve the value of g. Repeat Steps 2, 3, and 4 until the value of g is 0. 110 REVIEW Efficiency of Bubble and Shell Sorts Array Elements Bubble Sort Comparisons

Shell Sort Comparisons 5 10 17 10 45 57

15 105 115 20 190 192 25 300

302 30 435 364 50 1225 926

100 4950 2638 500 124,750 22,517 1000 499,500

58,460 REVIEW Efficiency of Sequential and Binary Search Array Elements Sequential Search Comparisons Binary Search Comparisons

2000 1000 (Average) 11 (At most) 113 REVIEW Chapter 8 REVIEW name = input.Substring(0, (input.IndexOf(",")))

Input = James,88 0 1 2 3 4 5 6

7 J a m e s ,

8 8 WRITEALLLINES IO.File.WriteAllLines _ ("fileName.txt", States) Creates a new text file Copies the contents of a string array Places one element on each line Close the file

115 REALALLLINES Read all the lines of a text-file into an array Method opens a file Reads each line of the file Adds each line as an element of a string array

Closes the file A line is defined as a sequence of characters followed carriage return a line feed a carriage return followed by a line feed 116 DELETING INFORMATION FROM A SEQUENTIAL FILE

An individual item of a file cannot be changed or deleted directly. A new file must be created by reading each item from the original file and recording it, with the single item changed or deleted, into the new file. The old file is then erased, and the new file renamed with the name of the original file. 117 DELETE AND MOVE METHODS

Delete method: IO.File.Delete(filespec) Move method (to change the filespec of a file): IO.File.Move(oldfilespec, newfilespec) Note: The IO.File.Delete and IO.File.Move methods cannot be used with open files.

118 STRUCTURED EXCEPTION HANDLING Two types of problems in code: Bugs (logic error) something wrong with the code the programmer has written Exceptions errors beyond the control of the programmer Programmer can use the debugger to find

bugs; but must anticipate exceptions in order to be able to keep the program from terminating abruptly. 119 TRY CATCH BLOCK SYNTAX Try normal code Catch exc1 As FirstException exception-handling code for FirstException Catch exc2 As SecondException exception-handling code for SecondException . .

Catch exception-handling code for any remaining exceptions Finally clean-up code End Try 120 CATCH BLOCKS Visual Basic allows Try-Catch-Finally blocks to have one or more specialized Catch clauses that only trap a specific type of

exception The general form of a specialized Catch clause is Catch exp As ExceptionName where the variable exp will be assigned the name of the exception. The code in this block will be executed only when the specified exception occurs.

121 WORKING WITH HASHTABLE Arrays can store only one data type collections can hold any objects Accessing the element is very simple and very fast

Removing the element in Collection is very simple 122 WORKING WITH HASHTABLE Array: MyArray(100) returns element 100

What if I want element George? Hashtable MyHash.Item(George) 123 WORKING WITH HASHTABLE Adding an element to the HashTable

{hash table object}.Add(Key as Object, value as Object) Ex: MyHash.Add(George, 45) 124 WORKING WITH HASHTABLE

Accessing an element {hash table object}.Item({key}) Ex: MyArray.Item(George) 125 WORKING WITH HASHTABLE Searching for an element {hash table object}.Contains({key}) Ex: MyArray.Contains(George)

126 127 REVIEW Chapter 9 LIST BOX EVENTS Three main types of events with list boxes: 1. Click the user clicks on an item in the list box 2. SelectedIndexChanged - the user clicks

on an item or uses the arrow keys to select it 3. DoubleClick - the user double-clicks on an item All three events are triggered when the user double-clicks on an item. 128 USING AN ARRAY TO FILL A LIST BOX The statement lstBox.DataSource = arrayName

fills the list box with the elements of the array. 129 THE GROUP BOX CONTROL Group boxes are passive objects used to group other objects together When you drag a group box, the attached controls follow as a unit

To attach a control to a group box, create the group box, then drag the control you want to attach into the group box. 130 THE CHECK BOX CONTROL Consists of a small square and a caption Presents

the user with a Yes/No choice During run time, clicking on the check box toggles the appearance of a check mark Checked property is True when the check box is checked and False when it is not CheckedChanged

event is triggered when the user clicks on the check box 131 THE RADIO BUTTON CONTROL Consists of a small circle with a caption (that is set by the Text property) Normally several radio buttons are attached to a group box

Gives the user a single choice from several options Clicking on one radio button removes the selection from another 132 THE TIMER CONTROL Invisible

during run time Triggers an event after a specified period of time The Interval property specifies the time period measured in milliseconds To begin timing, set the Enabled property to True

To stop timing, set the Enabled property to False The event triggered each time Timer1.Interval elapses is called Timer1.Tick 133 SCROLL BAR PROPERTIES The main properties of a scroll bar

control are Minimum Maximum Value SmallChange, LargeChange hsbBar.Value, a number between hsbBar.Minimum and hsbBar.Maximum, gives the location of the scroll box, 134

THE CLIPBOARD OBJECT Used to copy information from one place to another Maintained by Windows, so it can even be used with programs outside Visual Basic A portion of memory that has no properties or events

135 THE RANDOM CLASS A random number generator declared with the statement: Dim randomNum As New Random() If m and n are whole numbers and m < n then the following generates a whole number between m and n (including m, but excluding

n) randomNum.Next(m, n) 136 THE MENUSTRIP CONTROL Used to create menus like the following: Top-level menu Second-level menu 137 MENU EVENTS

Each menu item responds to the Click event Click event is triggered by the mouse Alt + access key Shortcut key 138 MULTIPLE FORMS

Visual Basic programs can contain more than one form To add the new form, select Add Windows Form from the Project menu, to invoke the Add New Items dialog box. 139 VARIABLES AND MULTIPLE FORMS

Variables declared in the Declarations section of a form with Public, instead of Dim, will be available to all forms in the program When a Public variable is used in another form, it is referred to by an expression such as secondForm.variableName 140 141

REVIEW Chapter 10 WHAT IS A DATABASE? A database (DB) is a very large, integrated, permanent collection of data Models real-world Entities (e.g., students, courses)

Relationships (e.g., Madonna is taking CMPT354) Example databases: Customer Transactions Human Genome Online Bookstore . . .

DATABASE TERMINOLOGY A table is a rectangular array of data Each column of the table, called a field, contains the same type of information Each row, called a record, contains all the information about one entry in the database

143 CONNECTING WITH A DATATABLE Dim dt As New DataTable() Dim connStr As String = _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=MEGACITIES.MDB" Dim sqlStr As String = "SELECT * FROM Cities" Dim dataAdapter As New _ OleDb.OleDbDataAdapter(sqlStr, connStr) dataAdapter.Fill(dt) dataAdapter.Dispose() 144

(Boilerplate to be inserted into every program in chapter.) PRIMARY KEYS A primary key is used to uniquely identify each record Databases of student enrollments in a college usually use a field of Social Security numbers as the primary key

Why wouldn't names be a good choice as a primary key? 145 TWO OR MORE TABLES When a database contains two or more tables, the tables are usually related For instance, the two tables Cities and

Countries are related by their country field Notice that every entry in Cities.country appears uniquely in Countries.country and Countries.country is a primary key 146 We say that Cities.country is a foreign key of Countries.country

SQL Structured Query Language developed for use with relational databases Very powerful language Allows for the request of specified information from a database

Allows displaying of information from database in a specific format 147 VIRTUAL TABLES SQL statements create a new virtual table from existing tables SELECT city, pop2015 FROM Cities WHERE pop2015>=20

Results in virtual table city pop2015 Bombay 22.6 Delhi 20.9 Mexico City 20.6 Sao Paulo 20.0 Tokyo 36.2 148

149 REVIEW Chapter 11 WHAT IS OBJECT ORIENTED PROGRAMMING? An object is like a black box. The internal details are hidden.

Identifying objects and assigning responsibilities to these objects. Objects communicate to other objects by sending messages. Messages are received by the methods of an object 150 OOP ANALOGY Classes noun A word used to denote or

name a person, place, thing, quality, or act. Methods verb That part of speech that expresses existence, action, or occurrence. Properties adjective Any of a class of words used to modify a noun or other substantive by limiting, qualifying, or specifying.

151 GET AND SET Private m_name As String Property block Public Property Name() As String Get Return m_name End Get Set(ByVal value As String) m_name = value End Set

End Property 152 STUDENT CLASS: WRITEONLY PROPERTY BLOCKS Public WriteOnly Property Midterm() As Double Set(ByVal value As String) m_midterm = value End Set End Property Public WriteOnly Property Final() As Double Set(ByVal value As String) m_final = value End Set End Property

153 STUDENT CLASS: METHOD Function CalcSemGrade() As String Dim grade As Double grade = (m_midterm + m_final) / 2 grade = Math.Round(grade) Select Case grade Case Is >= 90 Return "A" Case Is >= 80 Return "B" : End Function

154 STEPS USED TO CREATE A CLASS 1. Identify a thing in your program that is to become an object 2. Determine the properties and methods that you would like the object to have. (As a rule of thumb, properties should access data, and methods should perform operations.)

3. A class will serve as a template for the object. The code for the class is placed in a class block of the form Class ClassName statements End Class 155 STEPS CONTINUED 4. For each of the properties in Step 2, declare

a private member variable with a statement of the form Private m_variableName As DataType 5. For each of the member variables in Step 4, create a Property block with Get and/or Set procedures to retrieve and assign values of the variable. 6. For each method in Step 2, create a Sub procedure or Function procedure to carry

out the task. 156 EVENTS User-defined events can be created for classes. The statement for triggering an event is located in the class block

The event is dealt with in the forms code. 157 USER DEFINED EVENT Suppose that the event is named UserDefinedEvent and has the parameters par1, par2, and so on. In the class block, place the following statement in

the Declarations section Public Event UserDefinedEvent(ByVal par1 As _ DataType1, ByVal par2 As DataType2, ...) The next statement should be placed at the locations in the class block code at which the event should be triggered RaiseEvent UserDefinedEvent(arg1, arg2, ...) 158 RESPONDING TO EVENTS

When declaring an object variable, the keyword WithEvents must be added so that the object will respond to events: Dim WithEvents object1 As ClassName The declaration line of an event procedure would be Private Sub object1_UserDefinedEvent(ByVal par1 As _ DataType1, ...) Handles object1.UserDefinedEvent 159

CONTAINMENT Class A contains class B when a member variable of class A is an object of type class B. Class DeckOfCards Private m_deck(51) As Card 'Class DeckOfCards contains class Card 160 INHERITANCE HIERARCHY

GrandChild1 has access to Property A, Sub B, and Event C from its parent and adds Function E and Sub F 161 OVERRIDABLE The keyword Overridable is used to designate the parents methods that are overridden, and the keyword Overrides is used to designate the

childs methods that are doing the overriding There are situations where a child class's needs to access the parent classs implementation of a method that the child is overriding. Visual Basic provides the keyword MyBase to support this functionality 162 MUSTOVERRIDE

Sometimes you want to insist that each child of a class have a certain property or method that it must implement for its own use Such a property or method is said to be abstract and is declared with the keyword MustOverride 163

Good luck!

Recently Viewed Presentations

  • Integrating Mindfulness Concepts Ricardo Horn, LMSW Agenda  Introduction

    Integrating Mindfulness Concepts Ricardo Horn, LMSW Agenda Introduction

    Defining Mindfulness. Bare Attention - "Pay precise attention, moment by moment, to exactly what you are experiencing, right now, separating out your reactions from the raw sensory events."
  • Life Science

    Life Science

    Arial Arial Black Times New Roman Wingdings Glass Layers Life Science The Cell Theory Types of Microscopes Parts of a Microscope Robert Hooke's Work Leeuwenhoek's Work Parts of a typical animal cell Parts of a typical animal cell Parts of...
  • Object Oriented Programming (OOP)

    Object Oriented Programming (OOP)

    Classes and Objects. Inheritance. Polymorphism. Classes and Objects. class Dog {String name; ... lass Fish extends Animal { } c. lass Frog extends Animal { } c. ... Object Oriented Programming (OOP) Last modified by: rinchen
  • WELCOME [www.governor.wa.gov]

    WELCOME [www.governor.wa.gov]

    Defining & Measuring Success "Economic success is foundational and entails many of the traditional measures of poverty, including income and assets.However, it is not enough. Equally important are . power and autonomy, which speak to individual agency, having a sense...
  • Chapter 1

    Chapter 1

    Bölüm 4 Sözcüksel(Lexical) ve Sentaks Analiz
  • Singular Value Decomposition in Digital Signal Processing

    Singular Value Decomposition in Digital Signal Processing

    Singular Value Decomposition in Digital Signal Processing By Tin Sheen Signals Flow of information Measured quantity that varies with time (or position) Electrical signal received from a transducer (microphone, thermometer, accelerometer, antenna, etc.) Electrical signal that controls a process SVD...
  • Information Security in Today&#x27;s World

    Information Security in Today's World

    Information Security in Today's World ... Desktop tools Alternative Web browsers Media applications Microsoft Office applications Latest Trends - Ransomware Type of malware that encrypts the victim's data, demanding ransom for its restoration Cryptovirology predates ransomware Latest Trends ...
  • Univariate Visualization CMSC 120: Visualizing Information 2/21/08 Types

    Univariate Visualization CMSC 120: Visualizing Information 2/21/08 Types

    Tahoma Arial Gill Sans MT Wingdings 2 Verdana Calibri Wingdings Solstice 1_Solstice 2_Solstice 3_Solstice 4_Solstice 5_Solstice 6_Solstice 7_Solstice 8_Solstice Microsoft Office Excel Chart SigmaPlot 10.0 Graph Univariate Visualization Types of Data Univariate Data Weather Conditions: 2/17/08 Univariate Data The Raw...