Thursday, February 11, 2016

Exception handling while using Entity Framework

Taken from - https://blogs.infosupport.com/improving-dbentityvalidationexception/

Use the code snippet below either by applying in each dataaccess method or via partial class for DBEntites -


public partial class NorthwindEntities
{
    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            // Retrieve the error messages as a list of strings.
            var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);

            // Join the list to a single string.
            var fullErrorMessage = string.Join("; ", errorMessages);

            // Combine the original exception message with the new one.
            var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

            // Throw a new DbEntityValidationException with the improved exception message.
            throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
        }
    }
}

if the above approach is not used - simply printing ex.Message will not give the full error information and will make diagnosing tougher.

Disposing WCF clients


Taken from

http://web.archive.org/web/20100703123454/http://old.iserviceoriented.com/blog/post/Indisposable+-+WCF+Gotcha+1.aspx


OrderServiceClient proxy = null;
bool success = false;
try
{
  proxy = new OrderServiceClient();
  proxy.PlaceOrder(request);
  proxy.Close();
  success = true;
}
finally
{
  if(!success)
  {
    proxy.Abort();
  }
}



If you do not want to clutter your code with the above code all the places, use the following approach-

Service<IOrderService>.Use(orderService=>
{
  orderService.PlaceOrder(request);
}

=====================Implementation of Service class========

public delegate void UseServiceDelegate<T>(T proxy);

public static class Service<T>
{
    public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>("");

    public static void Use(UseServiceDelegate<T> codeBlock)
    {
        IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel();
        bool success = false;
        try
        {
            codeBlock((T)proxy);
            proxy.Close();
            success = true;
        }
        finally
        {
            if (!success)
            {
                proxy.Abort();
            }
        }
    }
}