public static async Task <IEnumerable <T> > Find <T>(this IDocumentCollection <T> self, IWorkContext context, IInstructionCollection instruction) { Verify.IsNotNull(nameof(self), self); Verify.IsNotNull(nameof(instruction), instruction); IInstructionCollection and = instruction as And; IInstructionCollection or = instruction as Or; IInstructionCollection andOr = and ?? or; if (andOr != null) { return(await self.Find(context, andOr.ToDocument())); } OrderBy orderBy = instruction.OfType <OrderBy>().SingleOrDefault(); Projection projection = instruction.OfType <Projection>().SingleOrDefault(); FindOptions <T, T> options = new FindOptions <T, T> { Sort = orderBy?.ToDocument(), Projection = projection?.ToDocument(), }; Query query = instruction.OfType <Query>().FirstOrDefault(); return(await self.Find(context, query?.ToDocument() ?? new BsonDocument(), options)); }
public UserDocument GetUserBySwid(string swid) { try { return((swid == null) ? null : (from id in users.FindDocumentIdsEqual(UserDocument.SwidFieldName, swid) select users.Find(id)).FirstOrDefault()); } catch (CorruptionException ex) { databaseCorruptionHandler.HandleCorruption(ex); throw; } }
internal void SaveCollection <T>(IDocumentCollection <T> collection) where T : class { var serializer = GetSerializer(collection.Configuration); var items = collection.Find(arg => true).ToList(); if (IsMultiFile(collection.Configuration)) { foreach (var item in items) { var fileContent = serializer.Serialize(new[] { item }, collection.Configuration.DocumentType); var collectionDir = collection.Configuration.SourceFile; var key = collection.GetKey(item); var serializerInfo = serializer.GetInfo(); var fileName = Path.Combine(collectionDir, key + serializerInfo.Extension); _configuration.StorageEngine.WriteFile(fileName, fileContent); } } else { var fileContent = serializer.Serialize(items, collection.Configuration.DocumentType); _configuration.StorageEngine.WriteFile(collection.Configuration.SourceFile, fileContent); } collection.HasChanges = false; }
/// <inheritdoc /> public Key GetNextKey(IDocumentCollection <T> collection, T entity) { string collectionName = collection.ConfigurationTyped.Name; int ParseKey(string key) { if (key.Length > collectionName.Length + 1 && key.StartsWith(collectionName)) { key = key.Substring(collectionName.Length + 1); } return(int.Parse(key)); } int max = _startValue; if (collection.Count > 0) { max = collection .Find(arg => true) .Select(collection.GetKey) .Select(ParseKey) .Max(); } int nextId = max + 1; return(new Key(KeyType.Identity, nextId.ToString(), collectionName)); }
public async Task CreateReadTest() { IDocumentDatabase db = _documentServer.GetDatabase(_workContext, _dbName); IDocumentCollection <TestDocument> collection = db.GetCollection <TestDocument>(_collectionName); TestDocument test = CreateTestDocument(0); await collection.Insert(_workContext, test); IEnumerable <TestDocument> results = await collection.Find(_workContext, new BsonDocument()); results.Should().NotBeNull(); results.Count().Should().Be(1); TestDocument result = results.First(); result.Should().NotBeNull(); result.Index.Should().Be(test.Index); result.FirstName.Should().Be(test.FirstName); result.LastName.Should().Be(test.LastName); result.Birthdate.ToString("s").Should().Be(test.Birthdate.ToString("s")); result.Address1.Should().Be(test.Address1); result.Address2.Should().Be(test.Address2); result.City.Should().Be(test.City); result.State.Should().Be(test.State); result.ZipCode.Should().Be(test.ZipCode); }
public async Task CreateReadTestWithDatabaseInConnectionString() { const string connectionDatabaseName = "TestIndexDatabase2"; string connectionString = Constants.CreateConnectionString(connectionDatabaseName); IDocumentDatabase db = new DocumentDatabase(connectionString); IDocumentCollection <TestDocument> collection = db.GetCollection <TestDocument>(_collectionName); TestDocument test = CreateTestDocument(0); await collection.Insert(_workContext, test); IEnumerable <TestDocument> results = await collection.Find(_workContext, new BsonDocument()); results.Should().NotBeNull(); results.Count().Should().Be(1); TestDocument result = results.First(); result.Should().NotBeNull(); result.Index.Should().Be(test.Index); result.FirstName.Should().Be(test.FirstName); result.LastName.Should().Be(test.LastName); result.Birthdate.ToString("s").Should().Be(test.Birthdate.ToString("s")); result.Address1.Should().Be(test.Address1); result.Address2.Should().Be(test.Address2); result.City.Should().Be(test.City); result.State.Should().Be(test.State); result.ZipCode.Should().Be(test.ZipCode); await db.DocumentServer.DropDatabase(_workContext, connectionDatabaseName); }
public async Task <HeaderDoc <UserRoleDoc> > Get(IWorkContext context, string roleId) { Verify.IsNotNull(nameof(context), context); Verify.IsNotEmpty(nameof(roleId), roleId); context = context.WithTag(_tag); var options = new driver.FindOptions <HeaderDoc <UserRoleDoc> > { Limit = 1, Projection = "{'_id': 0}" }; var query = new And() + (new Field(HeaderDoc.FieldName(nameof(UserRoleDoc.RoleId))) == roleId); var result = await _collection.Find(context, query.ToDocument(), options).ConfigureAwait(false); return(result.FirstOrDefault()); }
private static void UpdateFriend(IDocumentCollection <FriendDocument> friends, string swid, Action <FriendDocument> update) { FriendDocument[] array = (from id in EnumerateFriendDocumentIds(friends, swid) select friends.Find(id)).ToArray(); foreach (FriendDocument friendDocument in array) { update(friendDocument); friends.Update(friendDocument); } }
public async Task CreateMultipleReadDeleteTest() { const int count = 10; IDocumentDatabase db = _documentServer.GetDatabase(_workContext, _dbName); IDocumentCollection <TestDocument> collection = db.GetCollection <TestDocument>(_collectionName); var documentList = new List <TestDocument>(); foreach (var index in Enumerable.Range(0, count)) { TestDocument test = CreateTestDocument(index); await collection.Insert(_workContext, test); documentList.Add(test); } IEnumerable <TestDocument> results = await collection.Find(_workContext, new BsonDocument()); results.Should().NotBeNull(); results.Count().Should().Be(count); // Create filter to delete odd records var builder = Builders <TestDocument> .Filter; var filter = builder.In("Index", new int[] { 1, 3, 5, 7, 9 }); await collection.Delete(_workContext, filter); results = await collection.Find(_workContext, new BsonDocument()); results.Should().NotBeNull(); results.Count().Should().Be(count - 5); filter = builder.Gte("Index", 0); await collection.Delete(_workContext, filter); results = await collection.Find(_workContext, new BsonDocument()); results.Should().NotBeNull(); results.Count().Should().Be(0); }
private AlertDocument GetAlertDocument(long alertId) { try { return((from id in alerts.FindDocumentIdsEqual(AlertDocument.AlertIdFieldName, alertId) select alerts.Find(id)).FirstOrDefault()); } catch (CorruptionException ex) { databaseCorruptionHandler.HandleCorruption(ex); throw; } }
public string Retrieve(string path) { var meta = Context.Find(file => file.Path == path).FirstOrDefault(); if (meta != null) { return(meta.Hash + Path.GetExtension(meta.Path)); } else { return(string.Empty); } }
private static void CheckPersons(IDocumentCollection <Person> collection) { var person = collection.Find(_ => _.Id == "2").First(); person.Should().NotBeNull(); person.FirstName.Should().Be("Steve"); person.LastName.Should().Be("Ballmer"); person = collection.Get("1"); person.Should().NotBeNull(); person.FirstName.Should().Be("Bill"); person.LastName.Should().Be("Gates"); }
public async Task SmallCappedOverFiveCollectionTest() { const int maxDocuments = 10; const int maxSizeInBytes = maxDocuments * 1000; const int createDocumentCount = maxDocuments + 5; var model = new CappedCollectionModel { CollectionName = _collectionName, MaxSizeInBytes = maxSizeInBytes, MaxNumberOfDocuments = maxDocuments, }; var package = new CollectionModelPackage(_documentDatabase, model, new CollectionModelSettings { ReCreate = true }); bool result = await package.Apply(_workContext); result.Should().BeTrue(); IDocumentCollection <TestDocument> collection = _documentDatabase.GetCollection <TestDocument>(_collectionName); foreach (var index in Enumerable.Range(0, createDocumentCount)) { TestDocument doc = CreateTestDocument(index); await collection.Insert(_workContext, doc); } long count = await collection.Count(_workContext); count.Should().Be(maxDocuments); IEnumerable <TestDocument> results = await collection.Find(_workContext, new BsonDocument()); results.Should().NotBeNull(); results.Count().Should().Be(maxDocuments); int testIndex = createDocumentCount - maxDocuments; foreach (var item in results.OrderBy(x => x.Index)) { TestDocument compareDoc = CreateTestDocument(testIndex++); item.IsEqual(compareDoc).Should().BeTrue(); } }
public void InsertOrUpdateFriendInvitation(FriendInvitationDocument doc) { try { FriendInvitationDocument friendInvitationDocument = (from id in friendInvitations.FindDocumentIdsEqual(FriendInvitationDocument.FriendInvitationIdFieldName, doc.FriendInvitationId) select friendInvitations.Find(id)).FirstOrDefault(); if (friendInvitationDocument == null) { friendInvitations.Insert(doc); return; } doc.Id = friendInvitationDocument.Id; friendInvitations.Update(doc); } catch (CorruptionException ex) { databaseCorruptionHandler.HandleCorruption(ex); throw; } }
public async Task CreateReadDeleteTest() { IDocumentDatabase db = _documentServer.GetDatabase(_workContext, _dbName); IDocumentCollection <TestDocument> collection = db.GetCollection <TestDocument>(_collectionName); TestDocument test = CreateTestDocument(0); await collection.Insert(_workContext, test); IEnumerable <TestDocument> results = await collection.Find(_workContext, new BsonDocument()); results.Should().NotBeNull(); results.Count().Should().Be(1); TestDocument result = results.First(); result.Should().NotBeNull(); result.Index.Should().Be(test.Index); result.FirstName.Should().Be(test.FirstName); result.LastName.Should().Be(test.LastName); result.Birthdate.ToString("s").Should().Be(test.Birthdate.ToString("s")); result.Address1.Should().Be(test.Address1); result.Address2.Should().Be(test.Address2); result.City.Should().Be(test.City); result.State.Should().Be(test.State); result.ZipCode.Should().Be(test.ZipCode); var builder = Builders <TestDocument> .Filter; var filter = builder.Eq("_id", result._id); await collection.Delete(_workContext, filter); List <TestDocument> currentList = collection.MongoCollection .AsQueryable() .Where(x => x._id == result._id) .ToList(); currentList.Count.Should().Be(0); }
public async Task CreateMultipleReadTest() { const int count = 10; IDocumentDatabase db = _documentServer.GetDatabase(_workContext, _dbName); IDocumentCollection <TestDocument> collection = db.GetCollection <TestDocument>(_collectionName); var documentList = new List <TestDocument>(); foreach (var index in Enumerable.Range(0, count)) { TestDocument test = CreateTestDocument(index); await collection.Insert(_workContext, test); documentList.Add(test); } IEnumerable <TestDocument> results = await collection.Find(_workContext, new BsonDocument()); results.Should().NotBeNull(); results.Count().Should().Be(count); int docIndex = 0; foreach (var result in results.OrderBy(x => x.Index)) { var test = documentList[docIndex++]; result.FirstName.Should().Be(test.FirstName); result.LastName.Should().Be(test.LastName); result.Birthdate.ToString("s").Should().Be(test.Birthdate.ToString("s")); result.Address1.Should().Be(test.Address1); result.Address2.Should().Be(test.Address2); result.City.Should().Be(test.City); result.State.Should().Be(test.State); result.ZipCode.Should().Be(test.ZipCode); } }
/// <summary> /// Marks a book taken and updates the data file /// </summary> /// <param name="takenID">ID of the taken book</param> /// <param name="takenName">Name of the person taking the book</param> /// <param name="retDate">Expected return date of the book</param> public Book TakeBook(int takenID, string takenName, DateTime retDate) { Book tkBook = collection.Find(x => x.Id == takenID).First(); int takenBooks = collection.Find(x => x.TakenBy == takenName).Count(); TimeSpan timeSpan = retDate - DateTime.Now; if (takenBooks >= 3 || timeSpan.TotalDays > 60) { throw new ArgumentException("3 books per person or maximum lend lenght rule vioalted."); } tkBook.TakenBy = takenName; tkBook.ReturnDate = retDate; tkBook.IsAvailable = false; collection.UpdateOne(takenID, tkBook); return(tkBook); }
public void Find_With_Predicate() { _collection.Find(e => e.Id == 1); }
private static SessionDocument GetSessionDocument(string swid, IDocumentCollection <SessionDocument> sessions) { uint?sessionDocumentId = GetSessionDocumentId(swid, sessions); return(sessionDocumentId.HasValue ? sessions.Find(sessionDocumentId.Value) : null); }
public T GetById(int id) { return(_collection.Find(item => item.Id == id).FirstOrDefault()); }