The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

'Coding' or 'Programming' for you probably mean 'software engineering' - i.e. the science of building software applications. Persons new to the field often confuse knowledge of a specific programming language (e.g. Java, C++, PHP, Python) with the skill of software engineering. A programming language is a simply a means of achieving the goal of building an application. This course can help you design and develop these systems via the .Net technologies.

This course aims to introduce students to the basic concepts of Visual Programming. In this course the students will be involved in the development of graphical user interfaces (GUI), designing complete windows applications, creating and using custom controls, developing web database applications, learning some of the new and more advanced programming concepts introduced in Visual Basic (VB) and the .NET framework. The skills that you gain from this course can be applied at daily life and your tomorrow workplace to solve related programming problems or for setting up your own software-based business.

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Choo Jun Tan, 2021-01-01 11:31:15

Visual Programming

'Coding' or 'Programming' for you probably mean 'software engineering' - i.e. the science of building software applications. Persons new to the field often confuse knowledge of a specific programming language (e.g. Java, C++, PHP, Python) with the skill of software engineering. A programming language is a simply a means of achieving the goal of building an application. This course can help you design and develop these systems via the .Net technologies.

This course aims to introduce students to the basic concepts of Visual Programming. In this course the students will be involved in the development of graphical user interfaces (GUI), designing complete windows applications, creating and using custom controls, developing web database applications, learning some of the new and more advanced programming concepts introduced in Visual Basic (VB) and the .NET framework. The skills that you gain from this course can be applied at daily life and your tomorrow workplace to solve related programming problems or for setting up your own software-based business.

Keywords: Wawasan Open University

13: Set(ByVal Value As String)
14: student = Value
15: End Set
16: End Property
17: End Class

10.6 Inheritance

Inheritance involves ’making a new class based on an existing class’. The new class will inherit the
members of an existing class. The existing class is called the ’base class’, and the new class is called
the ’derived class’. Sometimes we refer the base class as a ’superclass’, and the derived class as a
subclass’. Three types of access modifier for protecting members: Public, Private, and Protected. VB
class directly or indirectly inherits Object’s method.

10.7 Method overloading

Creating a multiple methods in a class with same name, but different parameters and types is called
as method overloading.

10.8 Encapsulation

We use it without understanding the details of how it works. It is also known as ’data-hiding’.
Types of encapsulation:

i. Public: Members are accessible wherever the program has a reference to an object of that
class or one of its derived classes.

ii. Private: Members are accessible only within the class itself. A base class’s Private members
are not inherited by its derived classes.

iii. Protected: Members can be accessed only by members of that base class and by members of
its derived class.

201

Note that keyword Dim (old version) is replaced by Private in an instance variable declaration. There
is a list of good practice as follows.

i. Good practice: Instance variables should be declared Private.
ii. Good practice: Methods and properties should be declared Public.
You may examine these practice in VB code of CommissionEmployee, as available at GitHub.

10.9 Polymorphism

It allows developer to write programs that process objects which share the same base class in a class
hierarchy. In other words, objects of different type are used to respond differently to the same message
(method). For example, sending a ’move’ message to instances of Fish and Bird. Each instance has
its own ’move’ method to implement the move operation for animals. As a result, program issues the
same move method to each animal object generically, but each object knows the appropriate type of
movement.

In another example, examine the VB code in project Polymorphism, which demonstrate polymorphic
behaviour. It use a base class reference to manipulate both the base class objects (i.e. Commis-
sionEmployee) and the derived class objects (i.e. BasePlusCommissionEmployee) polymorphically.
Note that the class BasePlusCommissionEmployee is inherited from the class CommissionEmployee.
In other words, a BasePlusCommissionEmployee object is a CommissionEmployee because it is in-
herited from the class CommissionEmployee. The baseSalaryValue is an instance variable of the
class BasePlusCommissionEmployee.

202

BasePlusCommissionEmployee inherits the Public instance variable and the methods of class Com-
missionEmployee, i.e. Constructor, Public methods and properties such as earning() and ToSting().
Class BasePlusCommissionEmployee does not need to re-declare the base class instance variable
because these are present in the derived class through inheritance. Class CommissionEmployee is a
base class, and class BasePlusCommissionEmployee is a derived class.
In class PolymorphismTest, it shows three ways to use the base class and the derived class variables
to store reference to base class and derived class objects as follows.

i. Assigning a base class reference to a base class variable.
ii. Assigning a derived class reference to a derived class variable.
iii. Assigning a derived class reference to a base class variable.
We the first two ways in inheritance, and the third is to establish an ’is-a’ relationship between the
derived class and the base class.

10.10 Method overriding

Sometimes, it is necessary for the subclass to modify the methods defined in the superclass.

10.11 Interfaces

An interface describes a set of methods that can be called on an object, to tell the object to perform
some tasks or return some piece of information. An interface declaration begins with the keyword
Interface and can contain abstract methods and properties. It cannot contain instance variables,
concrete methods or concrete properties. All members declared in an interface are implicitly Public
and may not specify an access modifier. In order to use an interface, a concrete class must implement
the interface. The keyword Implements indicates interface.

203

10.12 Summary

In this section, you learnt how to declare a class with a method and instantiate an object of a class
and the way to declare a method with a parameter. You also picked up the way to initialise objects
with constructors as well as how to implement an inheritance class were. The section also provides
VB code in learning the method overloading, method overriding, encapsulation, interfaces and poly-
morphism.

204

11 Topic 11: Advanced VB Programming with OOP

11.1 Objectives

By the end of this section, you should be able to:
i. Demonstrate data structure programming methods in VB
ii. Use generic and collection methods as a new tool in VB
iii. Create and manipulate static and dynamic data structures

11.2 Introduction

We will explore basic concepts of data structures in this section. Arrays are simple data structures
consisting only of data items of the same type. Arrays are ’static’, i.e. the size of an array is fixed once
they are created. After that, we explore dynamic data structures, i.e. lists, queues and stacks.

11.3 Arrays

An array is a collection of variables (elements) that have the same type. Example:
i. Dim array1 As Integer()
ii. Dim array1() As Integer

iii. array1 = New Integer(10) {}
iv. array1 = New Integer(0 To 10) {}

Note that we assign a single value to a variable. However, we can assign a list of values to an array
variable same type. Example:

i. array1 = New Integer(0 To 10) {}

array1(2) = 1998
array1(3) = 2008

ii. Dim array1 As Integer()

array1 = New Integer() {2, 4, 6, 8}
iii. Dim array1 As Integer() = New Integer() {2, 4, 6, 8}

The name of below array is array1.

array1(0) array1(1) array1(2) ... array1(10)
array1() 50 19 80 ... 68

Note that the position number inside the parentheses is called and index or subscript. Values can be
assigned to individual members of an array. The 11 elements of the array are score(0) to score(10),

205

which is referred to as ’array1 sub zero’ through ’array1 sub 10’. Sub is derived from subscript. The
value of score(0) is 50, the value of score(1) is 19. Note that the values stored in array can be used
for arithmetic calculations.

11.4 Linked list

A linked list is a linear collection of self-referential class objects called nodes which are connected
by a reference link. The advantage of linked list over array is that linked list provides better memory
utilization because they can grow and shrink at execution time.

A linked list is accessed through a reference to the first node of the list. Each subsequent node is
accessed via the link-reference member stored in the previous node. The last node of a list is set to
Nothing to indicate the end of the list. Note that data are stored in a linked list dynamically where each
node is created as and when necessary
Advantage of linked list over array: linked list provides better memory utilisation because they can
grow and shrink at execution time. Note that the size of an array cannot be altered as the array size is
fixed at creation time. Disadvantage is reference link in the linked list can occupy space and dynamic
allocation incurs the overhead of method calls.
A few useful methods for populating data:

i. InsertAtFront to insert an object at the beginning of the list. Part (a) shows a list and a new node
during the InsertAtFront operation and before the new node is linked into the list. The dashed
lines and arrows in part (b) indicate the last step, which allows the node containing 5 to become
the new list front.

206

ii. InsertAtBack to insert an object at the end of the list. Part (a) shows a list and a new node
during the InsertAtBack operation and before the new node has been linked into the list. The
dashed lines and arrows in part (b) indicate the last step, which allows a new node containing
11 to be added to the end of a list.

iii. RemoveFromFront to delete an object from the front of the list. Part (a) indicates a list before a
removal operation. The dashed lines and arrows in part (b) indicate that the firstNode containing
the number 5 is removed from the List.

iv. RemoveFromBack to delete an object from the end of the list. Part (a) indicates a list before a
removal operation. The dashed lines and arrows in part (b) indicate that the lastNode containing
the number 11 is removed from the List.

v. Print to display the contents of the current list.
vi. EmptyListException to avoid an attempt to remove an item from an empty list.

207

11.5 Stacks

A stack receives new nodes and releases nodes only at the top. It is referred to as a Last-In, First-
Out (LIFO) data structure. Push and pop are two primary operations to manipulate a stack. Push
operation is to add a new node to the top of the stack. Pop operation is to remove a node from the top
of the stack.

11.6 Queues

Queue nodes are removed only from the head (front) of the queue and new nodes are inserted at the
tail (end). This is referred to as a first-in, first-out (FIFO) data structure.

For example, people line up in a queue to buy a movie ticket at a counter. The first person to join the
tail of the line is the first person to reach the front of the line and buy a ticket. The last person to line
up is the last person to buy a ticket. Insert operations are known as enqueue and remove operations
are known as dequeue.

208

11.7 Generics

A generic type is a single programming element that adapts to perform the same functionality for a
variety of data types. An analogy is a screwdriver set with removable heads. You inspect the screw
you need to turn and select the correct head for that screw (slotted, crossed, starred). Generics could
be used in dealing with collections of items such as integers, strings, and so on. We can write a
generic method for sorting an array of objects, then invoke the generic method separately with an
Integer array, and a Double array, to sort each different type of array.

Usefulness: When we create a data structure to store and manipulate Object references, it requires
us to store everything in it as an object. The Object references need to be downcast to an appropriate
type to allow the application to process the objects correctly. It may result in overhead processing of

209

data. It may also limit the ability of the compiler to perform type checking. In order to solve these
problems, it would be nice if we could detect any mismatches at compile time: compile-time type
safety. For example, a Sort method should be able to compare all elements of the same type, such as
Integer type or Double type, but not a mixture of both types.

11.8 Collections

It focus on the pre-packaged data-structure classes provided by the .NET Framework (i.e., collection
classes). These classes store collections of data. Each instance of one of these classes is a collection
of items. Collection classes enable us to store sets of items by using existing data structures without
concern for how they are implemented.
Usefulness: We can code faster and achieve better performance in terms of execution speed and
memory consumption. The System.Collections namespace contains collections that store references
to Objects. The collections in this namespace gives us standardised components that are written for
reuse so we do not need to write your own collection classes.
Non-generic Collection: The System.Collections namespace in the .NET Framework Class Library
is the primary source for non-generic collections. Example: class Stack. Note that Stack is last-in,
first-out (LIFO).
Generic Collection: The System.Collections.Generic namespace in the .NET Framework Class Li-
brary contains generic classes that are used to create collections of specific types. Example: class
SortedDictionary. It is a a collection of key-value pairs, and it sorts data by the keys in a binary
tree.

210

11.9 Summary

In this section, you learnt how to declare and allocate arrays as well as the way to create and manip-
ulate linked lists, queues and stacks. You were also explored to the way in creating generic methods
and collections provided by the .NET Framework.

211

12 Topic 12: Exception Handing with VB Programming

12.1 Objectives

By the end of this section, you should be able to:
i. Understand exceptions and error handling.
ii. Use Try blocks to delimit code in which exceptions might occur.
iii. Able to Throw exceptions.
iv. Use Catch blocks to specify exception handlers.
v. Use the Finally block to release resources.

vi. To understand the use of breakpoints to debug program execution.
vii. To examine data using expressions in the debugging windows.

12.2 Exception Handling

An exception is an indication of a problem that occurs during a program’s execution. Exception han-
dling is designed to process synchronous errors.
Example errors:

i. Out-of-range array subscripts.
ii. Arithmetic overflow.
iii. Division by zero.
iv. Invalid method parameters.
Exception Handling is useful in the following environments:
i. Debug mode In debug mode, when the runtime environment detects an uncaught exception:

• A dialog appears that enables the programmer to view the problem in the debugger.
• To continue program execution by ignoring the problem.
ii. Try...Catch VB uses Try blocks to enable exception handling. A Try block consists of keyword Try
followed a block of code. Immediately following the Try block are zero or more Catch handlers.
Each Catch specifies an exception parameter representing the exception type that the Catch
can handle.
iii. DivideByZeroException In integer arithmetic, an attempt to divide by zero causes a DivideByZe-
roException. A Try block encloses a portion of code that might throw exceptions, and any code

212

that should not execute if an exception occurs. Note that each Catch handler begins with key-
word Catch, followed by an optional exception parameter that specifies the type of exception.
The exception-handling code appears in the body of the Catch handler.
iv. .NET Exception Hierarchy ApplicationException is a base class that programmers can extend
to create exception data types that are specific to their applications. Programs can recover
from most ApplicationExceptions and continue execution. Suppose that a program attempts to
access an out-of-range array subscript, the Common Language Runtime (CLR) throws Index-
OutOfRangeException. An attempt to manipulate an object through a Nothing reference causes
a NullReferenceException.
v. .NET Exception Hierarchy Programs typically cannot recover from most exceptions thrown by
the CLR. Programs generally SHOULD NOT throw SystemExceptions nor attempt to catch
them. For methods in the .NET Framework classes, programmers should investigate the de-
tailed description of the method in the online documentation to determine whether the method
’throws exceptions’.
vi. Finally A program should release a resource when the resource is no longer needed. The
Finally block is guaranteed to execute if program control enters the corresponding Try block,
regardless of whether that Try block executes successfully or an exception occurs.
A Try block that contains one or more Catch blocks DOES NOT require a Finally block. The
Finally block is optional and appears after the LAST Catch. A Try block that DOES NOT contain
any Catch blocks requires a Finally block.

12.3 Debugger - Breakpoints

A breakpoint is a marker set at a line of code. When a program reaches a breakpoint, execution is
suspended. The programmer then can examine the state of the program and ensure that the program
is working properly. To enable the debugging features, the program must be compiled using the debug
configuration.
In examining data of your program, you may need to perform the following steps:

i. To set breakpoints, click the gray area to the left of any line of code. Alternatively, Debug − >

Toggle Breakpoint (or F9). The Watch window allows the programmer to examine variable
values and expressions.

213

ii. The Watch window allows the programmer to examine variable values and expressions.

iii. The Locals window displays the name and current value for all the local variables or objects in
the current scope.

iv. The Autos window displays the variables and objects used in the previous statement and the
current statement (indicated by the yellow arrow).

v. To evaluate an expression in the Immediate window, simply type the expression into the window
and press Enter.

In handling the program debugging, you need to use those buttons in debug toolbar, as icons as
follows.

i. The Continue button resumes execution of a suspended program.
214

ii. The Stop Debugging button ends the debugging session.
iii. The Break All button allows the programmer to place an executing program in break mode.
iv. The Show Next Statement button places the cursor on the same line as the yellow arrow that

indicates the next statement to execute.
v. The Step Over button executes the next executable line of code and advances the yellow arrow

to the following executable line in the program.
vi. The Step Into button executes next statement.
vii. The Step Out finishes executing the procedure and returns control to the line that called the

procedure.

12.4 Summary

You have learned the concept of exceptions and error handling. We used Try blocks to delimit code in
which exceptions might occur, and that allowed us to Throw exceptions. We also used Catch blocks
to specify exception handlers as well as the Finally block to release resources. You also learned the
use of breakpoints to debug program execution, that helps us in examining data with expressions in
the debugging windows.

215

13 Topic 13: Multithreading with VB Programming

13.1 Objectives

By the end of this section, you should be able to:
i. Understand the concept of multithreading.
ii. Extends the life cycle of a thread.
iii. Use the thread synchronization.
iv. Explain the Producer/Consumer Relationship.

13.2 Concurrent programming

Computers can perform operations concurrently, e.g.
i. Compiling programs.
ii. Printing files.
iii. Receiving electronic mail messages over a network.

Programming languages generally provide only a simple set of control structures that enable
i. Programmers to perform one action at a time.
ii. Proceeding to the next action only after the previous one finishes.

There are ways of multithreading improving program performance, as listed as follows.
i. The .NET Framework Class Library makes concurrency primitives available to the applications
programmer.
ii. Allow programmer specify an application with threads of execution.
iii. Each thread designates a portion of a program that might execute concurrently with other
threads.
iv. This capability is known as multithreading.

216

13.3 Thread life cycle

i. Initialization: A thread that was just created is in the Unstarted state. A thread is initialized using
the Thread class’s constructor, which receives a ThreadStart delegate.

ii. Start: A thread remains in the Unstarted state until the thread’s Start method is called. A
thread in the Started state enters the Running state when the system assigns a processor to
the thread.

iii. Termination: A thread enters the Stopped (or Dead) state when its ThreadStart delegate com-
pletes or terminates. A thread is forced into the Stopped state when its Abort method is called
(by itself or by another thread).

iv. Run: A Running thread enters the Blocked state when the thread issues an input/output request.
A Blocked thread becomes Started when the I/O it is waiting for completes.

217

13.4 Thread-priority scheduling

It demonstrate basic threading techniques. Construction of a Thread object and the use of the Thread
class’s Shared method Sleep.

Three threads were created, as the above figures. Each thread displays a message indicating that it is
going to sleep for a random interval between 0 and 5000 milliseconds. When each threads awakens,
the thread displays message indicating its name and that it is done sleeping and enters the Stopped
state. Check out the source code from GitHub.

13.5 Thread Synchronization

When multiple threads share data and that data is modified by one or more of those threads, then
’indeterminate results’ might occur. We can solve by giving the thread that is manipulating shared
data exclusive access. While one thread is manipulating the data, other threads desiring to access
the data should be kept waiting. This is called ’mutual exclusion’, or thread synchronization.

218

Placing the SyncLock keyword before a block of code, the lock is acquired on the specified object
as program control enters the block; the lock then is released when the block terminates for any
reason. If a thread decides that it cannot continue execution, it can call Wait. Note that as long as the
SyncLock statement is present, the statement block is a critical section and balance never becomes
a negative number. (Try remove/comment the SyncLock and End SyncLock statements to see the
effect of leaving out the SyncLock keyword in your VB .Net code).

13.6 Producer/Consumer Relationship

In a producer/consumer relationship, the producer of an application generates data. The consumer
portion of the application uses that data. In a multithreaded producer/consumer relationship, a pro-
ducer thread calls a produce method to generate data. Activity of placing it into shared region memory
is known as buffer. A consumer thread then calls a consume method to read that data.

13.7 When without Thread Synchronization

The producer thread writes to the cell, whereas the consumer thread reads from it. Ideally, we would
like each value that the producer thread writes to the shared cell to be consumed exactly once by the
consumer thread. When it is ’not synchronized’, data may be lost if the producer places new data
into the slot before the consumer consumes the previous data. As a result, data can be incorrectly
repeated if the consumer consumes data again before the producer produces the next item.
To solve the problems regarding lost and repeatedly consumed data, we synchronize the concurrent
producer and consumer threads access to the shared data by using Monitor class methods Enter,
Wait, Pulse and Exit. When a thread uses synchronization to access a shared object, the object is
locked, and no other thread can acquire the lock for that shared object until the thread holding the

219

lock releases it. The consumer thread object remains in the WaitSleepJoin state until the thread is
notified that it can proceed-at which point the thread returns to the Started state and waits for the
system to assign a processor to the thread.

13.8 Summary

This section introduced the concept of multithreading. You studied the life cycle of a thread, thread
synchronization as well as the producer/consumer relationship. Explore the VB code, by practising it,
as provided in GutHub.

References

[1] Vaskaran Sarcar. Design Patterns in C#. Microsoft and .NET. Apress, 2018. http:
//doi.org/10.1007/978-1-4842-3640-6 Source code: https://github.com/Apress/
design-patterns-c-sharp.

[2] Daniel Solis and Cal Schrotenboer. Illustrated C# 7. Microsoft and .NET. Apress, 2018. http:
//doi.org/10.1007/978-1-4842-3288-0 Source code: https://github.com/apress/
illustrated-csharp-7.

[3] Dirk Strauss. Getting Started with Visual Studio 2019: Learning and Implementing New Features.

Microsoft and .NET. Apress, 2019. http://doi.org/10.1007/978-1-4842-5449-3.

[4] Wikipedia. Microsoft visual studio, December 2019.

220


Click to View FlipBook Version