I'm doing a WPF (NOT web) application.
3-tiers
EF Code First
UI tier references to Logical tier and Logical tier references to Data tier.
Now, I have an exception in the Data tier and I need to show a MessageBox based on the text generated by the exception.
But I don't want to add references to WindowsBase, PresentationCore and PresentationFramework in the Data tier.
How can I send text to the UI tier from the Data tier and show the MessageBox?
TIA
Relevant code:
In the UI tier
public void guardar(UserControlCliente UCCliente)
{
admin.guardarEntidadCliente(UCCliente.textBoxNombre.Text,
UCCliente.textBoxPrimerApellido.Text,
UCCliente.textBoxSegundoApellido.Text,
"Normal",
DateTime.Parse("01/01/2012"),
DateTime.Parse("02/02/2012"),
"obs 1");
}
private void buttonAgregar_Click(object sender, RoutedEventArgs e)
{
guardar(this);
}
In the logical tier
public void guardarEntidadCliente(String nombre, String app1, String app2, String tipo,
DateTime fechaReg, DateTime fechaUltCita, String obs)
{
Cliente cliente = new Cliente();
cliente.Nombre = nombre;
cliente.Apellido1 = app1;
cliente.Apellido2 = app2;
cliente.Tipo = tipo;
cliente.FechaRegistro = fechaReg;
cliente.FechaUltimaCita = fechaUltCita;
cliente.Observaciones = obs;
ControlDatos cd = new ControlDatos();
cd.agregarCliente(cliente);
}
In the data tier
public void agregarCliente(Cliente cliente)
{
db.Clientes.Add(cliente);
try
{
db.SaveChanges();
}
catch (DbEntityValidationException exc)
{
String mensaje = "";
foreach (var validationErrors in exc.EntityValidationErrors)
foreach (var validationError in validationErrors.ValidationErrors)
mensaje += validationError.ErrorMessage + "\n";
db.Entry(cliente).State = EntityState.Detached;
// MessageBox.Show(mensaje, "Se han encontrado errores", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
I need to run the commented line but in the UI tier.
You can handle Data tier exceptions on the UI tier. Aren't you?
You can use for this purpose System.Windows.Application.Current.DispatcherUnhandledException event.
EDIT
According to your code, you can throw an exception (where you want MessageBox
to show) of special type (MyDataTierException, for example) and initialize it with your message.
In your UI tier you should subscribe to the DispatcherUnhandledException, and handle it as you want - show the MessageBox, for which text you can take from exception.