عرض المحاضرات الاولى codeSmith

advertisement
VB .Net
Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Introduction to VB .Net
Creating VB .Net Project in VS 2005
Data types and Operators in VB .Net
String Functions
Conditions (If Else, Select Case)
Loops (Do While, Do Until, For)
Classes, Objects
Sub routines and Functions
Constructor and Destructor
Windows Application
Collections
File Handling
Exception Handling
Data base connectivity
Introduction
•
•
•
•
VB .Net is developed by Microsoft
It is Visual Basic for .Net Platform
Ancestor of VB .Net is BASIC
In 1991, Microsoft added visual components to
BASIC and created Visual Basic
• After the development of .Net, VB was added
with more set of controls and components and
thus evolved a new language VB .Net
Pros and Cons
• Pros
– Faster development of programs
– Rich set of controls
– Object Orientation of language enhances
modularity, readability and maintainability
• Cons
– Debugging larger programs is difficult, due to
the absence of an effective debugger
Features of VB .Net
• Object Oriented Language
• We can drag controls from the tool bar and
drop them on the form and write code for
the controls
• Runs on the CLR (Common Language
Runtime)
• Release of unused objects taken care by
the CLR
Creating VB .Net Project in VS 2005
•
•
•
•
Open Visual Studio 2005
Click File -> New -> Project
Choose Language as VB .Net
Choose Type (Either Console Application
or what ever we want)
• Give the path under which the project
need to be saved
• Click OK
Input and Output
• Under the namespace System there is a class
called Console
• Console has 2 methods
• ReadLine() – Reads a line from the user
• WriteLine() – writes as line to the screen
• Name spaces can be included in our code using
the keyword imports
• Eg:
Imports System.Console
Data types and Operators in VB .Net
• Data types
– Integer, string, single, double, boolean, char
• Operators
– Arithmetic (+,-,*,/,\,Mod)
– Logical (Or, And)
– Relational (=,<>,<,<=,>,>=)
String Functions
• Len(str) – Length of the string str
• Str.Replace(“old”,”New”) – Replaces Old
with New in the string Str
• Str.Insert(pos,”string”) – Inserts the string
specified at the position pos in the string
Str
• Trim(str) – Removes the leading and
trailing spaces in the string str
If Else
If (Condition)
Then
Statements executed if condition is true
Else
Statements executed if condition is false
EndIf
We can also have Else If block in If Else
statements
Select Case
Select Case var
Case 1
stmt1 // executed if var = 1
Case 2
stmt2 // executed if var = 2
Case Else
stmt3 // executed if var is other than 1 and 2
End Select
For Loop
For <<var>> = start To end Step <<val>>
Statements
Next
Eg
For I = 1 To 10 Step 2
Console.WriteLine(I)
Next
Here the values printed will be 1,3,5,7,9
Do While Loop
1. Do While(a<>0)
Console.Writeline(a)
a=a–1
Loop
2. Do
Console.Writeline(a)
a=a–1
Loop While(a<>0)
Do Until Loop
1. Do Until(a=0)
Console.Writeline(a)
a=a–1
Loop
2. Do
Console.Writeline(a)
a=a–1
Loop Until(a=0)
Class
• Software structure that is important in
Object Oriented Programming
• Has data members and methods
• Blue print or proto type for an object
• Contains the common properties and
methods of an object
• Few examples are Car, Person, Animal
Object
• Instance of a class
• Gives Life to a class
• Ram is an object belonging to the class
Person
• Ford is an object belonging to the class
Car
• Jimmy is an object belonging to the class
Animal
Subroutines and Functions
• Subroutines
– Does not return any value
– Can have zero or more parameters
• Functions
– Always Returns some value
– Can have zero or more parameters
Constructor
•
•
•
•
•
Used for initializing private members of a class
Name of the constructor should be New() always
Can have zero or more parameters
Does not return any value. So they are sub routines
Need not be invoked explicitly. They are invoked
automatically when an object is created
• A class can have more than one constructor
• Every constructor should differ from the other by means
of number of parameters or data types of parameters
• Constructors can be inherited
Destructor
• Used for releasing memory consumed by objects
• Name of the destructor should be Finalize() and the
method is already defined in CLR. So we can only
override it.
• Does not return any value. Hence it is a subroutine
• Does not accept any parameters
• Only one destructor for a class
• Destructors are not inherited
• No need of explicit invocation. They are called when the
execution is about to finish.
Collections
•
•
•
•
•
•
Array List
Sorted List
Hash Table
Stack
Queue
These can be accessed via the
System.Collections namespace
Array List
•
•
•
•
Array List is a dynamic array
Its size grows with the addition of element
Searching is based on the index
Sequential search is performed on
elements
• Hence it is slow
• Occupies less space
Sorted List
•
•
•
•
•
•
•
Elements are stored as key value pairs
They are sorted according to the key
Search is based on index as well as on keys
Hence faster than Array List
Occupies Medium amount of space
Keys cannot be duplicate or null
Values can be duplicated and also can be null
Hash Table
•
•
•
•
•
Hash table stores data as a key value pair
Here the keys can be duplicated
Search is based on the hash of key values
Very fast way of searching elements
Occupies large space
Stack
• Stack is a data structure where elements
are retrieved in the order opposite to which
they are added
• It implements LIFO (Last In First Out)
algorithm
• Its method called Push() is for adding
elements
• Its method Pop() is for removing elements
Queue
• Queue is a data structure where elements
are retrieved in the same order in which
they are added
• It implements FIFO (First In First Out)
algorithm
• Its method called Enqueue() is for adding
elements
• Its method called Dequeue() is for
removing the elements
Windows Application
• File -> New -> Project
• Select Language as VB .Net
• Select .Net template as Windows
Application
• Give the path where the application need
to be saved
• A application opens up with a Form
Forms and other controls
• Form is a container for other controls
• We can place the following in a form
– Label
– Text Box
– Check Box
– Radio Button
– Button
– Date Picker
– And more…
Properties and Events
• Every Control has a set of properties, methods
and events associated with it
• Eg Form
– Properties
• Name (program will use this name to refer)
• Text (title of the form)
– Methods
• Show
• Hide
• Close
– Events
• Load
• UnLoad
Exception Handling
• Exception is Run time error
• It is not known at the compile time
• Examples of exceptions
– Divide by zero
– Accessing non existing portion of memory
– Memory overflow due to looping
• In VB .Net, exception is handled via Try
Catch Mechanism
Try Catch Finally
Try
Suspicious code that may throw an exception to
be written here
Catch ex As Exception
What to be done if exception occurs to be written
here
Finally
Optional portion which will be executed
irrespective of the happening of exception to be
written here. Can contain code for releasing
unnecessary space
File Handling
• In the System Namespace, the IO class
has several subclasses for file handling,
text processing etc
• Classes File, Directory are used for
creating, deleting file or folders and also
has methods to play with them
• Class FileStream is used for creating and
manipulating files
Reader and Writer
• BinaryReader
– This class has methods to read binary or raw data
• BinaryWriter
– This class has methods to write binary or raw data
• StreamReader
– This class has methods to read stream of data
• StreamWriter
– This class has methods to write stream of data
• Stream is a channel through which an object (file
in this case) is accessed
File Handling
• Open the file using FileStream class. This
makes use of FileMode and FileAccess
enumeration to specify how to open a file
(for creating a new file or opening an
existing file) and whether the file is read
only or write only or read write
• Associate a reader for the stream
• Read the file and do the manipulations
File Handling
• Open a file stream for writing
• Associate a writer
• Write contents to file
• Close the stream, so that it will be
released back to the memory pool
Operations on a file
•
•
•
•
•
•
•
Create
Move
Copy
Replace
Read
Write
Delete
Database Connectivity
• Following are important to get connected to the
database and perform operations
– Connection Object
– Command Object
– Operation on the Command Object
• Using Dataset and Data adapter
• Using Data Reader
• If we use data adapter, it is called as
disconnected architecture
• If we use data reader, it is called as connected
architecture
Connection Object
• Dim con as New
OdbcConnection(connectionstring)
• Where connectionstring is a string that
contains details about the server where
the database is located, the name of the
database, user id and password required
for getting connected and the driver details
Command Object
• Dim cmd as New
OdbcCommand(strCmd,con)
• strCmd – is the select/insert/update/delete
statement or exec <<storedProc>>
command
• Con is the connection object created in the
first step
• Properties – cmd.CommandType
– This can be either Text or StoredProcedure
Command Methods
• Cmd.ExecuteReader() – Returns one or
more table row(s) – for select statement
• Cmd.ExecuteScalar() – Returns a single
value – for select statement with
aggregate function
• Cmd.ExecuteNonQuery() – Used for
executing stored procedure or
insert/update/delete statements
Data Reader and Data Set
• Data Reader
– Dim dr as OdbcDataReader
– This dr holds the result set present in
datareader object
• Data Set
– Dim ds as New DataSet()
– ds holds the result of select statement
– Data adapter is used to fill the data set
Data Adapter
• Data adapter fills in the data set with the
result of the select query
• Dim da as New OdbcDataAdapter(cmd)
• Cmd is the command object created
• da.Fill(ds) fills the dataset
• The data set can be set as a data source
for various controls in the web form or
windows form
Download