VB NET

196
VB.NET Deepak Patil Deepak Patil

Transcript of VB NET

Page 1: VB NET

VB.NET

Deepak PatilDeepak Patil

Page 2: VB NET

Overview of the .NET Framework

• The .NET Framework– Common Language Runtime– Managed and Unmanaged Code– MSIL– JIT– Assemblies

Page 3: VB NET

Event Driven Programming

• Event Model• Event Handlers• Callbacks• Asynchronous Event-Firing (Callbacks in multithread)• Event driven programming and VB .NET

Page 4: VB NET

Introduction to VS.NET

Page 5: VB NET

Agenda• VS.NET Projects

– Types of Projects• Analyzing structure of project• Using Solution Explorer• Using Server Explorer• Object Browser• Toolbox• Property Window• My First VB.NET App.

Page 6: VB NET

Creating Visual Basic .NET Projects

• Windows Application– Standard Windows -based applications.

• Class Library– Class libraries that provide similar functionality to Microsoft

ActiveX® dynamic-link libraries (DLLs) by creating classes accessible to other applications.

• Windows Control Library– User-defined Windows control projects, which are similar to

ActiveX Control projects in previous versions of Visual Basic.

• ASP .NET Web Application– Web applications that will run from an Internet Information

Services (IIS) server and can include Web pages and XML Web services.

Page 7: VB NET

Creating Visual Basic .NET Projects…

• Web Service– Web applications that provide XML Web Services to client

applications.

• Web Control Library– User-defined Web controls that can be reused on Web pages in the same way that Windows controls can be reused in Windows applications.

• Console Application– Console applications that will run from a command line.

• Windows Service– Windows services that will run continuously regardless of whether a user is logged on or not.

Page 8: VB NET

Analyzing Project Structures

• Solution files (.sln, .suo)– The .sln extension is used for solution files that link one or

more projects together, and are also used for storing certain global information.

• Project files (.vbproj)– The project file is an Extensible Markup Language (XML)

document tha contains references to all project items, such as forms and classes, as w ell as project references and compilation options.

• Local project items (.vb)– It may contains classes, forms, modules, and user controls

Page 9: VB NET

Using Solution Explorer

• Displays Project Hierarchy– Project references– Forms, classes, modules– Folders with subitems

• “Show All Files” Mode• Manipulating Projects

– l Drag-and-drop editing– l Context menus

Page 10: VB NET

Using Server Explorer

• Managing Data Connections

• Viewing and Managing Servers

• Using Drag-and-Drop Techniques

Page 11: VB NET

Object Browser

• Examine Objects and their Members

• Access Lower-level Items– Shows inheritance and

interfaces• Examine How the .NET

Framework Class Libraries Use Inheritance

Page 12: VB NET

Tool Box

Page 13: VB NET

Property Window

Page 14: VB NET

My First VB.NET App.

Page 15: VB NET

Introduction to Visual Basic .NET

Page 16: VB NET

Visual Basic.NET

• Leave it in VB6– WebClasses, ActiveX Documents, DHTML Projects

• Thinking in VB.NET– Data Types, Type vs. Structure– Property Functions, Zero Bound Arrays– Default Parameters

• New Features– Forms Designer, Declaration Syntax– Structured Exception Handling– Overloading, Inheritance– Free Threading

• ADO.NET

Page 17: VB NET

VB.NET Lang. Fundamentals

• Variables• Data Types• Identifiers• Keywords• Literals• Dimensioning Variables• Operators• Expressions• Statements

Page 18: VB NET

Variable

What is a variable?• It is a container (with a name) that holds ‘stuff’• Remember Algebra?

X + 3 = 7

X is a variable. It contains/holds/represents a value, that we can deduce is 4.

Page 19: VB NET

Variable…

• We must ‘dimension’ variables … i.e. tell the computer that you want one before you use it– ‘declare’ a variable (in C)– The computer allocates memory and then you can put what

you want in it– You can put only something which the variable can hold – read

‘DATATYPE’.

Page 20: VB NET

Value Types & Reference Types

• Stack Vs Heap• Value types are stored on stack.

– Eg. All primitive types except. String

• Reference Types are stored on heap (Managed heap).– Eg.Class Object

Page 21: VB NET

Data Types

What are Data Types?• Data Types restrict what a variable can hold• Memory is allocated depending on the data type – text,

number, date– Text: “BITS”, “Visual”, “Basic”– Number: 3, 9, 432156– Dim name as String

• name = 7 ‘WRONG!

Page 22: VB NET

Data types visited

• Plenty of them– String– Integer– Boolean (for True/False types)– DateTime– Double (for money, fractions)– And more …

Page 23: VB NET

Data type: String$

• Any text value– Names– Colors– Login ids

• Examples– “Rahul”– “Red”– “f1997408”

Page 24: VB NET

Data type: Integer%

• Can hold whole numbers– Both positive & negative

• Examples– 10– -666– 0

Page 25: VB NET

Data Type: Boolean & DateTime

• Boolean: ‘Logic’ values– Only 2 values possible– True or false

• True: any non-zero value• False: zero

• DateTime: To store date in various formats– 30-01-2004– 30-01-2004 5:50 PM– etc

Page 26: VB NET

Data Type: Double#

• Double: to store Real numbersFractions

• Examples– 0.00– 19.7– -98.3674501

Page 27: VB NET

VB.NET Lang. Fundamentals…

• Identifiers– Identifiers are names given to types (enumerations,

structures, classes, standard modules, interfaces, and delegates), type members (methods, constructors, events, constants, fields, and properties), and variables.

• Keywords– Keywords are words with special meaning in a programming

language. In Visual Basic .NET, keywords are reserved; that is, they cannot be used as tokens for such purposes as naming variables and subroutines.

– E.g. Binary, Boolean, ByRef, Byte, ByVal, Auto, integer, Float, else, exit …

Page 28: VB NET

VB.NET Lang. Fundamentals…

• LiteralsLiterals are representations of values within the text of a program.

For example, in the following line of code, 10 is a literal, but x and y are not:

x = y * 10– Numeric Literals (Integer, Single, Double, and Decimal)– String Literals– Character Literals: followed by char ‘c’

Dim MyChar As Char

MyChar = "A"c

– Date Literals – Boolean Literals

Page 29: VB NET

Dimensioning Variables

• Two ways– Dim x as Integer– Dim x as Integer = 7 ‘initialized also here

• Points to note– You can do it only once per procedure– Variables have a scope– Access to variables can be defined: Public, Private, etc

Page 30: VB NET

Operators• Operators are symbols & specify operations to be

performed on one or two operands (or arguments).

• Operators that take one operand are called unary operators. Operators that take two operands are called binary operators.

• Type of Operators:– Unary Operators– Arithmetic Operators– Relational Operators– String-Concatenation Operators– Logical Operators

Page 31: VB NET

Unary Operators• - (unary minus) The unary minus operator takes any numeric operand. The value

of the operation is the negative of the value of the operand. In other words, the result is calculated by subtracting the operand from zero.

• Not (logical negation) The logical negation operator takes a Boolean operand. The

result is the logical negation of the operand.

Page 32: VB NET

Arithmetic Operators

• * (multiplication)• / (regular division)

– The regular division operator is defined for all numeric operands. The result is the value of the first operand divided by the second operand.

• \ (integer division)– The integer division operator is defined for integer operands (Byte,

Short, Integer, and Long).– The result is the value of the first operand divided by the second operand, then

rounded to the integer nearest to zero.

• Mod (modulo)– The modulo operator is defined for integer operands (Byte, Short, Integer, and

Long). The result is the remainder after the integer division of the operands.

• ^ (exponentiation)

• + (addition)• - (subtraction)

Page 33: VB NET

Relational Operators• = (equality)• <> (inequality)• < (less than)• > (greater than)• <= (less than or equal to)• >= (greater than or equal to)• Like• TypeOf

Page 34: VB NET

String-Concatenation Operators• & and +

– The & (ampersand) and + (plus) characters signify string concatenation.

Page 35: VB NET

Logical OperatorsLogical operators are operators that require

Boolean operands. They are:

• And The result is True if and only if both of the operands are True; otherwise,

the result is False.• Or The result is True if either or both of the operands is True; otherwise,

the result is False.• Xor The result is True if one and only one of the operands is True;

otherwise, the result is False.• Not This is a unary operator. The result is True if the operand is False; False

if the operand is True.

Page 36: VB NET

Statements

• Made up of– Keywords (like Dim)– Operators– Variables– Constants– Expressions

Page 37: VB NET

Statements…

• Types of statements– Declaration

• Dim x% =10

– Assignment:

variable, field, or property = expression• x = y + 3 * 6

• Lblcolor.forcolor=system.drawing.color.red

– Executable• If – Then – Else

• Function calls

Page 38: VB NET

Statements…

• Each statement is a command

• Each statement can be on a new line or combined together with :

• Statements can span multiple lines using _

• Your program – a lot of statements that do interesting things

Page 39: VB NET

VB.NET Language Improvements

• Variables can be declared and initialized in same line

• As New syntax does not result in lazy instantiation

• Return statement can be used in functions

Dim obj As New Human '*** object created here

Dim i As Integer = 100

Public Class Human Public Name As String = "John Doe" Function Speak() As String Return "Hi, my name is " & Name End FunctionEnd Class

Page 40: VB NET

VB.NET Language Improvements• Many inconsistencies and idiosyncrasies have been

removed– Set statement not required/allowed on assignment

– parameters always passed in parentheses

– default parameter passing convention has changed to ByVal

Class MyApp

Shared Sub Main() Dim p1, p2 As Human Set p1 = New Human MySub(10, 20.1) p2 = New Human MySub(10, 20.1) End Sub

Sub MySub(ByVal x As Integer, y As Double) '*** definition End Sub

End Class

Causes compile-time errors

Correct syntax

defined with ByVal semantics

Page 41: VB NET

VB.NET Language Improvements• Error reporting based on structure exception handling

– Try statements replace On Error GoTo syntax– On Error GoTo syntax supported for backward compatibility

• Try statement provides ability to catch exceptions– Try statement contains one Try block with guarded code– Try statement can contain one or more Catch blocks

Sub ProccessNumbers(ByVal x As Integer, ByVal y As Integer) Dim temp As Integer Try temp = x * y '*** operation could result in overflow Catch ex As ArithmeticException '*** handle math exceptions MsgBox("Math exception: " & ex.Message) Catch ex As Exception '*** handle all other exceptions MsgBox("Unexpected system exception: " & ex.Message) Finally 'code that always happens End TryEnd Sub

Try block

Catch block #1

Catch block #2

Page 42: VB NET

VB.NET Language Improvements

• Strict type checking improve quality of your code– Enable using option strict on– Every variable and parameter must be defined with specific

type– Many implicit conversions are prohibited– You are required to write more conversions explicitly

Option Explicit On Option Strict On

Class MyApp

Shared Sub Main() '*** my application code End Sub

End Class

Page 43: VB NET

"Hello World" With VB.NET

'*** source file: MyApp.vb'*** build target: MyApp.exe'*** references: MyLibrary.dllClass MyApp Shared Sub Main() Dim obj As New Human obj.Name = "Bob" Dim msg As String = obj.Speak System.Console.WriteLine(msg) End SubEnd Class

'*** source file: MyLibrary.vb'*** build target: MyLibrary.dllPublic Class Human Public Name As String Function Speak() As String Return "Hi, my name is " & Name End FunctionEnd Class

A component library DLLA component library DLL

A console-based A console-based applicationapplication

Page 44: VB NET

Agenda

• If, then, End If• If, Then, Else, End If• Select Case• While Statement• Do … Loop• For … next• Arrays

Page 45: VB NET

If – Then – End If

• Allows conditional branching in code

If stars > 4 Then

rating = “Super Hit”

End If

Page 46: VB NET

If – Then – Else – End If

If choice = 1 Then

shop = “Shoppers Stop”

Else

shop = “Walden”

End if

Page 47: VB NET

If – Then – Else – End If …

If choice = 1 Then

shop = “Shoppers Stop”

ElseIf choice = 2 Then

shop = “Big Bazaar”

Else ‘ for any other choice

shop = “Walden”

End if

‘The Else must be at the end

Page 48: VB NET

Select Case• A Select Case statement executes statements based on the value of an

expression. The expression must be classified as a value and its type must be a primitive type or Object.

• When a Select Case statement is executed, the Select expression is evaluated first, and the Case statements are then evaluated in order of textual declaration. The first Case statement that evaluates to True has its block executed. If no Case statement evaluates to True and there is a Case Else statement, that block is executed. Once a block has finished executing, execution passes to the end of the Select statement.

Page 49: VB NET

Select Case• Syntax:

Select Expression1Case 1

‘Statement Block for Case 1Case 2

‘Statement Block for Case 2Case N

‘Statement Block for Case NCase Else

‘Catch AllEnd Select

Page 50: VB NET

Select Case…dim income as doubleselect case income

case 0 To 100000tax=0

case 0 To 100000tax=0

case 100001 To 150000tax=0.10 * (income-100000)

case 150001 To 200000tax=0.15*(income-150000) + 5000

case Elsetax=0.20*(income-200000) + 7500

end select

Page 51: VB NET

Select Case…Select number

case 1, 2, 3txtresult.text= “1”

case 4 To 10txtresult.text= “2”

case Is < 20txtresult.text= “3”

case Is > 20txtresult.text= “4”

End Select

Page 52: VB NET

While statement

• Used to iterate through a section of code• Iteration could be indefinite• Has a break condition

– Control comes out when this condition is met

• The break condition – an expression that evaluates to TRUE or FALSE

Page 53: VB NET

While statement…

Syntax:

While <Expr>

[statements]

End While

Page 54: VB NET

While statement…• Example 1

Dim counter as Integer = 0Dim value as integer = 0while value < 30

counter = counter + 1 value = value + 10

end while

Msgbox “The while loop” & counter & “times.”

Page 55: VB NET

Do Loop

Syntax:

Do[{while | Until} condition]

[statements]

[Exit Do]

[statements]

Loop

Page 56: VB NET

Do While

• Continues to loop while a certain condition (expression) evaluates to TRUE– Stops when condition evaluates to FALSE

Syntax:

Do While <Expr>

[statements]

Loop

Page 57: VB NET

Do While ExampleDim value as IntegerDim counter as Integer

Value = 11Counter = 0

Do While value > 10counter = counter + 1value = value – 1

Loop

Msgbox (“THE DO WHILE LOOP: “ + counter + “ times.”

Page 58: VB NET

Do Until

• Continues to loop until a certain condition (expression) evaluates to TRUE– Stops when condition evaluates to TRUE

Syntax:

Do Until <Expr>

[statements]

Loop

Page 59: VB NET

Do Until ExampleDim value as IntegerDim counter as Integer

Value = 9Counter = 0

Do Until value = 10counter = counter + 1value = value + 1

Loop

Msgbox (“THE DO UNTIL LOOPED: “ + CStr(counter) + “ times.”)

Page 60: VB NET

Do While Variant

• Depending on the check condition– Check first and then execute [previous case]– Execute first and then ‘Check’

Do

[statements]

Loop While <Expr>

Page 61: VB NET

Do While Variant ExampleDim value as IntegerDim counter as Integer

Value = 10 ‘change these values n observerCounter = 0

Docounter = counter + 1value = value – 1

Loop While value > 10

Msgbox (“THE DO WHILE VARIANT LOOP: “ + counter + “ times.”)

Page 62: VB NET

Do Until Variant

• Depending on the check condition– Check first and then execute [previous case]– Check last and then execute

Do

[statements]

Loop Until <Expr>

Page 63: VB NET

Do Until Variant ExampleDim value as IntegerDim counter as Integer

Value = 9 ‘change these values n observerCounter = 0

Docounter = counter + 1value = value + 1

Loop Until value = 10

Msgbox (“THE DO UNTIL VARIANT LOOP: “ + counter + “ times.”)

Page 64: VB NET

For Next

• When it is known before hand how many times the iteration will happen.

Syntax:

For x = i To j

[statements]

Next

Page 65: VB NET

For-Next…Example 1:

For Counter = 1 To 1000 ‘ skip any values between 100 and 600 If Counter = 100 Then Counter = 601 ‘ set text value Text1.Text = Counter Text1.Refresh ‘ Update Text1Next Counter

Page 66: VB NET

For-Next…

• Steps– When the jump has to be something other than 1

Ex:

For Counter = 1 To 1000 Step 5

‘ skip any values between 100 and 600

If Counter = 100 Then Counter = 601

‘ set text value

Text1.Text = Counter

Text1.Refresh ‘ Update Text1

Next Counter

Page 67: VB NET

For-Next…

• Looping backwards

For Counter = 2000 To 1 Step -1

‘ counting back from 2000 to 1

Text1.Text = Counter

Text1.Refresh ‘ Update Text1

Next Counter

Msgbox "Count down finished"

Page 68: VB NET

Exit For

For I = 1 To 10

if I = 7 then

exit for

end if

Text1.Text = Counter

Text1.Refresh ‘ Update Text1

Next

Page 69: VB NET

Arrays in VB.NET

• An array is a reference type that contains variables accessed through indices corresponding in a one-to-one fashion with the order of the variables in the array.

• The variables contained in an array, also called the elements of the array, must all be of the same type, and this type is called the element type of the array.

• An array has a rank that determines the number of indices associated with each array element. The rank of an array determines the number of dimensions of the array.

Page 70: VB NET

Arrays in VB.NET…

Array declaration:

Dim arr(5) as IntegerArr(0) = 1Arr(1) = 2Arr(2) = 3Etc

OR

Dim arr(5) as Integer = (1, 2, 3, 4, 5)

ReDim Preserve arr(10)

Page 71: VB NET

Arrays in VB.NET…

Array Declaration:

dim square(2,2) as integersquare(0,0)=1square(0,1)=2square(1,0)=3…

OR

Dim rectArray(,) As Integer = {{1, 2, 3}, {12, 13, 14}, {11, 10, 9}}

OR

Dim colors(2)() as Stringcolors(0)=New String(){"Red","blue","Green"}colors(1)=New String(){"Yellow","Purple","Green","Violet"}colors(2)=New String(){"Red","Black","White","Grey","Aqua"}

Page 72: VB NET

Array Methods• Array.GetLowerBound(rank) • Array.GetUpperBound(rank)• Array.Sort(arr)• Array.BinarySearch(arr, element)• Array.Reverse(MyIntArray)• Array.GetValue(index)• Array.IndexOf(arr, element)• Array.LastIndexOf(arr, element)• Array.copy()

Page 73: VB NET

Array Property

• Array.Length• Array.IsReadOnly (always false)• Array.IsFixedSize (always true)

Page 74: VB NET

Scope of Variables • It refers to as the visibility and life of a data item or

object

Types:• Local/Procedural Scope• Block Scope• Module Scope

Page 75: VB NET

Local Scope• Such variable are visible only inside that particular

module/ procedure/ function.

E.g.:Private Sub button1_Click…

Dim i as integer=10Dim k=i/5

End Sub

Private Sub button1_Click…Dim j as integerDim j= i*5

End Sub

Page 76: VB NET

Block Scope• If a variable is declared inside a code block (a set of

statements that is terminated by an End..., Loop, or Next statement), then the variable has block-level scope ; that is, it is visible only within that block.

For example, consider the following code:If x <> 0 Then

Dim rec As Integerrec = 1/x

End IfMsgBox CStr(rec)

Page 77: VB NET

Module Scope• It means that every procedure within that module has

the full access to the data items.OR

• Module scope limits access to the module in which the definition occurs.

IMP: If two variables with the same name are both in scope, the most recently defined variable is the variable that is being accessed.

Page 78: VB NET

Subroutines/ Functions

• They are set of instructions designed to accomplish one specific task.– They eliminates duplicate code– Promotes modularity– Which further leads to “CODE RESUE”

Page 79: VB NET

Parameters and Arguments

Function RepeatString(ByVal sInput As String, ByVal iCount As Integer) As String

Dim i As IntegerFor i = 1 To iCountRepeatString = RepeatString & sInputNext

End Function

• The variables sInput and iCount are the parameters of this function. Note that each parameter has an associated data type.

Now, when we call this function, we must replace the parameters by variables, constants, or literals, as in:

s = RepeatString("Donna", 4)

• The items that we use in place of the parameters are called arguments.

Page 80: VB NET

Passing Arguments• Arguments can be passed in 2 ways:

– ByVal (Call by value):

Passing by value means that the actual value of the argument is passed to the function.

– ByRef (Call by reference)

if we pass an object variable by reference, we are passing the address of the variable.

Page 81: VB NET

Optional Arguments

The following rules apply to optional arguments:– Every optional argument must specify a default value, and this

default must be a constant expression (not a variable).– Every argument following an optional argument must also be

optional.

Page 82: VB NET

Advancements In OOP Support• Visual Basic .NET provides OOP support

– As powerful as C# or Java– VB6 programmers must learn many new OOP concepts

• New concepts in OOP– Shared members– Overloading methods– Constructors– Inheritance– Overridable methods and polymorphism– Interfaces– Delegates– Object finalization and disposal

Page 83: VB NET

OOP Fundamentals• Encapsulation

Encapsulation is all about the separation between implementation and interface. It implements “Data Hiding”

• AbstractionThe ability to create an abstract representation of a concept in code.Its a mechanism and practice to reduce and factor out details irrelevant to the user.

• InheritanceIt allows you to derive new classes from other classes. It is intended to help reuse of existing code with little or no modification.

• Polymorphism The idea of allowing the same definitions to be used with different types of

data (specifically, different classes of objects), resulting in more general and abstract implementations.

Page 84: VB NET

Class

• The idea is that classes are a type.

• Class defines the behavior of possibly many objects (instances).

• A class is a blueprint that defines the variables and the methods common to all objects of a certain kind.

Page 85: VB NET

Object• If class is a blueprint, then object is the implementation

of that blueprint.

• Each object has data members, corresponding to what objects knows, and data functions, corresponding to what an object can do.

• A region of storage with associated semantics.

Page 86: VB NET

Fields, Properties, Methods, and Events

• FieldsThe fields of a class, also called the class's data members, are much like built-in variables

• PropertiesProperties are retrieved and set like fields, but are handled with the Property Get and Property Set procedures They provide more control on how values are set or returned

• MethodsMethods represent the object's built-in procedures. They are used to implement the behavior of the class.

• EventsEvents allow objects to perform actions whenever a specific occurrence takes place.

Page 87: VB NET

Creating Class

To create a class, you only need to use the Class statement, which, like other compound statements in Visual Basic, needs to end with End Class:

Syntax:

Public Class DataClass

End Class

Page 88: VB NET

Example of a Class

Public Class Employee

Private Name as String

Public Salary as Double

End Class

Page 89: VB NET

Creating Data Members

As discussed earlier, the fields of a class, also called the class's data members, are much like built-in variables. They are defined as:

- Public Class Employee Public Salary As Double

End Class

- Public Class Employee Public Const PSRN As Integer = 0

End Class

Page 90: VB NET

Member Variables

• Private– Available only to code within the class

• Friend– Available only to code within our project/component

• Protected– Available only to classes that inherit from our class

• Protected Friend– Available only to code within our project/component and

classes that inherit from our class

• Public– Available to code outside our class

Page 91: VB NET

Creating Methods• As discussed earlier, methods represent the object's

built-in procedures.• You define methods by adding procedures, either Sub

procedures or functions, to your class.

Public Class Animal

Public Sub Eating() MsgBox("Eating...")

End Sub

Friend Sub Sleeping() MsgBox("Sleeping...")

End Sub

End Class

Page 92: VB NET

Creating Methods…Public Class Employee ‘Class Employee defined here

Private m_Tax as double ‘Declared Data member

Public Sub Set_Tax(Byval Value as double) ‘Declared Function

M_Tax=Value ‘to set value

End Sub

‘another such function defined below…

Public Function GET_PAYABLE_TAX() As Double

GET_PAYABLE_TAX = m_TAX

End Function

End Class ‘class employee end here

Page 93: VB NET

Creating Properties

If you often don't want to give code outside an object direct access to the data in the object then, you can use properties, which use methods to set or get an internal value.

Syntax:

Public Property <prop_name>( ) as <ret_type>

Get Return PropertyValue End Get

Set(ByVal Value As String) PropertyValue = Value End Set

End Property

Page 94: VB NET

Creating Properties…Public Property SET_NAME() As String

‘property name SET_NAME with return type as string

Get ‘get starts here for getting this value

SET_NAME = m_NAME End Get ‘get ends here

Set(ByVal Value As String) ‘set starts here

m_NAME = Value ‘setting the value of the data member here

End Set ‘set property ends here

End Property

Page 95: VB NET

Parameterized Properties

• Pass parameters to properties

Public Property Pin(ByVal Pincode as String) As String

Get

‘Write the code to get

End Get

Set (ByVal value as String)

‘Write the code to set

End Set

Page 96: VB NET

Read only Properties

• Property to be read only i.e. it cannot be changed

– Public ReadOnly Property Age() as Integer

Get

Return m_age

End Get

End Property

Page 97: VB NET

Write Only Properties

• Value can be changed but cant be retrieved.– Public WriteOnly Property BirthDate() as Date

Set (ByVal value as Date)

m_BirthDate = value

End Set

End Property

Page 98: VB NET

Default Property

• Sets the default value– Default Public Property IsActive (ByVal value As String) As

Boolean

Get

Return True

End Get

Set(ByVal value as Boolean)

m_Is_Active = value

End set

End Property

Page 99: VB NET

Constructor…

• A constructor is a special member function whose task is to initialize the objects of it's class.

• A constructor is invoked whenever an object of it's associated class is created.

• If a class contains a constructor, then an object created by that class will be initialized automatically.

Page 100: VB NET

Constructor…

Here are the characteristics of a constructor:• Always defined as a Sub. It therefore does not have a

return value.• Regardless the name of the class, the constructor in

VB.NET is called New.• In most cases, a constructor has a Public access

modifier.• A class can have multiple constructors.

Page 101: VB NET

Constructor…e.g.

Public Sub New()m_name = ""m_nickname = ""m_dob = Now.Datem_email = ""m_ph = 0m_mob = 0m_address = ""m_org = ""

End Sub

Page 102: VB NET

Overloading Constructors

Public Class Employeeprivate m_name as string

public sub new()m_name=“”

End sub

public sub new(byval name as string)m_name = name

End sub

End Class

Page 103: VB NET

Destructor

• Destructors run when an object is destroyed. Within a destructor we can place code to clean up the object after it is used.

• We use Finalize method in Visual Basic for this and the Finalize method is called automatically when the .NET runtime determines that the object is no longer required.

• When working with destructors we need to use the overrides keyword with Finalize method as we will override the Finalize method built into the Object class.

Page 104: VB NET

Destructor…Protected Overrides Sub finalize()

‘ this distructor is called by Garbage Collector... ‘ its called when GC feels like freeing the memory ‘ which can even be long after the application exits MsgBox("DIstructor Called Again BY 'GC' this time”)

End Sub

Page 105: VB NET

Creating Objects

There are two ways for creating an object. They are:

- Dim data As New DataClass()

- Dim data As DataClass = New DataClass()

Page 106: VB NET

DEMO

Page 107: VB NET

Events

• Objects can raise events.• Handles

– Private Sub btnObject_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click

– Private Sub MyClickMethod(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click,button2.Click

• WithEvents– Makes any events from an object available for use.– Cannot be used to declare a variable of a type that doesn’t

raise events.

Page 108: VB NET

Handling Events

• Raise Event– Define Event

• Public Event Brake( )

– Raise Event• RaiseEvent Brake()

– Receive Event (in Form)• Private WithEvents mobjCar As Car

– Receiving Events with AddHandler• AddHandler mobjCar.Brake, AddressOf OnBrake

Page 109: VB NET

Interface - IDisposable

• Finalize– GC class Finalize immediately before it collects an object that

is no longer required by application.– Protected scope and Overrides.

• IDisposable– Force the object cleanup.– Public Class Car Implements IDisposable

Page 110: VB NET

Shared Variables

• Variable’s value should be shared across all objects within the application.– Private Shared sCounter As Integer

• 2 Ways to call– Call directly from class– Call from instance

Page 111: VB NET

Shared Method

• Common across all instances of the class.– Shared methods doesn’t belong to any specific object– Can’t access any instance variables from any objects.– Only variables available for use within shared method are

shared variables,parameters passed into method or variables declared locally within the method itself.

Page 112: VB NET

Shared Properties

• Follow same rules as regular methods– Can interact with shared variables, but not member variables– Can invoke other shared methods or properties– Cannot invoke instance methods without first creating an

instance of class.

Page 113: VB NET

Inheritance

• New class can be based on existing class, inheriting its interface and functionality from original class.

• Also referred as generalization or “is-a” relationship.• Superclass /Parent Class/ Base Class• Derived Class• Variable Access

– Variables and methods that are Private are available only within that class.

– Variables and methods that are Public in one class can be called from other class.

– Variables and methods that are Friend are available between classes if both the classes are in same VB.NET project.

Page 114: VB NET

Creating Base Class

• Virtually any class we crate can act as base class.

Page 115: VB NET

Creating Derived Class

• Inherits Keyword– Indicates that a class should derive from existing class –

inheriting interface and behavior from that class.– Public Class SportsCar Inherits Car

Page 116: VB NET

Overloading Methods

• Overloads Keyword

Page 117: VB NET

Overriding Methods

• Override the behavior of methods on base class• Overridable keyword

Page 118: VB NET

MyBase Keyword

• Invoke the methods directly from the base class.

Page 119: VB NET

Inheritance

• Inherits– Used to indicate that a class should derive from existing class –

inheriting interface and behavior from that class

• Overloading– Overloading a method from base class and is done by

Overloads keyword.

• Overriding Methods– Not only Extend the original functionality but actually change or

entirely replace the functionality from base class.• Overridable

– If we don’t use the keyword when declaring a method, it is non virtual.

• Overrides

• MyBase

Page 120: VB NET

Abstract Class

• Create a class so that it can only be used as base class for inheritance.– MustInherit keyword

• Preventing anyone from creating objects based directly on the class and requiring them instead to create a subclass and then create objects based on that subclass.

– Public MustInherit Class Vehicle

– MustOverride keyword• Base class also relied on subclass to provide some behavior in

order to function properly.

• Class that contaisn methods with MustOverride should be declared with MustInherit

Page 121: VB NET

Interface

• Define the Interface

Public Interface iPrint ‘Function Definitions here!

End Interface

• Implementing Interface– Using Implements keyword– To implement an interface, we must implement ALL the

methods and properties defined by that interface.

Page 122: VB NET

Error Handling

• All .NET exceptions inherit from System.Exception

Namespace ClassSystem ApplicationException

SystemExceptionVB6Exception

System.Data InvalidConstraintExceptionSystem.IO IOExceptionSystem.Runtime.InteropServices COMExceptionSystem.XML XmlException

Page 123: VB NET

On Error

• On Error Goto ErrorHandler• Write ErrorHandler

Page 124: VB NET

Try..Catch..Finally

• Try• Catch• Finally• Exit Try• Nested Try

Page 125: VB NET

Clipboard

• Temporary memory area that holds copied objects• Copied objects can be used in Paste Operation.• DataObject• Clipboard

Page 126: VB NET

Assembly

• Private• Shared

Page 127: VB NET

Creating Shared Assembly

• Shared Assembly Names– Globally unique and must be possible to protect name.– Must have Strong Name– Strong Name made up of

• Name of Assembly

• A Version Number– Makes it possible to use different versions of same assembly at same

time

• Public Key – Guarantees that the strong name is unique.– Also guarantees that a referenced assembly can’t be replaced from

different source.

• Culture.

Page 128: VB NET

Public Key Cryptography

• Symmetric Encryption– Same key can be used for encryption and decryption.

• Public/Private Key– If something is encrypted using a public key, it can be

decrypted by using the corresponding private key, but it is not possible with the public key. Also works other way round!

– Always created as pair.

Page 129: VB NET

Integrity using Strong Names

• Compiler writes the public key to the manifest.• It then creates a hash of all files that belong to

assembly and signs the hash with Private Key.• Private key is not stored within the assembly.• During development , client assembly must reference

the shared assembly. • Compiler writes the public key of referenced assembly

to the manifest of client assembly.• To reduce storage, public key is not written to manifest,

but public key token is written.• Public key token is last eight bytes of a has of public

key and it is unique.

Page 130: VB NET

Creating Shared Assembly

• Create Strong Name• sn –k mykey.snk• View key using ildasm• GACUtil

– Gacutil /I SharedDemo.dll

Page 131: VB NET

Using Shared Assembly

• LocalCopy

Page 132: VB NET

Windows® Forms

System.DrawingSystem.Drawing

Drawing2DDrawing2D

ImagingImaging

PrintingPrinting

TextText

System.Windows.FormsSystem.Windows.Forms

DesignDesign ComponentModelComponentModel

Page 133: VB NET

Windows® Forms

• Use of Form• Reuse of Form• Methods and Properties

Page 134: VB NET

Form• Properties

– AcceptButton– CancelButton– ControlBox– Font– Location– Maximize/Minimize– Size– StartPosition– TopMost– Window State

Page 135: VB NET

Form…

• Events– Load Event– Activated Event (Occurs when the form is activated in code or

by the user.)– Closing Event– Closed Event (Occurs when the form is closed)– Resize

• Methods– Close– Hide– Show– Focus– Dispose

Page 136: VB NET

ControlsA control is an object that can be drawn on to the Form to enable or enhance user interaction with the application. Example textbox, radiobutton, checkbox etc…

All these Windows Controls are based on the Control class, the base class for all controls. Visual Basic allows us to work with controls in two ways: at design time and at runtime.

Some of the properties of this class are:Allowdrop DataBindings SizeAnchor Dock WidthBackcolor Enable TabIndexBottom Focused TextCanFocus Forecolor Visible etcCanSelect FontCursor Name

Page 137: VB NET

Textbox

• Properties– Text– Maxlength– Multiline– Passwordchar– Scrollbars– SelectedText– SelectionStart– TextAlign– TextLength…

• Methods– AppendText– Clear– Cut– Copy– Paste– Select…

• Events– Click– DoubleClick– GotFocus– Keydown– KeyUp– KeyPress– MouseHover– TextChanged…

Page 138: VB NET

Label• Properties

– Text– Name– BackColor– BorderStyle– Image– Location– Size

– Visible…

• Methods– Focus– Hide– Show– Dispose– ToString

• Events– Click– DoubleClick– GotFocus– Keydown– KeyUp– KeyPress– MouseHover– TextChanged…

Page 139: VB NET

Button

• Properties– Text– Name– BackColor– BorderStyle– Image– Location– Size

– Visible…

• Methods– Focus– Hide– Show– Dispose– ToString

• Events– Click– DoubleClick– GotFocus– Keydown– KeyUp– KeyPress– MouseHover– TextChanged…

Page 140: VB NET

CheckBox

• Property– Checked– CheckState

• Methods– OnClick

• Events– Click– CheckedChange

Page 141: VB NET

RadioButton

• Properties– Appearance– BackgroundImage– Checked

• Methods– OnClick

• Events– Click– CheckedChange

Page 142: VB NET

ListBox

• Properties– Items

– SelectedIndex

– SelectedItem

– HorizontalScrollbar

– MultiColumn

– SelectionMode

– Sorted

• Events– SelectedIndexChanged

– SelectedValueChanged

Page 143: VB NET

ListBox…

• To add item

Listbox1.items.add(<value>)• To count no. of items

Listbox1.items.count• To get the selected value

Listbox1.selectedItem• To remove item

Listbox1.items.RemoveAt(index_value)• To remove all the items

Listbox1.items.Clear()

Page 144: VB NET

ComboBox

• Properties– Items

– SelectedIndex

– SelectedItem

– Text*

– Sorted

– DropDownStyle

– MaxDropDown

• Events– SelectedIndexChanged

– SelectedValueChanged

Page 145: VB NET

ScrollBars

• Property– SmallChange– LargeChange– Maximum– Minimum– Value

• Events– Scroll– ValueChanged

Page 146: VB NET

ScrollBars

• Property– SmallChange– LargeChange– Maximum– Minimum– Value

• Events– Scroll– ValueChanged

Page 147: VB NET

PictureBox

The Windows Forms PictureBox control is used to display graphics in bitmap, GIF, JPEG, metafile, or icon format.

Properties:– Image– Borderstyle – SizeMode

Page 148: VB NET

PictureBox…

To display a picture at design time • Draw a PictureBox control on a form. • On the Properties window, select the Image property,

then click the ellipsis button to display the Open dialog box.

• If you are looking for a specific file type (for example, .gif files), select it in the Files of type box.

• Select the file you want to display.

Page 149: VB NET

PictureBox…

To set a picture programmatically • Set the Image property using the FromFile method of

the Image class.

e.g.PictureBox1.Image = Image.FromFile(path)

Page 150: VB NET

DateTimePicker

The DateTimePicker control is used to allow the user to select a date and time, and to display that date/time in the specified format.

Major properties are:

– MaxDate Property

Gets or sets the maximum date and time that can be selected in the control

– MinDate Property

Gets or sets the minimum date and time that can be selected in the control

Page 151: VB NET

DateTimePicker…– Format Property

Gets or sets the format of the date and time displayed in the control.

– CustomFormat PropertyGets or sets the custom date/time format string. with the appropriate formatting or custom formatting applied.

– Value PropertyGets or sets the date/time value assigned to the control.

Page 152: VB NET

Timer Control

Implements a timer that raises an event at user-defined intervals.

Properties:– Enabled Property

Gets or sets whether the timer is running.

– Interval Property

Gets or sets the time, in milliseconds, between timer ticks.

Event:

– Tick Event

Occurs when the specified timer interval has elapsed and the timer is enabled.

Page 153: VB NET

Timer Control…

Methods:– OnTick Method

Raises the “Tick” event.

– Start Method

Starts the timer.

– Stop Method

Stops the timer.

Page 154: VB NET

Richtext Box

Properties• Color• Font• Forecolor• Zoomfactor• WordWrap• SelectionColor• SelectionFont

• SelectedText• SelectionLength• SelectionIndent• SelectionRightIndent• SelectionBullet• SelectionAlignment• SelectionHangingIndent

Page 155: VB NET

Richtext Box…

Methods• LoadFile• SaveFile• Find• Undo• Redo

Events• LinkClicked

Page 156: VB NET

DialogBox Controls

• OpenFileDialog• SaveFileDialog• FontDialog• ColorDialog

Page 157: VB NET

DialogResult Enumeration

Specifies identifiers to indicate the return value of a dialog box.– Abort– Cancel– Ignore– Ok – Yes– No– Retry

Page 158: VB NET

OpenFileDialog

Page 159: VB NET

OpenFileDialog…OpenFileDialog's are supported by the OpenFileDialog class and they allow us to select a file to be opened.

Properties:– AddExtension: Gets/Sets if the dialog box adds extension to file

names if the user doesn't supply the extension.– CheckFileEixsts: Checks whether the specified file exists before

returning from the dialog. – CheckPathExists: Checks whether the specified path exists before

returning from the dialog. – DefaultExt: Allows you to set the default file extension.

Page 160: VB NET

OpenFileDialog…– FileName: Gets/Sets file name selected in the file dialog box.

– FileNames: Gets the file names of all selected files.

– Filter: Gets/Sets the current file name filter string, which sets the choices that appear in the "Files of Type" box.

– FilterIndex: Gets/Sets the index of the filter selected in the file dialog box.

– InitialDirectory: This property allows to set the initial directory which should open when you use the OpenFileDialog.

– MultiSelect: This property when set to True allows to select multiple file extensions.

– ReadOnlyChecked: Gets/Sets whether the read-only checkbox is checked.

Page 161: VB NET

OpenFileDialog…OpenFileDialog1.Filter = “Text files (*.txt)|*.txt|" & "All files|*.*”

OpenFileDialog1.Filter =“All Image Files| *.bmp; *.gif; *.jpg”

Dim myfile = OpenFileDialog1.Filename

OpenFileDialog1. InitialDirectory=“c:\abc”

OpenFileDialog1.Title = "My Image Browser"

msgbox(OpenFileDialog1.OpenFile())

Page 162: VB NET

OpenFileDialog…

One approach is to use the ShowDialog method to display

the Open File dialog box, and use an instance of the

StreamReader class to open the file.

If OpenFileDialog1.ShowDialog() = DialogResult.OK Then Dim sr As New System.IO.StreamReader(OpenFileDialog1.FileName)

MessageBox.Show(sr.ReadToEnd) sr.Close()

End if

Page 163: VB NET

OpenFileDialog…

Use the ShowDialog method to display the dialog box and the OpenFile method to open the file.

Dim openFileDialog1 As New OpenFileDialog() openFileDialog1.Filter = "Cursor Files|*.cur“

openFileDialog1.Title = "Select a Cursor File"

If openFileDialog1.ShowDialog() = DialogResult.OK Then Me.Cursor = New Cursor(openFileDialog1.OpenFile())

End If

Page 164: VB NET

OpenFileDialog…Dim sr as StreamReader

With OpenFileDialog1.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"

If .ShowDialog() = DialogResult.OK Then

FileName = .FileNamesr = New StreamReader(.OpenFile)RichTextBox1.Text = sr.ReadToEnd()

End IfEnd With

Page 165: VB NET

SaveFileDialog

Page 166: VB NET

SaveFileDialog…Save File Dialog's are supported by the SaveFileDialog class and they allow us to save the file in a specified location.

Properties:– Same as that of OpenDialog Box– OverwritePrompt

Gets or sets a value indicating whether the Save As dialog box displays a warning if the user specifies a file name that already

exists.

Page 167: VB NET

SaveFileDialog…

To save file

1. Open SaveFileDialog Box

2. Declare a stream writer

3. Get the Filename

4. Write into that Filename(from a perticular control)

Page 168: VB NET

SaveFileDialog…

With SaveFileDialog1.FileName = FileName

.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"

If .ShowDialog() = DialogResult.OK Then

FileName = .FileName

End WIth

sw = New StreamWriter(FileName)

Page 169: VB NET

FontDialog

Page 170: VB NET

FontDialog… Represents a common dialog box that displays a list of fonts that

are currently installed on the system.

Properties:

– Color Property

Gets or sets the selected font color.

– Font Property

Gets or sets the selected font.

– MaxSize Property

Gets or sets the maximum point size a user can select.

– ShowColor Property

Gets or sets a value indicating whether the dialog box displays the color choice.

Page 171: VB NET

FontDialog…– MinSize Property

Gets or sets the minimum point size a user can select.– ShowEffects Property

Gets or sets a value indicating whether the dialog box contains controls that allow the user to specify strikethrough, underline, and text color options.

e.g.FontDialog1.Font =textBox1.Font fontDialog1.Color=textBox1.ForeColorFontDialog1.MaxSize = 32 FontDialog1.MinSize = 18

If FontDialog1.ShowDialog() = DialogResult.OK Then

TextBox1.Font =FontDialog1.Font End if

Page 172: VB NET

ColorDialog

Page 173: VB NET

ColorDialog…

Represents a common dialog box that displays available colors along with controls that allow the user to define custom colors.

Properties:• AllowFullOpen Property

Gets or sets a value indicating whether the user can use the dialog box to define custom colors.

• AnyColor Property

Gets or sets a value indicating whether the dialog box displays all available colors in the set of basic colors

Page 174: VB NET

ColorDialog…• Color Property

Gets or sets the color selected by the user.

• CustomColors PropertyGets or sets the set of custom colors shown in the dialog box.

• FullOpen PropertyGets or sets a value indicating whether the controls used to create custom colors are visible when the dialog box is opened

• SolidColorOnly PropertyGets or sets a value indicating whether the dialog box will restrict users to selecting solid colors only.

Page 175: VB NET

ColorDialog…e.g.

- Dim MyDialog As New ColorDialog()MyDialog.AnyColor = True MyDialog.SolidColorOnly = False MyDialog.AllowFullOpen = True MyDialog.CustomColors = New Integer() {6916092, 15195440} If (MyDialog.ShowDialog() = DialogResult.OK) Then textBox1.ForeColor = MyDialog.Color

End If

Page 176: VB NET

Main Menu

Menus are those controls that allow the user to make selections

• In Visual Basic, the MenuStrip control represents the container for the menu structure of a form

• Menus are made up of MenuItem objects that represent the individual parts of a menu

Page 177: VB NET

Menu Items• Menus like File or Edit and the actual items in such

menus are supported with the MenuItem class

Properties:

Checked PropertyGets or sets a value indicating whether a check mark appears next to the text of the menu item.

MdiList PropertyGets or sets a value indicating whether the menu item will be populated with a list of the Multiple Document Interface (MDI) child windows that are displayed within the associated form.

Page 178: VB NET

Menu Items…Shortcut Property

Gets or sets a value indicating the shortcut key associated with the menu item.

ShowShortcut PropertyGets or sets a value indicating whether the shortcut key that is associated with the menu item is displayed next to the menu item caption.

Text PropertyGets or sets a value indicating the caption of the menu item.

Visible PropertyGets or sets a value indicating whether the menu item is visible.

Page 179: VB NET

Adding checkmarks to MenuItem

• You can use the Checked property of a MenuItem object to toggle the checkmark – True (checkmark is displayed )– False (its hidden)

MenuItem.Checked = Not MenuItem.Checked

Page 180: VB NET

Creating Menu Shortcuts

• To display the shortcut next to the menu item's caption at run time, you set the ShowShortcut property to True

menuItem.Shortcut = Shortcut.CtrlX

Page 181: VB NET

Changing a Menu Item's Caption at Run Time

• To change a menu item's caption at run time, you only have to set its Text property.

MenuItem.Text = “My Menu Item”

Note: Try and make use of Popup event in case if u want to change the caption of a menu item

Page 182: VB NET

Showing and Hiding Menu Items

• To show and hide menu items, you can use their Visible property – True (Menu Item will be visible)– False (Menu Item will become invisible)

MenuItem.Visible = False

Page 183: VB NET

Disabling Menu Items

• To disable, or "gray out" a menu item, so that it can't be selected, you set its Enabled property to False. – True (User will be able to interact with it)– False (No interaction possible)

MenuItem5.Enabled = False

Page 184: VB NET

MDI Applications MDI (Multiple Document Interface) Application is an application in which we can view and work with several documents at once.

To create an MDI Application:

Select a Form and in it's Properties Window under the Windows Style section, set the property IsMdiContainer to True. Setting it to true designates this form as an MDI container for the child windows.

Page 185: VB NET

MDI Applications…• CREATING MDI CHILD FORMS:

An vital constituent of Multiple Document Interface (MDI) Applications is the MDI child forms, as these are the main windows for client interaction.

To create MDI child forms:

Form frmchild = new Form()frmchild.MDIParent = mefrmchild.Show()

Page 186: VB NET

MDI Applications…

• Determining the Active MDI Child

To specify the correct form, use the ActiveMDIChild property, which returns the child form that has the focus or that was most recently active.

e.g.Dim activeChild As Form = Me.ActiveMdiChild

Page 187: VB NET

MDI Applications…

• Sending Data to the Active MDI Child

1. Find the Active MDI Child form

Dim activeChild As Form = Me.ActiveMdiChild

2. Find the control on that active form to refer to<var_name> = CType(activeChild.ActiveControl, <control_type>)

3. Perform appropriate action… like

rtb.LoadFile(.FileName, RichTextBoxStreamType.PlainText)

Page 188: VB NET

MDI Applications…

ARRANGING CHILD FORMS:

• Applications will have menu commands for actions such as Tile, Cascade, and Arrange, with concerning to the open MDI child forms. One can use the LayoutMDI method with the MDILayout enumeration to rearrange the child forms in an MDI parent form.

e.g.

- Me.LayoutMdi(MdiLayout.TileVertical)- Me.LayoutMdi(MdiLayout.TileHorizontal)- Me.LayoutMdi(MdiLayout.Cascade)

Page 189: VB NET

DEMO

Page 190: VB NET

COM

• Default Interop Assembly– TlbImp.exe– Tlbimp MCalculator.dll /out:MCalculatorNet.dll /verbose

Page 191: VB NET

Late Binding

• Reflection– Type.GetTypeFromProgID

• Create Instance– Activator.CreateInstance

• Invoke Member– Parameter 1: Method to call– Parameter 2: BindingFlags enumeration tells to invoke the

method– Parameter 3: Language specific binding information– Parameter 4: Reference to COM object.– Parameter 5: Array of objects representing the arguments for

method.

Page 192: VB NET

Creating DLL in VB.NET

• Create a Class Library• Regasm

– Used to register the DLL.– Regasm MyCalculator.dll /tlb:MyCalculator.tlb

Page 193: VB NET

Creating Controls

• Creating/Extending Control• Extender /Ambient• Creating User Control

Page 194: VB NET

Reflection

• Ability to inspect and manipulate program elements at runtime.

• Allows you:– Enumerate the members of a type– Instantiate a new object– Execute the members of an object– Find out information about a type– Find out information about an assembly– Create and compile new assembly.

• System.Type• System.Reflection

Page 195: VB NET

System.Type class

• Holds the reference to a type

Dim t As Type

Dim d As Double = 10

t = d.GetType()

Page 196: VB NET

Q/A

• Any Questions please?