Similar a The different variable types supported by VB.NET are:1. Numeric Variables: - Integer (From -32,768 to 32,767) - Long (From -2,147,483,648 to 2,147,483,647) - Short (From -32,768 to 32,767) - Byte (From 0 to 255) - Decimal (Variable precision numbers) - Double (15-16 digit precision numbers) - Single (7-digit precision numbers)2. Date/Time Variables: - Date - TimeSpan3. Character Variables: - Char (Single character) - String (Sequence of characters)4. Boolean
Similar a The different variable types supported by VB.NET are:1. Numeric Variables: - Integer (From -32,768 to 32,767) - Long (From -2,147,483,648 to 2,147,483,647) - Short (From -32,768 to 32,767) - Byte (From 0 to 255) - Decimal (Variable precision numbers) - Double (15-16 digit precision numbers) - Single (7-digit precision numbers)2. Date/Time Variables: - Date - TimeSpan3. Character Variables: - Char (Single character) - String (Sequence of characters)4. Boolean (20)
The different variable types supported by VB.NET are:1. Numeric Variables: - Integer (From -32,768 to 32,767) - Long (From -2,147,483,648 to 2,147,483,647) - Short (From -32,768 to 32,767) - Byte (From 0 to 255) - Decimal (Variable precision numbers) - Double (15-16 digit precision numbers) - Single (7-digit precision numbers)2. Date/Time Variables: - Date - TimeSpan3. Character Variables: - Char (Single character) - String (Sequence of characters)4. Boolean
1. Advanced web technologies - 12261
Book1 contains VB.net part
Modules of Book 1 Slide No.
Module 1 : Introduction to Basic Windows programming using VB.net 2
Module 2 : Programming Concepts 17
Module 3: Streams And Files 71
Module 4 : Exception Handling 80
Module 5 : OO Programming Concepts 97
Module 6 : Namespaces 111
Module 7: Accessing Data with .Net 139
Module 8: Multi threading - Concept and Program 170
Book 2 contains ASP.net part
compiled by RJ , 9892544177 1
2. Module 1: Introduction to Basic Windows programming using VB.net
Short note on development/ history of VB.net( 4m)
Microsoft has developed many languages before reaching to the .NET
framework:
1964 – BASIC
Prob : no support for UI
1975 – QBASIC
Prob : slow response time
1976 – VB 1.0 , the series progressed uptill VB 5.0 ( 1997)
Adv : Allowed good UI development , component library to share code.
Library files are in .dll format.
2000 – VB 6.0
Prob : lots of garbage code due to garbage collection.
Viva Q : what is Garbage collection?
Therefore, finally a new and clean implementation developed =
.NET framework.
compiled by RJ , 9892544177 2
4. Coding the First Visual Basic .Net Application with out
using IDE
1. Open notepad. Create a new file save as
“step1.vb”
2. Type the following code in step1.vb file
Imports System // predefined package in the .NET framework
Public Class Step1
Shared Sub Main()
System.Console.WriteLine(“We are engineering students”)
End Sub
End Class
compiled by RJ , 9892544177 4
5. 3. launch the command prompt from
Start, Programs, Microsoft Visual Studio .NET 7.0, Visual Studio .NET Tools menu.
4. (To test the vb.net compilier is running or not)
Before you compile at the command prompt, type vbc and press Enter
5.o/p is
Microsoft (R) Visual Basic.NET Compiler version 7.00.9254
for Microsoft (R) .NET CLR version 1.00.2914.16
Copyright Microsoft Corp 2001. All rights reserved.
Visual Basic Compiler Options
compiled by RJ , 9892544177 5
6. Viva : why type vbc ?
To check the following
• Visual Basic.NET installed
• We have the appropriate permission to run the compiler
• The system was able to find the file vbc.exe. ie vb compiler
6. Compile and make exe
C:TYVBC1>vbc step2.vb /t:exe
Microsoft (R) Visual Basic.NET Compiler version 7.00.9254
for Microsoft (R) .NET CLR version 1.00.2914.16
Copyright Microsoft Corp 2001. All rights reserved.
7. Run the executable
C:TYVBC1>step2
We are engineering students
compiled by RJ , 9892544177 6
7. What are command line switches? ( 4m )
Command line switches are used to configure the output according to
application requirement.
Eg. Of switches are
3. /target or /t : < winexe or exe or library or module>
8. /out : < filename >
11. /help ( or /?)
compiled by RJ , 9892544177 7
8. List different components of IDE and its use? (4m)
Before we begin with the using the IDE we must set the profile. Choose
profile
”VB developer Profile”.
The main components are :
Toolbox : has window controls, common controls, containers, menus
and toolbars, data , components, printing, Dialogs, WPF
interoperability, reporting, Vb power packs.
Command / immediate window.
Server explorer : contains all data base components, used only when
we have SQL or Ms Access .
Solution explorer : all forms , its GUI components.
The development area, where the Form appears.
compiled by RJ , 9892544177 8
9. Create a simple form (window application). The application must accept
name and phone_number.
The name field must raise an exception when the numeric is entered or it is
left blank. Similarly validate the phone_no field.
Step 1: Create the project
Using the menus, choose the File, New, Project command, bringing up the New
Project dialog. Select the Windows Application icon and change the project
name from WindowsApplication1 to name_phno. (name_phno.vb)
Step 2: Develop the User- Interface.
Step 3: logic : “Raising an exception” means using validating or validated event
on the textbox where the user would enter the name and phone no.
Sub TextBox1_Validating(… )
Sub TextBox2_Validating (… )
Viva Q : difference between validating and validated event.
Validating checks for input moment we enter data. Validated checks only after we leave
the field and go to the next field.
9
compiled by RJ , 9892544177
10. Use ErrorProvider control to report an error message.
If TextBox1.Text = "" Then
ErrorProvider1.SetError(TextBox1, "plz enter a name")
e.Cancel = True Indicates that the
Else error control
If IsNumeric(TextBox1.Text) Then should be shown.
ErrorProvider1.SetError(TextBox1, "plz enter a correct name")
e.Cancel = True
Else
ErrorProvider1.SetError(TextBox1, "")
End If
End If
Apply similar logic with textbox2.
Step 4: Running the project : press play button or F5.
compiled by RJ , 9892544177 10
11. Coding steps
ErrorProvider1.SetError(TextBox1, "") -
Private Sub Button1_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles ?
Handles Button1.Click
End
End Sub Viva : difference
between end and exit
Sub Form1_Load (ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles MyBase.Load
compiled by RJ , 9892544177 11
12. Create a simple login having 2 textboxes – username and password.
Password must have “vesp” as input only. Provide 2 buttons “submit ”
and “exit”. Allow maximum 3 login attempts.
Step 1 : choose window application and create the UI as reqd.
Step2 : logic :
Both text boxes i.e the Username and password must have some data.
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("enter all fields")
No restriction on data entered in Username field – Textbox1
Check data entered in textbox2 = “vesp” or not.
If TextBox2.Text = "vesp" Then
MsgBox("login successfull")
compiled by RJ , 9892544177 12
13. Maximum 3 attempts indicates set up a counter variable
All validation must be done on “Submit button” , so put the code in
Sub Button1_Click(ByVal sender As Object,
ByVal e As System.EventArgs)
Handles Button1.Click
Every textbox experiences TextBox1_TextChanged event when we
give input. We need not handle it , as the logic is not asking for any
validation on typing.
Assignment “: Develop application to validate for numeric input on
typing. Handle TextBox1_TextChanged event.
compiled by RJ , 9892544177 13
14. Create a window application to calculate SI. It should
accept P, N and R as inputs. Raise exception if no input or
text is entered.
Step 1: Create a window application. Develop the UI.
Step 2: logic :
Sub TextBox1_Validating(ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If TextBox1.Text = "" Then Blank not allowed
ErrorProvider1.SetError(TextBox1, "enter an amount")
e.Cancel = True
Else
If IsNumeric(TextBox1.Text) Then No numbers
allowed
ErrorProvider1.SetError(TextBox1, "")
Else
ErrorProvider1.SetError(TextBox1, "enter an correct amount")
e.Cancel = True
End If
End If
compiled by RJ , 9892544177 14
15. Logic of PNR / 100 to find SI is implemented on click of a button.
Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click
MessageBox.Show(((TextBox1.Text * TextBox2.Text *
TextBox3.Text) / 100))
end sub
compiled by RJ , 9892544177 15
16. Create a window application which highlights the
importance of validating event over validated.
Step 1: Create Window application with 2 textboxes.
Step2 : logic :
On Textbox 1 handle validated event.
On Textbox 2 handle validating event.
Sub TextBox1_Validated(ByVal sender As Object, ByVal e As
System.EventArgs) Handles TextBox1.Validated
Sub TextBox2_Validating(ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles TextBox2.Validating
compiled by RJ , 9892544177 16
17. Module 2: Programming Concepts
> Variable types
> Built –In functions
> String functions
> Console Based programming.
Q> List with ranges the different types of variables supported by
VB.NET. ( 4m )
VARIABLES: Defn : A temporary storage location.
5. Integer
6. Numbers with Decimal Places
7. Strings and Characters
8. Boolean
9. Date
compiled by RJ , 9892544177 17
18. Data Type ( integer) Size (Bytes) Range
Byte 1 0 to 255
Short 2 -32,768 to 32,767
Integer 4 -2,147,483,648 to
2,147,483,647
Long 8 –9,223,372,036,
854,775,808, 9,223,372,036,
854,775,807
compiled by RJ , 9892544177 18
19. Data Type ( number with decimal places) Size (Bytes) Range
Single 4 –3.402823 × 10^38
to –1.401298 × 10^–45
Double 8 for negative numbers;
1.401298 × 10^–45
to 3.402823 × 10^38
for positive numbers
–1.797693134
86231 × 10^308 to
–4.940656458
41247 × 10^–324
for negative numbers;
4.940656458
41247 × 10^–324 to
1.797693134
86232 × 10^308 for
positive numbers
compiled by RJ , 9892544177 19
20. Data Type Size (Bytes) Range
Char 2 One character
String 10+2 Up to 2
Per billion
character characters
Data Type Size (Bytes) Range
Boolean 2 True or False
Date 8 January 1, 100 to December
31,9999
compiled by RJ , 9892544177 20
21. Declaring Variables
Dim sFirstName As String
Dim dblGrossDomesticProduct As Double
Dim bLearned As Boolean
Dim dtDateOfMagnaCartaSigning As Date = #DEC 15,
2010#
Dim lPeopleOnEarth As Long = 6000000000
compiled by RJ , 9892544177 21
22. WAP to declare 3 arrays of integer, date and string type resp.
demonstrate different ways of initialing the array . ( 4m )
– Refer pg 14 of notes
1 ‘Simple declaration
2 Dim iValues(3) As Integer // note no ; at end
3 Dim dtDates() As Date
4 Dim I As Integer
5 For I = 1 To 3 // 1st way of init an array.
6 iValues(I-1) = I
7 Next
compiled by RJ , 9892544177 22
23. 8 ‘Changing the size of an existing array
9 ReDim dtDates(4)
10 ‘fill the list of dates of sem 6 TT
11 dtDates(0)=”4/24/2011” ‘management // 2nd way of initzn
12 dtDates(1)=”4/27/2011” ‘s/w testing or DCNE
13 dtDates(2)=”5/03/2011” ‘AJP
7 dtDates(3)=”5/06/2011” ‘AWT
15 ‘Declaration with Initialization
16 Dim sMonths() As String = {“Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”, _
• “Jul”,”Aug”,”Sep”,”Oct”,”Nov”,”Dec”} // 3rd way of initzn
18 ‘Using arrays
14 Console.WriteLine(“”)
20 Console.WriteLine(“Second value in iValues = {0}”, iValues(1))
21 Console.WriteLine(“Third date in dtDates = {0}”, dtDates(2))
22 Console.WriteLine(“Eleventh month of the year = {0}”, sMonths(10))
compiled by RJ , 9892544177 23
24. Constants
Constants are declared using one of the two
forms
Const PI = 3.1415 As Double
Const DSN As String = “Random”
compiled by RJ , 9892544177 24
25. BUILT-IN FUNCTIONS Refer awt pracs > variables
Function Description
CBool Converts to a Boolean. Anything that evaluates to False or 0 will be set to False; otherwise, it will be True.
CByte Converts to a Byte. Any value greater than 255, or any fractional information,will be lost.
CChar Converts to a single character. If the value is greater than 65,535, it will be lost. If you convert a String, only
the first character is converted.
CDate Converts to a Date. One of the more powerful conversion functions, CDate can recognize some of the more
common formats for entering a date.
CDbl Converts to a Double.
CInt Converts to an Integer. Fractions are rounded to the nearest value.
CLng Converts to a Long. Fractions are rounded to the nearest value.
CSht Converts to a Short. Fractions are rounded to the nearest value.
CStr Converts to a String. If the value is a Date, this will contain the Short Date format.
CType Converts to any type. This is a powerful function that enables you to convert any data type into any other
type. Therefore, the syntax for this function is slightly different than the others.
compiled by RJ , 9892544177 25
26. Syntax of CType( )
oNewVariable = CType(oOldVariable, NewType)
In which oNewVariable and oOldVariable are placeholders for the
variables that we’re converting to and from, respectively. NewType
is the type you are converting to.
Eg : convert object of customer to employee.
Dim oCust As Customer = New Customer ( “a”, “b”)
Dim oEmp As Employee = New Employee ( “c”, “d”)
// here assuming that the no. and type of attributes is the same In both
the classes.
Then oEmp = CType( oCust, Employee ) ‘ converts
compiled by RJ , 9892544177 26
27. Example : uses the CBool function to convert expressions to Boolean
values. If an expression evaluates to a nonzero value, CBool returns
True; otherwise, it returns False.
Example : uses the CByte function to convert an expression to a Byte.
compiled by RJ , 9892544177 27
28. Example: uses the CChar function to convert the first character of a String
expression to a Char type.
The input argument to CChar must be of data type Char or String. You cannot use CChar to
convert a number to a character, because CChar cannot accept a numeric data type. The
following example obtains a number representing a code point (character code) and converts
it to the corresponding character. It uses the InputBox function to obtain the string of digits,
CInt to convert the string to type Integer, and ChrW to convert the number to type Char.
compiled by RJ , 9892544177 28
29. Example: uses the CDate function to convert strings to Date values.
Example of Cdbl
compiled by RJ , 9892544177 29
30. Example of Clng() function
Example : uses the CObj function to convert a numeric value to Object. The
Object variable itself contains only a four-byte pointer, which points to the
Double value assigned to it.
compiled by RJ , 9892544177 30
31. CSng Example
Example: uses the CStr function to convert a numeric value to String.
compiled by RJ , 9892544177 31
32. Example: uses the CStr function to convert Date values to String values.
Or short note on CStr()
CStr always renders a Date value in the standard short format for the current locale, for
example, "6/15/2003 4:35:47 PM". However, CStr suppresses the neutral values of 1/1/0001
for the date and 00:00:00 for the time.
Date/Time Conversions. Use the IsDate function to determine if a value can be converted to a
date and time. CDate recognizes date literals and time literals but not numeric values. To
convert a Visual Basic 6.0 Date value to a Date value in Visual Basic 2005 or later versions,
you can use the DateTime.FromOADate method.
compiled by RJ , 9892544177 32
33. String Manipulation Functions : The following table lists the functions
that Visual Basic provides to search and manipulate strings.
compiled by RJ , 9892544177 33
35. Example : uses the UCase function to return an uppercase version of a string.
Example : uses the LTrim function to strip leading spaces and the RTrim
function to strip trailing spaces from a string variable. It uses the Trim
function to strip both types of spaces.
Refer awt pracs > Console Application3
35
compiled by RJ , 9892544177
36. Example: uses the Mid function to return a specified number of characters from
a string.
Example : uses Len to return the number of characters in a string.
compiled by RJ , 9892544177 36
37. Example: uses the InStr function to return the position of the first occurrence
of one string within another.
compiled by RJ , 9892544177 37
38. Home Assignment
A> Specify the string functions which would
1> Check len of the sPassword .
2> if sPassword is containing “ Engineering students” find the postn of
string “students”.
Hint : be case sensitive
Stringdemo.vb
compiled by RJ , 9892544177 38
39. How to develop a Console Based application.
Select File > New > Project > Console application.
Eg : A simple console Application which reads 5 integers and calculates
average. Print the average number.
Refer exp4 > Module2.vb
Readline() and writeline() functions are predefined in
NameSpace = Systems.console
Eg : Make a console application and accept input via InputBox.
Refer exp4 > Module1.vb
compiled by RJ , 9892544177 39
40. Develop console application for showing different date and time formats.
Dateformatspecifiers.vb
Refer > console Application 1
compiled by RJ , 9892544177 40
41. Programming user-defined Routines or Functions
There are 2 types of procedures
Subroutine ( or sub in coding )
Function
Sub does not return any value
1 Sub ShowMessage(ByVal Message As String)
2 Console.WriteLine(Message)
3 End Sub
4 ShowMessage(“Hello World from Visual Basic .NET”)
compiled by RJ , 9892544177 41
42. Eg. Of function
Function returns some value
1 Private Function GetValue(ByVal Prompt As String) As String
2 Console.Write(Prompt)
3 Return Console.ReadLine
5 End Function
Analysis :
Develop a console based application showing how to interchange or swap numbers.
Define a sub or function to swap.
Refer exp4 > Module3.vb
compiled by RJ , 9892544177 42
43. Define scope of a Variable. Describe it with all details.
The scope of a declared element is the set of all code that can refer to it
without qualifying its name or making it available through an
Imports Statement (.NET Namespace and Type). An element can have
scope at one of the following levels:
These levels of scope progress from the narrowest (block) to the widest (namespace), where
narrowest scope means the smallest set of code that can refer to the element without
qualification.
compiled by RJ , 9892544177 43
44. Specify the scope of an element when you declare it. The scope can
depend on the following factors:
• The region (block, procedure, module, class, or structure) in which
you declare the element
• The namespace containing the element's declaration
• The access level you declare for the element
Block Scope
A block is a set of statements enclosed within initiating and terminating
declaration statements, such as the following:
Do and Loop
For [Each] and Next
If and End If
Select and End Select
SyncLock and End SyncLock
Try and End Try
While and End While
With and End With
compiled by RJ , 9892544177 44
45. The scope of the integer variable cube is the
block between If and End If, and you can no
longer refer to cube when execution passes
out of the block.
Note : Even if the scope of a variable is limited to a block, its lifetime is still that of
the entire procedure. If you enter the block more than once during the procedure,
each block variable retains its previous value.
Procedure scope :
An element declared within a procedure is not available outside that procedure. Only the
procedure that contains the declaration can use it. Variables at this level are also known as
local variables. You declare them with the Dim Statement (Visual Basic), with or without the
Static (Visual Basic) keyword.
Procedure and block scope are closely related. If you declare a variable inside a procedure
but outside any block within that procedure, you can think of the variable as having block
scope, where the block is the entire procedure.
compiled by RJ , 9892544177 45
46. Module Scope
• The single term module level applies equally to modules, classes, and structures.
You can declare elements at this level by placing the declaration statement outside of
any procedure or block but within the module, class, or structure.
• When you make a declaration at the module level, the access level you choose
determines the scope. The namespace that contains the module, class, or structure
also affects the scope.
Refer awt pracs > ScopeVar
compiled by RJ , 9892544177 46
47. Namespace Scope
If you declare an element at module level using the Friend (Visual Basic) or
Public (Visual Basic) keyword, it becomes available to all procedures throughout
the namespace in which the element is declared.
Public strMsg As String
compiled by RJ , 9892544177 47
48. • Namespace scope includes nested namespaces. An element available from
within a namespace is also available from within any namespace nested
inside that namespace.
• If your project does not contain any Namespace Statements, everything in
the project is in the same namespace. In this case, namespace scope can
be thought of as project scope. Public elements in a module, class, or
structure are also available to any project that references their project.
Access level or Visibility Modifiers applicable to variables
1. Public or Friend variables
2. Private or local variables
3. Protected – only used during Inheritance.
4. Shared
5. Static
compiled by RJ , 9892544177 48
49. Advantages of Local Variables
• Local variables are a good choice for any kind of temporary calculation, for the
following reasons:
• Name Conflict Avoidance. Local variable names are not susceptible to conflict.
For example, you can create several different procedures containing a variable
called intTemp. As long as each intTemp is declared as a local variable, each
procedure recognizes only its own version of intTemp. Any one procedure can
alter the value in its local intTemp without affecting intTemp variables in other
procedures.
• Memory Consumption. Local variables consume memory only while their
procedure is running. Their memory is released when the procedure returns to
the calling code. By contrast, Shared (Visual Basic) and Static (Visual Basic)
variables consume memory resources until your application stops running, so
use them only when necessary. Instance variables consume memory while their
instance continues to exist, which makes them less efficient than local
variables, but potentially more efficient than Shared or Static variables.
Q> Develop a console application to demonstrate scope of variables in a module.
variableScope.vb
compiled by RJ , 9892544177 49
50. How to: Control the Scope of a Variable (Visual Basic or VB.net)
To make a variable visible only within a block
• Place the Dim Statement (Visual Basic) for the variable between the
initiating and terminating declaration statements of that block, for example
between the For and Next statements of a For loop.
To make a variable visible only within a procedure
• Place the Dim statement for the variable inside the procedure but outside
any block (such as a While...End While block).
To make a variable visible throughout a module, class, or structure
• Place the Dim statement for the variable inside the module, class, or
structure, but outside any procedure.
• Include the Private (Visual Basic) keyword in the Dim statement.
• You can refer to the variable from anywhere within the module, class, or
structure, but not from outside it.
compiled by RJ , 9892544177 50
51. To make a variable visible throughout a namespace
• Place the Dim statement for the variable inside the module, class, or
structure, but outside any procedure.
• Include the Friend (Visual Basic) or Public (Visual Basic) keyword in the Dim
statement.
• You can refer to the variable from anywhere within the namespace
containing the module, class, or structure.
Example: Declares a variable at module level and limits its visibility to code within the module.
compiled by RJ , 9892544177 51
52. Case study 1: The Investment Calculation Application
To be done by students as Home practicals
I/O of The Investment Calculator:
1 InvestCalc.exe
2 Initial Balance: 10000
3 Annual Interest (e.g. for 5%, enter 5): 5
4 Monthly Deposit: 200
5 Years of Investment: 30
6
7 If you start with $10,000.00,
8 and invest $200.00 per month
9 for 30 years
10 at 5% interest.
11 Your final balance would be: $211,129.17
compiled by RJ , 9892544177 52
53. Logic to be implemented
The program requires the user to enter the four values (Initial Balance,
Annual Interest, Monthly Deposit, and Years of Investment). In turn,
the program calculates the final balance. This calculation is known
as the Future Value (FV) calculation.
The formula( given in Question) for Future Value is
FV = MonthlyDeposit * (((1 + MonthlyInterest)^Months - 1 ) /
MonthlyInterest ) + StartingBalance * ( 1 + MonthlyInterest )^Months
FV = 200 * ( ( ( 1+5 /1200) ^ 360 – 1) / (5 / 1200) ) + 10000 * ( 1+
(5/1200) ) ^ 360
Refer awt pracs> ConsoleApplication2
compiled by RJ , 9892544177 53
54. Solution
• Create new project in Visual Basic .NET. Select
option “visual Basic Console Application”.
( Visual Basic .NET creates a new project with one module.)
2. Rename the file using the Solution Explorer. Right-click
on the filename Module1.vb in the Solution Explorer
and select Rename. Change the filename to
modInvest.vb.
3. Change the name of the Startup Object, also. Right-click
on the project in the Solution Explorer and select
Properties. On the General page, change the Startup
Object to Invest.
compiled by RJ , 9892544177 54
55. Controlling Flow in Programs
Visual basic.net consists of two categories of control statements:
1. Choice statements ( If , If-Else ,If-Elseif-Else, and select case)
2. Looping statements
• For..Next loop
• while..End While loop
• Do loop
compiled by RJ , 9892544177 55
56. Choice statements
The If statement
SYNTAX:
If <condition>Then
Code to execute if the condition is true
End If
Example program for If statement
Develop Application : Following are the grading rule of the mark list:
1) If the marks is greater than 80 then the student get higher first class
2) If the marks less than 80 and greater than 60 then the student get first class
3) If the marks less than 60 and greater than 40 then the student get second class
4) The last condition is , if the marks less than 40 then the student fail.
Refer loop demo > Windows Application 7 [change mark in the program]
compiled by RJ , 9892544177 56
57. Boolean Expressions and Boolean Logic
1. Comparison Operators:
– >, greater than
– <, less than
– =, equal to
– <>, not equal to
– >=, greater than or equal to
– <=, less than or equal to
– Like
Special characters that can be used with Like include
* to indicate any number of additional characters
? to represent one character
# to represent any digit (0–9)
Ranges ([a-g], for example) to specify that any character within that
range should be considered a match.
compiled by RJ , 9892544177 57
58. Example program using If statement and Like operator
(PatternMatcher.vb)
1 Public Class PatternMatcher
2 Shared Sub Main()
3 Dim sInput As String
4 Dim sPattern As String
5 Dim sMatch As String
6
7 System.Console.Write(“Please Enter A Pattern:”)
8 sInput = System.Console.ReadLine()
9 sPattern = sInput
10
11 System.Console.Write(“Please Enter A String To Compare
Against:”)
12 sInput = System.Console.ReadLine()
13 sMatch = sInput
14
compiled by RJ , 9892544177 58
59. 15 If sMatch Like sPattern Then
16 System.Console.WriteLine(sMatch & “ Matched with “ & sPattern)
17 Else
18 System.Console.WriteLine(sMatch & “ did not Match with “ & sPattern)
19 End If
20 End Sub
7 End Class
compiled by RJ , 9892544177 59
60. Loops :
Whenever you face a situation in programming to repeat a task for
several times (more than one times ) or you have to repeat a task till
you reach a condtition, in these situations you can use loop statements
to achieve your desired results.
• FOR NEXT Loop, FOR EACH Loop , WHILE Loop and DO WHILE Loop are the
Commonly used loops in Visual Basic.NET 2010 .
FOR NEXT Loop :
• The FOR NEXT Loop , execute the loop body (the source code within For ..Next code
block) to a fixed number of times.
• For var=[startValue] To [endValue] [Step] [loopBody] Next [var]
var : The counter for the loop to repeat the steps.
starValue : The starting value assign to counter variable .
endValue : When the counter variable reach end value the Loop will stop .
loopBody : The source code between loop body.
compiled by RJ , 9892544177 60
61. Show a messagebox 5 times and each time you want to see how many times
the message box shows. Logic : refer loop demo > windows application3
1. startVal=1
2. endVal = 5
3. For var = startVal To endVal
4. show message
5. Next var
compiled by RJ , 9892544177 61
62. If you want to Exit from FOR NEXT Loop even before completing the loop
Visual Basic.NET provides a keyword Exit to use within the loop body.
Refer loop demo > Windows Application 4
Nested For loop
Create a 2 dimensional array using 2 for loops.
Refer loop demo > Windows Application 6
While ..End While
Syntax :
While [condition]
[loop body]
End While
Refer loop demo > Windows Application 5
compiled by RJ , 9892544177 62
63. Logical Operators:
Binary : AND, OR, and XOR
Unary :NOT
Viva : What is Short Circuiting Concept?
To make Visual Basic .NET short-circuit a Boolean expression, we
need to use alternative forms of the AND and OR operators,
ANDALSO and ORELSE.
compiled by RJ , 9892544177 63
64. Example program to test ANDALSO:
ShortCircuiting.vb
1 Public Class ShortCircuiting
2
3 Shared Sub Main()
4 If Test(“Left”) ANDALSO Test(“Right”) Then
5 ‘do something
6 End If
7 End Sub
8
9 Shared Function Test(sInput As String) As Boolean
10 System.Console.WriteLine(sInput)
11 Test = FALSE
12 End Function
13
14 End Class
compiled by RJ , 9892544177 64
65. WhileSearch.vb
1 Imports System Demonstrate use of AND operator
2 Public Class WhileExample
4 Shared Sub Main()
4 Dim iCounter As Integer = 0
5 Dim arrList(10) As String
6 Dim iMatch As Integer = -1
7 Dim sMatch As String
8 sMatch = “Chembur”
9 arrList(0) = “thane”
10 arrList(1) = “Chembur”
11 arrList(2) = “Ghatkopar”
12 arrList(3) = “dadar”
13 arrList(4) = “Borivali”
14 arrList(5) = “andheri”
15 arrList(6) = “Nerul”
16 arrList(7) = “Panvel”
17 arrList(8) = “Belapur”
18 arrList(9) = “Worli”
19 While iCounter <= 9 AND iMatch = -1
65
compiled by RJ , 9892544177
66. 20 If arrList(iCounter) Like sMatch Then
21 iMatch = iCounter
22 Else
23 iCounter = iCounter + 1
24 End If
6 End While
26 If iMatch <> -1 Then
27 System.Console.WriteLine(“Matched “ & iMatch)
28 End If
29 End Sub
31 End Class
compiled by RJ , 9892544177 66
67. Do Loop:
SYNTAX:
Do
Code to be executed
Loop
The syntax doesn’t specify any exit condition so the code will continue to
execute forever.
There are 2 forms :
Do While iMatch = 3 // note : Truewala
// Code to be executed
Loop
Do Until Not (iMatch = 3) // note : Falsewala
‘iMatch <> 3 would have also worked
Loop
compiled by RJ , 9892544177 67
68. Q> Write a Program to read from a file using Do…Loop and .Net
Framework classes.
NOTE:
Use two different objects, both part of the System.IO namespace of the .Net
Framework, System.IO.File and System.IO.StreamReader.
System.IO.File has methods like open(), openText() , openRead() , openwrite()
System.IO.StreamReader : has methods like read() and readLine()
compiled by RJ , 9892544177 68
69. 1 Public Class ReadFromFile
2
3 Shared Sub Main()
4 Dim sFileName As String
5 Dim srFileReader As System.IO.StreamReader
6 Dim sInputLine As String
7
8 sFileName = “MySampleFile.txt”
9 srFileReader = System.IO.File.OpenText(sFileName)
10 sInputLine = srFileReader.ReadLine()
11 Do Until sInputLine is Nothing
12 System.Console.WriteLine(sInputLine)
13 sInputLine = srFileReader.ReadLine()
14 Loop
15 End Sub
16 End Class
Note : To run this code create a text file with sample content in the same
directory as the compiled executable. [ file class in detail in module 3 ]
compiled by RJ , 9892544177 69
70. Define Recursion with an example. (RecursiveFactorial.vb )
1 Public Class RecursiveFactorial
2 Shared Sub Main()
3 Dim sInput As String
4 Dim iInput As Integer
5 Dim iCounter As Integer
6 Dim iFactorial As Integer
7 System.Console.Write(“Please Enter A Number: “)
8 sInput = System.Console.ReadLine()
9 iInput = CInt(sInput)
10 System.Console.WriteLine(Factorial(iInput))
11 End Sub
12
13 Shared Function Factorial(n as Integer) as Integer
14
15 If n = 1 Then
16 Return 1
17 Else
18 Return n * Factorial(n-1)
19 End If
20 End Function
21 End Class
compiled by RJ , 9892544177 70
71. Module 3: Streams And Files
Stream : It is a flow of information that passes in some sequential manner.
compiled by RJ , 9892544177 71
72. Methods of the File Class
Methods Description
Copy Copies a file.
Create Creates a new file.
CreateText A special version of Create that creates a text file.
Delete Deletes a file.
Exists Returns True if the file exists.
Open Opens a file for reading, writing, or both.
OpenRead Specialized version of Open that always opens the file for reading.
Specialized version of Open that opens text files only for reading.
OpenText This would be a handy shortcut if you were writing an application
that needed to read configuration information, or a log file.
OpenWrite Specialized version of Open that always opens the file for writing.
compiled by RJ , 9892544177 72
73. Methods and Properties of FileStream.
Viva : why use Filestream class over File class?
Filestream class is having more defined methods for reading, writing.
Name Description
// Property
Length Number of bytes in the file.
Position The current position in the file.
Close ( ) Closes the FileStream.
Read ( ) Reads a number of bytes from the FileStream. The return value is an
array.
Seek ( ) Moves forward or backward through the file.
Write ( ) Writes a number of bytes to the FileStream.
compiled by RJ , 9892544177 73
74. Viva Q : We always read from StreamReader
which reads with FileStream
The Read method of the FileStream class deals with bytes.
If you apply a StreamReader to the FileStream we can read
information in the file as Chars or ints or whatever form they are.
compiled by RJ , 9892544177 74
75. Important Methods of the StreamReader
Name Description
Close Closes the StreamReader.
Read Reads the next character from the Stream. (one character at a time.)
ReadBlock Reads a block of characters from the Stream.
ReadLine Reads the next line from the Stream. Viva : used wrt Files
ReadToEnd Reads all the characters from the Stream at once.
This is the fastest way to get all the information out of the Stream and into
a variable.
compiled by RJ , 9892544177 75
76. Eg 1: Reading from a File . List steps for creating a file.
A> 1st create obj of FileStream, 2nd create obj StreamReader
1 Dim oFile As FileStream
2 Dim oReader As StreamReader
3 Dim sContents As String
5 oFile = New FileStream(“MyFile.txt”, FileMode.OpenOrCreate,
FileAccess.Read)
7 oReader = New StreamReader(oFile)
9 sContents = oReader.ReadToEnd()
7 oReader.Close()
8 oReader = Nothing
9 oFile = Nothing
compiled by RJ , 9892544177 76
77. Writing to a Text File using
StreamWriter
Name Description
Close Closes the StreamWriter.
Write Writes to the Stream.
WriteLine Writes to the Stream, ending the added information with a new
line.
compiled by RJ , 9892544177 77
78. Eg 2: Writing to a File
1 Dim oFile As FileStream
2 Dim oWriter As StreamWriter
3 oFile = New FileStream(“MyFile.txt”, _
4 FileMode.OpenOrCreate, FileAccess.Write)
5 oWriter = New StreamWriter(oFile)
6 ’Writes the Integer 123 to the file
7 oWriter.Write(123)
8 ’Writes the String “Customer” to the file
9 oWriter.Write(“Customer”)
10 ’Writes the String “Suven Consultants” to the file, next writes will be on a
new line
11 oWriter.WriteLine(“Suven Consultants”) //Writes on the new line
12 oWriter.Close()
13 oWriter = Nothing
14 oFile = Nothing
compiled by RJ , 9892544177 78
79. Example: Create a temporary file and writes some text to it. Then open the file,
using System.IO.FileMode.Open; that is, if the file did not already exist, it
would not be created.
1> The declaration of the Open is
Public Shared Function Open (path As String, mode As FileMode ) As FileStream
refer awt pracs > file demo.
compiled by RJ , 9892544177 79
80. Module 4 : EXCEPTION HANDLING
Syntax for Try…End Try ( or syntax for exception handling )
Q. Write a program with intentional exception, so you can see how it works and
do exception handling.
Ans >
compiled by RJ , 9892544177 80
81. 1 Module modExceptional
2 Sub Main()
3 Dim dDividend As Decimal = 5
4 Dim dDivisor As Decimal = 0
6 Dim dResult As Decimal = 0
8 dResult = dDividend / dDivisor
7 System.Console.ReadLine()
8 End Sub
9
10 End Module
compiled by RJ , 9892544177 81
82. The o/p of the above program through IDE
compiled by RJ , 9892544177 82
83. The o/p of the above program through command prompt
1 Unhandled Exception: System.DivideByZeroException:
2 An exception of type System.DivideByZeroException was thrown.
3 System.Decimal.Divide(Decimal d1, Decimal d2)
4 at Exceptions.modExceptional.Main() in
5 modExceptional.vb:line 6
Note : Moment the program runs , as it contains an exception , the line
at which an exception occurs Just-In-Time Debugging dialog
opens. Select No. then we see the above o/p.
compiled by RJ , 9892544177 83
84. Exception handling in the Above program
1 Module modExceptional
2 Sub Main()
3 Dim dDividend As Decimal = 5
4 Dim dDivisor As Decimal = 0
5 Dim dResult As Decimal = 0
6 Try
7 dResult = dDividend / dDivisor
8 Catch Ex As Exception
9 System.Console.WriteLine(“A division by zero error has occurred.”)
10 System.Console.WriteLine(“Please check the divisor.”)
11 End Try
12 System.Console.ReadLine()
13 End Sub
14 End Module
compiled by RJ , 9892544177 84
85. Q. Can try-blocks be nested. Demonstrate with program
which writes days current time and date to a file.( 4m )
1 Sub WriteToFile(ByVal FileName As String)
2 Dim fsOut As System.IO.FileStream
3 Dim strOut As System.IO.StreamWriter
4 Try
5 ‘Open the File Open, OpenCreate,
6 fsOut = _ OpenRead,OpenWrite
7 New System.IO.FileStream(FileName, _
8 System.IO.FileMode.OpenOrCreate, _
9 System.IO.FileAccess.Write)
10 Try
11 ‘Write to the file
12 strOut = _ Today , now attributes
13 New System.IO.StreamWriter(fsOut)
14 strOut.Write(DateTime.Today.ToString())
15 Catch eIO As Exception
compiled by RJ , 9892544177 85
86. 16 Console.WriteLine(“Couldn’t write to file: {0}.”, FileName)
17 End Try
18 Catch eFile As Exception
19 Console.WriteLine(“Couldn’t open file: {0}.”, FileName)
20 End Try
21 End Sub
compiled by RJ , 9892544177 86
87. Raising Exceptions by using “Throw” keyword
The Throw Statement
1 Dim oCust As Customer = New Customer(“abc”, “xyz”)
3 Dim oEmp As Employee = New Employee(“abc1”, “xyz1”)
// assumption …
3 Dim oSomething As Object
4 oSomething = oEmp
5 If TypeOf oSomething Is Customer Then
6 oCust = oSomething
7 Else
8 Throw New InvalidCastException(“Cannot assign an Employee to a Customer.”)
9 End If
O/p: Opens dialog box (by the default debugger) with the message above.
compiled by RJ , 9892544177 87
88. List all the exceptions that might occur when calling the File.Open method. Or
All exceptions related to file operations
To test this procedure, try a number of specific exceptions. For example, change the file
name to be:
In a valid path, but select a file that doesn't exist.
On a drive that doesn't exist.
In a path that doesn't exist.
On a drive that isn't ready.
compiled by RJ , 9892544177 88
89. If no file name given
If wrong file name given
If Nothing entered
Self
explanatory
compiled by RJ , 9892544177 89
91. List all exceptions under the ArgumentException class.
ArgumentException is thrown when a method is invoked and at least one of the passed
arguments does not meet the parameter specification of the called method.
ArgumentNullException whenever a null reference (Nothing in Visual Basic) is
passed to a method that does not accept it as a valid argument.
ArgumentOutOfRangeException when the value of an argument is outside the
range of acceptable values; for example, when the value "46" is passed as the month
argument during the creation of a DateTime.
InvalidEnumArgumentException thrown when using invalid arguments that are
enumerators.
compiled by RJ , 9892544177 91
93. Home assignment
2. Specify with e.g.. ( not complete code ) use of following exceptions
• ArgumentNullException
• ArgumentOutOfRangeException
• IndexOutOfRangeException
• OverflowException
• FileNotFoundException
compiled by RJ , 9892544177 93
94. An IndexOutOfRangeException exception is thrown when an attempt is made
to access an element of an array or collection with an index that is outside the
bounds of the array or less than zero.
• Make sure that the maximum index on a list is less than the list size
• Make sure the index is not a negative number.
• Make sure data column names are correct.
Example :
Uses a Try…Catch block to trap the IndexOutOfRangeException when
index i is outside the array bounds, 0 to 3.
The example displays the following:
• Element at index 0: 3
• Element at index 2: 5
• Element at index -1: IndexOutOfRangeException caught
• Element at index 4: IndexOutOfRangeException caught
compiled by RJ , 9892544177 94
96. The exception that is thrown when an arithmetic, casting, or conversion
operation in a checked context results in an overflow.
compiled by RJ , 9892544177 96
98. Creating Classes:
Step 1 > Open up Visual Studio .NET, and
create a new Empty Project from under
the Visual Basic Projects folder.
Step 2 > Add Class from the project menu.
This adds a new, empty class to the
project.
Step 3> The above class is empty ,
therefore put Properties into it.
In Vb.NET property is a special method
which is designed to assign and read
values of class data. Each property has
2 methods get( ) and set( ). Get is used
for retr values and set used for initzn it.
98
99. Eg . Of Set and Get methods
Understand a class definition , using constructor.
Refer exp 4> module 4.vb – this console application does not use get() and set()
Understand class definition with get() and set() , interface definition.
Refer exp 5> module 4.vb
compiled by RJ , 9892544177 99
100. Why to create Properties.
• To create a property within a class, you can either create a field (i.e.. a
Public variable), or you can create a Private variable and expose the Private
variable using a Property statement.
There are several reasons to expose properties through a Property statement.
• You can create a read-only or write-only property, as opposed to a Public
variable, which will always be read-write.
• You can add error handling within a Property statement to check for invalid
values being set. You can't check for invalid values when setting a Public
variable because there is no code that runs in response to setting a Public
variable.
• You can expose calculated values as properties even if they are not stored
as actual data within the class.
compiled by RJ , 9892544177 100
101. Properties can be
1> ReadOnly
2> WriteOnly
For a write-only property
Dim m_sPassword As String
Public WriteOnly Property Password() // no rtype as no get method
Set(ByVal Value As String)
m_sPassword = Value
End Set
compiled by RJ , 9892544177 101
102. Develop the sub main () to instantiate an object of class Line .
output :
compiled by RJ , 9892544177 102
103. Overloading : By using Overloads keyword ahead of the Function or Sub
Definition:
Use:
Refer exp 5 > module3.vb
How would we call these methods with different set of parameters.
>
compiled by RJ , 9892544177 103
104. Inheritance : Child class deriving properties from a parent, using keyword inherits
Understand single Inheritance
Refer exp 5 > module1.vb
Understand multi level Inheritance
Refer exp 5 > solved.vb
Understand multiple Inheritance ( same as java using Class and Interface)
Refer exp 5 > module2.vb
compiled by RJ , 9892544177 104
105. Over riding
• Derived classes inherit properties and methods defined in their base class. This
is useful because it means you can reuse these items when appropriate for the
class you are using. If the inherited member cannot be used "as is" you have the
option of using the Overrides keyword to define a new implementation, provided
that the property or method in the base class is marked with the Overridable
keyword, or shadowing the member by redefining it in the derived class.
• Overridden members are used to implement polymorphism.
The following rules apply to overriding methods.
• You can only override members that are marked with the Overridable keyword
in their base class.
• Properties and methods are NotOverridable by default.
• Overridden members must have the same arguments as the inherited members
from the base class.
• The new implementation of a member can call the original implementation in the
parent class by specifying MyBase before the method name.
compiled by RJ , 9892544177 105
106. Q> what is the use of the k/w “Overridable ”.
For a child class to override some part of the base class, that portion must
be marked Overridable in the base class definition.
1 Public Class Vehicle
2
3 ‘Code removed for simplicity....
4
5 Public Overridable Function Description() As String
6 Return “This is my generic vehicle description!”
7 End Function
8 End Class
9
10 Public Class Car
11 Inherits Vehicle
12
13 ‘Code removed for simplicity....
14
15 Public Overrides Function Description() As String
16 Return “This is my Car Description”
17 End Function
18
19 End Class
compiled by RJ , 9892544177 106
107. Example defines a base
class, Payroll, and a derived
class, BonusPayroll, which
overrides an inherited
method, PayEmployee.
A procedure, RunPayroll,
creates and then passes a
Payroll object and a
BonusPayroll object to a
function, Pay, that executes
the PayEmployee method of
both objects.
107
compiled by RJ , 9892544177
108. Constructors
Constructors and destructors control the creation and destruction of objects.
• To create a constructor for a class, create a procedure named Sub New
anywhere in the class definition. To create a parameterized constructor,
specify the names and data types of arguments to Sub New.
Eg : Sub New(ByVal sString As String)
Constructors can be overloaded, as in the following code:
Sub New(ByVal sString As String, iInt As Integer)
• When you define a class derived from another class, the first line of a
constructor must be a call to the constructor of the base class, unless the
base class has an accessible constructor that takes no parameters. A call to
the base class containing the above constructor, for example, would be
MyBase.New(sString). Otherwise, MyBase.New is optional, and the Visual
Basic .NET runtime calls it implicitly.
compiled by RJ , 9892544177 108
109. Q> How to define a constructor? (4m)
Ans: The creation of a constructor for Vehicle class
Step 1: create a method named New that is public and has no parameters.
Public Sub New()
End Sub
Step 2: Initialize internal
variables of the class.
Step 3: to call the Base
class constructor fro m
The child class
compiled by RJ , 9892544177 109
110. • Finalize Methods and Destructors
• For the majority of the objects that an application creates, the .NET
Framework's garbage collector implicitly perform all the necessary memory
management tasks.
• However, when you create objects that encapsulate unmanaged resources,
you must explicitly release the unmanaged resources when you are finished
using them in your application. The most common type of unmanaged
resource is an object that wraps an operating system resource, such as a
file, window, or network connection. Although the garbage collector is able
to track the lifetime of an object that encapsulates an unmanaged resource,
it does not have specific knowledge about how to clean up the resource. For
these types of objects, the .NET Framework provides the
Object.Finalize method, which allows an object to clean up its unmanaged
resources properly when the garbage collector reclaims the memory used
by the object.
Implementing Finalize methods or destructors can have a negative impact
on performance and you should avoid using them unnecessarily.
compiled by RJ , 9892544177 110
111. Module 6 : Namespaces (similar to concept of Packages in Java)
Viva : Q : why is it needed.
Namespaces organize the objects defined in an assembly. Assemblies can
contain multiple namespaces, which can in turn contain other namespaces.
Namespaces prevent ambiguity and simplify references when using large
groups of objects such as class libraries. Example of Name Spaces :
Within a namespace, you can define items such as modules, interfaces,
classes, delegates, enumerations, structures, and other namespaces. You
cannot define items such as properties, procedures, variables and events at
the namespace level. These items must be declared within containers such as
modules, structures, or classes.
compiled by RJ , 9892544177 111
112. When should we use global Keyword.
If you have defined a nested hierarchy of namespaces, code inside that
hierarchy might be blocked from accessing the System namespace of the .NET
Framework. The following example illustrates a hierarchy in which the
SpecialSpace.System namespace blocks access to System.
As a result, the Visual Basic compiler cannot successfully resolve the reference
to System.Int32, because SpecialSpace.System does not define Int32. You can
use the Global keyword to start the qualification chain at the outermost level of
the .NET Framework class library. This allows you to specify the System
namespace or any other namespace in the class library. The following example
illustrates this. 112
compiled by RJ , 9892544177
114. • Console: Enables reading and writing to the command-line.
compiled by RJ , 9892544177 114
115. Eg: Using the Console Class for Input and Output .
1 Imports System
2 Public Class ConsoleTest
3 Private Const ITEM_COUNT As Integer = 10
4 Shared Sub Main()
5 Dim I As Integer
6 Dim sItems(ITEM_COUNT) As String
7 Console.WriteLine(“Please enter {0} items. “ & _
8 Press ENTER between items.”, ITEM_COUNT)
8 For I = 0 To ITEM_COUNT-1
9 sItems(I) = Console.ReadLine
10 Next
11 Console.WriteLine()
12 Console.WriteLine(“Items in reverse order:”)
14 For I = ITEM_COUNT - 1 To 0 Step -1
14 Console.WriteLine(sItems(I))
15 Next
16 End Sub
17 End Class
compiled by RJ , 9892544177 115
116. Redirection: sending the o/p and error messages or recv the i/p
from a device or place other than the default
Dg :
1 Imports System
2 Imports System.IO
3 Public Class ConsoleTest
4 Private Const ITEM_COUNT As Integer = 10
5 Shared Sub Main()
13 Dim I As Integer
compiled by RJ , 9892544177 116
117. 6 Dim I As Integer
7 Dim sItems(ITEM_COUNT) As String
8 Dim oFile As TextWriter = File.CreateText(“Output.txt”)
9 Dim oOut As TextWriter = Console.Out //Needed to reset the
output back from file
to monitor.
10 Console.WriteLine(“Please enter {0} items. Press ENTER between
items.”, ITEM_COUNT)
11 For I = 0 To ITEM_COUNT-1
12 sItems(I) = Console.ReadLine
13 Next
14 Console.WriteLine()
15 Console.SetOut(oFile)
16 Console.WriteLine(“Items in reverse order:”)
17 For I = ITEM_COUNT - 1 To 0 Step -1
18 Console.WriteLine(sItems(I))
19 Next
compiled by RJ , 9892544177 117
118. Running the application:
1 [c:workconsole]Console2.exe
2 Please enter 10 items. Press ENTER between items.
3 Aardvark
4 Bandicoot
5 Cassowary
6 Dugong
7 Echidna
8 Finch
9 Giraffe
10 Hippopotamus
11 Iguana
12 Jackalope
13
14 Done
compiled by RJ , 9892544177 118
119. The code should produce a file Output.txt with the following contents:
1 Items in reverse order:
2 Jackalope
3 Iguana
4 Hippopotamus
5 Giraffe
6 Finch
7 Echidna
8 Dugong
9 Cassowary
10 Bandicoot
11 Aardvark
compiled by RJ , 9892544177 119
120. 2. Environment class
Provides information about, and means to manipulate, the current environment and
platform. This class cannot be inherited.
Refer awt pracs >console application 4
120
124. Use the Environment class to retrieve information such as command-line
arguments, the exit code, environment variable settings, contents of the call
stack, time since last system boot, and the version of the common language
runtime.
compiled by RJ , 9892544177 124
126. 3. Random :
Represents a pseudo-random number generator, a device that produces a
sequence of numbers that meet certain statistical requirements for randomness.
Constructors :
Methods
126
compiled by RJ , 9892544177
127. Eg . Random class
Dim oRand As New Random
Dim iValue As Integer = oRand.Next(1, 100)
compiled by RJ , 9892544177 127
128. 4. Collection Classes in the .NET Framework
The .NET Framework provides specialized classes for data storage and
retrieval. These classes provide support for stacks, queues, lists, and hash
tables.
4. A . ArrayList : Is a Array which can hold objects .
Intially it is empty and has the default initial capacity. The size can dynamically
change.
Dim arrList As New ArrayList
‘creates a new ArrayList, with 16 members initially
Dim arrList2 As New ArrayList(20)
‘ creates a new ArrayList, with 20 members initially
Methods : add(int n ), retrieve(int n), and delete(int n)
compiled by RJ , 9892544177 128
132. 4.b) Queue : A Queue is a “first-in, first-out” (FIFO) collection
compiled by RJ , 9892544177 132
133. Queues are useful for storing messages in the order they were received for
sequential processing. This class implements a queue as a circular array. Objects
stored in a Queue are inserted at one end and removed from the other.
The capacity of a Queue is the number of elements the Queue can hold. As
elements are added to a Queue, the capacity is automatically increased as
required through reallocation. The capacity can be decreased by calling
TrimToSize.
The growth factor is the number by which the current capacity is multiplied when a
greater capacity is required. The growth factor is determined when the Queue is
constructed. The default growth factor is 2.0. The capacity of the Queue will
always increase by at least a minimum of four, regardless of the growth factor.
For example, a Queue with a growth factor of 1.0 will always increase in capacity
by four when a greater capacity is required.
Queue accepts Nothing as a valid value and allows duplicate elements.
compiled by RJ , 9892544177 133
135. 4.c) Stack: Is a “first-in, last-out” (FILO) or LIFO collection
135
compiled by RJ ,
9892544177
136. 4.d SortedList: Represents a collection of key/value pairs that are sorted by
the keys and are accessible by key and by index.
A SortedList object internally maintains two arrays to store the elements of the
list; that is, one array for the keys and another array for the associated values.
Each element is a key/value pair that can be accessed as a DictionaryEntry
object. A key cannot be Nothing, but a value can be.
compiled by RJ , 9892544177 136
139. Module 7: Accessing Data with .Net
ADO.Net:
ADO.NET is the data access technology that is part of
the .NET Framework
• In .NET, database access is handled by the classes in
and under the System.Data namespace.
• The namespace is divided into two distinct areas: the
System.Data.OleDB classes and the
System.Data.SQLClient classes. The first set,
System.Data.OleDB, is designed to allow you to connect
to any database for which we have an OLEDB provider
i.e an ODBC driver.
• System.Data.SQLClient, is designed to work only with
Microsoft SQL Server,
compiled by RJ , 9892544177 139
140. Standard Database Tasks( # )
1> Connecting to Database:
Requires 2 elements the connection object and a connection string.
// in java we have simply make a connection object by providing a data source name.
• In ADO.NET, there are two different connection objects
(one for OLEDB and one for SQL Server). Before you can
start coding, you should obtain the proper connection
string for your database. Which can be obtained by
opening special file of Microsoft Datalink.
• Follow these steps to create a Microsoft Datalink file (.udl )
and retrieve from it connection string information:
compiled by RJ , 9892544177 140
141. • Create a blank Microsoft Data Link file by creating a new text file
and renaming it to something with a .udl file extension (New.udl)
• Double-click the new file, and a dialog appears with a set of four
tabs for creating and editing the connection information for your
database.
• Using the dialog that has just opened, start with the first tab,
Provider, and set up the correct information for your database:
– For the Access database select the Microsoft Jet 4.0 provider.
– For SQL Server database, select the Microsoft OLEDB
Provider for SQL Server.
Now the second tab “ Connection tab “, select the path For Access
(.mdb file.) // this depends on provider.
compiled by RJ , 9892544177 141
142. • Test the connection (by Clicking the Test Connection button )
• If the test successful then close datalink properties window
• open the .udl file
It contains the following connection string for access database
[oledb]
; Everything after this line is an OLE DB initstring
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=student;Persist Security Info=False
The contents of a .udl file configured for SQL Server is
[oledb]
; Everything after this line is an OLE DB initstring
Provider=SQLOLEDB.1;Password=password;
Persist Security Info=True;User ID=sa;
Initial Catalog=CD;Data Source=(local)
compiled by RJ , 9892544177 142
143. • To create a connection, you need to create a new instance of either the
System.Data.OleDB.OLEDBConnection
or the
System.Data.SqlClient.SQLConnection
A connection string to make connection with .mdb
1 Module Module1
2 Private Const sConnection As String =”Provider=Microsoft.Jet.OLEDB.4.0;” &_
8 “Data Source=C:CD.mdb;”&_
4 “Persist Security Info=False”
5
6
7 Sub Main()
8 Dim objConn As New System.Data.OleDb.OleDbConnection(sConnection)
9 End Sub
10 End Module
compiled by RJ , 9892544177 143
144. 2> Opening Connection
1 Module Module1
2 Private Const sConnection As String = “Provider=
Microsoft.Jet.OLEDB.4.0;” & _
3 “Data Source=C:CD.mdb;”&_
4 “Persist Security Info=False”
5 Sub Main()
6 Dim objConn As New
System.Data.OleDb.OleDbConnection(sConnection)
7 Try
8 objConn.Open()
9 Catch myException As System.Exception
10 Console.WriteLine(myException.Message)
11 End Try
12 Console.ReadLine()
13 End Sub
14 End Module
compiled by RJ , 9892544177 144
145. For Opening a connection with the SQLServer
Use SQLClient class
Modify the above program :
First: Remove the Provider section from your connection
string and
second : Change your objConn declaration to refer to the
System.Data.SQLClient.SQLConnection object
instead of the OLEDB class.
compiled by RJ , 9892544177 145
146. Opening connection with SQL server #
1 Imports System
2 Module Module1
3 Private Const sConnection As String
4 sConnection = “Password=password;” & _
5 “Persist Security Info=True;” & _
6 “User ID=sa;” & _
7 “Initial Catalog=CD;” & _
8 “Data Source=(local)”
9 Sub Main()
10 Dim objConn As New Data.SqlClient.SqlConnection(sConnection)
11 Try
12 objConn.Open()
13 Catch myException As Exception
14 Console.WriteLine(myException.Message)
15 End Try
16 Console.ReadLine()
17 End Sub
18 End Module
compiled by RJ , 9892544177 146
147. 3. Executing a SQL Statement
After a connection is established we can add, delete, modify, and retrieve
records. To accomplish any of those tasks, you can use a command object
(SQLCommand or OleDBCommand) to represent and then execute a
SQLstatement.
Steps are:
a) Create a connection object using the connection string.
b) Create a command object of OLEDB command or SQL command.
c) Open connection with database. Refer exp6 > Application1
d) Create object of OleDbDataAdapter.
e) Use fill().
This executes the query. DataSet can hold one or more table objects.
f) Use DataGrid.
Dataset cannot show the records of the table, use Datagrid
compiled by RJ , 9892544177 147
148. Data Set (System.Data.DataSet).
.NET provides a totally disconnected model of data access through
the Data Set (System.Data.DataSet). Data Sets are capable of
loading information, from a database and then disconnecting.
Here the data becomes independent of its original source. This
independence from the data source is why this information is
considered disconnected and can be kept for as long as needed in a
totally offline environment.
Note: If u make changes to the dataSet does it affect the data source.
Ans >
compiled by RJ , 9892544177 148
149. 1. Getting Data into a Data Set :
# To load data from the database into a DataSet, we will need a data
adapter. The data adapter objects, SQLDataAdapter and
OleDBDataAdapter, are designed to provide the glue or link between
your database and a DataSet object. This link works in two parts,
filling the DataSet, and then sending changes on the DataSet back
to the data source to update the original data.
Steps : 1> Create a connection object.
2> Create the appropriate data adapter class (OLEDB or SQL)
3> Use the desired SQL statement, or a command object that
refers to the correct SQL, and the connection object in the
constructor of the data adapter, and it will be completely set up
i.e. Data Adapter object is installed.
compiled by RJ , 9892544177 149
150. 4.To fill the dataset with the results of query, a DataSet object must first
be created.
Dim objDS As New DataSet(“dummy_dataSet”)
5. To load the data into the DataSet, use the Fill method of the
DataAdapter, but before that will work, the connection object must
be opened successfully:
objConn.Open()
objDataAdapter.Fill(objDS, “Disc”)
After the above code has executed, a table has been created inside
the DataSet, with the name “Disc”, and filled with the results of your
SQL query.
6. To work with its contents through the DataSet’s Tables collection:
Console.WriteLine(“{0} Rows”, objDS.Tables(“Disc”).Rows.Count)
compiled by RJ , 9892544177 150
151. Viva : dataset is a disconnected model . Justify.
As the DataSet is a disconnected object, you could have completely
closed the connection to your database before working with the
DataSet’s contents; therefore,
objDataAdapter.Fill(objDS, “Disc”)
objConn.Close()
Console.WriteLine(“{0} Rows”, objDS.Tables(“Disc”).Rows.Count)
o/p :
compiled by RJ , 9892544177 151
152. 2. Navigation Data
1> After populating the Data Set, we have to retrieve 1 table out of the data
Set.
( Note : why?
Because Dataset is a collection of tables.)
Dim objTable As DataTable
objTable = objDS.Tables(“Disc”)
The DataTable object provides two collections :
1> The Rows collection, which contains all the records from the table,
and the Columns collection, which contains a collection of
DataColumn objects describing each individual field in the table.
The Rows collection can be used in one of several ways to loop
through all the records of the table:
compiled by RJ , 9892544177 152
153. Eg 1: Using a For Each loop
Dim objRow As DataRow
For Each objRow In objTable.Rows
Console.WriteLine(objRow.Item(“CDTitle”)) // Item() retrieves attr value
Next // it takes index value or attr name
Eg 2: Using a regular For loop
Dim i As Integer
Dim objRow As DataRow
For i = 0 To objTable.Rows.Count - 1
objRow = objTable.Rows(i)
Console.WriteLine(objRow.Item(“CDTitle”))
compiled by RJ , 9892544177 153
154. The Columns collection contains details of the fields of the DataTable, each
one represented as a DataColumn object. We can loop through the table’s
fields using either a For Each or a For loop:
Dim objColumn As DataColumn
For Each objColumn In objTable.Columns
Console.WriteLine(“Column Name: {0} Data Type: {1}”, _
objColumn.ColumnName, _
objColumn.DataType.FullName)
Next
Develop an application - creating a table dynamically in the program and
showing it in the DataGrid. Do not connect to any Database.
Refer Exp6 > application2
compiled by RJ , 9892544177 154
155. Home Assignment
Develop an application having UI to navigate through the database.
Connect to the Student table having at least 2 columns – Roll no. , name.
Use DataView and CurrencyManager object.
Refer Exp6> application3
Develop an application to generate an XML file representing the table. The
table ( DataTable object ) is created by adding some Columns.
To generate XML ( tags showing the schema of the table) , use GetXml()
method over the DataSet object.
Refer Exp7>consolbased
compiled by RJ , 9892544177 155
156. Develop an application – creating
table and writing its schema to an
xml file. Use WriteXML ( String,
WriteXMLMode )
Refer exp 7 > empdetial
Another Example :
Refer exp 7 > solved
// this program contains Contact information
Refer exp 7 > studentinfo
// this program contains student information
compiled by RJ , 9892544177 156
157. 3> Editing Data (Add, Edit, Delete) using DataSet object
When we modify the database through the DataSet the changes are not
committed. The changes you make to the DataSet will be translated by the
DataAdapter into the SQL statements that need to be executed against the
database.
DataAdapter.Update Method
Calls the respective INSERT, UPDATE, or DELETE statements for each
inserted, updated, or deleted row in the specified DataSet from a DataTable
named "Table."
Namespace: System.Data.Common
The update is performed on a by-row basis. For every inserted, modified,
and deleted row, the Update method determines the type of change that has
been performed on it (Insert, Update or Delete). Depending on the type of
change, the Insert, Update, or Delete command template executes to
propagate the modified row to the data source. When an application calls
the Update method, the DataAdapter examines the RowState property, and
executes the required INSERT, UPDATE, or DELETE statements iteratively
for each row, based on the order of the indexes configured in the DataSet.
compiled by RJ , 9892544177 157
158. For example, Update might execute a DELETE statement, followed by an
INSERT statement, and then another DELETE statement, due to the ordering of
the rows in the DataTable.
If INSERT, UPDATE, or DELETE statements have not been specified, the
Update method generates an exception. However, you can create a
SqlCommandBuilder or OleDbCommandBuilder object to automatically generate
SQL statements for single-table updates if you set the SelectCommand property
of a .NET Framework data provider. Then, any additional SQL statements that
you do not set are generated by the CommandBuilder.
Working of the Update method:
• The Update method retrieves rows from the table listed in the first mapping
before performing an update. The Update then refreshes the row using the value
of the UpdatedRowSource property. Any additional rows returned are ignored.
• After any data is loaded back into the DataSet, the OnRowUpdated event is
raised, allowing the user to inspect the reconciled DataSet row and any output
parameters returned by the command. After a row updates successfully, the
changes to that row are accepted.
compiled by RJ , 9892544177 158
159. When using Update, the order of execution is as follows:
• The values in the DataRow are moved to the parameter values.
• The OnRowUpdating event is raised.
• The command executes.
• If the command is set to FirstReturnedRecord, then the first returned result is
placed in the DataRow.
• If there are output parameters, they are placed in the DataRow.
• The OnRowUpdated event is raised.
• AcceptChanges is called.
compiled by RJ , 9892544177 159
160. Adapter has many properties
To create the SQL query
To check for any update
compiled by RJ , 9892544177 160
163. Short note on OleDbCommandBuilder
• The OleDbDataAdapter does not automatically generate the SQL statements required to
reconcile changes made to a DataSet with the associated data source.
• OleDbCommandBuilder object is needed to automatically generate SQL statements for
single-table updates if you set the SelectCommand property of the OleDbDataAdapter.
• The OleDbCommandBuilder registers itself as a listener for RowUpdating events
whenever you set the DataAdapter property. You can only associate one
OleDbDataAdapter or OleDbCommandBuilder object with each other at one time.
• To generate INSERT, UPDATE, or DELETE statements, the OleDbCommandBuilder
uses the SelectCommand property to retrieve a required set of metadata automatically.
• The OleDbCommandBuilder also uses the Connection, CommandTimeout, and
Transaction properties referenced by the SelectCommand. The user should call
RefreshSchema if one or more of these properties are modified, or if the SelectCommand
itself is replaced. Otherwise the InsertCommand, UpdateCommand, and DeleteCommand
properties retain their previous values.
compiled by RJ , 9892544177 163
164. 1. Adding Records
After you have created a connection, created a data adapter, and
loaded some data into your DataSet, you can directly access a
DataTable object:
objDataAdapter.Fill(objDS, “Disc”)
Dim objTable As DataTable
objTable = objDS.Tables(“Disc”)
After you have that DataTable, you can access its contents through the
Rows collection, which returns a DataRowCollection object.
Dim drRows As DataRowCollection
drRows = objTable.Rows
This object represents all the records in the table as a collection of
DataRow objects. The collection itself provides a method, Add, to create
new records.
compiled by RJ , 9892544177 164
165. Adding a DataRow to a Data Table by passing of a DataRow Object
as the Parameter to the Add Method of DataRow collection.
1 Dim drRows As DataRowCollection //Contains all Rows
2 Dim objNewRow As DataRow
3 drRows = objTable.Rows //Returns all Rows
4
5 ‘Assume - we have 3 columns
6 ‘ArtistID
7 ‘ArtistName
8 ‘CDTitle
9
10 objNewRow = objTable.NewRow() //Instantiating a new Row
object with schema/structure of the
ObjTable.
11 objNewRow(“ArtistID”) = 3
12 objNewRow(“ArtistName”) = “Mohit Chawan”
compiled by RJ , 9892544177 165
166. 13 objNewRow(“CDTitle”) = “NewYork”
2 drRows.Add(objNewRow) //Adding new Row to the DataTable
Note : These changes are reflected to the Database Server only after the update( ).
compiled by RJ , 9892544177 166
167. Steps similar to adding records.
objDataAdapter.Fill(objDS, “Disc”)
Dim objTable As DataTable
2. Editing Records:
objTable = objDS.Tables(“Disc”)
Dim drRows As DataRowCollection
Dim objRow As DataRow
drRows = objTable.Rows
objRow = drRows(5) ‘ retriving the 5th row
Each individual DataRow object has several methods for editing:
BeginEdit, EndEdit, and CancelEdit. BeginEdit and EndEdit put the
DataRow into and out of edit mode, which is a special state in which the row
maintains information about the in-progress edit, and therefore change
events will not fire for each individual field modification.
For Eg:
objRow.BeginEdit()
objRow(“student_name”) = “Suven”
objRow.EndEdit()
compiled by RJ , 9892544177 167
168. 3. Deleting Records:
objDataAdapter.Fill(objDS, “Disc”)
Dim objTable As DataTable
objTable = objDS.Tables(“Disc”)
Dim drRows As DataRowCollection
Dim objRow As DataRow
drRows = objTable.Rows
objRow = drRows(3) // Retreiving 3rd row
objRow.delete() // or drRows.Remove(3)
Note : Remove() used when changes are not to be
committed to the database. Therefore used delete().
compiled by RJ , 9892544177 168
169. Demonstrate use of adapter.DeleteCommand and ExecuteNonQuery()
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As New SqlDataAdapter
Dim sql As String connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
sql = "delete product where Product_name ='Product7'"
Try
Refer awt pracs>DB Navigation
connection.Open()
adapter.DeleteCommand = connection.CreateCommand
adapter.DeleteCommand.CommandText = sql
adapter.DeleteCommand.ExecuteNonQuery()
MsgBox("Row(s) deleted !! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
compiled by RJ , 9892544177 169
End Class
170. Module 8: Multi threading - Concept and Program
Multithreading is new to VB .NET. The .NET Framework, and thus VB.NET
provides full support for multiple execution threads in a program. You can
add threading functionality to your application by using the
System.Threading namespace.
– A thread in .NET is represented by the System.Threading.Thread class. We
can create multiple threads in our program by creating multiple instances
(objects) of this class.
– A thread starts its execution by calling the specified method and terminates
when the execution of that method gets completed. We can specify the
method name that the thread will call when it starts by passing a delegate of
the ThreadStart type in the Thread class constructor. The delegate
System.Threading.ThreadStart may reference any method which has the
void return type and which takes no arguments.
compiled by RJ , 9892544177 170
171. Example below does not use Multithreading
Public Sub Main()
Fun1()
Fun2() The output of the program is:
Console.WriteLine("End of Main()")
End Sub
Fun1() writes: 1
Public Sub Fun1()
Fun1() writes: 2
Dim i As Integer Fun1() writes: 3
For i = 1 To 5 Fun1() writes: 4
Console.WriteLine("Fun1() writes: {0}", i) Fun1() writes: 5
Next Fun2() writes: 10
Fun2() writes: 9
End Sub Fun2() writes: 8
Public Sub Fun2() Fun2() writes: 7
Dim i As Integer Fun2() writes: 6
For i = 10 To 6 Step -1 End of Main()
Console.WriteLine("Fun2() writes: {0}", i)
Next
End Sub
compiled by RJ , 9892544177 171
172. The method Fun2() only started its execution when Fun1() had completed its
execution. This is because when a method gets called, the execution control
transfers to that method. And when the method returns the execution starts
from the very next line of the code that called the method. i.e. the program
implicitly has only one execution path. Using multithreading, we can define
multiple concurrent execution paths within our program called threads.
For example, we can use threads so that the two methods Fun1() and
Fun2() may execute without waiting for each other to terminate.
Imports System.Threading
Public Sub Main()
Dim firstThread As New Thread(New ThreadStart(AddressOf Fun1))
Dim secondThread As New Thread(New ThreadStart(AddressOf Fun2))
firstThread.Start()
secondThread.Start()
Console.WriteLine("End of Main()")
End Sub
compiled by RJ , 9892544177 172
173. Public Sub Fun1()
Here we have created two instances
Dim i As Integer of the Thread class and passed a
For i = 1 To 5 ThreadStart type delegate in the
constructor which references a
Console.WriteLine("Fun1() writes: {0}", i) method in our program.
It is important that the method
Next referenced in the Thread class
End Sub constructor, through the ThreadStart
delegate is parameter-less and has
no return type.
Public Sub Fun2()
We have to start the execution of a
Dim i As Integer thread by calling the Start() method
For i = 10 To 6 Step -1 of the Thread class.
Console.WriteLine("Fun2() writes: {0}", i) The output of the program would now
be interleaving Fun1 () and Fun2()
Next
End Sub
End Module
compiled by RJ , 9892544177 173
174. Synchronization of thread in VB.NET
Note : Does VB6 support Multi – threading.
No. VB6 supports multiple single-threaded apartments. This means each individual thread
application ( i.e. an apartment ) can use only the same set of data. Data cannot be shared
and a thread cannot be run in the background.
To understand synchronization, 1st understand a multithreaded program without
synchronize method (Thread.join ( )) and then with Thread.join().
Public Class SquareClass Use this code to start the CalcSquare procedure on a new
Public Value As Double thread, as follows:
Public Square As Double
// code in a form, add a button and handle button click
Private Sub Button1_Click(ByVal sender As System.Object,_
Public Sub CalcSquare() ByVal e As System.EventArgs) Handles Button1.Click
Square = Value * Value Dim oSquare As New SquareClass()
End Sub t = New Thread(AddressOf oSquare.CalcSquare)
oSquare.Value = 30
End Class
t.Start()
End Sub
compiled by RJ , 9892544177 174
175. We do not inspect the square value of the class, because it is not guaranteed to have
executed once you call the start method of the thread. i.e. there is no synchronization.
There are a 2 ways to synchronize
• By raising an event when the thread is complete.
• By using Thread. join().
compiled by RJ , 9892544177 175
176. Method 1:
Public Class SquareClass
Public Value As Double
Public Square As Double
Public Event ThreadComplete(ByVal Square As Double)
Public Sub CalcSquare()
Square = Value * Value
RaiseEvent ThreadComplete(Square)
End Sub
End Class
// code in a form, add a button and handle button click
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
oSquare = New SquareClass()
t = New Thread(AddressOf oSquare.CalcSquare)
oSquare.Value = 30
t.Start()
End Sub
Sub SquareEventHandler(ByVal Square As Double) _
Handles oSquare.ThreadComplete
MsgBox("The square is " & Square)
End Sub
End Class
compiled by RJ , 9892544177 176