private static bool HandleDbUpdateException(DbUpdateException ex, ModelStateDictionary modelState, Issue issue) { var baseEx = ex.GetBaseException(); if (baseEx is OptimisticConcurrencyException) { // Concurrency violation modelState.AddModelError("OptimisticConcurrencyError", "The issue was changed while you were editing it. Check the \"Force save changes\" box to override the latest values."); return true; } var sqlEx = baseEx as SqlException; if (sqlEx != null && sqlEx.Number == 2601 && sqlEx.Message.Contains("IDX_Issues_Title")) { // Unique index violation modelState.AddModelError("Title", String.Format("An issue with the title \"{0}\" already exists", issue.Title)); return true; } return false; }
public void GetEntry_returns_null_if_the_DbUpdateException_contains_null_entries() { var mockInternalContext = new Mock<InternalContextForMock>().Object; var ex = new DbUpdateException(mockInternalContext, new UpdateException(), involvesIndependentAssociations: false); Assert.Null(ex.Entries.SingleOrDefault()); }
/// <summary> /// Converts System.Data.Entity.Infrastructure.DbUpdateException exception to database-independent DbException exception used in Data Layer and View Model Layer. /// </summary> /// <param name="exception">Exception to convert.</param> public static DbException Convert(DbUpdateException exception) { Exception originalException = exception; while (originalException.InnerException != null) { originalException = originalException.InnerException; } return new DbException(originalException.Message, CommonResources.Exception_UpdateErrorCaption, exception); }
private void LogError(DbUpdateException ex) { try { Error _error = new Error() { Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now }; _errorsRepository.Add(_error); _unitOfWork.Commit(); } catch { } }
public void DbUpdateException_exposes_public_string_and_inner_exception_constructor() { var inner = new Exception(); var ex = new DbUpdateException("Foo", inner); Assert.Equal("Foo", ex.Message); Assert.Same(inner, ex.InnerException); }
public List<KeyValuePair<int, string>> FormatExceptions(DbUpdateException exception) { List<KeyValuePair<int, string>> errorList = new List<KeyValuePair<int, string>>(); if (exception.InnerException != null && exception.InnerException.InnerException != null) { SqlException sqlException = exception.InnerException.InnerException as SqlException; errorList.Add(new KeyValuePair<int, string>(sqlException.Number, sqlException.Message)); } return errorList; }
/// <summary> /// Metoda obsługująca wyjątek dotyczący bazy danych. /// </summary> /// <param name="Ex">Wyjątek dotyczący bazy danych.</param> public static void ShowException(DbUpdateException Ex) { var innerEx = Ex.InnerException; while (innerEx.InnerException != null) innerEx = innerEx.InnerException; SqlException ProjectedException = (SqlException)innerEx; ExceptionHandling.SpecificException(ProjectedException.Number, ProjectedException.Message); }
public static SqlException GetInnerException(DbUpdateException dbUpdateEx) { for (Exception ex = dbUpdateEx; (ex = ex.InnerException) != null;) { var sqlEx = ex as SqlException; if (sqlEx != null) { return sqlEx; } } return null; }
public String valorDuplicado(System.Data.Entity.Infrastructure.DbUpdateException e) { string error = e.InnerException.ToString(); int pos = 0; while (pos == 0) { pos = error.IndexOf("(", 0); } int pos1 = error.IndexOf(")", pos); return(error.Substring(pos, pos1 - pos + 1)); }
/// <summary> /// Recopila todas las validación falladas de una DbEntityValidationException y las convierte a string. /// </summary> /// <param name="ex"></param> /// <returns></returns> public static string ParseDbEntityValidationException(DbUpdateException ex, bool getTrace = false) { var innerEx = ex.InnerException; while (innerEx.InnerException != null) { innerEx = innerEx.InnerException; } if (getTrace) { return innerEx.ToString(); } else { return innerEx.Message; } }
public IEnumerable<ValidationResult> TryDecodeDbUpdateException(DbUpdateException ex) { if (!(ex.InnerException is System.Data.Entity.Core.UpdateException) || !(ex.InnerException.InnerException is System.Data.SqlClient.SqlException)) { return null; } var sqlException = (System.Data.SqlClient.SqlException)ex.InnerException.InnerException; var result = new List<ValidationResult>(); for (int i = 0; i < sqlException.Errors.Count; i++) { var errorNum = sqlException.Errors[i].Number; string errorText; if (SqlErrorTextDict.TryGetValue(errorNum, out errorText)) { result.Add(new ValidationResult(errorText)); } } return result.Any() ? result : null; }
// ReSharper restore InconsistentNaming public static IEnumerable<string> GetErrors( DbUpdateException dbuex ) { var errors = new List<string>(); if( dbuex.InnerException != null && dbuex.InnerException.InnerException != null && dbuex.InnerException.InnerException is SqlException ) { var ex = dbuex.InnerException.InnerException as SqlException; if( ex.Errors.Count > 0 ) { if( ex.Errors[0].Message.Contains( @"unique index" ) ) { var regex = new Regex( @".*?unique index\s+?'(?<index>.+?)'.+\((?<value>.+?)\).*", RegexOptions.ExplicitCapture ); var match = regex.Match( ex.Errors[0].Message ); if( match.Success ) { var msg = string.Format( @"Could not insert duplicate value '{0}' due to constraint '{1}'.", match.Groups[@"value"].Value, match.Groups["index"].Value ); errors.Add( KENDO_ROLLBACK_ERROR_COMMAND ); errors.Add( msg ); } else { errors.Add( KENDO_ROLLBACK_ERROR_COMMAND ); errors.Add( ex.Errors[0].Message ); } } else { errors.AddRange( GetErrors( ex ) ); } } } else { errors.Add( KENDO_ROLLBACK_ERROR_COMMAND ); Exception ex2 = dbuex; while( null != ex2 ) { errors.Add( ex2.Message ); ex2 = ex2.InnerException; } } return errors; }
private Exception HandleDbUpdateException(DbUpdateException dbu) { var builder = new StringBuilder("A DbUpdateException was caught while saving changes. "); try { foreach (var result in dbu.Entries) { builder.AppendFormat("Type: {0} was part of the problem. ", result.Entity.GetType().Name); } } catch (Exception e) { builder.Append("Error parsing DbUpdateException: " + e.ToString()); } string message = builder.ToString(); return new Exception(message, dbu); }
public static bool HandleCreateOrUpdateOneUserException(DbUpdateException dbUpdateEx, ModelStateDictionary modelState, string modelStateKey_emailAddress, string modelStateKey_username = null) { var db = CurrentDbContext; switch (db.ParseInsertOrUpdateOneUserErrorCode(dbUpdateEx)) { case InsertOrUpdateOneUserErrorCode.DuplicateEmailAddress: if (modelStateKey_emailAddress == null) throw new NotImplementedException(); modelState.AddModelError(modelStateKey_emailAddress, string.Format(StringResources.ErrorMessage_ThatXIsAlreadyTaken, StringResources.EmailAddress)); break; case InsertOrUpdateOneUserErrorCode.DuplicateUserName: if (modelStateKey_username == null) throw new NotImplementedException(); modelState.AddModelError(modelStateKey_username, string.Format(StringResources.ErrorMessage_ThatXIsAlreadyTaken, StringResources.Username)); break; case InsertOrUpdateOneUserErrorCode.None: default: return true; } return false; }
private string ExceptionToString(DbUpdateException dbUpdateException) { StringBuilder exceptionString = new StringBuilder(); exceptionString.AppendLine("DbUpdateException:"); foreach (DbEntityEntry dbEntityEntry in dbUpdateException.Entries) { foreach (DbValidationError validationError in dbEntityEntry.GetValidationResult().ValidationErrors) { exceptionString.AppendFormat("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } return exceptionString.ToString(); }
public void LogException(DbUpdateException dbUpdateException) { Error(ExceptionToString(dbUpdateException), dbUpdateException); }
public void CreateAddress_SaveChangesAsyncThrowingProvinceForeignKeyViolationException_HandlesException() { AddressViewModel viewModel = new AddressViewModel(); Mock<IVeilDataAccess> dbStub = TestHelpers.GetVeilDataAccessFake(); Mock<DbSet<MemberAddress>> addressDbSetStub = TestHelpers.GetFakeAsyncDbSet(new List<MemberAddress>().AsQueryable()); addressDbSetStub. Setup(adb => adb.Add(It.IsAny<MemberAddress>())). Returns<MemberAddress>(ma => ma); Mock<DbSet<Country>> countryDbSetStub = TestHelpers.GetFakeAsyncDbSet(new List<Country>().AsQueryable()); countryDbSetStub.SetupForInclude(); dbStub. Setup(db => db.MemberAddresses). Returns(addressDbSetStub.Object); dbStub. Setup(db => db.Countries). Returns(countryDbSetStub.Object); DbUpdateException provinceConstraintException = new DbUpdateException("See inner", SqlExceptionCreator.Create( // This message was copied verbatim from the actual exception being thrown "The INSERT statement conflicted with the FOREIGN KEY constraint " + "\"FK_dbo.MemberAddress_dbo.Province_ProvinceCode_CountryCode\". " + "The conflict occurred in database \"prog3050\", table " + "\"dbo.Province\".\r\nThe statement has been terminated.", (int)SqlErrorNumbers.ConstraintViolation)); dbStub. Setup(db => db.SaveChangesAsync()). ThrowsAsync(provinceConstraintException); Mock<IGuidUserIdGetter> idGetterStub = TestHelpers.GetSetupIUserIdGetterFake(memberId); Mock<ControllerContext> contextStub = TestHelpers.GetSetupControllerContextFakeWithUserIdentitySetup(); ManageController controller = CreateManageController(veilDataAccess: dbStub.Object, idGetter: idGetterStub.Object); controller.ControllerContext = contextStub.Object; Assert.That(async () => await controller.CreateAddress(viewModel), Throws.Nothing); }
public void GetEntry_throws_if_the_DbUpdateException_contains_null_context() { var ex = new DbUpdateException("", new UpdateException()); Assert.Null(ex.Entries.SingleOrDefault()); }
public FormattedEntityValidationException(DbUpdateException innerException) : base(null, innerException) { }
public void DbUpdateException_exposes_public_string_constructor() { var ex = new DbUpdateException("Foo"); Assert.Equal("Foo", ex.Message); }
public InsertOrUpdateOneUserErrorCode ParseInsertOrUpdateOneUserErrorCode(DbUpdateException dbUpdateEx) { return ExceptionParsing.ParseInsertOrUpdateOneUserErrorCode(dbUpdateEx); }
public static InsertOrUpdateOneUserErrorCode ParseInsertOrUpdateOneUserErrorCode(DbUpdateException dbUpdateEx) { var sqlEx = GetInnerException(dbUpdateEx); return ParseInsertOrUpdateOneUserErrorCode(sqlEx); }
public void DeleteConfirmed_SaveAsyncThrowingForeignKeyViolationException_HandlesException() { Game game = new Game { Id = gameId, GameSKUs = new List<GameProduct>() }; Mock<IVeilDataAccess> dbStub = TestHelpers.GetVeilDataAccessFake(); StubEmptyProductLocationInventories(dbStub); Mock<DbSet<Game>> gameDbSetStub = TestHelpers.GetFakeAsyncDbSet(new List<Game> { game }.AsQueryable()); gameDbSetStub. Setup(gdb => gdb.FindAsync(It.IsAny<Guid>())). ReturnsAsync(game); dbStub. Setup(db => db.Games). Returns(gameDbSetStub.Object); DbUpdateException orderConstraintException = new DbUpdateException("See inner", SqlExceptionCreator.Create( // This message was copied verbatim from the actual exception being thrown "The DELETE statement conflicted with the REFERENCE constraint " + "\"FK_dbo.ProductLocationInventory_dbo.Product_ProductId\"." + "The conflict occurred in database \"prog3050\", table " + "\"dbo.ProductLocationInventory\", column 'ProductId'." + "The statement has been terminated.", (int)SqlErrorNumbers.ConstraintViolation)); dbStub. Setup(db => db.SaveChangesAsync()). ThrowsAsync(orderConstraintException); GamesController controller = new GamesController(dbStub.Object, idGetter: null); Assert.That(async () => await controller.DeleteGameConfirmed(game.Id), Throws.Nothing); }
bool checkSku(DbUpdateException ex) { // Not the most elegant, but it works. if (ex.InnerException != null && ex.InnerException.InnerException != null) { string message = ex.InnerException.InnerException.Message; if (message.StartsWith("Cannot insert duplicate key row in object 'dbo.StoreItems' with unique index 'IX_Sku'")) { ModelState.AddModelError("Sku", "Sku already exists"); return true; } } return false; }
public void GetEntry_throws_if_the_DbUpdateException_contains_null_context() { var ex = new DbUpdateException("", new UpdateException()); Assert.Null(ex.Entries.SingleOrDefault()); }
public void DbUpdateException_exposes_public_string_constructor() { var ex = new DbUpdateException("Foo"); Assert.Equal("Foo", ex.Message); }
/// <summary> /// This decodes the DbUpdateException. If there are any errors it can /// handle then it returns a list of errors. Otherwise it returns null /// which means rethrow the error as it has not been handled /// </summary> /// <param name="ex"></param> /// <returns>null if cannot handle errors, otherwise a list of errors</returns> private static IEnumerable<ValidationResult> TryDecodeDbUpdateException(DbUpdateException ex) { if (!(ex.InnerException is System.Data.Entity.Core.UpdateException) || !(ex.InnerException.InnerException is System.Data.SqlClient.SqlException)) return null; var sqlException = (System.Data.SqlClient.SqlException)ex.InnerException.InnerException; //Otherwise see if the GenericServicesConfig.SqlErrorDict has a entry for this error var result = new List<ValidationResult>(); for (int i = 0; i < sqlException.Errors.Count; i++) { var errorNum = sqlException.Errors[i].Number; HandleSqlException errorHandler; string errorText; if (GenericServicesConfig.SqlHandlerDict.TryGetValue(errorNum, out errorHandler)) { var error = errorHandler(sqlException, ex.Entries); if (error != null) { result.Add(error); continue; } } if (GenericServicesConfig.SqlErrorDict.TryGetValue(errorNum, out errorText)) result.Add(new ValidationResult(errorText)); } return result.Any() ? result : null; }
private void HandleDbUpdateException(DbUpdateException e) { /* We can either have: - A duplicate username (defined by the "username_is_unique" index in the DB) - A duplicate email address (defined by the "email_is_unique" index) Anything else is handled by a generic error message */ if (e.InnerException.InnerException.Message.Contains("username_is_unique")) { ModelState.AddModelError(Global.User_Username, Global.UserNameAlreadyExists); } else if (e.InnerException.InnerException.Message.Contains("email_is_unique")) { ModelState.AddModelError(Global.User_Email, Global.EmailAlreadyExists); } else { ModelState.AddModelError(string.Empty, Global.ServerError); } }