views:

105

answers:

2

I am trying to use MVC in C#. So the form controller uses the authentication class instance. I am handling the invalid credentials in the authentication class. But I cannot display that message in the message box as it is not in the form controller class instance. Please help

+3  A: 

Can't you simply throw your exception in your authentication class, and have your main form handle the exception?

// main form
try
{
    User _loggedOnUser = Authenticate.GetLoggedOnUser();
}
catch (AuthenticationException ex)
{
    MessageBox.Show(this, ex.Message, "Unable to authenticate user");
}


// Authenticate class
// ... do something
if (something == true)
    throw new AuthenticationException("User account has been disabled");

Alternatively if an Exception isn't appropriate, use a return value:

// main form
User _loggedOnUser = Authenticate.GetLoggedOnUser();
if (_loggedOnUser == null)
    MessageBox.Show(this, "Unable to authenticate the user");
Bryan
A: 

So you have an authentication class but you can't access any error messages if authentication fails? In that case you'll have to modify this class to expose the error message - you could add a property which returns the last authentication error:

public bool Authenticate(...) { }
public string LastAuthenticationError { get; }

Or you could add an out parameter to the Authenticate method:

public bool TryAuthenticate(..., out string errorMessage) { ... }

If for what ever reason you can't modify this class, then all you can really do is display a generic 'authentication failed' message.

The only other way I can interpret this question is that you can't access the MessageBox class from within the controller. In this case, since MessageBox.Show is static you could just call that if authentication fails:

public void Authenticate(...)
{
        ...
    if(! authenticator.Authenticate(...))
    {
     System.Windows.Forms.MessageBox.Show(errorMessage);
    }
}

However a better way would be to add a 'ShowError' method on the view and call that from the controller so as not to couple the controller to the view library.

Lee