473,756 Members | 1,810 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using a Delegate to Simulate Invoking Events in Base Class

I have a base class and derived classes that relate to a set of documents I
process. e.g. DocBase, DocA, DocB, DocC. The processing of each document is
handled in teh derived classes, as you might imagine, but the base class has
properties and methods that are common to all documents.

The processing of each docuemnt can result in a range of document specific
errors, which I want to raise as events on the document object, but there
are some events that are common to all documents, so I would like to have
those raised in the base class. In fact, I want to raise all events through
a delegate in the base class so that the object owners don't have to do too
much work.

So, I have in mind something like this for the caller:

Main
Sub ProcessDocA
Dim doc As DocBase = New DocA(path)

doc.Process(Add ressOf DocA_ProcessErr or) <--- Problem here
End Sub

Sub ProcessDocB
Dim doc As DocBase = New DocB(path)

doc.Process(Add ressOf DocB_ProcessErr or) <--- Problem here
End Sub

Sub DocA_ProcessErr or(ByVal sender As Object, ByVal e As
DocAProcessErro rEventArgs)
' Prompt User
End Sub

Sub DocB_ProcessErr or(ByVal sender As Object, ByVal e As
DocBProcessErro rEventArgs)
' Prompt User
End Sub

My base class looks like this

Public MustInherit Class DocBase

Delegate Sub ProcessErrorEve ntHandler(ByVal sender As Object, ByVal
e As EventArgs)

Protected ProcessErrorCal lBack As ProcessErrorEve ntHandler

MustOverride Sub Process(ByVal callback As ProcessErrorEve ntHandler)

Protected Sub OnProcessError( ByVal e As EventArgs)
ProcessErrorCal lBack.Invoke(Me , e)
End Sub

End Class

My derived class looks like this

Public Class DocA

Inherits DocBase

Public Overrides Sub Process(ByVal processErrorCal lback As
ProcessErrorEve ntHandler)
MyBase.ProcessE rrorCallback = processErrorCal lback

DoProcessing()

End Sub

Private Sub Do Processing()

' Trap Error
MyBase.OnProces sError(New DocAProcessErro rEventArgs("Err or in
Doc A"))

End Sub

End Class
The problem is where I have arrowed above, becase the compiler doesn't like
an implicit narrowing conversion from DocA_ProcessErr or() to
ProcessErrorEve ntHandler.

I know this all looks very complicated, and perhaps unnecessarily so, but
can anyone suggest a better, more generic way to do this.

TIA

Charles
Sep 27 '08 #1
6 2819
Have you tried or do you know about events with the standard OnXXXX
sub raising the XXXX event ? In your description you are talking
multiple times about events but you are using delegates in your code
so I'm not sure if you know about events or if you are trying to avoid
them for some reason (not sure what is this "too much work" you are
talking about)...
--
Patrice
Sep 27 '08 #2
Hi Patrice

Thanks for the reply. I do know about events, but as I understand it events
in a base class can't be raised by a derived class, so that is why I'm using
delegates. They also can' te b used as a contract in an interface, which is
another goal.

The too much work I'm talking about is work the client of my Doc classes has
to do. I thought that if they just passed a reference to a call back to
handle errors then that would be the easiest solution. I also mean that I
want to impose some sort of contract on the user so that I can use the
compiler to pickup errors at design time if the classes are not used
correctly. Also, if I can create an interface in a particular way, it will
ensure that the rest of the code is written correctly.

Charles
"Patrice" <pa************ @hotmail.comwro te in message
news:4e******** *************** ***********@34g 2000hsh.googleg roups.com...
Have you tried or do you know about events with the standard OnXXXX
sub raising the XXXX event ? In your description you are talking
multiple times about events but you are using delegates in your code
so I'm not sure if you know about events or if you are trying to avoid
them for some reason (not sure what is this "too much work" you are
talking about)...
--
Patrice

Sep 27 '08 #3
Try :

MustInherit Class DocBase
Event ProcessingError ()
Protected Overridable Sub OnProcessingErr or()
Debug.WriteLine ("Here in DocBase.OnProce ssingError")
RaiseEvent ProcessingError ()
End Sub
MustOverride Sub Processing()
End Sub
End Class

Class DocA
Inherits DocBase
Sub Processing()
OnProcessingErr or()
End Sub
Sub Test() Handles Me.ProcessingEr ror
Debug.WriteLine ("Here in DocA.Test that handles
ProcessingError ")
End Sub
End Class

It will display both messages. Is this what you are looking for ?

If not the problem in your first code is that you seems to use a
specific argument type for each of your child class. It should work if
you replace DocAProcessEven tArgs, DocB... by just EventArgs so that it
match what you used in the base class.
--
Patrice

Sep 28 '08 #4
Hi Patrice

I can see what you have done there, and you are right that I am using a
specific argument type for each of my derived classes.

I agree that that is the problem, so perhaps I have to find a way to make
the argument common, even if it is not EventArgs. Currently, each derived
class returns specific information relating to the document it is
processing, so I'm not sure how to make the argument common, but I will try.
It would be nice to find a generic way to do it where the argument types
were different though.

Thanks.

Charles
"Patrice" <pa************ @hotmail.comwro te in message
news:b4******** *************** ***********@c65 g2000hsa.google groups.com...
Try :

MustInherit Class DocBase
Event ProcessingError ()
Protected Overridable Sub OnProcessingErr or()
Debug.WriteLine ("Here in DocBase.OnProce ssingError")
RaiseEvent ProcessingError ()
End Sub
MustOverride Sub Processing()
End Sub
End Class

Class DocA
Inherits DocBase
Sub Processing()
OnProcessingErr or()
End Sub
Sub Test() Handles Me.ProcessingEr ror
Debug.WriteLine ("Here in DocA.Test that handles
ProcessingError ")
End Sub
End Class

It will display both messages. Is this what you are looking for ?

If not the problem in your first code is that you seems to use a
specific argument type for each of your child class. It should work if
you replace DocAProcessEven tArgs, DocB... by just EventArgs so that it
match what you used in the base class.
--
Patrice

Sep 28 '08 #5
refering to the Foo event in Bill McCarthy's reply, there are several ways of
defining different event data for each derived class. One way is to define a
base class event args
Friend Class FooBaseEventArg s
Inherits System.EventArg s

Friend New( .. )

.. you can include an e.g. typeID so the comsumer can determine
.. the actual eventargs type,
.. Or use typeof or some other logic

.. properties ..
end class

then
Friend Class Derived1_FooEve ntArgs
Inherits FooBaseEventArg s

...
End Class

and so on...

In the base class,
Protected Sub OnFoo(ev as FooBaseEventArg s)
( you don't need the Overriable if you are only going to invoke the event)

Then in the derived class,
Dim eArgs as New Derived1_FooEve ntArgs(..)
OnFooEvent(eArg s)

There are other schemes for accomplishing the same thing. It is then up to
the comsumer of the event to sort out the desired data from the event data
--
JB
"Bill McCarthy" wrote:
Hi Charles,

"Charles Law" <bl***@nowhere. comwrote in message
news:uB******** ******@TK2MSFTN GP03.phx.gbl...
Hi Patrice

Thanks for the reply. I do know about events, but as I understand it
events in a base class can't be raised by a derived class, so that is why
I'm using delegates.

The Usual Pattern there is to have:

Class BaseClass

Event Foo As EventHandler

Protected Overridable Sub OnFoo(ev as eventargs)
RasieEvent Foo(Me,ev)
End sub
End CLass

Class Derived : Inherits BaseClass

Sub Dosomething
OnFoo(eventargs .empty)
End sub
End Class

They also can' te b used as a contract in an interface, which is another
goal.


Yes they can.
Sep 28 '08 #6
Hi JB

My news reader isn't showing Bill's reply, so I have only just seen it in
your reply below.

I started down this route, and then decided that I didn't want the consumer
to have to cast the eventargs parameter received to the specific derived
eventargs type for the event. I wanted them to receive the correctly typed
parameter for the event raised by the derived class.

Charles
"JB" <JB@discussions .microsoft.comw rote in message
news:DD******** *************** ***********@mic rosoft.com...
refering to the Foo event in Bill McCarthy's reply, there are several ways
of
defining different event data for each derived class. One way is to
define a
base class event args
Friend Class FooBaseEventArg s
Inherits System.EventArg s

Friend New( .. )

.. you can include an e.g. typeID so the comsumer can determine
.. the actual eventargs type,
.. Or use typeof or some other logic

.. properties ..
end class

then
Friend Class Derived1_FooEve ntArgs
Inherits FooBaseEventArg s

...
End Class

and so on...

In the base class,
Protected Sub OnFoo(ev as FooBaseEventArg s)
( you don't need the Overriable if you are only going to invoke the
event)

Then in the derived class,
Dim eArgs as New Derived1_FooEve ntArgs(..)
OnFooEvent(eArg s)

There are other schemes for accomplishing the same thing. It is then up
to
the comsumer of the event to sort out the desired data from the event data
--
JB
"Bill McCarthy" wrote:
>Hi Charles,

"Charles Law" <bl***@nowhere. comwrote in message
news:uB******* *******@TK2MSFT NGP03.phx.gbl.. .
Hi Patrice

Thanks for the reply. I do know about events, but as I understand it
events in a base class can't be raised by a derived class, so that is
why
I'm using delegates.

The Usual Pattern there is to have:

Class BaseClass

Event Foo As EventHandler

Protected Overridable Sub OnFoo(ev as eventargs)
RasieEvent Foo(Me,ev)
End sub
End CLass

Class Derived : Inherits BaseClass

Sub Dosomething
OnFoo(eventargs .empty)
End sub
End Class

They also can' te b used as a contract in an interface, which is
another
goal.


Yes they can.

Sep 28 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
25286
by: Todd Schinell | last post by:
Back in July, Jeffery Tan posted this: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=OWOTdf0VDHA.2296%40cpmsftngxa06.phx.gbl In response as to how to get click events from a user control to invoke a method in the parent form. This code doesn't seem to work for me, I've tried it a number of times with very simple test cases (A user control with a single button and a parent form with a single text box) and it always...
9
3974
by: Guy | last post by:
I have extended the datetimepicker control to incorporate a ReadOnly property. I have used the new keyword to implement my own version of the value property, so that if readonly == true then it will not set the value of the control and will leave the checked status of the checkbox to false when a user selects a new date. this works fine when using the control on a win2k machine but if we use it on a win XP box and call
11
1290
by: ZorpiedoMan | last post by:
This is either a bad bug, or I'm not understanding somthing. In my mind, this should NOT work: ------------------------------------------ Class ShouldntWork Delegate Sub goHere() Sub StartHere() Dim DC as new DeadClass Dim myDel as New goHere(AddressOf DeadClass.Here)
7
1704
by: tony | last post by:
Hello! What is the differens if I use event handler onSizeChanged compare to using the other event handler MeltPracForm_SizeChanged. I see both as event handler is that right? I catch the event in both cases. So is it more or less the same thing which of these two event handler I use. protected override void OnSizeChanged(EventArgs e) {
0
2016
by: Haxan | last post by:
Hi, I have an unmanaged application that converts a function pointer to a delegate and then pass this as a parameter(delegate) to a managed function which then invokes it. Currently Im able to jump to this unmanaged function, but the values of the parameters inside this function Im seeing are not correct(they have some garbage values). //unmanaged class (C++ application)
2
1393
by: MuZZy | last post by:
Hi, Consider i have this code: // --------------------------------------------------------------------- public delegate void DoSearchEventHandler(Form f, DoSearchEventArgs e); public class DoSearchEventArgs { public String m_sIDColumn; public String m_sQuery; public DoSearchEventArgs(String sQuery, String sIDColumn)
6
1712
by: RobKinney1 | last post by:
Hello, This may be an easy question, but I cannot stumle upon the correct way of doing this. I have a function in a base class. I then pass it to a class as a delegate so I don't have to repeat the code within that class. But then that class, calls another class and needs that same function back in the parent. How do I keep passing that delegate up the chain? I am getting errors that says: Cannot convert type...
2
2666
by: mswlogo | last post by:
I looked high and low for code to do this and finally found some VB code that did it right. This is a C# flavor of it. public event EventHandler<EventArgsMyEventToBeFired; public void FireEvent(Guid instanceId, string handler) { EventArgs e = new EventArgs(instanceId);
6
1572
by: Charles Law | last post by:
I have a base class and derived classes that relate to a set of documents I process. e.g. DocBase, DocA, DocB, DocC. The processing of each document is handled in teh derived classes, as you might imagine, but the base class has properties and methods that are common to all documents. The processing of each docuemnt can result in a range of document specific errors, which I want to raise as events on the document object, but there are...
0
9431
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9255
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9844
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9689
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8688
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5119
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5289
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3326
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2647
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.