Custom Events for Integers - c#

I know how silly this may sound, but is there a way to attach an event to an integer?
For example, if you're in a while loop and you do: i++; is it at all possible to do something like this?:
int i;
Form1_Load(object sender, EventArgs e)
{
i.MaximumNumberReached += new IntegerMaximumNumberReachedEventArgs();
}
while(x != y)
{
i++
}
private void MaximumNumberReached(object sender, EventAgrs e)
{
if(e.Value == 7)
{
this.Dispose(true);
}
}
Or should I just stop using my imagination so much?
Thank you

Firstly, no, you can't do that. You could if, say, you had your own class representing numbers and overloaded relevant operators such that they initiated certain events, but you can't invent events and attach them to existing classes (aside, say, from using an AOP framework and hooking into certain methods).
Secondly, no, don't stop using your imagination. You may be interested in the following article: Arithmetic Overflow Checking.

You can't add events to a type outside of your control, and events on structs is usually a very bad idea; but: the best approach here would be to use a property:
private int someMeaningfulName;
public int SomeMeaningfulName {
get { return someMeaningfulName; }
set {
// pre-validation checks and "changing" notification
someMeaningfulName = value;
// side effect code and "changed" notification
}
}

Extension methods? Not events but you can do something similar. http://msdn.microsoft.com/en-us/library/bb383977.aspx
class Program
{
static void Main(string[] args)
{
int a = 10;
a.MaximumNumberReached();
}
}
public static class Extns
{
public static void MaximumNumberReached(this int number)
{
if (number == 7)
{
//Do something
}
}
}

Related

Subscribing to an event of a class that holds the override method of the class you reference

I am working with background workers to update a progress bar in a WPF UI I am working on. This background worker is getting its progress updates from multiple events that I am subscribed to, because the progress bar goes through several loading stages, and the percentages for those come from several places. here is some example/pseudo code explaining what I mean
The DoWork method of my background worker and the methods I am using to currently get some progress updates
// These are working fine
private void BwOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
orderProcessing.OnOrderProgress += OrderStatus;
orderProcessing.OnStandardOrderProgress += StandardOrderStatus;
orderProcessing.CreateOrders(orders);
}
private void OrderStatus(int currentCount, int totalItems, string Message)
{
if (totalItems > 0)
bw.ReportProgress(Convert.ToInt32(((double)currentCount / (double)totalItems) * 100),
Message);
}
private void StandardOrderStatus(int currentCount, int totalItems, string Message)
{
if (totalItems > 0)
bw.ReportProgress(Convert.ToInt32(((double)currentCount / (double)totalItems) * 100),
Message);
}
Some code from my order processing class
public abstract class OrderProcessing
{
public delegate void OrderProgress(int CurrentItems, int TotalItems, string Message);
public event MasterSalesOrder.StandardOrderProgress OnStandardOrderProgress;
public event OrderProgress OnOrderProgress;
public abstract List<MasterSalesOrder> CreateOrders(List<Order> orders);
}
Some code from the class that holds the override method for CreateOrders()
public abstract class OrderProcessingFile : OrderProcessing
{
public event OrderProgress OnOrderProgress;
public override List<MasterSalesOrder> CreateOrders(List<Order> orders)
{
//Does Some Stuff
foreach(var stuff in stuffs)
{
OnOrderProgress(currentCount, totalCount, "Message");
}
}
}
Since I am clearly not explaining this well, I need to get info from the OrderProcessingFiles OnOrderProgress event via the OrderProcessing class that I create in the DoWork method.I am unsure on how to subscribe to an event when my code never directly instantiates an instance of the OrderProcessingFile class and it is never directly referred to.
I have tried looking for answers but as my title will show I am having a hard time even wording this in a way to get useful results, and I am genuinely stuck on this one. Let me know if more detail is needed, I tried to strip down my code to only the relevant parts but I feel like I'm explaining this strangely.
I would recommend that you create a thread safe singleton progress manager. Then have each of the background workers contact it with updates. The progress manager will use a DispatcherTimer (which runs on the GUI thread) to update the GUI appropriately.
Raw example:
public static class StatusReportManager
{
// Standard singleton code to create the manager and access it.
// Start/create the dispatch time as well.
private static DispatcherTimer Timer { get; set; }
private static object _syncObject = new object();
public static void ReportStatus(...)
{
lock (_syncObject)
{
// Process any states and set instance properties for reading
// by the timer operation.
}
}
private void ShowStatus() // Used by the dispatch timer
{
lock (_syncObject)
{
// Do any updates to the GUI in here from current state.
}
}
}
I have realized what it is I was really trying to do and have thus found an answer. Using the method found in this MSDN article I have implemented the follow code:
This is my UI
private void BwOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
orderProcessing.OnOrderProgress += OrderStatus;
orderProcessing.CreateOrders(FanGlobal.BrandItems, FanGlobal.BrandItemMasterCustomers);
}
private void OrderStatus(object obj, OrderProcessing.OrderProgressEventArgs e)
{
if (e.totalCount > 0)
bw.ReportProgress(Convert.ToInt32(((double)e.currentCount / (double)e.totalCount) * 100),e.message);
}
This in my OrderProcessing class
public event EventHandler<OrderProgressEventArgs> OnOrderProgress;
public class OrderProgressEventArgs : EventArgs
{
public int currentCount;
public int totalCount;
public string message;
public OrderProgressEventArgs(int c, int t, string m)
{
currentCount = c;
totalCount = t;
message = m;
}
}
protected virtual void OnOrderProgressChanged(OrderProgressEventArgs e)
{
EventHandler<OrderProgressEventArgs> handler = OnOrderProgress;
if (handler != null)
{
handler(this, e);
}
}
public abstract List<MasterSalesOrder> CreateOrders(List<BrandItem> BrandItems = null, List<BrandItemMasterCustomer> BrandItemMasterCustomers = null);
and then I can use it in my child class OrderProcessingFile like so
public override List<MasterSalesOrder> CreateOrders(List<BrandItem> BrandItems = null, List<BrandItemMasterCustomer> BrandItemMasterCustomers = null)
{
//Do some Stuff
OnOrderProgressChanged(new OrderProgressEventArgs(count, totalItems, "Extracting"));
}
and everything is working like a charm. Sorry for the utterly confusing question and the apparent huge gap of knowledge I have/had, but hopefully this will help someone else in the future.

C# delegate v.s. EventHandler

I want to send an alert message to any subscribers when a trap occurred.
The code I created works fine using a delegate method myDelegate del.
My questions are:
I want to know whether it's better to use EventHandler instead of a delegate?
I'm not sure what the differences are between a delegate and an EventHandler in my case.
notify(trapinfo t), that's what I've done here to get trap information. But it seems not to be a good idea. I read some online tutorial lesson introducing passing delegate object; I'm wondering if it's appropriate in my case? And how should I do it? Any suggestions?
Thanks a lot :)
My code:
public class trapinfo
{
public string info;
public string ip;
public string cause;
}
public class trap
{
public delegate void myDelegate(trapinfo t);
public myDelegate del;
trapinfo info = new trapinfo();
public void run()
{
//While(true)
// If a trap occurred, notify the subscriber
for (; ; )
{
Thread.Sleep(500);
foreach (myDelegate d in del.GetInvocationList())
{
info.cause = "Shut Down";
info.ip = "192.168.0.1";
info.info = "Test";
d.Invoke(info);
}
}
}
}
public class machine
{
private int _occuredtime=0;
public trapinfo info = new trapinfo();
public void notify(trapinfo t)
{
++_occuredtime;
info.cause = t.cause;
info.info = t.info;
info.ip = t.ip;
getInfo();
}
public void subscribe(trap t)
{
t.del += new trap.myDelegate(notify);
}
public void getInfo()
{
Console.WriteLine("<Alert>: cauese/{0}, info/ {1}, ip/{2}, time/{3}",
info.cause, info.info, info.ip,_occuredtime);
}
}
class Program
{
static void Main(string[] args)
{
trap t = new trap();
machine machineA = new machine();
machineA.subscribe(t);
t.run();
}
}
Update 2013-08-12
How about the observer/observable design pattern, that looks great in my case (EventHandler).
In my case, a machine subscribes to a trap messenger. (Add a machine to an invocation list)
Once a trap occurred, I send a message to all machines which are subscribed. (Call HandleEvent to handle it)
Advantages:
don't care about GetInvocationList() anymore, just use (+=) and (-=) to decide whom to send the trap.
It's easier to understand the logic of my program.
I know there are several ways to do it, but I wish I could analyze its pros and cons.
And thanks for your comments and suggestions, that would be very helpful!
I read the MSDN EventArgs article which Matthew Watson suggested.
Here's my Event Version:
public class TrapInfoEventArgs : EventArgs
{
public int info { get; set; }
public string ip { get; set; }
public string cause { get; set; }
}
public class trap
{
public event EventHandler<TrapInfoEventArgs> TrapOccurred;
protected virtual void OnTrapOccurred(TrapInfoEventArgs e)
{
EventHandler<TrapInfoEventArgs> handler = TrapOccurred;
if (handler != null)
{
handler(this, e);
}
}
public void run()
{
//While(true)
// If a trap occurred, notify the subscriber
for (; ; )
{
Thread.Sleep(500);
TrapInfoEventArgs args = new TrapInfoEventArgs();
args.cause = "Shut Down";
OnTrapOccurred(args);
}
}
}
public class machine
{
public void c_TrapOccurred(object sender, TrapInfoEventArgs e)
{
Console.WriteLine("<Alert>: cauese/{0}, info/ {1}, ip/{2}, time/{3}",
e.cause, e.info, e.ip, DateTime.Now.ToString());
}
}
class Program
{
static void Main(string[] args)
{
trap t = new trap();
machine machineA = new machine();
t.TrapOccurred += machineA.c_TrapOccurred; //notify machine A
t.run();
}
}
The difference between event and delegate is that:
event declaration adds a layer of protection on the delegate instance.
This protection prevents clients of the delegate from resetting the
delegate and its invocation list, and only allows adding or removing
targets from the invocation list
See What are the differences between delegates and events?
2) As I see it, your subscriber should not change delegates freely. One subscriber can assign = to it instead of adding +=. This will assign a new delegate, therefore, the previous delegate with its invocation list will be lost and previous subscribers will not be called anymore. So you should use Event for sure. Or you can change your code to make your delegate private and write additional functions for manipulating it to define your own event behavior.
//preventing direct assignment
private myDelegate del ;
public void AddCallback(myDelegate m){
del += m;
}
public void RemoveCallback(myDelegate m){
del -= m;
}
//or
public static trap operator +(trap x,myDelegate m){
x.AddCallback(m);
return x;
}
public static trap operator -(trap x, myDelegate m)
{
x.RemoveCallback(m);
return x;
}
//usage
//t.AddCallback(new trap.myDelegate(notify));
t+=new trap.myDelegate(notify);
It is much better to use an event for your example.
An event is understood by the Visual Studio Form and WPF designers, so you can use the IDE to subscribe to events.
When raising events, there is no need for you to write your own foreach handling to iterate through them.
events are the way that most programmers will expect this functionality to be accessed.
If you use a delegate, the consuming code can mess around with it in ways that you will want to prevent (such as resetting its invocation list). events do not allow that to happen.
As for your second question: Using an event you would create a class derived from EventArgs to hold the data, and pass that to the event when you raise it. The consumer will then have access to it.
See here for details: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

Restricting Member Access to Multiple Specific Classes

My PUMP can (inflate) my BALLOON. No problem! But when I try to use my PUMP to (pop) the BALLOON, it really doesn't work very well. I can keep using my PUMP and, eventually, it will (pop) the balloon, but my arm is getting really tired, and I want to (pop) it now. So, instead, I get my POINTY STICK and (pop)! Of course, my POINT STICK is even less effective at (inflate)ing my BALLOON, than the PUMP is at (pop)ing it.
Class Balloon
{
Private int _volume = 0;
Private bool _popped = false;
Public Balloon() { }
//Restrict calling to only a PUMP object
Internal Inflate()
{
if (_popped) return;
_volume += 1;
if (volume > 10) this.Pop();
}
//Restrict calling to only a POINTY STICK object
Internal Pop()
{
if (!_popped) _popped = true;
}
Public string GirlHappiness
{ get
{
if (!_popped)
{
if (_volume < 3)
return "......";
if (_volume < 6)
return "Ooohhh";
else
return "Ahhhh! Yay!";
}
else
return "WaAaAaAaHhHhHh";
}
}
Public string BoyHappiness
{ get
{
if (!_popped)
{
if (_volume < 3)
return "zzzzzz";
if (_volume < 6)
return "zzzzzz";
else
return "zzzzzz";
}
else
return "Ahahaha YAY!";
}
}
}
So, is there any way to achieve this? I cannot achieve the desired result via separating assemblies, and the other method I've explored, using reflection and tracing the stack, is unreliable outside of debugging. What to do?!
Two ways that pop up in my mind: Use explicit interface implementation or events.
With explicit interfaces, you hide the implementation for those who do not threat the instance 'as is'. Example:
interface IPumpable
{
void Pump();
}
interface IPoppable
{
void Pop();
}
class Balloon :IPumpable, IPoppable
{
private void IPumpable.Pump()
{
throw new NotImplementedException();
}
private void IPoppable.Pop()
{
throw new NotImplementedException();
}
}
public static void PopMethod(IPoppable poppable)
{
poppable.Pop();
}
public static void PumpMethod(IPumpable pumpable)
{
pumpable.Pump();
}
static void Main(string[] args)
{
Balloon balloon = new Balloon();
PumpMethod((IPumpable)balloon);
PopMethod((IPoppable)balloon);
}
Note that the Pump and Pop implementations can be marked private. They are only visible when you threat the balloon as IPumpable or IPoppable respectively.

Avoid duplicate event subscriptions in C#

How would you suggest the best way of avoiding duplicate event subscriptions? if this line of code executes in two places, the event will get ran twice. I'm trying to avoid 3rd party events from subscribing twice.
theOBject.TheEvent += RunMyCode;
In my delegate setter, I can effectively run this ...
theOBject.TheEvent -= RunMyCode;
theOBject.TheEvent += RunMyCode;
but is that the best way?
I think, the most efficient way, is to make your event a property and add concurrency locks to it as in this Example:
private EventHandler _theEvent;
private object _eventLock = new object();
public event EventHandler TheEvent
{
add
{
lock (_eventLock)
{
_theEvent -= value;
_theEvent += value;
}
}
remove
{
lock (_eventLock)
{
_theEvent -= value;
}
}
}
I have done this before....it assumes it is acceptable that the last subscriber is what gets called.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
MyObject my = new MyObject();
my.Changed += new EventHandler(my_Changed);
my.Changed += new EventHandler(my_Changed1);
my.Update();
Console.ReadLine();
}
static void my_Changed(object sender, EventArgs e)
{
Console.WriteLine("Hello");
}
static void my_Changed1(object sender, EventArgs e)
{
Console.WriteLine("Hello1");
}
}
public class MyObject
{
public MyObject()
{
}
private EventHandler ChangedEventHandler;
public event EventHandler Changed
{
add
{
ChangedEventHandler = value;
}
remove
{
ChangedEventHandler -= value;
}
}
public void Update()
{
OnChanged();
}
private void OnChanged()
{
if (ChangedEventHandler != null)
{
ChangedEventHandler(this, null);
}
}
}
}
Is your code multi threaded ? Concurrency lock is needed only when its multi threaded. If not its a overhead.
As such your approach of unsubscribing and subscribing is correct.
Thanks
If you own the source for the class of theObject, then you have access to the InvocationList of TheEvent. You can implement your own add accessor for the event and check before adding.
However, I think that your approach is fine too.
I use your approach except one detail. I think, that events should be subscribed when you create new instance of subscriber or theObject, this makes code more straight. Thus, all you need is just carefully watch after correct objects disposing (dispose patten is convenient solution for this).
You mentioned that you use 3rd party event, that means that you can't provide your own realisation for add/remove methods, as you have been advised. But in your own classes with your own events you should define your own realisation of add/remove methods for event in order to solve your problem.

Why is it useful to inherit from EventArgs?

I don't understand why inheriting from EventArgs is useful.
public class ClickedEventArgs : EventArgs
{
int x;
int y;
public ClickedEventArgs (int x, int y)
{
this.x = x;
this.y = y;
}
public int X { get { return x; } }
public int Y { get { return y; } }
}
In the code above, how can I use this inheritance?
I also want to learn how I can call this code block from default.aspx
Are you asking why it's useful to derive from EventArgs in the first place? I have to say that with C# 1 it didn't make a lot of sense, because of the way delegate conversion worked - but as of C# 2 it's more sensible. It allows an event handler to be registered with an event even if it doesn't care about the details of the event arguments.
For example:
void LogEvent(object sender, EventArgs e)
{
Console.WriteLine("Event sent from " + sender);
}
...
textArea.KeyPress += LogEvent;
This works even though Control.KeyPress is an event of type KeyPressEventHandler. C# and .NET don't mind that the signature of LogEvent doesn't exactly match the signature of KeyPressEventHandler - it's compatible enough.
Admittedly this would still be feasible if we didn't have EventArgs at all (you could just use object) but given the EventArgs class and the pattern, it makes sense to derive your own event arguments from EventArgs.
What is really important here is that you can easily UPGRADE your event later to have MORE details and don't break existing decoupled listeners.
Here is a example of how you might use your code:
public class MyClass () {
public event EventHandler<ClickedEventArgs> ClickedEvent = delegate {}; //Register the event
protected void SomethingWasClicked(int x, int y) {
ClickedEvent(this, new ClickedEventArgs(x,y)); //Invoke the event that is subscribed to
}
}
public class AnotherClass () {
public AnotherClass () {
MyClass mClass = new MyClass();
mClass.ClickedEvent += new EventHandler(mClass_clickedEvent);
}
protected void mClass_clickedEvent(object sender, ClickedEventArgs e) {
//Retrieve the X parameter that was passed from the MyClass instance
int x = e.X;
}
}

Categories