private void DeleteAndAssert(DocumentRevision updated) { var deleteTask = db.DeleteAsync(updated); deleteTask.Wait(); Assert.IsFalse(deleteTask.IsFaulted); }
public byte[] TransactionGet(int transactionId, DocumentId documentId) { Transaction transaction; if (!m_pendingTransaction.TryGetValue(transactionId, out transaction)) { throw new TransactionNotExistException(); } Document document = m_documentStore.GetDocument(documentId); if (document == null) { return(ZeroBlob); } // if updated by current transaction we just return the current blob if (document.TransactionId == transactionId) { return(transaction.GetBlob(documentId)); } // we need to find the current revision DocumentRevision revision = document.GetDocumentRevisionByTimestamp(transaction.DBTimestamp); // if there is no revision the object is not exist for this timestamp if (revision == null) { return(ZeroBlob); } return(ReadInternal(revision.BlobFileLocation, revision.BlobSize)); }
public void testCreateDocumentInDbWithSlash() { var db = client.Database("my/database"); try { db.EnsureExistsAsync().Wait(); var document = new DocumentRevision() { docId = "my/document", body = new Dictionary <string, Object>() { ["hello"] = "world" } }; var savedDocument = CreateAndAssert(document); //read ReadAndAssert(document, savedDocument); // update var updated = UpdateAndAssert(document, savedDocument); // delete DeleteAndAssert(updated); } finally { db.DeleteAsync().Wait(); } }
public void testEqualityQueryTest() { doQuerySetup(); var sortField = new SortField() { sort = Sort.desc, name = ageKey }; var task = db.QueryAsync(selector: new Dictionary <string, object>() { [ageKey] = 5 }, sort: new List <SortField>() { sortField }); task.Wait(); IList <DocumentRevision> result = task.Result; Assert.False(task.IsFaulted, "findByIndex() failed"); Assert.IsNotNull(task.Result, "Query result was null"); Assert.True(result.Count == 1); DocumentRevision revision = result[0]; Object age; revision.body.TryGetValue(ageKey, out age); Assert.True((long)age == 5); }
public void testGreaterThanQueryWithSortOptionTest() { doQuerySetup(); var sortField = new SortField(); sortField.name = ageKey; sortField.sort = Sort.desc; var task = db.QueryAsync(selector: new Dictionary <string, object>() { [ageKey] = new Dictionary <string, int>() { ["$gt"] = 1 } }, sort: new List <SortField>() { sortField }); task.Wait(); IList <DocumentRevision> result = task.Result; Assert.False(task.IsFaulted, "findByIndex() failed"); Assert.IsNotNull(task.Result, "Query result was null"); Assert.True(result.Count == 18); DocumentRevision revision = result[0]; Object age; revision.body.TryGetValue(ageKey, out age); Assert.True((long)age == 19); }
/// <summary> /// Code sample to retrieve a document from the database. /// </summary> private void OnRetrieveDocument() { //Database must exist. if (!ValidateDatabaseExists()) { return; } try { Task <DocumentRevision> readTask = db.ReadAsync(docName); readTask.Wait(); DocumentRevision rev = readTask.Result; DisplayAlert("Document Retrieved", DisplayDocument(rev), "OK"); } catch (AggregateException ae) { DisplayAlert("Error Rerieving Document", "Document does not exist, it must be created first.", "OK"); } catch (Exception e) { HandleException(e, "Error Retrieving Document"); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jsonObject = JObject.Load(reader); var document = new DocumentRevision(); document.body = new Dictionary<string,object>(); foreach (var kv in jsonObject) { switch (kv.Key) { case "_id": case "id": document.docId = kv.Value.ToObject<string>(); break; case "_rev": case "rev": document.revId = kv.Value.ToObject<string>(); break; case "_deleted": document.isDeleted = kv.Value.ToObject<bool>(); break; default: // Other values go in the body document.body.Add(kv.Key, kv.Value.ToObject<dynamic>()); break; } } return document; }
private void ReadAndAssert(DocumentRevision document, DocumentRevision savedDocument) { var readDocumentTask = db.ReadAsync(document.docId); readDocumentTask.Wait(); Assert.IsFalse(readDocumentTask.IsFaulted); Assert.AreEqual(savedDocument, readDocumentTask.Result); }
public void PropertiesMustReturnExpectedValuesWhenSet() { DocumentRevision revision = new DocumentRevision("test.txt", "test/test"); Assert.False(revision.Approved); revision.Approve(); Assert.True(revision.Approved); }
public void testBasicSaveWithoutBody() { // Save DocumentRevision without a body DocumentRevision revision = new DocumentRevision(); Task <DocumentRevision> saveTask = db.CreateAsync(revision); saveTask.Wait(); Assert.True(!saveTask.IsFaulted, "failed to save DocumentRevision with empty body"); }
private DocumentRevision UpdateAndAssert(DocumentRevision document, DocumentRevision savedDocument) { savedDocument.body.Add("updated", true); var updateTask = db.UpdateAsync(savedDocument); updateTask.Wait(); Assert.IsFalse(updateTask.IsFaulted); Assert.AreEqual(document.docId, updateTask.Result.docId); return(updateTask.Result); }
public void testBasicSaveWithBody() { DocumentRevision revision = new DocumentRevision(); Dictionary<String, Object> body = new Dictionary<String, Object>(); body.Add("key", "value"); revision.body = body; // Save DocumentRevision with a body Task<DocumentRevision> saveTask = db.CreateAsync(revision); saveTask.Wait(); Assert.True(!saveTask.IsFaulted, "failed to save DocumentRevision with body"); }
public void testCreateWithEmptyDocId() { var document = new DocumentRevision() { docId = "", body = new Dictionary <string, object>() { ["hello"] = "world" } }; Assert.DoesNotThrow(() => db.CreateAsync(document).Wait()); }
public void testUpdateWithEmptyDocId() { var document = new DocumentRevision() { docId = "", revId = "1-blhjyurbgufbhfuonUJFB", body = new Dictionary <string, object>() { ["hello"] = "world" } }; Assert.Throws <AggregateException>(() => db.UpdateAsync(document).Wait()); }
// Private helpers private DocumentRevision CreateAndAssert(DocumentRevision document) { Task <DocumentRevision> task = db.CreateAsync(document); task.Wait(); Assert.IsFalse(task.IsFaulted); Assert.IsNotNull(task.Result); var savedDocument = task.Result; Assert.AreEqual(document.docId, savedDocument.docId); Assert.AreEqual(document.body, savedDocument.body); return(savedDocument); }
public void testBasicSaveWithBody() { DocumentRevision revision = new DocumentRevision(); Dictionary <String, Object> body = new Dictionary <String, Object>(); body.Add("key", "value"); revision.body = body; // Save DocumentRevision with a body Task <DocumentRevision> saveTask = db.CreateAsync(revision); saveTask.Wait(); Assert.True(!saveTask.IsFaulted, "failed to save DocumentRevision with body"); }
/// <summary> /// Returns the value of the QueryRow and interprets it as the given type /// </summary> /// <returns>The value of the QueryRow and interprets it as the given type.</returns> /// <typeparam name="T">The type to interpret the result as</typeparam> public T ValueAs <T>() { var value = _parsedValue; if (value == null || !(value is T)) { value = _value; var valueData = value as IEnumerable <byte>; if (valueData != null) { // _value may start out as unparsed Collatable data var storage = _storage; Debug.Assert(storage != null); if (storage.RowValueIsEntireDoc(valueData)) { // Value is a placeholder ("*") denoting that the map function emitted "doc" as // the value. So load the body of the revision now: if (DocumentRevision != null) { value = DocumentRevision.GetProperties(); } else { Debug.Assert(SequenceNumber != 0); value = storage.DocumentProperties(SourceDocumentId, SequenceNumber); if (value == null) { Log.To.Query.W(TAG, "Couldn't load doc for row value"); } } } else { value = storage.ParseRowValue <T>(valueData); } } _parsedValue = value; } T castVal = default(T); if (!ExtensionMethods.TryCast(_parsedValue, out castVal)) { throw new InvalidCastException(); } return(castVal); }
public void testInvalidDeleteWithoutBody() { try { // Save DocumentRevision without a body DocumentRevision revision = new DocumentRevision(); Task <String> deleteTask = db.DeleteAsync(revision); deleteTask.Wait(); Assert.True(deleteTask.IsFaulted, "delete DocumentRevision that does not exist should fail"); } catch (Exception e) { Assert.Pass("expected testInvalidDeleteWithoutBody exception caught. Cause:" + e.InnerException.Message); } }
/// <summary> /// Helper class to convert the document contents to a string. /// </summary> /// <returns>A string with the dictionary contents.</returns> /// <param name="d">A DocumentRevision object.</param> private string DisplayDocument(DocumentRevision rev) { Dictionary <string, object> dictionary = rev.body; string body = ""; foreach (string key in dictionary.Keys) { object value; dictionary.TryGetValue(key, out value); body += string.Format("{0} : {1}\n", key, value.ToString()); } return(string.Format("docId: {0}\nrevId: {1}\n\n--- Document data ---\n{2}", rev.docId, rev.revId, body)); }
private void doQuerySetupWithFields(String indexName, List <SortField> indexFields) { var indexTask = db.CreateJsonIndexAsync(fields: indexFields, indexName: indexName); indexTask.Wait(); for (int i = 0; i < 20; i++) { Dictionary <String, Object> dictionary = new Dictionary <String, Object>(); dictionary.Add(nameKey, nameValue + i); dictionary.Add(ageKey, ageBaseValue + i); DocumentRevision revision = new DocumentRevision(); revision.body = dictionary; Task <DocumentRevision> task = db.CreateAsync(revision); task.Wait(); } }
/// <summary> /// Code sample to save a document in the database. /// </summary> private void OnSaveDocument() { //Database must exist. if (!ValidateDatabaseExists()) { return; } try { //Data to be saved Dictionary <string, object> docContents = new Dictionary <string, object>(); docContents.Add("Name", "Mike"); docContents.Add("age", 28); docContents.Add("boolValue", true); docContents.Add("savedDate", DateTime.Now.ToString()); //Create a DocumentRevision and set the data to be saved in the body. DocumentRevision doc = new DocumentRevision() { docId = docName, body = docContents }; //Save to the database. Task <DocumentRevision> createTask = db.CreateAsync(doc); createTask.Wait(); DocumentRevision rev = createTask.Result; DisplayAlert("Document Saved", DisplayDocument(rev), "OK"); } catch (AggregateException ae) { DisplayAlert( "Error Saving Document", "The document already exists. To update an existing document use update ().", "OK"); } catch (Exception e) { HandleException(e, "Error Saving Document"); } }
private void OnUpdateDocument() { //Database must exist. if (!ValidateDatabaseExists()) { return; } //Retrieve the latest document revision. DocumentRevision doc; try { Task <DocumentRevision> readTask = db.ReadAsync(docName); readTask.Wait(); doc = readTask.Result; } catch { DisplayAlert("Error Updating Document", "Document does not exist, it must be created first.", "OK"); return; } //Update data in the DocumentRevision. doc.body["savedDate"] = DateTime.Now.ToString(); //Save a new revision in the database. try { Task <DocumentRevision> updateTask = db.UpdateAsync(doc); updateTask.Wait(); DocumentRevision rev = updateTask.Result; DisplayAlert("Document Updated", DisplayDocument(rev), "OK"); } catch (Exception e) { HandleException(e, "Error Updating Document"); } }
public void testCreateDocumentWithExclamation() { var document = new DocumentRevision() { docId = "my!document", body = new Dictionary <string, Object>() { ["hello"] = "world" } }; var savedDocument = CreateAndAssert(document); //read ReadAndAssert(document, savedDocument); // update var updated = UpdateAndAssert(document, savedDocument); // delete DeleteAndAssert(updated); }
public void testCreateWithEmptyDocId() { var document = new DocumentRevision() { docId = "", body = new Dictionary<string,object>() { ["hello" ] = "world" } }; Assert.DoesNotThrow(() => db.CreateAsync(document).Wait()); }
public void testSaveFetchDeleteDocument() { String stringKey = "stringKey"; String stringValue = "nicestringvalue"; String numberKey = "numberKey"; int numberValue = 42; String newKey = "newKey"; int newValue = 43; Dictionary <String, Object> dictionary = new Dictionary <String, Object>(); dictionary.Add(stringKey, stringValue); dictionary.Add(numberKey, numberValue); // Insert a document DocumentRevision revision = new DocumentRevision(); revision.body = dictionary; Task <DocumentRevision> task = db.CreateAsync(revision); task.Wait(); // Validate save result Assert.False(task.IsFaulted, "create unexpectedly failed"); Assert.True(task.Result is DocumentRevision, "DocumentRevision not returned on create"); DocumentRevision savedRevision = (DocumentRevision)task.Result; Assert.NotNull(savedRevision.docId, "savedRevision.docId == null"); Assert.NotNull(savedRevision.revId, "savedRevision.revId == null"); // perform find task = db.ReadAsync(savedRevision.docId); task.Wait(); // Validate find result Assert.False(task.IsFaulted, "create unexpectedly failed"); Assert.True(task.Result is DocumentRevision, "DocumentRevision not returned on create"); DocumentRevision fetchedRevision = (DocumentRevision)task.Result; fetchedRevision.body.Add(newKey, newValue); fetchedRevision.body.Remove(stringKey); // perform update task = db.UpdateAsync(fetchedRevision); task.Wait(); Assert.False(task.IsFaulted, "update unexpectedly failed"); Assert.True(task.Result is DocumentRevision, "DocumentRevision not returned on create"); DocumentRevision updatedRevision = (DocumentRevision)task.Result; Assert.NotNull(updatedRevision.docId, "updatedRevision.docId == null"); Assert.NotNull(updatedRevision.revId, "updatedRevision.revId == null"); Assert.True(updatedRevision.body.ContainsKey(newKey), "updatedBody did not contain newKey as expected"); Assert.False(updatedRevision.body.ContainsKey(stringKey), "updatedBody did contained stringKey when not expected"); // remove the document from the database Task <String> deleteTask = db.DeleteAsync(updatedRevision); deleteTask.Wait(); Assert.False(deleteTask.IsFaulted, "delete unexpectedly failed"); Assert.NotNull(deleteTask.Result, "delete result not returned as expected."); }
public void testBasicSaveWithoutBody() { // Save DocumentRevision without a body DocumentRevision revision = new DocumentRevision(); Task<DocumentRevision> saveTask = db.CreateAsync(revision); saveTask.Wait(); Assert.True(!saveTask.IsFaulted, "failed to save DocumentRevision with empty body"); }
/// <summary> /// Helper class to convert the document contents to a string. /// </summary> /// <returns>A string with the dictionary contents.</returns> /// <param name="d">A DocumentRevision object.</param> private string DisplayDocument(DocumentRevision rev) { Dictionary<string,object> dictionary = rev.body; string body = ""; foreach (string key in dictionary.Keys) { object value; dictionary.TryGetValue(key, out value); body += string.Format("{0} : {1}\n", key, value.ToString()); } return string.Format("docId: {0}\nrevId: {1}\n\n--- Document data ---\n{2}", rev.docId, rev.revId, body); }
public void testCreateDocumentWithStar() { var document = new DocumentRevision() { docId = "my*document", body = new Dictionary<string,Object>() { ["hello" ] = "world" } }; var savedDocument = CreateAndAssert(document); //read ReadAndAssert(document, savedDocument); // update var updated = UpdateAndAssert(document, savedDocument); // delete DeleteAndAssert(updated); }
public bool OnBeforeSave(IEnumerable <IEntity> entities, IDictionary <string, object> state) { foreach (Document document in from entity in entities where entity.Is <Document>() select entity.AsWritable <Document>()) { // Populate the document revision DocumentRevision revision = Entity.Create <DocumentRevision>(); bool createNewRevision = false; bool initialRevision = false; if (EntityTemporaryIdAllocator.IsAllocatedId(document.Id)) { // Populate the initial version string for the document revision.VersionComments = @"Initial Version"; revision.Version = @"1.0"; revision.Name = revision.Version; createNewRevision = true; initialRevision = true; } else { DocumentRevision currentRevision = document.CurrentDocumentRevision; if (currentRevision?.FileDataHash != document.FileDataHash) { // Extract the version number and increment it string newRevision = string.Format("{0}.0", Convert.ToInt32(currentRevision.Version.Split('.')[0]) + 1); revision.VersionComments = document.Description; // Need to modify the document entity to include a hidden field for comments ?? revision.Version = newRevision; revision.Name = newRevision; createNewRevision = true; } } if (createNewRevision) { revision.FileExtension = document.FileExtension; revision.ModifiedDate = DateTime.UtcNow; revision.Size = document.Size; // Get the entity that represents the user UserAccount userAccount = Entity.Get <UserAccount>(RequestContext.GetContext().Identity.Id); // Associate the revision to the account revision.RevisionUpdatedBy = userAccount; // Associate the file to this revision revision.FileDataHash = document.FileDataHash; SaveGraph saveGraph = EventTargetStateHelper.GetSaveGraph(state); saveGraph.Entities[revision.Id] = revision; document.CurrentDocumentRevision = revision; // Associate the document to the revision (documentHasDocumentRevision - used for version history listing) document.DocumentHasDocumentRevision.Add(revision); // Associate the last created user to the document if (initialRevision) { document.DocumentCreatedBy = userAccount; } // Associate the last modified user to the document document.DocumentModifiedBy = userAccount; } document.DocumentHasDocumentType = document.DocumentFileType; if (document.InFolder == null) { // Default document dumping ground if not specified document.InFolder = Entity.Get <DocumentFolder>(new EntityRef("core", "documentsDocumentFolder")); } } return(false); }
/// <summary> /// Sample code to search for a document with a given index. /// </summary> private void OnQuery() { //Database must exist. if (!ValidateDatabaseExists()) { return; } string indexName = "index1"; string designDocName = "index1design"; string indexField = "age"; try { //Create an index for the field 'age'. var indexTask = db.CreateJsonIndexAsync(fields: new List <SortField>() { new SortField() { name = indexField } }, indexName: indexName, designDocumentName: designDocName); indexTask.Wait(); // Find all documents with indexes that match the given selector. // In this example it returns all documents where 'age' is 28. var queryTask = db.QueryAsync(selector: new Dictionary <string, object>() { ["age"] = 28 }, sort: new List <SortField>() { new SortField() { name = indexField, sort = Sort.desc } }); queryTask.Wait(); IList <DocumentRevision> queryResult = queryTask.Result; if (queryResult.Count > 0) { DocumentRevision rev = queryResult[0]; DisplayAlert("Query Succeeded", DisplayDocument(rev), "OK"); } else { DisplayAlert("Query Failed", "No documents were found, a document must be created first.", "OK"); } } catch (Exception e) { HandleException(e, "Error Querying Index"); } }
// Private helpers private DocumentRevision CreateAndAssert(DocumentRevision document) { Task<DocumentRevision> task = db.CreateAsync(document); task.Wait(); Assert.IsFalse(task.IsFaulted); Assert.IsNotNull(task.Result); var savedDocument = task.Result; Assert.AreEqual(document.docId, savedDocument.docId); Assert.AreEqual(document.body, savedDocument.body); return savedDocument; }
public void testUpdateWithEmptyRevId() { var document = new DocumentRevision() { docId = "helloworld", revId = "", body = new Dictionary<string,object>() { ["hello" ] = "world" } }; Assert.Throws<AggregateException>(() => db.UpdateAsync(document).Wait() ); }
public void testSaveFetchDeleteDocument() { String stringKey = "stringKey"; String stringValue = "nicestringvalue"; String numberKey = "numberKey"; int numberValue = 42; String newKey = "newKey"; int newValue = 43; Dictionary<String, Object> dictionary = new Dictionary<String, Object>(); dictionary.Add(stringKey, stringValue); dictionary.Add(numberKey, numberValue); // Insert a document DocumentRevision revision = new DocumentRevision(); revision.body = dictionary; Task<DocumentRevision> task = db.CreateAsync(revision); task.Wait(); // Validate save result Assert.False(task.IsFaulted, "create unexpectedly failed"); Assert.True(task.Result is DocumentRevision, "DocumentRevision not returned on create"); DocumentRevision savedRevision = (DocumentRevision)task.Result; Assert.NotNull(savedRevision.docId, "savedRevision.docId == null"); Assert.NotNull(savedRevision.revId, "savedRevision.revId == null"); // perform find task = db.ReadAsync(savedRevision.docId); task.Wait(); // Validate find result Assert.False(task.IsFaulted, "create unexpectedly failed"); Assert.True(task.Result is DocumentRevision, "DocumentRevision not returned on create"); DocumentRevision fetchedRevision = (DocumentRevision)task.Result; fetchedRevision.body.Add(newKey, newValue); fetchedRevision.body.Remove(stringKey); // perform update task = db.UpdateAsync(fetchedRevision); task.Wait(); Assert.False(task.IsFaulted, "update unexpectedly failed"); Assert.True(task.Result is DocumentRevision, "DocumentRevision not returned on create"); DocumentRevision updatedRevision = (DocumentRevision)task.Result; Assert.NotNull(updatedRevision.docId, "updatedRevision.docId == null"); Assert.NotNull(updatedRevision.revId, "updatedRevision.revId == null"); Assert.True(updatedRevision.body.ContainsKey(newKey), "updatedBody did not contain newKey as expected"); Assert.False(updatedRevision.body.ContainsKey(stringKey), "updatedBody did contained stringKey when not expected"); // remove the document from the database Task<String> deleteTask = db.DeleteAsync(updatedRevision); deleteTask.Wait(); Assert.False(deleteTask.IsFaulted, "delete unexpectedly failed"); Assert.NotNull(deleteTask.Result, "delete result not returned as expected."); }
private void doQuerySetupWithFields(String indexName, List<SortField> indexFields) { var indexTask = db.CreateJsonIndexAsync(fields: indexFields, indexName: indexName); indexTask.Wait(); for (int i = 0; i < 20; i++) { Dictionary<String, Object> dictionary = new Dictionary<String, Object>(); dictionary.Add(nameKey, nameValue + i); dictionary.Add(ageKey, ageBaseValue + i); DocumentRevision revision = new DocumentRevision(); revision.body = dictionary; Task<DocumentRevision> task = db.CreateAsync(revision); task.Wait(); } }
/// <summary> /// Code sample to save a document in the database. /// </summary> private void OnSaveDocument() { //Database must exist. if (!ValidateDatabaseExists()) return; try { //Data to be saved Dictionary<string, object> docContents = new Dictionary<string, object>(); docContents.Add("Name", "Mike"); docContents.Add("age", 28); docContents.Add("boolValue", true); docContents.Add("savedDate", DateTime.Now.ToString()); //Create a DocumentRevision and set the data to be saved in the body. DocumentRevision doc = new DocumentRevision() { docId = docName, body = docContents }; //Save to the database. Task<DocumentRevision> createTask = db.CreateAsync(doc); createTask.Wait(); DocumentRevision rev = createTask.Result; DisplayAlert("Document Saved", DisplayDocument(rev), "OK"); } catch (AggregateException ae) { DisplayAlert( "Error Saving Document", "The document already exists. To update an existing document use update ().", "OK"); } catch (Exception e) { HandleException(e, "Error Saving Document"); } }
private DocumentRevision UpdateAndAssert(DocumentRevision document, DocumentRevision savedDocument) { savedDocument.body.Add("updated", true); var updateTask = db.UpdateAsync(savedDocument); updateTask.Wait(); Assert.IsFalse(updateTask.IsFaulted); Assert.AreEqual(document.docId, updateTask.Result.docId); return updateTask.Result; }
public void testCreateDocumentInDbWithSlash() { var db = client.Database("my/database"); try { db.EnsureExistsAsync().Wait(); var document = new DocumentRevision() { docId = "my/document", body = new Dictionary<string,Object>() { ["hello" ] = "world" } }; var savedDocument = CreateAndAssert(document); //read ReadAndAssert(document, savedDocument); // update var updated = UpdateAndAssert(document, savedDocument); // delete DeleteAndAssert(updated); } finally { db.DeleteAsync().Wait(); } }