vb net
TRANSCRIPT
VB.NET
Deepak PatilDeepak Patil
Overview of the .NET Framework
• The .NET Framework– Common Language Runtime– Managed and Unmanaged Code– MSIL– JIT– Assemblies
Event Driven Programming
• Event Model• Event Handlers• Callbacks• Asynchronous Event-Firing (Callbacks in multithread)• Event driven programming and VB .NET
Introduction to VS.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.
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.
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.
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
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
Using Server Explorer
• Managing Data Connections
• Viewing and Managing Servers
• Using Drag-and-Drop Techniques
Object Browser
• Examine Objects and their Members
• Access Lower-level Items– Shows inheritance and
interfaces• Examine How the .NET
Framework Class Libraries Use Inheritance
Tool Box
Property Window
My First VB.NET App.
Introduction to Visual Basic .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
VB.NET Lang. Fundamentals
• Variables• Data Types• Identifiers• Keywords• Literals• Dimensioning Variables• Operators• Expressions• Statements
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.
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’.
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
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!
Data types visited
• Plenty of them– String– Integer– Boolean (for True/False types)– DateTime– Double (for money, fractions)– And more …
Data type: String$
• Any text value– Names– Colors– Login ids
• Examples– “Rahul”– “Red”– “f1997408”
Data type: Integer%
• Can hold whole numbers– Both positive & negative
• Examples– 10– -666– 0
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
Data Type: Double#
• Double: to store Real numbersFractions
• Examples– 0.00– 19.7– -98.3674501
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 …
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
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
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
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.
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)
Relational Operators• = (equality)• <> (inequality)• < (less than)• > (greater than)• <= (less than or equal to)• >= (greater than or equal to)• Like• TypeOf
String-Concatenation Operators• & and +
– The & (ampersand) and + (plus) characters signify string concatenation.
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.
Statements
• Made up of– Keywords (like Dim)– Operators– Variables– Constants– Expressions
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
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
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
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
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
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
"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
Agenda
• If, then, End If• If, Then, Else, End If• Select Case• While Statement• Do … Loop• For … next• Arrays
If – Then – End If
• Allows conditional branching in code
If stars > 4 Then
rating = “Super Hit”
End If
If – Then – Else – End If
If choice = 1 Then
shop = “Shoppers Stop”
Else
shop = “Walden”
End if
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
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.
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
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
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
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
While statement…
Syntax:
While <Expr>
[statements]
End While
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.”
Do Loop
Syntax:
Do[{while | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
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
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.”
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
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.”)
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>
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.”)
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>
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.”)
For Next
• When it is known before hand how many times the iteration will happen.
Syntax:
For x = i To j
[statements]
Next
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
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
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"
Exit For
For I = 1 To 10
if I = 7 then
exit for
end if
Text1.Text = Counter
Text1.Refresh ‘ Update Text1
Next
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.
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)
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"}
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()
Array Property
• Array.Length• Array.IsReadOnly (always false)• Array.IsFixedSize (always true)
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
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
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)
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.
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”
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.
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.
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.
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
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.
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.
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.
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.
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
Example of a Class
Public Class Employee
Private Name as String
Public Salary as Double
End Class
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
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
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
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
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
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
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
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
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
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
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.
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.
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
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
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.
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
Creating Objects
There are two ways for creating an object. They are:
- Dim data As New DataClass()
- Dim data As DataClass = New DataClass()
DEMO
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.
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
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
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
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.
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.
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.
Creating Base Class
• Virtually any class we crate can act as base class.
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
Overloading Methods
• Overloads Keyword
Overriding Methods
• Override the behavior of methods on base class• Overridable keyword
MyBase Keyword
• Invoke the methods directly from the base class.
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
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
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.
Error Handling
• All .NET exceptions inherit from System.Exception
Namespace ClassSystem ApplicationException
SystemExceptionVB6Exception
System.Data InvalidConstraintExceptionSystem.IO IOExceptionSystem.Runtime.InteropServices COMExceptionSystem.XML XmlException
On Error
• On Error Goto ErrorHandler• Write ErrorHandler
Try..Catch..Finally
• Try• Catch• Finally• Exit Try• Nested Try
Clipboard
• Temporary memory area that holds copied objects• Copied objects can be used in Paste Operation.• DataObject• Clipboard
Assembly
• Private• Shared
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.
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.
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.
Creating Shared Assembly
• Create Strong Name• sn –k mykey.snk• View key using ildasm• GACUtil
– Gacutil /I SharedDemo.dll
Using Shared Assembly
• LocalCopy
Windows® Forms
System.DrawingSystem.Drawing
Drawing2DDrawing2D
ImagingImaging
PrintingPrinting
TextText
System.Windows.FormsSystem.Windows.Forms
DesignDesign ComponentModelComponentModel
Windows® Forms
• Use of Form• Reuse of Form• Methods and Properties
Form• Properties
– AcceptButton– CancelButton– ControlBox– Font– Location– Maximize/Minimize– Size– StartPosition– TopMost– Window State
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
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
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…
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…
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…
CheckBox
• Property– Checked– CheckState
• Methods– OnClick
• Events– Click– CheckedChange
RadioButton
• Properties– Appearance– BackgroundImage– Checked
• Methods– OnClick
• Events– Click– CheckedChange
ListBox
• Properties– Items
– SelectedIndex
– SelectedItem
– HorizontalScrollbar
– MultiColumn
– SelectionMode
– Sorted
• Events– SelectedIndexChanged
– SelectedValueChanged
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()
ComboBox
• Properties– Items
– SelectedIndex
– SelectedItem
– Text*
– Sorted
– DropDownStyle
– MaxDropDown
• Events– SelectedIndexChanged
– SelectedValueChanged
ScrollBars
• Property– SmallChange– LargeChange– Maximum– Minimum– Value
• Events– Scroll– ValueChanged
ScrollBars
• Property– SmallChange– LargeChange– Maximum– Minimum– Value
• Events– Scroll– ValueChanged
PictureBox
The Windows Forms PictureBox control is used to display graphics in bitmap, GIF, JPEG, metafile, or icon format.
Properties:– Image– Borderstyle – SizeMode
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.
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)
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
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.
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.
Timer Control…
Methods:– OnTick Method
Raises the “Tick” event.
– Start Method
Starts the timer.
– Stop Method
Stops the timer.
Richtext Box
Properties• Color• Font• Forecolor• Zoomfactor• WordWrap• SelectionColor• SelectionFont
• SelectedText• SelectionLength• SelectionIndent• SelectionRightIndent• SelectionBullet• SelectionAlignment• SelectionHangingIndent
Richtext Box…
Methods• LoadFile• SaveFile• Find• Undo• Redo
Events• LinkClicked
DialogBox Controls
• OpenFileDialog• SaveFileDialog• FontDialog• ColorDialog
DialogResult Enumeration
Specifies identifiers to indicate the return value of a dialog box.– Abort– Cancel– Ignore– Ok – Yes– No– Retry
OpenFileDialog
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.
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.
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())
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
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
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
SaveFileDialog
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.
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)
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)
FontDialog
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.
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
ColorDialog
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
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.
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
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
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.
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.
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
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
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
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
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
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.
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()
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
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)
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)
DEMO
COM
• Default Interop Assembly– TlbImp.exe– Tlbimp MCalculator.dll /out:MCalculatorNet.dll /verbose
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.
Creating DLL in VB.NET
• Create a Class Library• Regasm
– Used to register the DLL.– Regasm MyCalculator.dll /tlb:MyCalculator.tlb
Creating Controls
• Creating/Extending Control• Extender /Ambient• Creating User Control
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
System.Type class
• Holds the reference to a type
Dim t As Type
Dim d As Double = 10
t = d.GetType()
Q/A
• Any Questions please?