1. ArguS academy V.B-PART-IV
Page 1
Events and Delegates
Events and Event Handling
Events are action that triggered either by a user action, program logic or by the system.
Whenever an event occurs, the user may either ignore the event or deal with the event with the help of a suitable code. Good programming technique implies that we take care of events by placing appropriate codes in our programs that will execute whenever the event takes place. Procedures containing codes that will process the event are called event handlers.
Module m12
Public Event UserLoggedout(ByVal Loginname as string)
Sub checkstatus()
RaiseEvent UserLoggedout(“Catherine”)
End sub
Public sub onCheckStatus(name as string)
System.Console.WriteLine(name & “has looged out !!”)
End sub
Sub main()
AddHandler m.UserLoggedout,Addressof onChechStatus
checkStatus()
end sub
end module
Handles
The Handles keyword is used to declare that a particular procedure will handle a specific event. By using Handles keywords with a procedure declaration, we can enable the procedure to handle events that were raised by an object variable declared using the WithEvent keyword. The withEvents statement and Handles clause provide a declarative way of specifying event handlers.
Class x
Public event A
Public sub test()
RaiseEvent A
End sub
End class
Module m
Dim withEvents obj as x
Public sub main()
Obj= new x()
Obj.Test()
End sub
Public sub OurHandler Handles obj.A
System.Console.WriteLine(“Event is being handled ”)
End sub
End module
Delegates
The term delegates is defined as a representative of a country, organization or another person. In VB. Net, a delegate is defined as a representative of a function or a procedure. It holds a reference to a method.
A delegate declaration must specify the parameters and / or the return type for the method which it represents.
VB. Net allows us to create two type of Delegate classes – single cast delegates and multi cast delegates. Single cast delegates are delegate classes that are derived from the Delegate class. Multicast delegates are derived from the Multicast Delegate class. These delegates typically have an invocation list or linked list of delegates that are executed when the invoke method is called.
Single cast delegates contain invocation lists with only one method, whereas multicast delegates contain invocation lists with more than one method.
Delegate function isdivisible(n as integer)
Module m
Public function check (I as integer)
If I mod 5 = 0 then
System.Console.WriteLine(“Divisible ”)
Else
System.Console.WriteLine(“not Divisible”)
End if
End function
Public sub main()
Dim x as indivisible
2. ArguS academy V.B-PART-IV
Page 2
X=addressof check
X(11)
End sub
End module
Events and Delegates
The VB.Net event model is to a large extend based on delegates. The event model makes use of delegates to bind method used to handle them. A delegates can be bound
At run time to any method whose signature list matches that of the event handler, thus making it very dynamic.
Delegate sub isdivisible(n as Integer)
Module m
Public event a as isdivisible
Sub fire(I as integer)
If I mod 5=0 then
System.Console.WriteLine(“Divisible”)
Else
System.Console.WriteLine(“not Divisible”)
End if
End sub
Public sub main()
Addhandler a, (Addressof fire)
m.aEvent(13)
end sub
end module
Inheriting event
A derived class inherits events from its base class. It is perfectly valid to write a separate handler for the event in the derived class. This can be done using the Handles keyword with the MyBase keyword followed by the event name.
Class x
Public event p
Public sub test()
RaiseEvent p
End sub
End class
Class y
Inherits x
Public sub DerivedHandler Handles MyBase.p
System.Console.WriteLine(“Base class Event is being handled in derived class”)
End sub
End class
Module m
Dim withEvents obj as y
Public sub main()
obj = new y()
obj.Test()
end sub
end module
Multithreading and Garbage Collection
Multithreading
Multithreading is the ability of a single program to perform more than one task at the same time.
A thread is the smallest unit of executable code that performs a particular task. An application can be divided into multiple tasks and each task can be assigned to a thread. Two or more threads can be executed simultaneously. This is called multithreading. Let us take the simple instance of a game simulator. The program plays audio sounds, displays graphics and determines scores – all at the same time. This can be considered as a threaded application. Each task is a thread and all threads are executed simultaneously
Multithreading in VB.Net is accomplished primarily through the classes and interface in the System.Threading namespace. To create a new thread, we pass a delegate to the constructor of the System.Threading Thread class. This delegate must point to a method that will act as starting point for the thread.
Dim t as new System.Threading.Thread(AddressOf DoAction)
Here AddressOf DoAction is the delegate and DoAction is the start method for the thread.
The thread can then be instantiated with the help of the start method as follows
t.start()
3. ArguS academy V.B-PART-IV
Page 3
Module m
Public sub DoAction()
Dim i as Integer=1
While true
System.Console.WriteLine(i)
System.Console.WriteLine(“Thread is running ”)
i=i+1
end while
end sub
public sub main()
dim t as new System.Threading.Thread(AddressOf DoAction)
t.start()
end sub
end module
Declares a DoAction() method that will serve as the starting point for the thread. This method declares an integer variable and prints the incremented value of this variable each time within an infinite loop.
Sleep method
Module m
Public sub DoAction()
Dim i as integer=1
While true
System.Console.WriteLine(i)
System.Console.WriteLine(“Thread is running”)
System.Threading.Thread.sleep(400)
i=i+1
end while
end sub
public sub main()
dim t as new System.Threading.Thread(AddressOf DoAction)
t.Start()
end sub
end module
The suspend() method of the System.Threading.Thread class is used to suspend the action of a thread for an indefinite period. The thread can be resumed using the Resume() method.
Module m1
Dim t1 as new System.Threading.Thread(Addressof DoAction)
Dim t2 as new System.Threading.Thread(Addressof DoAction)
Public sub DoAction()
Dim I as integer=1
While true
System.Console.WriteLine(i)
i=i+1
if i=4 then
System.Console.WriteLine(“t1 is now going to be suspended ”)
System.Threading.Thread.CurrentThread.Suspend()
End if
System.Threading.Thread.sleep(200)
End while
End sub
Public sub DoAction2()
Dim j as integer=100
While true
System.Console.WriteLine(j)
System.Threading.Thread.Sleep(200)
End while
End sub
Public sub main()
t1.Start()
t2.Start()
end sub
end module
4. ArguS academy V.B-PART-IV
Page 4
Synchronization
When two or more threads in a multithread application access a common method or data simultaneously, there will be conflict and as a result vital information could be lost or data will become inconsistent. To avoid this, it is necessary to have some kind of mechanism in a multithreaded application that allows the methods or data to be accessed by one thread at a time. Synchronization is a process that allows threads to access methods or data one thread at a time.
Module m
Dim a1 as new A()
Dim a2 as new A()
Dim t1 as new System.Threading.Thread(AddressOf a1.Test)
Dim t2 as new System.Threading.Thread(AddressOf a2.Test)
Public i as integer =1
Public sub main()
t1.Start()
t2.Start()
end sub
end module
class A
public sub Test()
while true
System.Console.WriteLine(i)
i=i+1
System.Threading.Thread.Sleep(200)
End while
End sub
End class
Memory Management and Garbage Collection
Applications need to use various types of resources such as network connections, Database connections and memory buffers. These applications require the memory to be reversed for usage by resources and at the end of the application the memory needs to be resealed in order to prevent the memory overflow. Memory management in earlier programming languages had to be carried out manually. Unused resources had to be released by writing cumbersome code. This process was very tedious and time consuming. However, recent programming languages use eliminates common errors that arise from manual methods of memory management. In an automatic memory management environment, a garbage collector program runs as a separate thread every now and then. The garbage collector frees memory that is no longer needed.
VB.NET uses a garbage collector to implement automatic memory management.
Finalize and Dispose methods
Earlier we have discussed that destructors in VB.NET are implemented by overriding the finalize() method. Cleanup operations such as releasing memory that is no longer in use and closing data base connections and files may be placed in destructor so that whenever an object goes out of scope, memory management is per formed. To reclaim each object that has a finalize() method, VB.NET will need to perform two cycles of garbage collections and this will lead to lower performance. This is because when the garbage collector performs a garbage collection, it reclaims memory for unused objects that do not have a finalize() method. For those object s that have finalize() method, it places their entries in a list of objects marked as ready for finalization. It then performs garbage collection later for these objects and finally destroys them. To avoid this, finalize() method should be used efficiently.
Ex.-1
Class x
Public sub new
System.Console.WriteLine(“Constructor”)
End sub
Protected Override sub Finalize
System.Console.WriteLine(“Destructor”)
End sub
End class
Module m
Sub main()
Dim a as new x
A=Nothiong
System.console.WriteLine(“End of Main”)
End sub
End module
Ex=II
Module m
Sub main
5. ArguS academy V.B-PART-IV
Page 5
Dim a as new x
A=Nothing
System.GC.collection()
System.GC.WaitPendingFinalizers()
System.Console.WriteLine(“End of Main”)
End sub
End module
Class x
Public sub new
System.Console.WriteLine(“Constructor”)
End sub
Protected Overrides sub Finalize
System.Console.WritelINE(“Destructors”)
End sub
End class
Working with Database Using VB. Net
Universal Data Access
With respect to data access, application scenario today has two emerging needs. They are:
1. Accessing legacy data or information that is stored in an organization in different formats in various types of systems.
2. Accessing non relational data.
The need of the hour is to have a single high-performance framework or model with the help of which applications can connect to various database products without changing the entire code.
Universal Data Access OR UDA is one such framework which application programs use to connect to database from various database venders through a single interface.
Managed Data Providers
A managed data provider is a set of software programs that allows access to databases by providing an interface that performs database related operations on behalf of the application.
Establish a connection to the database
Execute commands and retrieve result
Execute commands and update data.
Connection – Used to establish a connection to the database.
Command: Carries out operation while connected to the database.
Introduction to ADO.NET
Traditionally, an application maintained database connection as long as it executed. This is not feasible as open connection consume valuable resources. Also, performance is reduced because of the overheads in maintaining connection.
ADO.NET is a data object model that lets us work with databases version of ADO designed for the .Net framework. Data access in ADO.Net is based on disconnected architecture. This means that the connection need not be maintained continuously while the application is executing. The application connects to the database as and when it need to retrieve and update data.
Advantages offered by ADO.Net are summarized below:
Maintainability: It is difficult to increase the number of application tiers within an application after the application has been deployed. However, if the application is implemented using ADO.Net then increasing the number of tiers becomes a very easy process.
Programmability: Data classes in ADO.Net result in typed dataset and thus allows us to access data through typed programming. This marks code easier to read, write and debug. It is also safer because it provides for type checking at compile at compile time.
Performance: As stated earlier, Ado.NET works with disconnected architecture. This increases performance.
Interoperability : Since ADO.Net makes extensive use of XML, interoperability becomes very simple using ADO.Net
Command Object
The Command objects are used to retrieve and manipulate data. For this purpose, sqlDataAdapter and OleDbAdapter class are defined in the System.Data.SqlClient and System.Data.OleDb namespace respectively;
6. ArguS academy V.B-PART-IV
Page 6
DataSet
While working with database, applications often need to fetch sets of data repeatedly. In a disconnected architecture it is not feasible for the application to go back to the database every time data needs to be fetched. It is much more feasible to have a temporary storage of records from where the application can fetch data whenever needs. A dataset is one such temporary storage. It is a cache of records fetched from the database. The dataset class in the System.Data namespace is the main building block of
Imports Microsoft.visualbasic
Imports System
Imports System.data
Imports System.XML
Module m
Sub Main()
Dim myconn As new
Data.SqlClient.SqlConnection (“server=Ritchasqldb;database=EmpDep;uid=sa;password=passwd;”)
Myconn.open()
Dim adap As New Data.SqlClient.SqlDataAdapter(s, myconn)
Dim dataset As Data. Dataset=New Data.dataSet()
Adap.fill(dataset, “details”)
Dimtbl as datatable= dataset.tables(“details”)
Dim dr As DataRow
Dim I As DataRow
Dim j As Datacolumn
For Each I In tbl.Rows
For Each j In tbl.columns
System.Console.Write((i(j).ToString()).PadRight(15,””))
Next
System.Console.WriteLine(“”)
Next
Myconn.close()
End Sub
End Module
We create a database connection usi9ng the SqlConnection class. We pass the name of the database server, the name of the database and pass it an SQL command along with the connection name. The SQL command retrieves all the records from the department table. We fill the results of this command into a dataset and extract the dataset rows and columns using a nested for loop. We print each of these details on the console within the nested for loop. In order to format the data while printing. We use the PadRight() function to include appropriate spaces in-between the columns. Finally, when all the records have been retrieved and printed, we close the connection.