SlideShare a Scribd company logo
1 of 6
Download to read offline
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
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()
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
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
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;
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.

More Related Content

What's hot (20)

C# Generics
C# GenericsC# Generics
C# Generics
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3
 
Intake 37 6
Intake 37 6Intake 37 6
Intake 37 6
 
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
 
Chap2 class,objects
Chap2 class,objectsChap2 class,objects
Chap2 class,objects
 
Intake 38 4
Intake 38 4Intake 38 4
Intake 38 4
 
Intake 37 2
Intake 37 2Intake 37 2
Intake 37 2
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event Handling
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
 
Evolution of C# delegates
Evolution of C# delegatesEvolution of C# delegates
Evolution of C# delegates
 
Call Back
Call BackCall Back
Call Back
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Pertemuan 6-2-sequence-diagram
Pertemuan 6-2-sequence-diagramPertemuan 6-2-sequence-diagram
Pertemuan 6-2-sequence-diagram
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Intake 37 1
Intake 37 1Intake 37 1
Intake 37 1
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 

Similar to VB.NET Events and Delegates Guide

Similar to VB.NET Events and Delegates Guide (20)

Vb.net ii
Vb.net iiVb.net ii
Vb.net ii
 
Csharp
CsharpCsharp
Csharp
 
Function & procedure
Function & procedureFunction & procedure
Function & procedure
 
Vb.net iii
Vb.net iiiVb.net iii
Vb.net iii
 
Visual Basic User Interface -IV
Visual Basic User Interface -IVVisual Basic User Interface -IV
Visual Basic User Interface -IV
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3
 
Interface
InterfaceInterface
Interface
 
Vb (1)
Vb (1)Vb (1)
Vb (1)
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
 
Unit3
Unit3Unit3
Unit3
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
PATTERNS06 - The .NET Event Model
PATTERNS06 - The .NET Event ModelPATTERNS06 - The .NET Event Model
PATTERNS06 - The .NET Event Model
 
Xamarin: Namespace and Classes
Xamarin: Namespace and ClassesXamarin: Namespace and Classes
Xamarin: Namespace and Classes
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asma
 
Intake 37 5
Intake 37 5Intake 37 5
Intake 37 5
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
 
Progamming Primer Polymorphism (Method Overloading) VB
Progamming Primer Polymorphism (Method Overloading) VBProgamming Primer Polymorphism (Method Overloading) VB
Progamming Primer Polymorphism (Method Overloading) VB
 

More from argusacademy (20)

Css & dhtml
Css  & dhtmlCss  & dhtml
Css & dhtml
 
Html table
Html tableHtml table
Html table
 
Html ordered & unordered list
Html ordered & unordered listHtml ordered & unordered list
Html ordered & unordered list
 
Html level ii
Html level  iiHtml level  ii
Html level ii
 
Html frame
Html frameHtml frame
Html frame
 
Html forms
Html formsHtml forms
Html forms
 
Html creating page link or hyperlink
Html creating page link or hyperlinkHtml creating page link or hyperlink
Html creating page link or hyperlink
 
Html basic
Html basicHtml basic
Html basic
 
Java script
Java scriptJava script
Java script
 
Php string
Php stringPhp string
Php string
 
Php session
Php sessionPhp session
Php session
 
Php opps
Php oppsPhp opps
Php opps
 
Php oops1
Php oops1Php oops1
Php oops1
 
Php if else
Php if elsePhp if else
Php if else
 
Php creating forms
Php creating formsPhp creating forms
Php creating forms
 
Php create and invoke function
Php create and invoke functionPhp create and invoke function
Php create and invoke function
 
Php basic
Php basicPhp basic
Php basic
 
Php array
Php arrayPhp array
Php array
 
Sql query
Sql querySql query
Sql query
 
Rdbms
RdbmsRdbms
Rdbms
 

Recently uploaded

Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

VB.NET Events and Delegates Guide

  • 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.