tags:

views:

77

answers:

3

Hello,

I have a simple app with a MainForm that sometimes opens a second form. I have a Data Access Layer Class .cs and that has try catch statements. On a catch I call another class method logError.

Since logError can be called by any thread or from the 2 forms, it's in a separate class on its own.

What I would like is that if logError is called (meaning I have a DB connection problem) I would like to updade a control on the MainForm to indicate a Error Status.

I've looked at delegates etc, but everything is Form related, while what I need is to call a form control for an independent class function.

What would be an appropriate way to achieve this?

Thanks,

+2  A: 

Two possibilities:

1) Allow all exceptions to bubble up from the data access layer to the presentation layer (your forms), catch the exception in the presentation layer, and log the error at that point (as well as display the error).

2) Create an event (say, ErrorGenerated) on the class in the data access layer that could have an error. In your catch clause, log the error as you have it, but also trigger the ErrorGenerated event. Then, in your form, assign an event handler to the ErrorGenerated event of the data access class. In the event handler, update your form's error control with the desired error indicator.

If I were coding, I would prefer the first solution, but either should work for you.

Matt Hamsmith
A: 

If logError is a static method in a separate class, a very simple way to deal with this is to add to your separate error logging class a public static reference to an error control (whatever that happens to be), and then in your MainForm's Load event, set this reference to the error control on your form. Here's how your ErrorLogger class would look:

public static ErrorControl _errorDisplay = null;
public static logError(string msg)
{
    // log the error
    // display the error
    if (_errorDisplay != null)
    {
        _errorDisplay.DisplayError(msg);
    }
}

and then in your MainForm's Load event:

ErrorLogger._errorDisplay = errorControl1; // or whatever it's named

This is just a crude sample: _errorDisplay should be private, with a matching public property, and you have to account for the situation where some class might call logError after MainForm has been closed, but that's not my problem. :)

MusiGenesis
A: 

I would use the following comically simplified approach.

// main form or secondary form code
using (var db = new DbAccess())
{
    if (!db.SaveEmployee(...))
    {
       RecordError(db);
    }
}


void RecordError(DbAccess db)
{
    Logger.logError(db.LastError);

    // update the UI
    statusBar.Status = "Error!";
}



// code in the data access class
public bool SaveEmployee(...)
{
    try { SaveToDb(); return true; }
    catch (Exception ex) { lastError = ex; return false; }
}
AngryHacker