APPLICATION PROGRAMMING (VB), Schemes and Mind Maps of Information Technology

APPLICATION PROGRAMMING (VB)."Creating software solutions using Visual Basic for efficient and user-friendly applications."

Typology: Schemes and Mind Maps

2022/2023

Uploaded on 08/10/2023

caleb-laitetei
caleb-laitetei 🇰🇪

1 document

1 / 45

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
VB.NET
By Daniel Wainaina @2016 1
DESKTOP APPLICATION PROGRAMMING (VB.NET)
1. INTRODUCTION TO .NET PROGRAMMING
1.1 Introduction to .NET Framework
.NET framework is a Microsoft’s platform for developing component-based software. It provides
fundamental advances in runtime services for application software. The framework provides
services necessary to develop and deploy applications for the loosely coupled, disconnected
internet environment. That is, it supports development of applications that can be free of
dependencies on hardware, operating system, and language compiler. It contains compilers and
other command-line utilities to link modules together and install .NET components.
.NET architecture
.NET Framework contains a number of components arranged in layers as shown in the figure
below
Windows API and COM+ services
.NET offers an object oriented view of the operating system’s functions. Windows API helps in
making most calls into the .NET Framework. It ultimately resolves these calls into one of the
Windows kernel DLLs. .NET Framework rely on Component services, and therefore, .NET
components can take advantage of COM+ services such as transaction, synchronization and
security provided by COM+.
Common Language Runtime
CLR is the first layer that belongs to the .NET Framework. This layer is responsible for .NET base
services such as memory management, garbage collection, structured exception handling, and
multithreading. That is, it manages code execution (loads and runs programs, and manages their
interactions) as well as services that .NET provides. The CLR “knows” what to do through special
data called metadata, contained within the applications. This metadata store a map of where to find
classes, when to load classes, and when to set up runtime context boundaries, generate native code,
enforce security, determine which classes use which methods, and load classes when needed. It
.NET Framework
Operating system Level
IDE Level
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d

Partial preview of the text

Download APPLICATION PROGRAMMING (VB) and more Schemes and Mind Maps Information Technology in PDF only on Docsity!

DESKTOP APPLICATION PROGRAMMING (VB.NET)

1. INTRODUCTION TO .NET PROGRAMMING

1.1 Introduction to .NET Framework

.NET framework is a Microsoft’s platform for developing component-based software. It provides fundamental advances in runtime services for application software. The framework provides services necessary to develop and deploy applications for the loosely coupled, disconnected internet environment. That is, it supports development of applications that can be free of dependencies on hardware, operating system, and language compiler. It contains compilers and other command-line utilities to link modules together and install .NET components.

.NET architecture

.NET Framework contains a number of components arranged in layers as shown in the figure below

Windows API and COM+ services

.NET offers an object oriented view of the operating system’s functions. Windows API helps in making most calls into the .NET Framework. It ultimately resolves these calls into one of the Windows kernel DLLs. .NET Framework rely on Component services, and therefore, .NET components can take advantage of COM+ services such as transaction, synchronization and security provided by COM+.

Common Language Runtime

CLR is the first layer that belongs to the .NET Framework. This layer is responsible for .NET base services such as memory management, garbage collection, structured exception handling, and multithreading. That is, it manages code execution (loads and runs programs, and manages their interactions) as well as services that .NET provides. The CLR “knows” what to do through special data called metadata, contained within the applications. This metadata store a map of where to find classes, when to load classes, and when to set up runtime context boundaries, generate native code, enforce security, determine which classes use which methods, and load classes when needed. It

.NET Framework

Operating system Level

IDE Level

also determines when an object is used and when it is released. This is known as managed code, meaning that any dependencies your application might have are always met and never broken.

Base Class Library

BCL is the portion of.NET Framework that defines all the basic data types, such as System.Object (the root of the .NET object hierarchy), numeric and date types, string types, arrays, and collections. It also contains classes for managing .NET core features such as file I/O, threading, serialization, and security.

Data and XML layer

This layer contains the .NET classes that work with databases and with XML. XML is the format that .NET uses to store virtually any kind of information. All the .NET configuration files are based on XML. The Data portion – commonly called ADO.NET – is the .NET counterpart for the ActiveX Data Objects (ADO) technology. ADO.NET focuses mainly on disconnected result-sets called DataSets that store data coming from multiple tables, in the same database or different databases.

ASP.NET/ Web Services and Windows Forms/ User Interfaces

The ASP.NET contain all the classes that can generate the user interface in a browser, while Windows forms contain all classes that can generate user interface using the standard Win windows. ASP.NET comprises both Web Forms and Web services. Web Forms run on the server and produce HTML code that is rendered in a browser on the client while Windows Forms run on client’s Windows machine.

Common Language Specification

CLS is a set of specifications that Microsoft has supplied to help compiler vendors. These specifications dictate minimum group of features that a .NET language must have, such as support for signed integers of 16, 32 or 64 bits, zero-bound arrays, and structured exception handling.

CLS compliant Programming languages

At the top of the figure are programming languages that comply with CLS (they meet the minimum group of features that a .NET language must have). All these languages produce managed code, which is code that runs under the control of the runtime. Managed code is quite different from native code produced by traditional compilers, which is now referred to as unmanaged code.

1.2 VB.NET compilation process

A VB.NET application is wrapped up in an assembly. An assembly includes all the information you need about your application. It includes information that you would find currently in a type library as well as information you need to use for the application or component. This makes your application or component completely self-describing. When a VB.NET application is complied, it is converted to an intermediate language called Microsoft Intermediate Language (MSIL). It is

They are created using New keyword. For instance, we can instantiate (create an object) class Student above and create an object called mary as follows

Dim mary As Student = New Student()

Procedures

Procedures allow logical grouping of code into tasks. When a complex application is divided into procedures, the code become more flexible and easier to maintain and debug. Procedures offers the following advantages;

 The code in a procedure is reusable – created and tested procedure can be called from different places in the application  The application is easier to debug and maintain because source of errors in a procedure are easier to trace than in entire application.

Types of procedures There are two types of procedures;

Function procedure – perform a specific task and return a value to the calling statement. Delimited by Function…End Function keywords.  Sub procedure – perform specific task but do not return a value to the calling statement.  Namespaces

Namespaces are a way to group related classes together. They provide proper organization of classes, so that they are convenient to use. Often if other people’s code are used, there arises conflicts between method names. Such conflicts are avoided through namespaces. Namespaces can contain classes, structures, enumerations, delegates, interfaces, and other namespaces.

NB: if own namespaces are created, it is advisable to prefix namespaces by application name to ensure namespaces do not conflict with existing namespaces.

Exception handling

Errors and exceptions may occur during code development and often cause sudden failure of programs. Structured exception handling in VB.NET provide a better and more robust way to handle errors and exceptions. Exceptions are objects that are raised at runtime to abnormal behavior in the application. Try..Catch..Finally keywords are used. (To be discussed and implemented later).

Garbage collection

Objects usually have a lifetime, which is managed through garbage collection. When an objects gets into scope, it occupies memory and must release that memory once it gets out of scope. Released object references are automatically reclaimed by the operating system. Garbage

collection is therefore the process of reclaiming memory when the CLR decides that the object references are no longer in use.

OOP concepts

VB.NET is a full-fledged player in the world of Object-oriented (OO) programming languages. The primary advantage of OO languages compared to their procedural predecessors is that not only can you encapsulate data (properties) into structures, but can also encapsulate behaviors as well. For instance, a car is not only described by its color, number of tires etc. (properties), but can also be described as an object that can speed up and slow down (behaviors/methods). In addition, behavior can be propagated from one object to another, and this is where inheritance comes in.

Inheritance

Inheritance is the ability to create new classes based on existing class. The new created class acquires all the properties, methods, and events of the base class and can add its own properties and methods. The common terms used when referring to classes in inheritance are derived and base classes. The base class is the original class, or the framework class from which other classes acquire properties while a derived class is a class that acquire properties and methods from the base class. The Inherits keyword is used inside the derived class following the name of class that it inherits from. For example, consider class Student that inherits properties and methods of class Person and adds its own members.

Public Class Person Protected name As String Protected gender As Char Public Function showgender() As Char gender = InputBox("Enter Gender") Return gender End Function End Class Class Student Inherits Person Dim no_of_units As Integer Public Function Units() As Integer no_of_units = 6 Return no_of_units End Function End Class

Polymorphism means “more than one form”. It is the capability to have methods and properties in multiple classes that have the same name and can be used interchangeably, even though each class implements the same properties or methods in different ways. In VB.NET, this is known as inheritance-based polymorphism. In implementing polymorphism, the following terminologies are used.

Overridable: allows a property or method in a class to be overridden in a derived class.  Overrides : overrides an overridable property or method defined in the base class.  NotOverridable: prevents a property or method from being overridden in a derived class.  MustOverride: Requires that a derived class override the property or method of a base class.

Example of polymorphism: Notice method noofdoors() is defined in both classes with the same name, and each class implements the method differently.

Class Sedan

Public door As Integer Public Overridable Function noofdoors() As Integer door = 1 Return door End Function End Class Public Class Coupe Inherits Sedan Overrides Function noofdoors() As Integer door = 2 door = door + 4 Return door End Function End Class Sub Main() Dim s As Sedan = New Sedan() Dim c As Coupe = New Coupe() Console.WriteLine("The no of doors for coupe is:" & c.noofdoors()) Console.WriteLine("And that of Sedan is:" & s.noofdoors()) Console.ReadKey() End Sub

2. PROGRAMMING FUNDAMENTALS IN VB.NET

The main aim of this chapter is to discuss the syntax of VB.NET language that include basic concepts such as identifiers, variables, operators, statements, etc.

Identifiers

These are names given to namespaces, types (structures, classes, modules, delegates), type members (methods, events, constructors, constants, fields, properties), and variables. Identifiers must begin with either an alphabetic or underscore character, may be of any length, and after the first character it may contain alphanumeric and underscore characters. NB: although VB.NET is not case sensitive, the case of identifiers is preserved when applications are compiled. In addition, identifiers may not match VB.NET keywords. Keywords are words with special meaning in a programming language. They are reserved i.e., cannot be used for such purposes as naming variables and subroutines. However, if it is very necessary to declare or use an identifier that matches a keyword, the identifier must be enclosed in square brackets ([]). For example, Public Class [Public] defines a class called Public. NB: Public is a keyword. (Students to search for keywords in VB.NET)

Data types

Types in VB.NET are divided into two categories: primitive (fundamental) and custom type. Fundamental types are built-in types, each of which is an alias for a type supplied by the .NET architecture. They include:

Boolean - type limited to two values: True and False. Usually, logical operators result in a Boolean type.  Byte – holds a range of integers from 0 to 255 and represents values that can be held in eight bits of data.  Char – this holds any Unicode character (single character).  Date – hold values that specify dates and times. Used for accessing, comparing and manipulating dates and times.  Decimal – holds decimal numbers with a precision of 28 significant decimal digits. Its purpose is to represent and manipulate decimal numbers without the rounding errors of the Single and Double types.  Double – holds floating point numbers, which are 64 bit value.  Integer - holds integers in the range -2147483648 through 2147483647.  Long – is a 64bit integer data type that holds integers in the range -9223372036854775808 through

Object – this is the base type from which all other types are derived.  Short – holds integers in the range -32768 through 32767.  Single – holds a 32bit value.  String – holds a sequence of Unicode characters

Constants

A constant is a variable that holds a value that does not change throughout the execution of the application. To declare a constant, Const keyword is used within a procedure or at declaration sections of classes or modules. They can be declared with the scope of Private,Public, Friend, Protected or Protected friend. The syntax is: [scope] Const constant-name [As type] =expression.

For example, Private Const hourly_rate As Double = 120.50, defines a constant called hourly_rate that stores value 120.50 throughout the application.

Comments

These are statements that are neither executed nor processed by VB.NET. They do not take up room in your compiled code. Single quote is used as shown below.

Module CommentExample Sub main() Console.WriteLine("Hello World") 'this application prints a "Hello World" statement on the Console Console.ReadLine() End Sub End Module

Operators and expressions

VB.NET offers numerous operators that fall into the arithmetic, assignment, comparison, concatenation, logical and bitwise categories.

Arithmetic operators supply basic algebraic functions as shown below.

Arithmetic Operators Operator Action Description

  • Addition y=5+4 //
  • Subtraction y=5-4 //
  • Multiplication y=5*4 // / (Regular division) and (Integer division) Division y= 5/4 //1.25, y=5\4 // 1 Mod Modulus y=5 Mod 4 // 1 ‘gives remainder ^ Exponentiation y=5^4 // 625

Concatenation operators – combine string variables with string expressions. For example;

Dim y As Double = 5 Dim x As Double = 4 Dim d As Double d = y & x MsgBox(d) ‘ Returns 54

Similarly,

Module Module Sub Main() Dim y As String = "SCT121" Dim x As String = "2015"

y = y & "-7491/" & x MsgBox(y) 'Returns SCT121-7491/ End Sub End Module

Assignment operator – is used to set value to a variable. Assignment operators can take either of the forms shown below.

Assignment operators Operator Action Description = Equals assignment variable=expression += Addition/concatenation assignment

variable+=expression

-= Subtraction assignment variable-=expression = Multiplication assignment variable=expression /= and = Division assignment floatingpointvariable/=expression, integralvariable=expression ^= Exponentiation assignment variable^=expression &= String concatenation assignment

variable&=expression

For example, what is the output of the following code segment? Dim x As Integer = 2 x ^= 2 + 3 MsgBox(x) //should return 32

Comparison operator – evaluates an expression on the right-hand side of the equals sign and return a Boolean True or False based on the comparison of the expressions. The syntax is Result = expression1 comparison_operator expression They include; <, <=,>.>=, =, Is (object comparison), and Like (string pattern match).  Logical/bitwise operators – used for logical evaluation of Boolean expressions and bitwise evaluation for numeric expressions. Syntax: result= expr1 operator expr They include And, Or, Not, Xor, AndAlso etc. for example Dim x as integer=20, y as integer=15. Result= Not(x>y) ‘Returns False. Operator Precedence //students to research Operator example Consider the following expressions, indicate the results Dim x As Double = 54. Dim y As Double = 22. Dim a As String = "6" Dim b As String = "5" Dim z As Short z = CShort(a) + CShort(b) 'Returns 11 MsgBox(a + b) 'Returns 65 z = x + y 'Returns 77, cannot take decimals hence narrowing takes place a = x + y 'Returns 76.

Option Compare – controls the manner in which strings are compared to each other. The syntax is Option Compare [Binary|Text]. If Binary is specified, strings are compared based on their internal binary representations (case-sensitive comparisons). If Text is specified, strings are compared based on case-insensitive alphabetical order. Default is Binary.Option Explicit – determines whether the compiler requires all variables to be explicitly declared before use. The syntax is Option Explicit [On|Off]. If On the compiler requires all variables to be declared before use and if Off considers variable’s use to be an implicit declaration. The default is On.Option Strict – controls the implicit type conversions that compiler will allow. The syntax is Option Strict [On|Off]. If On the compiler only allows implicit widening conversions and hence narrowing conversions must be explicit (cast functions must be used). If Off compiler allows implicit narrowing conversions, and this would result in runtime exceptions unforeseen by programmers. The default is Off. It is considered good programming practice to require strict type checking.

3. CONTROL STRUCTURES

Programs are written to carry out a set of tasks, some of which require them to adjust their behavior depending on the user input. VB.NET support such programs through statements which execute a program conditionally, or repeating a set of statements. Such statements include If..Then..Else and Select…Case, which execute programs conditionally (Selection Structures), and Do…Loop, While…End While , and For..Next , which repeat statements conditionally (Repetition Structures).

Selection Structures

IF...THEN Statement

In VB.NET there are many forms for the IF statement. They all work by evaluating some expression and if the expression is correct (true) then the code within the IF block is executed. It takes the form

If expression Then Statement Statement …. End If

For example, consider a program that accepts two integers and determines whether they are equal or which is greater than the other. Using IF statement, would be written as follows;

Sub Main() Dim A As Integer Dim B As Integer A = InputBox("enter the value of A") B = InputBox("enter the value of B") If A > B Then MsgBox(A & " is greater than " & B) End If If A < B Then MsgBox(A & " is smaller than " & B) End If If A = B Then j MsgBox(A & " is equal to " & B) End If End Sub

IF…THEN...ELSE Statement

This is another variation of the IF statement which takes the following form;

If expression Then Statement Statement … Else

' you are a teenager MsgBox("Hello Teenager") ElseIf MyAge < 35 Then ' Your age is acceptable MsgBox("Hi there young man") Else ' the person is old MsgBox("Hello there old man") End If End Sub

In this case, if expression 1 is evaluated to true, then its statements are executed and the rest of the IF statements are ignored. If not, the expression 2 is evaluated and its corresponding statements are executed while other checks are ignored…until Else if all expressions evaluate false.

Exercises

  1. Write a program that outputs the grade scored by a student once the marks are supplied. (use Diploma in IT system)
  2. Write a program that accepts a digit and outputs the corresponding day of the week. E.g. 1= Monday, 2=Tuesday…etc.

The SELECT…CASE Statement

The Select…Case statement is similar to the If...then…Else statement. The only difference between the two is that If and ElseIf can evaluate different expressions in each statement, whereas the select statement can evaluate only one expression. The select statement then uses the result of this expression to execute different sets of statements. However, select …case is preferred over If…Elseif when multiple conditions are used because it makes the code easy to read and understand. The syntax is:

Select Case expression Case Expressionlist Statement(s) . . Case Else Statement(s) End Select Expressionlist refers to the constants or expressions that are compared with the result of expression mentioned with the Select..Case statement. The End select statement marks the end of the Select..case.For example, consider a program that outputs the name of months once corresponding number is given.

Dim month As Integer month = InputBox("enter number") Select Case month Case 1 MsgBox("This is January") Case 2 MsgBox("This is February") Case 3

MsgBox("This is March") Case 4 MsgBox("This is April") Case 5 MsgBox("This is April heading to may") Case Else MsgBox("Am tired I will define the rest later") End Select In some applications, it is practically impossible to write case statements for each and every value in a range, based on a condition given. In such situations, conditional expressions are specified instead of values. Is keyword is used to specify this conditional expression.

For example, consider a program that gives discounts depending on quantity bought as shown below. Since a range of values is required, Is keyword is used followed by conditional expression.

Dim Quantity, Discount As Integer Quantity = InputBox("enter quantity bought") Select Case Quantity Case Is <= 10 Discount = 10 Case Is <= 20 Discount = 20 Case Is <= 30 Discount = 30 Case Is > 30 Discount = 40 Case Else MsgBox("Invalid Entry") End Select MsgBox(Discount)

Alternatively, ranges in each Case statements given can be specified using To keyword.

For example;

Select Case Quantity Case 1 To 10 Discount = 10 Case 11 To 20 Discount = 20 Case 21 To 30 Discount = 30 Case Is > 30 Discount = 40 Case Else MsgBox("Invalid Entry") End Select MsgBox(Discount)

You may also want to have the same set statements for more than one value of the expression. In such cases, multiple values or ranges in a single Case statement is specified. For example;

Dim number As Integer number = InputBox("enter number") Select Case number

While…End While

This repeats a statement(s) as long as a condition is true. The syntax is;

While condition Statement(s) End While For example, the code below outputs integers in the range 1 to 10 using While…End While loop.

Dim i As Integer = 1 While i <= 10 Console.WriteLine(i) i += 1 End While Console.ReadLine()

For…Next Statement

This loop statement repeats statement(s) for a specified number of times. The syntax is;

For Counter= To [step Value] Statement(s) Next [counter] NB: counter is a numeric value. Startvalue is the initial value of the counter while endvalue is the final value of the counter. Stepvalue is the value by which the counter is incremented or decremented. It’s optional and can either be positive or negative. If omitted, default is set to 1. To exit the For loop, Exit For is used and causes statements after Next statement to be executed.

For example, the program below uses For…Next to print integers in the range 1 to 10.

Dim i As Integer = 1 For i = 1 To 10 Step 1 Console.WriteLine(i) Next i Console.ReadLine()

To print only the first seven integers, for instance, Exit..For can be used as follows;

Dim i As Integer = 1 For i = 1 To 10 Step 1 Console.WriteLine(i) If i = 7 Then Exit For End If Next i Console.ReadLine()

Exercise

  1. A survey has to be carried to discover the most popular sport. Every participant is required to type a letter representing the sport they support as follows; A-Athletics, S-

Swimming, F-Soccer, and B-badminton. Letter Q is used to finish the tally. Write an application that outputs the results and shows the popular sport. Solution

Sub Main() Dim F, B, S, A As Integer Dim vote As String Do vote = InputBox(" Select the Sport you Support:A-Athletics, S-Swimming, F- Soccer, and B-badminton.Enter Q to finish the tally").ToUpper

If vote = "F" Then F = F + 1 End If If vote = "B" Then B = B + 1 End If If vote = "A" Then A = A + 1 End If If vote = "S" Then S = S + 1 End If

Loop While Not (vote = "Q") Console.WriteLine("Soccer: " & F) Console.WriteLine("Swimming: " & S) Console.WriteLine("Athletics: " & A) Console.WriteLine("Badminton: " & B) If F > A And F > B And F > S Then Console.WriteLine("The favourite game is Soccer") ElseIf B > F And B > S And B > A Then Console.WriteLine("The favourite game is Badminton") ElseIf S > F And S > B And S > A Then Console.WriteLine("The favourite game is Swimming") ElseIf A > F And A > S And A > B Then Console.WriteLine("The favourite game is Athletics") Else Console.WriteLine("hard to determine") End If

Console.ReadLine()

End Sub

  1. Write an application to compute the sum of all numbers divisible by 9 between 50 and
  1. Write an application that compute the sum of all even numbers and product of all odd numbers between 1 and 100.