Search code examples
c#eventspushsharp

How to check if an event has fired?


I have trouble with the implementation of my code. I'm currently using the PushSharp library and one of the things I'd like to do is if the event triggers, I would like to return a true or false value depending on what event it is. Here is the code:

public static bool SenddNotification()
{
var push = new PushBroker();

        //Wire up the events for all the services that the broker registers
        push.OnNotificationSent += NotificationSent;
        push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;

}


static bool DeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, INotification notification)
    {
        //Currently this event will only ever happen for Android GCM
        Console.WriteLine("Device Registration Changed:  Old-> " + oldSubscriptionId + "  New-> " + newSubscriptionId + " -> " + notification);
        return false;
    }

    static bool NotificationSent(object sender, INotification notification)
    {
        Console.WriteLine("Sent: " + sender + " -> " + notification);
        return true;
    }

So what I'd like is if the event fires, return true or false depending on what happens, and then eventually return this value in the first method


Solution

  • You could set a global bool variable, and have your events set that variable, then have your first method return it. Something like this:

    private bool globalBool;
    
    public static bool SenddNotification()
    {
    var push = new PushBroker();
    
            //Wire up the events for all the services that the broker registers
            push.OnNotificationSent += NotificationSent;
            push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
    
            return globalBool;  
    }
    
    
    static bool DeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, INotification notification)
        {
            //Currently this event will only ever happen for Android GCM
            Console.WriteLine("Device Registration Changed:  Old-> " + oldSubscriptionId + "  New-> " + newSubscriptionId + " -> " + notification);
            globalBool = false;
        }
    
        static bool NotificationSent(object sender, INotification notification)
        {
            Console.WriteLine("Sent: " + sender + " -> " + notification);
            globalBool = true;
        }
    

    Of course, you'll have to check it for null before you return it, and handle it appropriately.