private async Task UpdateDocumentsAsync(IList <T> updatedObservations) { Dictionary <string, T> updatedObservationsByCompositeId = updatedObservations.ToDictionary(x => $"{x.DataProviderId}_{x.CatalogNumber}", x => x); var filterDef = new FilterDefinitionBuilder <VersionedDocumentObservation <T> >(); var filter = filterDef.In(x => x.CompositeId, updatedObservations.Select(x => $"{x.DataProviderId}_{x.CatalogNumber}")); var foundObservations = await(await Collection.FindAsync(filter)).ToListAsync(); var changedObservations = new ConcurrentBag <VersionedDocumentObservation <T> >(); Parallel.For(0, foundObservations.Count - 1, i => { VersionedDocumentObservation <T> versionedObservation = foundObservations[i]; var updatedObservation = updatedObservationsByCompositeId[versionedObservation.CompositeId]; if (UpdateVersionedObservationObject(versionedObservation, updatedObservation)) { changedObservations.Add(versionedObservation); } }); if (changedObservations.Count > 0) { // todo - create transaction? var deleteFilter = filterDef.In(x => x.CompositeId, changedObservations.Select(x => $"{x.DataProviderId}_{x.CatalogNumber}")); await Collection.DeleteManyAsync(deleteFilter); await Collection.InsertManyAsync(changedObservations); } }
private bool UpdateVersionedObservationObject(VersionedDocumentObservation <T> versionedObservation, T updatedObservation) { var previousVersionNumber = versionedObservation.Version; JToken jtokenCurrentDoc = versionedObservation.Current == null ? JToken.Parse("{}") : JToken.FromObject(versionedObservation.Current); JToken diff = _jdp.Diff(jtokenCurrentDoc, JToken.FromObject(updatedObservation)); if (diff == null) { return(false); // no change } versionedObservation.Current = updatedObservation; VersionHistory versionHistory = new VersionHistory(diff.ToString(Formatting.None)) { Version = previousVersionNumber, UtcDate = versionedObservation.UtcDate, Type = versionedObservation.Type, }; versionedObservation.UtcDate = DateTime.UtcNow; versionedObservation.Prev.Add(versionHistory); versionedObservation.Version = previousVersionNumber + 1; versionedObservation.IsDeleted = false; versionedObservation.Type = updatedObservation.GetType().ToString(); return(true); }
public async Task InsertDocumentAsync(T doc) { var currentDocument = await GetDocumentAsync(doc.DataProviderId, doc.CatalogNumber); if (currentDocument == null) // The document doesn't exist. First insert. { var versionedDoc = new VersionedDocumentObservation <T>(doc); Collection.InsertOne(versionedDoc); return; } UpdateVersionedObservationObject(currentDocument, doc); var result = Collection.ReplaceOne(item => item.DataProviderId == doc.DataProviderId && item.CatalogNumber == doc.CatalogNumber, currentDocument); if (result.ModifiedCount != 1) // the number of modified documents { // print("Someone must have gotten there first, re-fetch the new document, try again"); // todo - Is this something that can occur? } }