public async Task AddErrorAsync_CreatesErrorFromOperation_WithResultAndItemAndStatus() { var batch = await CreateBatch(); var item = new IdEntity { Id = Guid.NewGuid().ToString(), StringValue = "test" }; var obj = JObject.FromObject(item); var json = obj.ToString(Formatting.None); var op = new DeleteOperation("movies", Guid.NewGuid().ToString()) { Item = obj }; await batch.AddErrorAsync(op, HttpStatusCode.BadRequest, json, obj); Assert.Single(store.TableMap[SystemTables.SyncErrors]); var error = store.TableMap[SystemTables.SyncErrors].Values.First(); Assert.NotEmpty(error.Value <string>("id")); Assert.Equal(400, error.Value <int?>("status")); Assert.Equal("movies", error.Value <string>("tableName")); Assert.Equal(1, error.Value <int>("version")); Assert.Equal(1, error.Value <int>("kind")); Assert.Equal(json, error.Value <string>("item")); Assert.Equal(json, error.Value <string>("rawResult")); }
public async Task ExecuteRemote_CallsRemoteServer_WithFailure(HttpStatusCode statusCode) { var client = GetMockClient(); if (statusCode == HttpStatusCode.Conflict || statusCode == HttpStatusCode.PreconditionFailed) { MockHandler.AddResponse(statusCode, new IdEntity { Id = "1234", StringValue = "movie" }); } else { MockHandler.AddResponse(statusCode); } var sut = new DeleteOperation("test", "1234") { Item = testObject }; var exception = await Assert.ThrowsAnyAsync <DatasyncInvalidOperationException>(() => sut.ExecuteOperationOnRemoteServiceAsync(client)); if (statusCode == HttpStatusCode.Conflict || statusCode == HttpStatusCode.PreconditionFailed) { Assert.IsAssignableFrom <DatasyncConflictException>(exception); Assert.NotNull(exception.Value); } Assert.NotNull(exception.Request); Assert.NotNull(exception.Response); Assert.Equal(statusCode, exception.Response?.StatusCode); }
public bool Delete(object toDelete) { RepositoryService svc = GetService(toDelete); DeleteOperation operation = DeleteOperation.For(toDelete); return(svc.Delete(operation)); }
private static void Transform(DeleteOperation oa, DeleteOperation ob) { if (oa.EndPosition < ob.StartPosition) { ob.StartPosition += oa.Length; ob.EndPosition += oa.Length; } else if (ob.StartPosition >= oa.StartPosition && oa.EndPosition >= ob.StartPosition) { ob.EndPosition = ob.StartPosition; } else if (oa.StartPosition >= ob.StartPosition && ob.EndPosition >= oa.StartPosition) { ob.EndPosition -= oa.Length; } else if (ob.StartPosition < oa.EndPosition) { ob.StartPosition += oa.EndPosition - ob.StartPosition; } else if (oa.StartPosition < ob.EndPosition) { ob.EndPosition -= ob.EndPosition - oa.StartPosition; } }
public void Verify_History_OnDelete() { var test3User = _accountGrain.Find(test4UserId).GetAwaiter().GetResult(); var operation = new DeleteOperation <User>(adminId, test3User.Id); // Act var result = _accountGrain.Delete(operation).GetAwaiter().GetResult(); Assert.True(result.Succeeded); var updatedUser = _accountGrain.Find(test4UserId).GetAwaiter().GetResult(); var history = updatedUser.EntityHistory; var containsUpdate = history.Any(x => x.OperationType == OperationType.Delete); Assert.True(containsUpdate); var removedHistory = _context.RemovedEntities; var entityIsInRemovedTable = removedHistory.Any(x => x.EntityId == test4UserId); Assert.True(entityIsInRemovedTable); }
public async Task <IOperationResult> Delete(DeleteOperation <BlogPost> model) { try { var entityToMarkAsDeleted = _repository.Find <BlogPost>(page => page.Id == model.EntityId); entityToMarkAsDeleted.IsRemoved = true; entityToMarkAsDeleted.Content.IsRemoved = true; _repository.Update(entityToMarkAsDeleted); var removedEntity = new RemovedEntity(entityToMarkAsDeleted.Id, model.UserId); _repository.Add(removedEntity); await _repository.SaveChangesAsync(); await _repository.AggregateEntityHistory(entityToMarkAsDeleted.Id, model.UserId, OperationType.Delete); return(OperationResult.Success); } catch (Exception ex) { return(OperationResult.Failed(ex.Message)); } }
private void _mediaPRIRemoved(object o, MediaEventArgs e) { if (MediaDirectorySEC != null && MediaDirectorySEC != MediaDirectoryPRI && MediaDirectorySEC.IsInitialized) { var mediaToDelete = ((WatcherDirectory)MediaDirectorySEC).FindMediaByMediaGuid(e.Media.MediaGuid); if (mediaToDelete != null && mediaToDelete.FileExists()) { var operation = new DeleteOperation { Source = mediaToDelete }; if (mediaToDelete.Directory is ServerDirectory serverDirectory) { operation.Success += (sender, args) => { foreach (var ingestDirectory in IngestDirectories) { if (((IngestDirectory)ingestDirectory).FindMediaByMediaGuid(operation.Source.MediaGuid) is IngestMedia ingestMedia) { ingestMedia.NotifyIngestStatusUpdated(serverDirectory, TIngestStatus.Unknown); } } } } ; FileManager.Queue(operation); } } }
private void AppendDeleteOperation(IList <BaseOperation> operations, Difference diff) { var deleteOperation = new DeleteOperation { OwnerMetadata = diff.OwnerMetadata, OwnerPropertyMetadata = diff.OwnerPropertyMetadata, OwnerPrimaryKeyColumn = diff.OwnerMetadata == null ? null : diff.OwnerMetadata.PrimaryKey.Prop.Name, Owner = diff.Owner, TableName = diff.OwnerMetadata == null ? null : diff.OwnerMetadata.TableName, ValueMetadata = diff.ValueMetadata, Value = diff.OldValue }; if (IsViableParentUpdateOnManyToOneRelationship(deleteOperation, diff)) { AddUpdateOnParentTableForInsertDeleteOfManyToOneChildRow(operations, diff, deleteOperation); } else if (IsViableParentUpdateOnOneToOneWithFkInParent(deleteOperation, diff)) { AddUpdateOnParentTableForInsertDeleteOfOneToOneChildRow(operations, diff, deleteOperation); } else if (!ShouldFilterOutForParticularCardinalitiesBecauseFkOnParent(deleteOperation)) { AddDeleteToListAtCorrectLocation(operations, deleteOperation); } }
private static void PrependDeleteBeforeReferencedChildTableDelete( IList <BaseOperation> operations, DeleteOperation deleteOperation) { var firstIndex = -1; int index = operations.Count - 1; while (index >= 0) { var possibleMatch = operations [index] as DeleteOperation; if (null != possibleMatch && possibleMatch.OwnerMetadata == deleteOperation.ValueMetadata && possibleMatch.OwnerPropertyMetadata != null && possibleMatch.OwnerPropertyMetadata.IsOneToOneRelationship && possibleMatch.OwnerPropertyMetadata.HasAttribute <ForeignKeyReferenceAttribute>()) { firstIndex = index; break; } --index; } if (firstIndex < 0) { operations.Add(deleteOperation); } else { operations.Insert(firstIndex, deleteOperation); } }
protected virtual void Generate( [NotNull] DeleteOperation operation, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder) { Check.NotNull(operation, nameof(operation)); Check.NotNull(builder, nameof(builder)); if (operation.KeyValues.Length == 0) { return; } builder .Append("DELETE FROM ") .AppendLine(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)); builder.Append("WHERE "); var rowCount = operation.KeyValues.GetLength(0); var valueCount = operation.KeyValues.GetLength(1); for (var i = 0; i < rowCount; i++) { if (i != 0) { builder .AppendLine(" OR") .Append(" "); } builder.Append("("); for (var j = 0; j < valueCount; j++) { if (j != 0) { builder.Append(" AND "); } builder.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.KeyColumns[j])); var value = operation.KeyValues[i, j]; if (value == null) { builder.Append(" IS NULL"); } else { builder .Append(" = ") .Append(Dependencies.SqlGenerationHelper.GenerateLiteral(value)); } } builder.Append(")"); } builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); EndStatement(builder); }
public DeleteResourceRequest(ResourceKey resourceKey, DeleteOperation deleteOperation) { EnsureArg.IsNotNull(resourceKey, nameof(resourceKey)); ResourceKey = resourceKey; DeleteOperation = deleteOperation; }
public void Test_DeleteNotEmptyAt0() { stringTextContext = new StringTextContext("test content"); DeleteOperation delete = new DeleteOperation(0); stringTextContext.Delete(null, delete); Assert.AreEqual("est content", stringTextContext.Data, "Inconsistent state after deletion!"); }
public void ValidateCollapse_DeleteOperation_OK() { var sut = new UpdateOperation("test", "1234"); var newOp = new DeleteOperation("test", "1234"); sut.ValidateOperationCanCollapse(newOp); }
public void DeleteOperation_CreateInverse_CreatesInsertOperation() { var state = new DocumentState(1, "1234"); var delete = new DeleteOperation(state, 2); Assert.IsInstanceOfType(delete.CreateInverse(state), typeof(InsertOperation)); }
public void Delete(DeleteOperation deleteOperation) { Deletes ??= new List <DeleteOperation>(); deleteOperation.To = deleteOperation.To?.EnsureUtc(); deleteOperation.From = deleteOperation.From?.EnsureUtc(); Deletes.Add(deleteOperation); }
public async Task <IOperationResult> DeleteEntity <T>(DeleteOperation <T> operation) where T : EntityBase { try { var set = _context.Set <T>()?.Include(x => x.EntityHistory); var entity = await(set ?? throw new Exception("No entities found in set.")) .FirstOrDefaultAsync(x => x.Id == operation.EntityId); if (entity == null) { throw new Exception("Entity to perform delete operation could not be loaded."); } entity.IsRemoved = true; entity.EntityHistory.Add(new EntityHistory(entity.Id, operation.UserId, OperationType.Delete)); _context.Update(entity); await _context.SaveChangesAsync(); return(OperationResult.Success); } catch (Exception ex) { _logger?.LogError(ex); return(OperationResult.Failed(ex.Message)); } }
public void Operation_CanBeCancelled() { var operation = new DeleteOperation("test", "1234"); Assert.False(operation.IsCancelled); operation.Cancel(); Assert.True(operation.IsCancelled); }
public DeleteResourceRequest(string type, string id, DeleteOperation deleteOperation) { EnsureArg.IsNotNull(type, nameof(type)); EnsureArg.IsNotNull(id, nameof(id)); ResourceKey = new ResourceKey(type, id); DeleteOperation = deleteOperation; }
public bool Delete(DeleteOperation value) { Type type; object instance; ResolveTypeAndInstance(value, out type, out instance); return(Repository.Delete(type, instance)); }
public void DeleteOperation_CreateInverse_InverseUndoesDelete() { var state = new DocumentState(1, "1234"); var delete = new DeleteOperation(state, 2); var deletedstate = delete.ApplyTransform(state.CurrentState); Assert.AreEqual(state.CurrentState, delete.CreateInverse(state).ApplyTransform(deletedstate)); }
public void Validate_Throws_WithDeleteOperation_WhenInsertIsAttempted() { var newOperation = new DeleteOperation("test", MobileServiceTableKind.Table, "abc"); this.operation.State = MobileServiceTableOperationState.Attempted; var ex = AssertEx.Throws <InvalidOperationException>(() => this.operation.Validate(newOperation)); Assert.AreEqual("The item is in inconsistent state in the local store. Please complete the pending sync by calling PushAsync()before deleting the item.", ex.Message); }
public void DocumentState_ApplyTransform_CaretAdjustedForDeleteBefore() { var DocumentState = new DocumentState(1, "1234"); var transform = new DeleteOperation(DocumentState, 0); var caretIndex = 2; DocumentState.ApplyTransform(new AppliedOperation(transform), ref caretIndex); Assert.AreEqual(1, caretIndex); }
public void Test_DeleteNotEmptyAt0() { ICSharpCode.TextEditor.TextEditorControl textEditorControl = new ICSharpCode.TextEditor.TextEditorControl(); textEditorControl.Text = "test content"; textEditorTextContext = new TextEditorTextContext(textEditorControl); DeleteOperation delete = new DeleteOperation(0); textEditorTextContext.Delete(null, delete); Assert.AreEqual("est content", textEditorTextContext.Data, "Inconsistent state after deletion!"); }
/// <summary> /// Removes the specified item from the cache. /// </summary> /// <param name="key">The identifier for the item to delete.</param> /// <returns>true if the item was successfully removed from the cache; false otherwise.</returns> public bool Remove(string key) { using (DeleteOperation d = new DeleteOperation(this.pool, key)) { d.Execute(); return(d.Success); } }
public void DocumentState_ApplyTransform_CaretSameForDeleteSame() { var DocumentState = new DocumentState(1, "1234"); var transform = new DeleteOperation(DocumentState, 3); var caretIndex = 3; DocumentState.ApplyTransform(new AppliedOperation(transform), ref caretIndex); Assert.AreEqual(3, caretIndex); }
public void DocumentState_ApplyTransform_CaretClampedForDeleteBefore() { var DocumentState = new DocumentState(1, "1234"); var transform = new DeleteOperation(DocumentState, 0); var caretIndex = 0; DocumentState.ApplyTransform(new AppliedOperation(transform), ref caretIndex); Assert.IsTrue(caretIndex >= 0); }
public void Operation_CanBeUpdated() { var operation = new DeleteOperation("test", "1234"); Assert.False(operation.IsUpdated); operation.Update(); Assert.Equal(2, operation.Version); Assert.True(operation.IsUpdated); }
public void Operation_CanSetItem() { var operation = new DeleteOperation("test", "1234") { Item = testObject }; Assert.Equal(operation.Item, testObject); }
public void GetHashCode_Works() { var sut = new DeleteOperation("test", "1234") { Item = testObject }; var hash = "1234".GetHashCode(); Assert.Equal(hash, sut.GetHashCode()); }
public void Test_DeleteEmptyAt0() { DeleteOperation delete = new DeleteOperation(0); Assert.Throws(typeof(ArgumentOutOfRangeException), delegate { textEditorTextContext.Delete(null, delete); }, "Deletion out of range was accepted!"); }
public void Test_DeleteNotEmptyTwiceAt0ThenInMiddle() { stringTextContext = new StringTextContext("test content"); DeleteOperation delete1 = new DeleteOperation(0); DeleteOperation delete2 = new DeleteOperation(5); stringTextContext.Delete(null, delete1); Assert.AreEqual("est content", stringTextContext.Data, "Inconsistent state after deletion!");; stringTextContext.Delete(null, delete2); Assert.AreEqual("est cntent", stringTextContext.Data, "Inconsistent state after deletion!"); }
public ConditionalDeleteResourceRequest(string resourceType, IReadOnlyList <Tuple <string, string> > conditionalParameters, DeleteOperation deleteOperation, int maxDeleteCount) { EnsureArg.IsNotNullOrEmpty(resourceType, nameof(resourceType)); EnsureArg.IsNotNull(conditionalParameters, nameof(conditionalParameters)); ResourceType = resourceType; ConditionalParameters = conditionalParameters; DeleteOperation = deleteOperation; MaxDeleteCount = maxDeleteCount; }
public void Deserialize_Works_WithoutItem() { var expected = new DeleteOperation("test", "1234"); serializedObject["item"] = null; // We aren't expecting this. var operation = TableOperation.Deserialize(serializedObject); Assert.IsAssignableFrom <DeleteOperation>(operation); Assert.Equal(expected, operation); }
public async Task ExecuteAsync_DoesNotSaveTheResult_IfOperationDoesNotWriteToStore() { var op = new DeleteOperation("table", MobileServiceTableKind.Table, "id") { Item = new JObject() }; Assert.IsFalse(op.CanWriteResultToStore); await TestResultSave(op, status : null, resultId : "id", saved : false); }
private void ScanDestination() { DirectoryScanner scanTron = new DirectoryScanner(Destination); foreach (FileInfo file in scanTron) { FileInfo matchingSourceFile = new FileInfo(Helpers.TransformPath(Destination, Source, file.FullName)); if (!matchingSourceFile.Exists) { DeleteOperation delete = new DeleteOperation(file.FullName); delete.DeleteEmptyFolder = true; manager.AddOperation(delete); } } }
/// <inheritdoc/> public override void Delete(object issuer, DeleteOperation operation) { Data = Data.Substring(0, operation.Position) + Data.Substring(operation.Position+1); OnDeleted(new DeleteEventArgs(issuer, operation)); OnChanged(new ChangeEventArgs(issuer)); }
/// <inheritdoc/> public override void Delete(object issuer, DeleteOperation operation) { UnsubscribeFromTextBox(); TextBox.Document.Remove(operation.Position, 1); SubscribeToTextBox(); }
/// <inheritdoc/> public override void Delete(object issuer, DeleteOperation operation) { TextBox.TextChanged -= TextBoxChanged; TextBox.Text.Remove(operation.Position, 1); TextBox.TextChanged += TextBoxChanged; }
private bool HasAnyOneToOneChildrenWithFKOnParent(DeleteOperation deleteOperation) { foreach (var property in deleteOperation.ValueMetadata.WriteableProperties) { if (property.IsOneToOneRelationship && property.HasAttribute<ForeignKeyReferenceAttribute>()) { return true; } } return false; }
private static void PrependDeleteBeforeReferencedChildTableDelete( IList<BaseOperation> operations, DeleteOperation deleteOperation) { var firstIndex = -1; int index = operations.Count - 1; while (index >= 0) { var possibleMatch = operations [index] as DeleteOperation; if (null != possibleMatch && possibleMatch.OwnerMetadata == deleteOperation.ValueMetadata && possibleMatch.OwnerPropertyMetadata != null && possibleMatch.OwnerPropertyMetadata.IsOneToOneRelationship && possibleMatch.OwnerPropertyMetadata.HasAttribute<ForeignKeyReferenceAttribute>()) { firstIndex = index; break; } --index; } if (firstIndex < 0) { operations.Add(deleteOperation); } else { operations.Insert(firstIndex, deleteOperation); } }
private void AddDeleteToListAtCorrectLocation(IList<BaseOperation> operations, DeleteOperation deleteOperation) { var transformed = Transform(deleteOperation); if (transformed == deleteOperation) { if (HasAnyOneToOneChildrenWithFKOnParent(deleteOperation)) { PrependDeleteBeforeReferencedChildTableDelete(operations, deleteOperation); } else { operations.Add(transformed); } } else { operations.Add(transformed); } }
private void AppendDeleteOperation(IList<BaseOperation> operations, Difference diff) { var deleteOperation = new DeleteOperation { OwnerMetadata = diff.OwnerMetadata, OwnerPropertyMetadata = diff.OwnerPropertyMetadata, OwnerPrimaryKeyColumn = diff.OwnerMetadata == null ? null : diff.OwnerMetadata.PrimaryKey.Prop.Name, Owner = diff.Owner, TableName = diff.OwnerMetadata == null ? null : diff.OwnerMetadata.TableName, ValueMetadata = diff.ValueMetadata, Value = diff.OldValue }; if (IsViableParentUpdateOnManyToOneRelationship(deleteOperation, diff)) { AddUpdateOnParentTableForInsertDeleteOfManyToOneChildRow(operations, diff, deleteOperation); } else if (IsViableParentUpdateOnOneToOneWithFkInParent(deleteOperation, diff)) { AddUpdateOnParentTableForInsertDeleteOfOneToOneChildRow(operations, diff, deleteOperation); } else if (!ShouldFilterOutForParticularCardinalitiesBecauseFkOnParent(deleteOperation)) { AddDeleteToListAtCorrectLocation(operations, deleteOperation); } }
public void Test_InsertAndDelete() { InsertOperation insert = new InsertOperation("world", 0); DeleteOperation delete = new DeleteOperation(3); textEditorTextContext.Insert(null, insert); Assert.AreEqual("world", textEditorTextContext.Data, "Inconsistent state after insertion!"); textEditorTextContext.Delete(null, delete); Assert.AreEqual("word", textEditorTextContext.Data, "Inconsistent state after deletion!"); }
/// <summary> /// Initializes a new instance of the DeleteEventArgs with a /// DeleteOperation that has been performed. /// </summary> /// <param name="issuer">The issuer of the operation.</param> /// <param name="operation">See <see cref="Operation">Operation</see></param> public DeleteEventArgs(object issuer, DeleteOperation operation) { Operation = operation; Issuer = issuer; }
public DeleteCommand(DeleteOperation operation) : base(operation) { }