VB Net
VB Net
VB Net
à
á
The .NET Framework
± Common Language Runtime
± Managed and Unmanaged Code
± MSIL
± JIT
± Assemblies
Event Model
Event Handlers
Callbacks
Asynchronous
nrng
csnuhr
Event driven programming and VB .NET
4
_
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.
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.
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.
_ !
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.
Using Drag-and-Drop
Techniques
á$
4nrouconosusc
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
&
Variables
Data Types
Identifiers
Keywords
Literals
Dimensioning Variables
Operators
Expressions
Statements
$
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.
$
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¶.
#'(
#
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
#
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!
#
Plenty of them
± String
± Integer
± Boolean (for True/False types)
± DateTime
± Double (for money, fractions)
± And more «
#)*
Any text value
± Names
± Colors
± Login ids
Examples
± ³Rahul´
± ³Red´
± ³f1997408´
#)4+
Can hold whole numbers
± Both positive & negative
Examples
± 10
± -666
± 0
#)'
Boolean: µLogic¶ values
± Only 2 values possible
± True or false
True: any non-zero value
False: zero
± #
±
$
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 are symbols & specify operations to be
performed on one or two operands (or arguments).
Type of Operators:
± Unary Operators
± Arithmetic Operators
± Relational Operators
± String-Concatenation Operators
± Logical Operators
h á#
- (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.
* (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)
(á#
= (equality)
<> (inequality)
< (less than)
> (greater than)
<= (less than or equal to)
>= (greater than or equal to)
Like
TypeOf
-á#
>$
± The & (ampersand) and + (plus) characters signify string
concatenation.
&á#
%
%
&
%
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.
Made up of
± Keywords (like Dim)
± Operators
± Variables
± Constants
± Expressions
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
Each statement is a command
à
à
! "
#$%
& '(
)
* !
*
&4#
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
+(""
+
$%
à "'",
"
Causes compile-time errors
+($',-%
",
Correct syntax
+($',-%
*
á" *0" á
á" á
+(""
+
$%
(
""
*
*
® %®%
1 4+(""-3
4+(""- 0
1 4+(6
(-
+(""
+
$%
_
'
_
'
à
%%
-
.
à -"
#
( - -7 6 $%
*
*
_
If, then, End If
If, Then, Else, End If
Select Case
While Statement
Do « Loop
For « next
Arrays
4.
. 4
Allows conditional branching in code
If choice = 1 Then
shop = ³Shoppers Stop´
Else
shop = ³Walden´
End if
4.
. . 4
If choice = 1 Then
shop = ³Shoppers Stop´
ElseIf choice = 2 Then
shop = ³Big Bazaar´
Else µ for any other choice
shop = ³Walden´
End if
end select
Select number
case 1, 2, 3
txtresult.text= ³1´
case 4 To 10
txtresult.text= ³2´
case Is < 20
txtresult.text= ³3´
case Is > 20
txtresult.text= ³4´
End Select
%
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
%
Syntax:
While <Expr>
[statements]
End While
%
Example 1
Dim counter as Integer = 0
Dim value as integer = 0
while value < 30
counter = counter + 1
value = value + 10
end while
Syntax:
Do While <Expr>
[statements]
Loop
% "#
Dim value as Integer
Dim counter as Integer
Value = 11
Counter = 0
Syntax:
Do Until <Expr>
[statements]
Loop
h"#
Dim value as Integer
Dim counter as Integer
Value = 9
Counter = 0
Do Until value = 10
counter = counter + 1
value = value + 1
Loop
Do
[statements]
Loop While <Expr>
% "#
Dim value as Integer
Dim counter as Integer
Do
counter = counter + 1
value = value ± 1
Loop While value > 10
Do
[statements]
Loop Until <Expr>
h"#
Dim value as Integer
Dim counter as Integer
Do
counter = counter + 1
value = value + 1
Loop Until value = 10
Syntax:
For x = i To j
[statements]
Next
-"
Example 1:
OR
OR
Dim rectArray(,) As Integer = {{1, 2, 3}, {12, 13, 14}, {11, 10, 9}}
OR
IMP: If two variables with the same name are both in scope, the
most recently defined variable is the variable that is being
accessed.
$/
They are set of instructions designed to accomplish
one specific task.
± They eliminates duplicate code
± Promotes modularity
± Which further leads to ³CODE RESUE´
_
Function RepeatString(ByVal sInput As String, ByVal iCount As
Integer) As String
Dim i As Integer
For i = 1 To iCount
RepeatString = RepeatString & sInput
Next
End Function
Abstraction
The 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.
Inheritance
It 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.
The idea is that classes are a type.
Properties
Properties are retrieved and set like fields, but are handled with the
u%
,
and u%
procedures
They provide more control on how values are set or returned
Methods
Methods represent the object's built-in procedures. They are used to
implement the behavior of the
.
Events
Events allow objects to perform actions whenever a specific occurrence
takes place.
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:
*
End Class
"#
Public Class Employee
Private Name as String
Public Salary as Double
End Class
¢$
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
End Class
¢
Public Class Employee µClass Employee defined here
Private m_Tax as double µDeclared Data member
*
u
u%
-%%./-
.
%/
,
+
u%
|
,
u%
#
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
End Class
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.
Protected Overrides Sub finalize()
End Sub
á$
There are two ways for creating an object. They
are:
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.
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
4- 4#$
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
$
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
¢
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.
#
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.
4
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.
Virtually any class we crate can act as base class.
Inherits Keyword
± Indicates that a class should derive from existing class ±
inheriting interface and behavior from that class.
± Public Class SportsCar Inherits Car
á ¢
Overloads Keyword
á ¢
Override the behavior of methods on base class
Overridable keyword
¢ 1
Invoke the methods directly from the base class.
4
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
_$
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
4
Define the Interface
?
Ä
Ä
Ä
Ä
Ä Ä
Ä
á
On Error Goto ErrorHandler
Write ErrorHandler
Try
Catch
Finally
Exit Try
Nested Try
#$
Temporary memory area that holds copied objects
Copied objects can be used in Paste Operation.
DataObject
Clipboard
_$
Private
Shared
_$
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.
$1 ##
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.
4
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.
_$
Create Strong Name
sn ±k mykey.snk
View key using ildasm
GACUtil
± Gacutil /I SharedDemo.dll
h _$
LocalCopy
%®
3 4
# %
1
#
# 2# u
*
%®
Us ofor
R us ofor
M hosnro r s
Properties
± AcceptButton
± CancelButton
± ControlBox
± Font
± Location
± Maximize/Minimize
± Size
± StartPosition
± TopMost
± Window State
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
A 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.
± 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
± Format Property
Gets or sets the format of the date and time displayed in the control.
± CustomFormat Property
Gets or sets the custom date/time format string. with the appropriate
formatting or custom formatting applied.
± Value Property
Gets or sets the date/time value assigned to the control.
± 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.
Methods:
± OnTick Method
Raises the ³Tick´ event.
± Start Method
Starts the timer.
± Stop Method
Stops the timer.
( ""
u%
Color SelectedText
Font SelectionLength
Forecolor SelectionIndent
Zoomfactor SelectionRightIndent
WordWrap SelectionBullet
SelectionColor SelectionAlignment
SelectionFont SelectionHangingIndent
( ""
Methods Events
LoadFile LinkClicked
SaveFile
Find
Undo
Redo
"
OpenFileDialog
SaveFileDialog
FontDialog
ColorDialog
(
Specifies identifiers to indicate the return value of a
dialog box.
± Abort
± Cancel
± Ignore
± Ok
± Yes
± No
± Retry
á#
á#
OpenFileDialog's are supported by the OpenFileDialog class
and they allow us to select a file to be opened.
u%
± 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.
á#
± 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.
á#
OpenFileDialog1.Filter = ³Text files (*.txt)|*.txt|" & "All files|*.*´
OpenFileDialog1. InitialDirectory=³c:\abc´
msgbox(OpenFileDialog1.OpenFile())
á#
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.
With OpenFileDialog1
.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
FileName = .FileName
sr = New StreamReader(.OpenFile)
RichTextBox1.Text = sr.ReadToEnd()
End If
End With
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.
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)
With SaveFileDialog1
.FileName = FileName
.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
If .ShowDialog() = DialogResult.OK Then
FileName = .FileName
End WIth
sw = New StreamWriter(FileName)
+%
*
%
u%
± u%
Gets or sets the selected font color.
± 4
u%
Gets or sets the selected font.
± 1* 6u%
Gets or sets the maximum point size a user can select.
± u%
Gets or sets a value indicating whether the dialog box displays the
color choice.
± 1 6u%
Gets or sets the minimum point size a user can select.
±
u%
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.
4
# 74
0
*
*74
# 70
*
*74
4
# 71* 6082
4
# 71 6079
CustomColors Property
Gets or sets the set of custom colors shown in the dialog box.
FullOpen Property
Gets or sets a value indicating whether the controls used to create custom
colors are visible when the dialog box is opened
SolidColorOnly Property
Gets or sets a value indicating whether the dialog box will restrict users to
selecting solid colors only.
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
¢¢
Menus are those controls that allow the user to make
selections
Properties:
Checked Property
Gets or sets a value indicating whether a check mark appears next
to the text of the menu item.
MdiList Property
Gets 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.
¢4
u%
Gets or sets a value indicating the shortcut key associated with the
menu item.
u%
Gets or sets a value indicating whether the shortcut key that is
associated with the menu item is displayed next to the menu item
caption.
*
u%
Gets or sets a value indicating the caption of the menu item.
| u%
Gets or sets a value indicating whether the menu item is visible.
_ ¢4
You can use the
; property of a 1
object to toggle the checkmark
± True (checkmark is displayed )
± False (its hidden)
menuItem.Shortcut = Shortcut.CtrlX
¢42#(
MenuItem.Visible = False
$¢4
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
¢4_##
MDI (Multiple Document Interface) Application is an application
in which we can view and work with several documents at once.
e.g.
Dim activeChild As Form = Me.ActiveMdiChild
¢4_##
Sending Data to the Active MDI Child
e.g.
- Me.LayoutMdi(MdiLayout.TileVertical)
- Me.LayoutMdi(MdiLayout.TileHorizontal)
- Me.LayoutMdi(MdiLayout.Cascade)
#1(
á¢
Default Interop Assembly
± TlbImp.exe
± Tlbimp MCalculator.dll /out:MCalculatorNet.dll /verbose
&
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.
&&
Create a Class Library
Regasm
± Used to register the DLL.
± Regasm MyCalculator.dll /tlb:MyCalculator.tlb
Creating/Extending Control
Extender /Ambient
Creating User Control
(
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
#
Holds the reference to a type
Dim t As Type
Dim d As Double = 10
t = d.GetType()
/_
Any Questions please?