Question

I've been struggling with this for a while... I have a programm written using the MVP pattern, I want to have a LogHandler class that must retrieve a string that corresponds to an ID provided in one of these methods, but it also needs to update the GUI, adding items to a listbox. So to simplyfy, imagine this:

if (name != "Peter")
{
Log.RegisterError(31, 4) //errorType, errorID
}

So in the Log class it would then get the string that matches the type and IDs provided and MessageBox it, but what if I want to add that string to a control on the form? I'm using views implemented by the forms to accomplish GUI updating, but since this is a static class I can't...

Also where should errors be checked and raised? Presenter? View? Model?

Thanks in advance

Was it helpful?

Solution

You could add callbacks in you Log class that other object could subscribe to.

Example:

In this example the Presenter can listen for an error code to be logged then receive the error string from the Log from the Model class

public class Logger
{
   private static Dictionary<int, List<Action<string>>> _callbacks = new Dictionary<int,List<Action<string>>>();

    public static void RegisterLoggerCallback(int errorType, Action<string> callback)
    {
        // Just using errortype in this exaple, but the key can be anything you want.
        if (!_callbacks.ContainsKey(errorType))
        {
            _callbacks.Add(errorType, new List<Action<string>>());
        }
        _callbacks[errorType].Add(callback);
    }

    public static void RegisterLog(int errorType, int errorID)
    {
        // find error sring with codes
        string error = "MyError";

        // show messagebox
        MessageBox.Show(error);

        // tell listeners
        if (_callbacks.ContainsKey(errorType))
        {
            _callbacks[errorType].ForEach(a => a(error));
        }
    }
}

public class Model
{
    public Model()
    {
    }

    public void DoSomething()
    {
      Logger.RegisterLog(1, 2);
    }
}

public class Presenter 
{
    public Presenter()
    {
        Logger.RegisterLoggerCallback(1, AddToListbox);
    }

    private void AddToListbox(string error)
    {
        // add to listbox when errortype 1 is called somewhere
    }
}

This is a very simple example but should give you an idea of a way to achive this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top