473,756 Members | 6,852 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

raising an event . .. and getting a callback? to the originating object

I"m trying to figure out what concept I'm missing here, or if its not a good
idea .. or what.

Here is my example.. code is below.

I have an employee class.
It has an event that can be raised.
In the constructor, I check the to see if the employees birthday is today.
If it is today, then I raise an event.

I have a HumanResources class.
HumanResources creates an Employee class, providing the date of birth.
HR also wires up an event , to handle the case where the dob is today.

Employee raises the event.
HR responds to the event.

The question on the table is :::
Is there a way to let the Employee object .. know that all subscribers of
the said raisedEvent, got those messages?
Is it a callback? Or what key concept am I missing?

Is this too tight of a coupling? or cyclic reference? or some other
gotcha?

Below is sample code.
Everything is on order I think.. the thing sticking out ... related to my
question is the
SubscribersToMy EventGotTheirEv ent() method? aka, I have no idea if I'm
barking up the right tree here.
Most times I see the sender as "object sender"...
I guess I could cast it .. or change its object type. But that seems like
tight coupling.
I think java has a ICallback interface or something (long time since I
java'ed)


public class Employee

{
public delegate void BirthdayOccured EventHandler(ob ject sender,
EmployeeBirthda yArgs args);
public event BirthdayOccured EventHandler BDayOcurred;
public Employee(int empid , DateTime dateOfBirth)
{
this.CheckForBD ay(empid , dateOfBirth);
}

private void CheckForBDay(in t empid , DateTime dob)
{

if (null!=BDayOcur red)
{
DateTime now = DateTime.Now;

if( dob.Month == now.Month && dob.Day == now.Day)
{
//today! is your birthday, raise the event

BDayOcurred(thi s, new EmployeeBirthda yArgs(empid, dob));
}
}

}

public void SubscribersToMy EventGotTheirEv ent()
{

// Can I know somehow that my subscribers got their messages successfully,
and nothing exceptioned out??

}

}//End Employee class

public class EmployeeBirthda yArgs : EventArgs {
public EmployeeBirthda yArgs( int empid , DatTime dob ) {
this.EmployeeID = empid;
this.DateOfBirt h = dob ;
}

public int EmployeeID; // i'm not using properties to shorten the example
public DateTime DateOfBirth;// i'm not using properties to shorten the
example

} // End EventArgs class

public class HumanResources( )
{
public void Go()
{
Employee e = new Employee(123 , DateTime.Now)
e.BDayOcurred += new
BirthdayOccured EventHandler(Re spondToABirthda yEvent);
}

public void RespondToABirth dayEvent(object sender , EmployeeBirthda yArgs
args)
{

Console.Writeli ne ( arg.EmployeeID. ToString() + " " +
arg.DateOfBirth .ToShortDateStr ing());
//this doesn't exist, but lets put a fake call into something like
"SendCard"
CardFactory.Sen dCard ( args );
}
}//end human resources

Jul 26 '06 #1
4 1545
>In the constructor, I check the to see if the employees birthday is today.
>If it is today, then I raise an event.
An event on that instance? if so, nothing will have had chance to subscribe
yet...
>Is there a way to let the Employee object .. know that all subscribers of
the said raisedEvent, got those messages?
Event invocation (using the default approach) runs by executing the
delegates **on the current thread**; as such, when after you have invoked
the delegate you know that the chain has been invoked and completed.
>BDayOcurred(th is, new EmployeeBirthda yArgs(empid, dob));
This is dodgy; if you have no subscribers it will throw a null-object
exception; should be something like (following the common OnSomething
pattern):

// could be protected virtual if inheritance is likely
private void OnBDayOccurred( int empid) { // don't need param if available on
a field
BirthdayOccured EventHandler handler = BDayOcurred;
if(handler!=nul l) handler(this, new EmployeeBirthda yArgs(empid, dob));
}

Then you just call "OnBDayOccurren t(empid);" at the point you want to use
it.
Employee e = new Employee(123 , DateTime.Now)
e.BDayOcurred += new...
Too late; missed it. You would either need to pass in the delegate into the
ctor (eugh), or (my preferred option) something like:

Employee e = new Employee();
e.BDayOccurred += new...
e.Initialise(12 3, DateTime.Now);

Although even then it seems an odd way of going about it... perhaps a better
option would be to have the event static on the Employee class; you
subscribe once (independent of any individual Employees), and when the ctor
detects a birthday it invokes the static event, passing the details of the
employee in question (as current). You would need the On... method to accept
the sender and use this in place of "this", but other than that it would
hold some water...

Does this help?

Marc

Jul 26 '06 #2
sloan wrote:
I have an employee class.
It has an event that can be raised.
In the constructor, I check the to see if the employees birthday is today.
If it is today, then I raise an event.
As Marc already pointed out, no one will ever get that event. Raising
the event in the constructor is too early, as no one will have had the
chance to subscribe to it yet.
The question on the table is :::
Is there a way to let the Employee object .. know that all subscribers of
the said raisedEvent, got those messages?
When you raise the event and it returns, you can be sure that all
current subscribers have received it. The problem in your case is that
there cannot be any subscribers yet because you are raising the event in
the constructor.

Is the constructor the only place where you have to check for the
birthday? Or will the event also be raised if the application is running
for a few days and suddenly it figures out that an employee has birthday
today?

I would just add a boolean property to the employee class called
"HasBirthdayTod ay". So you can write:

Employee e = new Employee(DateTi me.Now);

if (e.HasBirthdayT oday) {
// celebrate birthday
}

... additionally you can also use the event (for the case that it can
also be raised after a few days).

hth,
Max
Jul 26 '06 #3
Ok.. I screwed up using hte Constructor.

That wasn't my main focus.. I was typing out a quick sample, and got that
screwed up.
Employee e = new Employee();
e.BDayOccurred += new...
e.Initialise(12 3, DateTime.Now);
I see that's the way to do that part of it.

My question still remains about the callback.


"Marc Gravell" <ma**********@g mail.comwrote in message
news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
In the constructor, I check the to see if the employees birthday is
today.
If it is today, then I raise an event.

An event on that instance? if so, nothing will have had chance to
subscribe
yet...
Is there a way to let the Employee object .. know that all subscribers of
the said raisedEvent, got those messages?

Event invocation (using the default approach) runs by executing the
delegates **on the current thread**; as such, when after you have invoked
the delegate you know that the chain has been invoked and completed.
BDayOcurred(thi s, new EmployeeBirthda yArgs(empid, dob));

This is dodgy; if you have no subscribers it will throw a null-object
exception; should be something like (following the common OnSomething
pattern):

// could be protected virtual if inheritance is likely
private void OnBDayOccurred( int empid) { // don't need param if available
on
a field
BirthdayOccured EventHandler handler = BDayOcurred;
if(handler!=nul l) handler(this, new EmployeeBirthda yArgs(empid, dob));
}

Then you just call "OnBDayOccurren t(empid);" at the point you want to use
it.
Employee e = new Employee(123 , DateTime.Now)
e.BDayOcurred += new...

Too late; missed it. You would either need to pass in the delegate into
the
ctor (eugh), or (my preferred option) something like:

Employee e = new Employee();
e.BDayOccurred += new...
e.Initialise(12 3, DateTime.Now);

Although even then it seems an odd way of going about it... perhaps a
better
option would be to have the event static on the Employee class; you
subscribe once (independent of any individual Employees), and when the
ctor
detects a birthday it invokes the static event, passing the details of the
employee in question (as current). You would need the On... method to
accept
the sender and use this in place of "this", but other than that it would
hold some water...

Does this help?

Marc

Jul 26 '06 #4
My question still remains about the callback.

Really? It has been answered by two respondants already... as long as you
just use the simple event invoke [i.e. somehandler(thi s, someargs)] then as
soon as that line completes all subscribers have received and processed the
events. Because you just did it! (i.e. it ran on your thread).

If you are doing something more complex (which your code doesn't show), then
yes you might need some kind of callback, but how you would implement this
would depend on the details.

So: why do you think you need the callback? What is this trying to achieve?
(genuine question - not meant critically; without that info its hard to give
a better answer).

Marc
Jul 26 '06 #5

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

Similar topics

2
9306
by: Jo Voordeckers | last post by:
Hello all, I'm pretty new to the Java newsgroups so I apologize for dropping this into several maybe offtopic groups. I'm sorry! So on to my problem... I've come to a point in our RMI application where I need to have server callbacks to the client RMI applications. I've used the technique where the client passes an UnicastRemoteObject of itself to a RMI server method that registers the clientinterface object in a Vector. Now when I do...
10
3604
by: tony kulik | last post by:
This code works fine in ie and opera but not at all in Mozilla. Anybody got a clue as to how to get it right? <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <script language="JavaScript" type="text/javascript"> function show(that) { if (box.style.visibility=='hidden') { that.style.visibility = 'visible'}; }
3
5134
by: David | last post by:
Hi, Ive been trying to work this out for the past 2 days now and im not getting anywhere fast. The problem i have is that i am using Asynchronous sockets to create a Socket Client library. When i try to connect to a server that doesnt exist it raises a "Connection forcibly rejected by the resmote host" SocketException.
6
2878
by: Dan | last post by:
I've created a pocketpc app which has a startup form containing a listview. The form creates an object which in turn creates a System.Threading.Timer. It keeps track of the Timer state using a TimerState object similar to the example in the System.Threading.Timer documentation. The method which handles the timer events, among other things, periodically calls a method in this TimerState object which raises an event to the startup form,...
3
1771
by: L | last post by:
Hi, I have a windows form say "Form1" which has a menuitem "SetUp". When I click this item, a new form "SetUpForm" opens up. When I change the fields in the "SetUpForm" and click the "OK" button, SetUpForm should validate the fields and if all the field values are right, it should close and raise an event in the "Form1". I tried defining an event using a delegate in "Form1" and then raise the event from "SetUpForm", but the compiler is...
3
1120
by: Jon Turner | last post by:
I have an asynchronous call to a remote procedure that is invoked thru BeginInvoke. The problem is that in the Delegate if I throw an event before the CallBack function exits, the CallBack will get called multiple times and error out with the following Error: <EndInvoke can only be called once for each asynchronous operation.> If I comment out the RaiseEvent, then the Callback exits with a single call to EndDelegate.
6
2271
by: Joseph Geretz | last post by:
Writing an Outlook AddIn with C#. For the user interface within Outlook I'm adding matching pairs of Toolbar buttons and Menu items. All of the buttons and menu items are wired up to send events to the same method (aka delegate?). I use the Tag property within this method to determine what user action is taking place. Very simple: When adding toolbar button: tbButton.Click += new...
9
1834
by: CuriousGeorge | last post by:
Can someone explain why this code DOES NOT raise a null reference exception? //////////////////////////// Program.cs ///////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; using CSharpLib;
2
3927
by: John Kotuby | last post by:
Hi guys, I am converting a rather complicated database driven Web application from classic ASP to ASP.NET 2.0 using VB 2005 as the programming language. The original ASP application works quite well, so at times it is tempting just to port parts of it over mostly as-is. In fact, one MSDN article I read suggested using straight HTML wherever possible to make the app more efficient and less resource demanding. On one page there are 2...
0
9212
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
9790
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...
1
9779
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9645
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...
1
7186
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5069
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
5247
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3742
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2612
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.