Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a callback to a webform Project

I want to add a common callback function to all the methods of an object. I found this SO question but in that aproach, I would have to modify every function of the class. I would like to define some beforeFilter method that get trigered before every method call. I know I could use Action delegates for that but I don't know how.

UPDATE: As an example, what I want would be something like this

Class MyClass

    Sub MyCallback
        'callback code...
    End Sub

    'Rest of tyhe code

End Class

As you can see, the ideal would be to add a simple (or more than one) method to get trigered before all the rest of the methods. Maybe with some base class or an interface, I don't know (that's why I ask for).

Some other option that I think it might be posible is to clone the object and define a new class instead to add code to the existing one. So in that Class use the Object to get access to the methods trhough the Type

Class NewClass

     Sub AddCallback(Obj As Object, Callback As Action)
          'Add the callback here
     End Sub
End Class

I'm just guessing, maybe some of my option are even unviable, so please help my on this

Closest approach

What I have for now, is this method

Sub RunWithCallback(beforFilter As Action, f As Action)

    beforeFilter()
    f()

End Sub

(This means a lot of overloads for the RunWithCallback to manage Sub's and Functions with Actions and Funcs delegates, with different number of parameters) To use this, I would have to run this Sub instead of calling any of the Object methods (passing ByRef parameter to catch returning value in functions). Something like this

Public Sub DoNothing()
    Debug.WriteLine("Callback working!")
End Sub

Public Sub BeforeFilter()
    Debug.WriteLine("Testing callback...")
End Sub

'To run the above function    
RunWithCallback(AddressOf BeforeFilter, AddressOf DoNothing)

I think there should be a better solution to this, something that allow to avoid calling the same sub, and avoid the overloads, some kind of dynamic extension method for the object Class

like image 594
Yerko Palma Avatar asked Apr 14 '15 13:04

Yerko Palma


People also ask

How do you create a callback?

A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.

How do you implement a callback in C#?

A callback is a function that will be called when a process is done executing a specific task. The usage of a callback is usually in asynchronous logic. To create a callback in C#, you need to store a function address inside a variable. This is achieved using a delegate or the new lambda semantic Func or Action .

What is callback function in asp net?

In a client callback, a client script function sends a request to the ASP.NET Web page, which then runs an abbreviated version of its normal life cycle to process the callback. To ensure that callback events originate from the expected user interface (UI), you can validate callbacks.

What is the difference between callback and postback in asp net?

Postback is a term that gets introduced very recently by ASP . NET programming as Dreas explained, whereas callback is more generic and has been used way before web development exists.


1 Answers

Here is an example how delegates work and how u can use them:

public class MyClass
{
    // MyDelegate callback holder
    private MyDelegate _myDelegate;

    // Singleton holder
    private static volatile MyClass _instance;

    ///<summary>
    /// Instance property
    ///</summary>
    public static MyClass Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new MyClass();
            }
            _instance.MyCallbacks(_instance.MyDelegateCallback, _instance.MyDelegateCallback1);
            return _instance;
        }
    }

    ///<summary>
    /// Instance multi-callback caller
    ///</summary>
    ///<param name="callbacks">calbacks to call</param>
    ///<returns>MyClass</returns>
    public static MyClass Instance(params MyDelegate[] callbacks)
    {
        if (_instance == null)
        {
            _instance = new MyClass();
        }
        _instance.MyCallbacks(callbacks);
        return _instance;
    }

    ///<summary>
    /// MyClass constructor
    ///</summary>
    private MyClass()
    {
        // Define the callback
        MyDelegate = MyDelegateCallback;
    }

    ///<summary>
    /// MyDelegate property, here u can change the callback to any function which matches the structure of MyDelegate 
    ///</summary>
    public MyDelegate MyDelegate
    {
        get
        {
            return _myDelegate;
        }
        set
        {
            _myDelegate = value;
        }
    }

    ///<summary>
    /// Call all given callbacks
    ///</summary>
    ///<param name="callbacks">callbacks u want to call</param>
    public void MyCallbacks(params MyDelegate[] callbacks)
    {
        if (callbacks != null)
        {
            foreach (MyDelegate callback in callbacks)
            {
                if (callback != null)
                {
                    callback.Invoke(null);
                }
            }
        }
    }

    ///<summary>
    /// RunTest, if u call this method the defined callback will be raised
    ///</summary>
    public void RunTest()
    {
        if (_myDelegate != null)
        {
            _myDelegate.Invoke("test");
        }
    }

    ///<summary>
    /// MyDelegateCallback, the callback we want to raise
    ///</summary>
    ///<param name="obj"></param>
    private void MyDelegateCallback(object obj)
    {
        System.Windows.MessageBox.Show("Delegate callback called!");
    }

    ///<summary>
    /// MyDelegateCallback1, the callback we want to raise
    ///</summary>
    ///<param name="obj"></param>
    private void MyDelegateCallback1(object obj)
    {
        System.Windows.MessageBox.Show("Delegate callback (1) called!");
    }
}

///<summary>
/// MyDelegate, the delegate function
///</summary>
///<param name="obj"></param>
public delegate void MyDelegate(object obj);

I updated my answer, have a look at MyCallbacks(params MyDelegate[] callbacks). It will call different callbacks which match the structure of MyDelegate.
Edit:
Added MyClass.Instance & MyClass.Instance(params MyDelegate[] callbacks).

like image 61
k1ll3r8e Avatar answered Sep 22 '22 05:09

k1ll3r8e