Introtodotnet

178
Advanced web technologies - 12261 compiled by RJ , 9892544177 1 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 Book1 contains VB.net part

description

 

Transcript of Introtodotnet

Page 1: Introtodotnet

Advanced web technologies - 12261

compiled by RJ , 9892544177 1

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

Book1 contains VB.net part

Page 2: Introtodotnet

compiled by RJ , 9892544177

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 UI1975 – QBASICProb : slow response time1976 – 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.

2

Page 3: Introtodotnet

compiled by RJ , 9892544177

What is .NET ?

3

Page 4: Introtodotnet

compiled by RJ , 9892544177

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 4

Page 5: Introtodotnet

compiled by RJ , 9892544177

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

5

Page 6: Introtodotnet

compiled by RJ , 9892544177

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:\TYVB\C1>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:\TYVB\C1>step2 We are engineering students

6

Page 7: Introtodotnet

compiled by RJ , 9892544177

What are command line switches? ( 4m )

Command line switches are used to configure the output according to application requirement.

Eg. Of switches are

1. /target or /t : < winexe or exe or library or module>

2. /out : < filename >

3. /help ( or /?)

7

Page 8: Introtodotnet

compiled by RJ , 9892544177

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.

8

Page 9: Introtodotnet

compiled by RJ , 9892544177

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

Page 10: Introtodotnet

compiled by RJ , 9892544177

Use ErrorProvider control to report an error message.

If TextBox1.Text = "" Then

ErrorProvider1.SetError(TextBox1, "plz enter a name")

e.Cancel = True

Else

If IsNumeric(TextBox1.Text) Then

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.

10

Indicates that the error control should be shown.

Page 11: Introtodotnet

Coding steps

ErrorProvider1.SetError(TextBox1, "") -

Private Sub Button1_Click(ByVal sender As Object,

ByVal e As System.EventArgs)

Handles Button1.Click

End

End Sub

Sub Form1_Load (ByVal sender As System.Object,

ByVal e As System.EventArgs)

Handles MyBase.Load

compiled by RJ , 9892544177 11

Viva : difference between end and exit

Handles ?

Page 12: Introtodotnet

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

Page 13: Introtodotnet

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

Page 14: Introtodotnet

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

ErrorProvider1.SetError(TextBox1, "enter an amount")

e.Cancel = True

Else

If IsNumeric(TextBox1.Text) Then

ErrorProvider1.SetError(TextBox1, "")

Else

ErrorProvider1.SetError(TextBox1, "enter an correct amount")

e.Cancel = True

End If

End If

compiled by RJ , 9892544177 14

Blank not allowed

No numbers allowed

Page 15: Introtodotnet

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

Page 16: Introtodotnet

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

Page 17: Introtodotnet

compiled by RJ , 9892544177

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.

1. Integer

2. Numbers with Decimal Places

3. Strings and Characters

4. Boolean

5. Date17

Page 18: Introtodotnet

compiled by RJ , 9892544177

Data Type ( integer) Size (Bytes) Range

Byte

Short

Integer

Long

1

2

4

8

0 to 255

-32,768 to 32,767

-2,147,483,648 to 2,147,483,647

–9,223,372,036, 854,775,808, 9,223,372,036,854,775,807

18

Page 19: Introtodotnet

compiled by RJ , 9892544177

Data Type ( number with decimal places) Size (Bytes) Range

Single

Double

4

8

–3.402823 × 10^38to –1.401298 × 10^–45

for negative numbers;1.401298 × 10^–45to 3.402823 × 10^38for positive numbers–1.79769313486231 × 10^308 to–4.94065645841247 × 10^–324for negative numbers;4.94065645841247 × 10^–324 to1.79769313486232 × 10^308 forpositive numbers

19

Page 20: Introtodotnet

compiled by RJ , 9892544177

Data Type Size (Bytes) Range

Char String

2 10+2Percharacter

One characterUp to 2 billioncharacters

Data Type Size (Bytes) Range

Boolean

Date

2

8

True or False

January 1, 100 to December 31,9999

20

Page 21: Introtodotnet

compiled by RJ , 9892544177

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

21

Page 22: Introtodotnet

compiled by RJ , 9892544177

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

22

Page 23: Introtodotnet

compiled by RJ , 9892544177

8 ‘Changing the size of an existing array9 ReDim dtDates(4)10 ‘fill the list of dates of sem 6 TT11 dtDates(0)=”4/24/2011” ‘management // 2nd way of initzn12 dtDates(1)=”4/27/2011” ‘s/w testing or DCNE13 dtDates(2)=”5/03/2011” ‘AJP14 dtDates(3)=”5/06/2011” ‘AWT

15 ‘Declaration with Initialization16 Dim sMonths() As String = {“Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”, _17 “Jul”,”Aug”,”Sep”,”Oct”,”Nov”,”Dec”} // 3rd way of initzn

18 ‘Using arrays19 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))

23

Page 24: Introtodotnet

compiled by RJ , 9892544177

Constants

Constants are declared using one of the two forms

Const PI = 3.1415 As Double

Const DSN As String = “Random”

24

Page 25: Introtodotnet

compiled by RJ , 9892544177

BUILT-IN FUNCTIONS

Function Description

CBool

CByte

CChar

CDate

CDbl

CInt

CLng

CSht

CStr

CType

Converts to a Boolean. Anything that evaluates to False or 0 will be set to False; otherwise, it will be True. Converts to a Byte. Any value greater than 255, or any fractional information,will be lost. 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.

Converts to a Date. One of the more powerful conversion functions, CDate can recognize some of the more common formats for entering a date.

Converts to a Double.

Converts to an Integer. Fractions are rounded to the nearest value.

Converts to a Long. Fractions are rounded to the nearest value.

Converts to a Short. Fractions are rounded to the nearest value.

Converts to a String. If the value is a Date, this will contain the Short Date format.

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.

25

Refer awt pracs > variables

Page 26: Introtodotnet

compiled by RJ , 9892544177

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

26

Page 27: Introtodotnet

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

Page 28: Introtodotnet

Example: uses the CChar function to convert the first character of a String expression to a Char type.

compiled by RJ , 9892544177 28

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.

Page 29: Introtodotnet

Example: uses the CDate function to convert strings to Date values.

Example of Cdbl

compiled by RJ , 9892544177 29

Page 30: Introtodotnet

Example of Clng() function

compiled by RJ , 9892544177 30

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.

Page 31: Introtodotnet

CSng Example

Example: uses the CStr function to convert a numeric value to String.

compiled by RJ , 9892544177 31

Page 32: Introtodotnet

Example: uses the CStr function to convert Date values to String values.Or short note on CStr()

compiled by RJ , 9892544177 32

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.

Page 33: Introtodotnet

String Manipulation Functions : The following table lists the functions that Visual Basic provides to search and manipulate strings.

compiled by RJ , 9892544177 33

Page 34: Introtodotnet

compiled by RJ , 9892544177 34

Page 35: Introtodotnet

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.

compiled by RJ , 989254417735

Refer awt pracs > Console Application3

Page 36: Introtodotnet

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

Page 37: Introtodotnet

Example: uses the InStr function to return the position of the first occurrence of one string within another.

compiled by RJ , 9892544177 37

Page 38: Introtodotnet

compiled by RJ , 9892544177

Home AssignmentA> 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

38

Page 39: Introtodotnet

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

Page 40: Introtodotnet

Develop console application for showing different date and time formats.Dateformatspecifiers.vb

compiled by RJ , 9892544177 40

Refer > console Application 1

Page 41: Introtodotnet

compiled by RJ , 9892544177

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 Sub4 ShowMessage(“Hello World from Visual Basic .NET”)

41

Page 42: Introtodotnet

compiled by RJ , 9892544177

Eg. Of functionFunction returns some value

1 Private Function GetValue(ByVal Prompt As String) As String

2 Console.Write(Prompt)

3 Return Console.ReadLine

4 End Function

Analysis :

42

Develop a console based application showing how to interchange or swap numbers. Define a sub or function to swap.

Refer exp4 > Module3.vb

Page 43: Introtodotnet

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:

compiled by RJ , 9892544177 43

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.

Page 44: Introtodotnet

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

compiled by RJ , 9892544177 44

Block ScopeA block is a set of statements enclosed within initiating and terminating declaration statements, such as the following:

Do and LoopFor [Each] and NextIf and End IfSelect and End SelectSyncLock and End SyncLockTry and End TryWhile and End WhileWith and End With

Page 45: Introtodotnet

compiled by RJ , 9892544177 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.

Page 46: Introtodotnet

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.

compiled by RJ , 9892544177 46

Refer awt pracs > ScopeVar

Page 47: Introtodotnet

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.

compiled by RJ , 9892544177 47

Public strMsg As String

Page 48: Introtodotnet

• 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.

compiled by RJ , 9892544177 48

Access level or Visibility Modifiers applicable to variables

1. Public or Friend variables 2. Private or local variables3. Protected – only used during Inheritance.4. Shared5. Static

Page 49: Introtodotnet

compiled by RJ , 9892544177

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

49

Page 50: Introtodotnet

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

Page 51: Introtodotnet

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.

compiled by RJ , 9892544177 51

Example: Declares a variable at module level and limits its visibility to code within the module.

Page 52: Introtodotnet

compiled by RJ , 9892544177

Case study 1: The Investment Calculation Application To be done by students as Home practicals

I/O of The Investment Calculator:

1 InvestCalc.exe2 Initial Balance: 100003 Annual Interest (e.g. for 5%, enter 5): 54 Monthly Deposit: 2005 Years of Investment: 3067 If you start with $10,000.00,8 and invest $200.00 per month9 for 30 years10 at 5% interest.11 Your final balance would be: $211,129.17

52

Page 53: Introtodotnet

compiled by RJ , 9892544177

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

53

Refer awt pracs> ConsoleApplication2

Page 54: Introtodotnet

compiled by RJ , 9892544177

Solution 1. 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.

54

Page 55: Introtodotnet

compiled by RJ , 9892544177

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

55

Page 56: Introtodotnet

compiled by RJ , 9892544177

Choice statementsThe If statement

SYNTAX:If <condition>Then Code to execute if the condition is trueEnd If

Example program for If statementDevelop 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]

56

Page 57: Introtodotnet

compiled by RJ , 9892544177

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

– LikeSpecial 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.

57

Page 58: Introtodotnet

compiled by RJ , 9892544177

Example program using If statement and Like operator (PatternMatcher.vb)

1 Public Class PatternMatcher2 Shared Sub Main()3 Dim sInput As String4 Dim sPattern As String5 Dim sMatch As String67 System.Console.Write(“Please Enter A Pattern:”)8 sInput = System.Console.ReadLine()9 sPattern = sInput1011 System.Console.Write(“Please Enter A String To Compare

Against:”)12 sInput = System.Console.ReadLine()13 sMatch = sInput14

58

Page 59: Introtodotnet

compiled by RJ , 9892544177

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

21 End Class

59

Page 60: Introtodotnet

compiled by RJ , 9892544177

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.

60

• 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.

Page 61: Introtodotnet

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

Page 62: Introtodotnet

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

Page 63: Introtodotnet

compiled by RJ , 9892544177

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.

63

Page 64: Introtodotnet

compiled by RJ , 9892544177

Example program to test ANDALSO:

ShortCircuiting.vb1 Public Class ShortCircuiting23 Shared Sub Main()4 If Test(“Left”) ANDALSO Test(“Right”) Then5 ‘do something6 End If7 End Sub89 Shared Function Test(sInput As String) As Boolean10 System.Console.WriteLine(sInput)11 Test = FALSE12 End Function1314 End Class

64

Page 65: Introtodotnet

compiled by RJ , 9892544177

WhileSearch.vb 1 Imports System2 Public Class WhileExample3 Shared Sub Main()4 Dim iCounter As Integer = 05 Dim arrList(10) As String6 Dim iMatch As Integer = -17 Dim sMatch As String8 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

Demonstrate use of AND operator

Page 66: Introtodotnet

compiled by RJ , 9892544177

20 If arrList(iCounter) Like sMatch Then

21 iMatch = iCounter

22 Else

23 iCounter = iCounter + 1

24 End If

25 End While

26 If iMatch <> -1 Then

27 System.Console.WriteLine(“Matched “ & iMatch)

28 End If

29 End Sub

31 End Class

66

Page 67: Introtodotnet

compiled by RJ , 9892544177

Do Loop:SYNTAX: DoCode to be executedLoop

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 executedLoop

Do Until Not (iMatch = 3) // note : Falsewala ‘iMatch <> 3 would have also workedLoop

67

Page 68: Introtodotnet

compiled by RJ , 9892544177

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()

68

Page 69: Introtodotnet

compiled by RJ , 9892544177

1 Public Class ReadFromFile23 Shared Sub Main()4 Dim sFileName As String5 Dim srFileReader As System.IO.StreamReader6 Dim sInputLine As String78 sFileName = “MySampleFile.txt”9 srFileReader = System.IO.File.OpenText(sFileName)10 sInputLine = srFileReader.ReadLine()11 Do Until sInputLine is Nothing12 System.Console.WriteLine(sInputLine)13 sInputLine = srFileReader.ReadLine()14 Loop15 End Sub16 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 ]

69

Page 70: Introtodotnet

compiled by RJ , 9892544177

Define Recursion with an example. (RecursiveFactorial.vb )

1 Public Class RecursiveFactorial2 Shared Sub Main()3 Dim sInput As String4 Dim iInput As Integer5 Dim iCounter As Integer6 Dim iFactorial As Integer7 System.Console.Write(“Please Enter A Number: “)8 sInput = System.Console.ReadLine()9 iInput = CInt(sInput)10 System.Console.WriteLine(Factorial(iInput))11 End Sub1213 Shared Function Factorial(n as Integer) as Integer1415 If n = 1 Then16 Return 117 Else18 Return n * Factorial(n-1)19 End If20 End Function21 End Class

70

Page 71: Introtodotnet

compiled by RJ , 9892544177

Module 3: Streams And Files

Stream : It is a flow of information that passes in some sequential manner.

71

Page 72: Introtodotnet

compiled by RJ , 9892544177

Methods of the File Class

Methods Description

CopyCreateCreateText

DeleteExists

Open

OpenRead

OpenText

OpenWrite

Copies a file.Creates a new file.A special version of Create that creates a text file.

Deletes a file.Returns True if the file exists.

Opens a file for reading, writing, or both.

Specialized version of Open that always opens the file for reading.Specialized version of Open that opens text files only for reading.

This would be a handy shortcut if you were writing an application that needed to read configuration information, or a log file.

Specialized version of Open that always opens the file for writing.

72

Page 73: Introtodotnet

compiled by RJ , 9892544177

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 Position

Close ( )Read ( )

Seek ( )

Write ( )

Number of bytes in the file.The current position in the file.

Closes the FileStream. Reads a number of bytes from the FileStream. The return value is an

array.Moves forward or backward through the file.

Writes a number of bytes to the FileStream.

73

Page 74: Introtodotnet

compiled by RJ , 9892544177

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.

74

Page 75: Introtodotnet

compiled by RJ , 9892544177

Important Methods of the StreamReader

Name Description

Close

Read

ReadBlock

ReadLine

ReadToEnd

Closes the StreamReader.

Reads the next character from the Stream. (one character at a time.)

Reads a block of characters from the Stream.

Reads the next line from the Stream. Viva : used wrt Files

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.

75

Page 76: Introtodotnet

compiled by RJ , 9892544177

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 FileStream2 Dim oReader As StreamReader3 Dim sContents As String

4 oFile = New FileStream(“MyFile.txt”, FileMode.OpenOrCreate, FileAccess.Read)

5 oReader = New StreamReader(oFile)

6 sContents = oReader.ReadToEnd()

7 oReader.Close()8 oReader = Nothing9 oFile = Nothing

76

Page 77: Introtodotnet

compiled by RJ , 9892544177

Writing to a Text File using StreamWriter

Name Description

Close

Write

WriteLine

Closes the StreamWriter.

Writes to the Stream.

Writes to the Stream, ending the added information with a new line.

77

Page 78: Introtodotnet

compiled by RJ , 9892544177

Eg 2: Writing to a File1 Dim oFile As FileStream2 Dim oWriter As StreamWriter3 oFile = New FileStream(“MyFile.txt”, _4 FileMode.OpenOrCreate, FileAccess.Write)5 oWriter = New StreamWriter(oFile)6 ’Writes the Integer 123 to the file7 oWriter.Write(123)8 ’Writes the String “Customer” to the file9 oWriter.Write(“Customer”)10 ’Writes the String “Suven Consultants” to the file, next writes will be on a

new line11 oWriter.WriteLine(“Suven Consultants”) //Writes on the new line12 oWriter.Close()13 oWriter = Nothing14 oFile = Nothing

78

Page 79: Introtodotnet

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

Page 80: Introtodotnet

compiled by RJ , 9892544177

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 >

80

Page 81: Introtodotnet

compiled by RJ , 9892544177

1 Module modExceptional2 Sub Main()

3 Dim dDividend As Decimal = 54 Dim dDivisor As Decimal = 05 Dim dResult As Decimal = 0

6 dResult = dDividend / dDivisor

7 System.Console.ReadLine()8 End Sub910 End Module

81

Page 82: Introtodotnet

compiled by RJ , 9892544177

The o/p of the above program through IDE

82

Page 83: Introtodotnet

compiled by RJ , 9892544177

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.

83

Page 84: Introtodotnet

compiled by RJ , 9892544177

Exception handling in the Above program

1 Module modExceptional2 Sub Main()3 Dim dDividend As Decimal = 54 Dim dDivisor As Decimal = 05 Dim dResult As Decimal = 06 Try7 dResult = dDividend / dDivisor8 Catch Ex As Exception9 System.Console.WriteLine(“A division by zero error has occurred.”)10 System.Console.WriteLine(“Please check the divisor.”)11 End Try12 System.Console.ReadLine()13 End Sub14 End Module

84

Page 85: Introtodotnet

compiled by RJ , 9892544177

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

6 fsOut = _

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 = _

13 New System.IO.StreamWriter(fsOut)

14 strOut.Write(DateTime.Today.ToString())

15 Catch eIO As Exception85

Open, OpenCreate, OpenRead,OpenWrite

Today , now attributes

Page 86: Introtodotnet

compiled by RJ , 9892544177

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

86

Page 87: Introtodotnet

compiled by RJ , 9892544177

Raising Exceptions by using “Throw” keyword

The Throw Statement1 Dim oCust As Customer = New Customer(“abc”, “xyz”)2 Dim oEmp As Employee = New Employee(“abc1”, “xyz1”)// assumption …

3 Dim oSomething As Object4 oSomething = oEmp5 If TypeOf oSomething Is Customer Then6 oCust = oSomething7 Else8 Throw New InvalidCastException(“Cannot assign an Employee to a Customer.”)

9 End If

87

O/p: Opens dialog box (by the default debugger) with the message above.

Page 88: Introtodotnet

List all the exceptions that might occur when calling the File.Open method. Or All exceptions related to file operations

compiled by RJ , 9892544177 88

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.

Page 89: Introtodotnet

compiled by RJ , 9892544177 89

If no file name given

If wrong file name given

If Nothing entered

Self explanatory

Page 90: Introtodotnet

compiled by RJ , 9892544177 90

Page 91: Introtodotnet

List all exceptions under the ArgumentException class.

compiled by RJ , 9892544177 91

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.

Page 92: Introtodotnet

compiled by RJ , 989254417792

Page 93: Introtodotnet

compiled by RJ , 9892544177

1. Specify with e.g.. ( not complete code ) use of following exceptions

• ArgumentNullException

• ArgumentOutOfRangeException

• IndexOutOfRangeException

• OverflowException

• FileNotFoundException

93

Home assignment

Page 94: Introtodotnet

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

Page 95: Introtodotnet

compiled by RJ , 9892544177 95

Page 96: Introtodotnet

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

Page 97: Introtodotnet

Module 5 : OO Programming Concepts

compiled by RJ , 9892544177 97

Page 98: Introtodotnet

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

Page 99: Introtodotnet

compiled by RJ , 9892544177

Eg . Of Set and Get methods

99

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

Page 100: Introtodotnet

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

Page 101: Introtodotnet

compiled by RJ , 9892544177

Properties can be 1> ReadOnly 2> WriteOnly

101

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

Page 102: Introtodotnet

compiled by RJ , 9892544177

Develop the sub main () to instantiate an object of class Line .

output :

102

Page 103: Introtodotnet

compiled by RJ , 9892544177

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.

>

103

Page 104: Introtodotnet

compiled by RJ , 9892544177

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

104

Page 105: Introtodotnet

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

Page 106: Introtodotnet

compiled by RJ , 9892544177

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 Vehicle23 ‘Code removed for simplicity....45 Public Overridable Function Description() As String6 Return “This is my generic vehicle description!”7 End Function8 End Class910 Public Class Car11 Inherits Vehicle1213 ‘Code removed for simplicity....1415 Public Overrides Function Description() As String16 Return “This is my Car Description”17 End Function1819 End Class

106

Page 107: Introtodotnet

compiled by RJ , 9892544177107

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.

Page 108: Introtodotnet

compiled by RJ , 9892544177

ConstructorsConstructors 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.

108

Page 109: Introtodotnet

compiled by RJ , 9892544177

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

109

Page 110: Introtodotnet

compiled by RJ , 9892544177 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.

Page 111: Introtodotnet

compiled by RJ , 9892544177

Module 6 : Namespaces (similar to concept of Packages in Java) Viva : Q : why is it needed.

111

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.

Page 112: Introtodotnet

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.

compiled by RJ , 9892544177112

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.

Page 113: Introtodotnet

compiled by RJ , 9892544177 113

Page 114: Introtodotnet

compiled by RJ , 9892544177

1. Console: Enables reading and writing to the command-line.

114

Page 115: Introtodotnet

compiled by RJ , 9892544177

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:”)

13 For I = ITEM_COUNT - 1 To 0 Step -1

14 Console.WriteLine(sItems(I))

15 Next

16 End Sub

17 End Class115

Page 116: Introtodotnet

compiled by RJ , 9892544177

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()

6 Dim I As Integer

116

Page 117: Introtodotnet

compiled by RJ , 9892544177

6 Dim I As Integer

7 Dim sItems(ITEM_COUNT) As String8 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-112 sItems(I) = Console.ReadLine13 Next14 Console.WriteLine()15 Console.SetOut(oFile)16 Console.WriteLine(“Items in reverse order:”)17 For I = ITEM_COUNT - 1 To 0 Step -118 Console.WriteLine(sItems(I))19 Next

117

Page 118: Introtodotnet

compiled by RJ , 9892544177

Running the application:

1 [c:\work\console]Console2.exe2 Please enter 10 items. Press ENTER between items.3 Aardvark4 Bandicoot5 Cassowary6 Dugong7 Echidna8 Finch9 Giraffe10 Hippopotamus11 Iguana12 Jackalope1314 Done

118

Page 119: Introtodotnet

compiled by RJ , 9892544177

The code should produce a file Output.txt with the following contents:

1 Items in reverse order:2 Jackalope3 Iguana4 Hippopotamus5 Giraffe6 Finch7 Echidna8 Dugong9 Cassowary10 Bandicoot11 Aardvark

119

Page 120: Introtodotnet

2. Environment classProvides information about, and means to manipulate, the current environment and platform. This class cannot be inherited.

120

Refer awt pracs >console application 4

Page 121: Introtodotnet

compiled by RJ , 9892544177121

Page 122: Introtodotnet

compiled by RJ , 9892544177 122

Page 123: Introtodotnet

compiled by RJ , 9892544177 123

Page 124: Introtodotnet

compiled by RJ , 9892544177 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.

Page 125: Introtodotnet

compiled by RJ , 9892544177

Methods and Properties of the Environment Class

125

Page 126: Introtodotnet

compiled by RJ , 9892544177

3. Random : Represents a pseudo-random number generator, a device that produces a sequence of numbers that meet certain statistical requirements for randomness.

Constructors :

126

Methods

Page 127: Introtodotnet

compiled by RJ , 9892544177

Eg . Random classDim oRand As New Random

Dim iValue As Integer = oRand.Next(1, 100)

127

Page 128: Introtodotnet

compiled by RJ , 9892544177

4. Collection Classes in the .NET FrameworkThe .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.

128

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)

Page 129: Introtodotnet

compiled by RJ , 9892544177 129

Page 130: Introtodotnet

compiled by RJ , 9892544177 130

Page 131: Introtodotnet

compiled by RJ , 9892544177 131

Page 132: Introtodotnet

compiled by RJ , 9892544177

4.b) Queue : A Queue is a “first-in, first-out” (FIFO) collection

132

Page 133: Introtodotnet

compiled by RJ , 9892544177 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.

Page 134: Introtodotnet

compiled by RJ , 9892544177

134

Page 135: Introtodotnet

compiled by RJ , 9892544177

4.c) Stack: Is a “first-in, last-out” (FILO) or LIFO collection

135

Page 136: Introtodotnet

compiled by RJ , 9892544177

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.

136

Page 137: Introtodotnet

compiled by RJ , 9892544177 137

Page 138: Introtodotnet

compiled by RJ , 9892544177

138

Page 139: Introtodotnet

compiled by RJ , 9892544177

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,

139

Page 140: Introtodotnet

compiled by RJ , 9892544177

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:

140

Page 141: Introtodotnet

compiled by RJ , 9892544177

• 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.

141

Page 142: Introtodotnet

compiled by RJ , 9892544177

• 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)

142

Page 143: Introtodotnet

compiled by RJ , 9892544177

• 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 .mdb1 Module Module12 Private Const sConnection As String =”Provider=Microsoft.Jet.OLEDB.4.0;” &_3 “Data Source=C:\CD.mdb;”&_4 “Persist Security Info=False”5 67 Sub Main()8 Dim objConn As New System.Data.OleDb.OleDbConnection(sConnection)9 End Sub10 End Module

143

Page 144: Introtodotnet

compiled by RJ , 9892544177

2> Opening Connection1 Module Module12 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 Try8 objConn.Open()9 Catch myException As System.Exception10 Console.WriteLine(myException.Message)11 End Try12 Console.ReadLine()13 End Sub14 End Module

144

Page 145: Introtodotnet

compiled by RJ , 9892544177

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.

145

Page 146: Introtodotnet

compiled by RJ , 9892544177

Opening connection with SQL server #1 Imports System2 Module Module13 Private Const sConnection As String4 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 Try12 objConn.Open()13 Catch myException As Exception14 Console.WriteLine(myException.Message)15 End Try16 Console.ReadLine()17 End Sub18 End Module

146

Page 147: Introtodotnet

compiled by RJ , 9892544177

3. Executing a SQL StatementAfter 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.

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

147

Refer exp6 > Application1

Page 148: Introtodotnet

compiled by RJ , 9892544177

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 >

148

Page 149: Introtodotnet

compiled by RJ , 9892544177

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.

149

Page 150: Introtodotnet

compiled by RJ , 9892544177

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)

150

Page 151: Introtodotnet

compiled by RJ , 9892544177

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 :

151

Page 152: Introtodotnet

compiled by RJ , 9892544177

2. Navigation Data1> 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:

152

Page 153: Introtodotnet

compiled by RJ , 9892544177

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”))153

Page 154: Introtodotnet

compiled by RJ , 9892544177

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

154

Page 155: Introtodotnet

compiled by RJ , 9892544177

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

155

Page 156: Introtodotnet

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

Page 157: Introtodotnet

compiled by RJ , 9892544177

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.

157

Page 158: Introtodotnet

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

Page 159: Introtodotnet

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

Page 160: Introtodotnet

compiled by RJ , 9892544177 160

Adapter has many properties

To create the SQL query

To check for any update

Page 161: Introtodotnet

Note : properties of adapter object. • SelectCommand

• InsertCommand

• UpdateCommand

• DeleteCommand

compiled by RJ , 9892544177

161

Page 162: Introtodotnet

compiled by RJ , 9892544177 162

Refer

Page 163: Introtodotnet

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

Page 164: Introtodotnet

compiled by RJ , 9892544177

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 DataTableobjTable = 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 DataRowCollectiondrRows = 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.

164

Page 165: Introtodotnet

compiled by RJ , 9892544177

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 Rows2 Dim objNewRow As DataRow3 drRows = objTable.Rows //Returns all Rows45 ‘Assume - we have 3 columns6 ‘ArtistID7 ‘ArtistName8 ‘CDTitle910 objNewRow = objTable.NewRow() //Instantiating a new Row

object with schema/structure of the

ObjTable.11 objNewRow(“ArtistID”) = 312 objNewRow(“ArtistName”) = “Mohit Chawan”

165

Page 166: Introtodotnet

compiled by RJ , 9892544177

13 objNewRow(“CDTitle”) = “NewYork”

14 drRows.Add(objNewRow) //Adding new Row to the DataTable

Note : These changes are reflected to the Database Server only after the update( ).

166

Page 167: Introtodotnet

compiled by RJ , 9892544177

2. Editing Records:

Steps similar to adding 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(5) ‘ retriving the 5th row

167

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()

Page 168: Introtodotnet

compiled by RJ , 9892544177

3. Deleting Records:objDataAdapter.Fill(objDS, “Disc”)Dim objTable As DataTableobjTable = objDS.Tables(“Disc”)Dim drRows As DataRowCollectionDim objRow As DataRowdrRows = objTable.RowsobjRow = 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().

168

Page 169: Introtodotnet

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

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

End Class

compiled by RJ , 9892544177 169

Demonstrate use of adapter.DeleteCommand and ExecuteNonQuery()

Refer awt pracs>DB Navigation

Page 170: Introtodotnet

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

Page 171: Introtodotnet

Example below does not use Multithreading

Public Sub Main()

Fun1()

Fun2()

Console.WriteLine("End of Main()")

End Sub

Public Sub Fun1()

Dim i As Integer

For i = 1 To 5

Console.WriteLine("Fun1() writes: {0}", i)

Next

End Sub

Public Sub Fun2()

Dim i As Integer

For i = 10 To 6 Step -1

Console.WriteLine("Fun2() writes: {0}", i)

Next

End Sub

compiled by RJ , 9892544177 171

The output of the program is:

Fun1() writes: 1Fun1() writes: 2Fun1() writes: 3Fun1() writes: 4Fun1() writes: 5Fun2() writes: 10Fun2() writes: 9Fun2() writes: 8Fun2() writes: 7Fun2() writes: 6End of Main()

Page 172: Introtodotnet

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

Page 173: Introtodotnet

Public Sub Fun1()

Dim i As Integer

For i = 1 To 5

Console.WriteLine("Fun1() writes: {0}", i)

Next

End Sub

Public Sub Fun2()

Dim i As Integer

For i = 10 To 6 Step -1

Console.WriteLine("Fun2() writes: {0}", i)

Next

End Sub

End Module

compiled by RJ , 9892544177 173

Here we have created two instances of the Thread class and passed a ThreadStart type delegate in the constructor which references a method in our program.  It is important that the method referenced in the Thread class constructor, through the ThreadStart delegate is parameter-less and has no return type.

We have to start the execution of a thread by calling the Start() method of the Thread class. The output of the program would now be interleaving Fun1 () and Fun2()  

Page 174: Introtodotnet

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

Public Value As Double

Public Square As Double

 

Public Sub CalcSquare()

Square = Value * Value

End Sub

End Class

compiled by RJ , 9892544177 174

Use this code to start the CalcSquare procedure on a new thread, as follows:

// 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 Dim oSquare As New SquareClass() t = New Thread(AddressOf oSquare.CalcSquare) oSquare.Value = 30 t.Start()End Sub

Page 175: Introtodotnet

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

Page 176: Introtodotnet

compiled by RJ , 9892544177 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 SubEnd 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 SubSub SquareEventHandler(ByVal Square As Double) _ Handles oSquare.ThreadComplete MsgBox("The square is " & Square)End SubEnd Class

Page 177: Introtodotnet

Method 2: To perform synchronizations, VB.NET provides the • SyncLock … End SyncLock statement and the Thread.Join method.

• SyncLock gains an exclusive lock to an object reference that is passed to it. By gaining this exclusive lock you can ensure that multiple threads are not accessing shared data.

• In order to gain lock find System.Type of object associated with each class. The System.Type object can be retrieved using the GetType method:

Public Sub CalcSquare()

SyncLock GetType(SquareClass)

Square = Value * Value

End SyncLock

End Sub

Lastly, the Thread.Join method allows you to wait for a specific amount of time until a thread has completed. If the thread completes before the timeout that you specify, Thread.Join returns True, otherwise it returns False.

compiled by RJ , 9892544177 177

Page 178: Introtodotnet

The code using synchronize methods

Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click

  Dim oSquare As New SquareClass()

  t = New Thread(AddressOf oSquare.CalcSquare)

  oSquare.Value = 30

t.Start()

  If t.Join(500) Then

MsgBox(oSquare.Square)

End If

End Sub

178

Thread.Abort stops a thread from executing. In above example, we can add another button on the form that allows us to stop the process. To do this all we would have to do is call the Thread.Abort method as follows:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click t.Abort()End Sub This is where the power of multithreading can be seen. The UI seems responsive to the user because it is running in one thread and the background process is running in another thread. The cancel button immediately responds to the user's click event and processing stops