public void Sync() { Shares.Clear(); DatabaseConnection connection = DatabaseConnection.Instance; var database = connection.Client.GetDatabase(Properties.Settings.Default.mongodb_database); var sharesCollection = database.GetCollection <BsonDocument>(Properties.Settings.Default.mongodb_collection_shares); using (IAsyncCursor <BsonDocument> cursor = sharesCollection.FindSync(new BsonDocument())) { while (cursor.MoveNext()) { IEnumerable <BsonDocument> batch = cursor.Current; foreach (BsonDocument document in batch) { string shareLetter = document["share_letter"].AsString; string sharePath = document["share_path"].AsString; bool mounted = NetworkDrives.IsDriveMapped(shareLetter); Shares.Add(new NetworkShare(shareLetter, sharePath, mounted)); } } } }
public async Task <IReadOnlyList <Role> > GetRoles() { try { FilterDefinitionBuilder <Role> builder = Builders <Role> .Filter; FilterDefinition <Role> filter = builder.Eq(nameof(Role.user_id), _UserId); IAsyncCursor <Role> result = await RoleCollection.FindAsync(filter); List <Role> roles = await result.ToListAsync(); if (roles == null) { return(new List <Role>()); } return(roles); } catch (Exception ex) { _Logger.LogError(ex, "GetRoles Failed!"); } return(null); }
private static async Task FetchAudioUrlsAsync() { IAsyncCursor <Card> cursor = await CardsCollection .FindAsync(x => x.Audio == null); while (cursor.MoveNext()) { foreach (string word in cursor.Current .Select(w => w.Word) .AsParallel()) { HtmlDocument doc = new HtmlWeb() .Load($"http://ordnet.dk/ddo/ordbog?query={word}"); HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a"); string href = string.Empty; foreach (HtmlNode node in nodes.Where(n => n != null && n.Attributes["href"] != null)) { if (node.Attributes["href"].Value.EndsWith(".mp3", StringComparison.InvariantCultureIgnoreCase)) { href = node.Attributes["href"].Value; break; } } FilterDefinition <Card> filter = Builders <Card> .Filter.Eq("_id", word); UpdateDefinition <Card> update = Builders <Card> .Update.Set("Audio", href); await CardsCollection.UpdateOneAsync(filter, update); Console.WriteLine($"Word: {word}\t\t\tAudio: {href}"); } } }
/// <inheritdoc/> public bool MoveNext(CancellationToken cancellationToken = default(CancellationToken)) { bool hasMore; try { hasMore = _cursor.MoveNext(cancellationToken); } catch (Exception ex) { if (CanResumeAfter(ex)) { _cursor = _changeStreamOperation.Resume(_binding, _resumeToken, cancellationToken); hasMore = _cursor.MoveNext(cancellationToken); } else { throw; } } ProcessBatch(hasMore); return(hasMore); }
//刷新周排行榜 1,周财富榜,2,周战绩榜 public static async Task <List <Log_Rank> > QueryJsonRank(this DBProxyComponent self, int type) { DBComponent dbComponent = Game.Scene.GetComponent <DBComponent>(); FilterDefinition <Log_Rank> filterDefinition = new JsonFilterDefinition <Log_Rank>($"{{}}"); FilterDefinition <Log_Rank> filterEmpty = Builders <Log_Rank> .Filter.Empty; SortDefinition <Log_Rank> sortDefinition = Builders <Log_Rank> .Sort.Descending(""); IAsyncCursor <Log_Rank> asyncCursor = await dbComponent.GetDBDataCollection <Log_Rank>(typeof(Log_Rank).Name).FindAsync(filterDefinition); List <Log_Rank> components = new List <Log_Rank>(); if (type == 1) { components = await dbComponent.GetDBDataCollection <Log_Rank>(typeof(Log_Rank).Name).Find(filterDefinition).SortByDescending(a => a.Wealth).Limit(50).ToListAsync(); } else if (type == 2) { components = await dbComponent.GetDBDataCollection <Log_Rank>(typeof(Log_Rank).Name).Find(filterDefinition).SortByDescending(a => a.WinGameCount).Limit(50).ToListAsync(); } return(components); }
//[Route("GetItemDetailsById")] public async Task <ActionResult <CatalogInfo> > GetItemDetailsById(int id, int itemId) { FilterDefinition <CatalogInfo> filter = Builders <CatalogInfo> .Filter.Eq("CategoryId", id); // filter. Builders<CatalogInfo>.Filter.Eq("itemid", itemId); IEnumerable <CatalogInfo> entity = null; using (IAsyncCursor <CatalogInfo> cursor = await this.catalogContext.CatalogInfo.FindAsync(filter)) { while (await cursor.MoveNextAsync()) { entity = cursor.Current; // var itemData = entity.FirstOrDefault().Items[0].itemid == itemId; var itemData = entity.ToArray()[0].Items.Where(c => c.itemid == itemId); //var itemData1 = entity.FirstOrDefault(c => c.Items.FirstOrDefault(t => t.itemid == itemId)); if (entity != null) { return(Ok(itemData)); } } } return(NotFound()); }
/// <summary> /// 根据条件获取获取列表 /// </summary> /// <param name="filterExp">查询条件表达式</param> /// <param name="includeFieldExp">查询字段表达式</param> /// <param name="sortExp">排序表达式</param> /// <param name="sortType">排序方式</param> /// <param name="limit"></param> /// <param name="skip"></param> /// <param name="hint">hint索引</param> /// <param name="readPreference">访问设置</param> /// <returns></returns> public List <TEntity> GetList(Expression <Func <TEntity, bool> > filterExp = null, Expression <Func <TEntity, object> > includeFieldExp = null, Expression <Func <TEntity, object> > sortExp = null, SortType sortType = SortType.Ascending, int limit = 0, int skip = 0, BsonValue hint = null, ReadPreference readPreference = null) { ProjectionDefinition <TEntity, TEntity> projection = null; FilterDefinition <TEntity> filter; if (filterExp != null) { filter = Builders <TEntity> .Filter.Where(filterExp); } else { filter = Builders <TEntity> .Filter.Empty; } SortDefinition <TEntity> sort = base.CreateSortDefinition <TEntity>(sortExp, sortType); if (includeFieldExp != null) { projection = base.IncludeFields <TEntity>(includeFieldExp); } FindOptions <TEntity, TEntity> options = base.CreateFindOptions <TEntity>(projection, sort, limit, skip, hint); IAsyncCursor <TEntity> source = base.GetCollection(readPreference).FindSync <TEntity>(filter, options, default(CancellationToken)); return(source.ToList(default(CancellationToken))); }
/// <inheritdoc/> public bool MoveNext(CancellationToken cancellationToken = default(CancellationToken)) { bool hasMore; try { hasMore = _cursor.MoveNext(cancellationToken); } catch (Exception ex) { if (RetryabilityHelper.IsResumableChangeStreamException(ex)) { _cursor = _changeStreamOperation.Resume(_binding, cancellationToken); hasMore = _cursor.MoveNext(cancellationToken); } else { throw; } } ProcessBatch(hasMore); return(hasMore); }
// constructors /// <summary> /// Initializes a new instance of the <see cref="ChangeStreamCursor{TDocument}" /> class. /// </summary> /// <param name="cursor">The cursor.</param> /// <param name="documentSerializer">The document serializer.</param> /// <param name="binding">The binding.</param> /// <param name="changeStreamOperation">The change stream operation.</param> /// <param name="aggregatePostBatchResumeToken">The post batch resume token from an aggregate command.</param> /// <param name="initialOperationTime">The initial operation time.</param> /// <param name="initialStartAfter">The start after value.</param> /// <param name="initialResumeAfter">The resume after value.</param> /// <param name="initialStartAtOperationTime">The start at operation time value.</param> /// <param name="serverVersion">The server version.</param> public ChangeStreamCursor( IAsyncCursor <RawBsonDocument> cursor, IBsonSerializer <TDocument> documentSerializer, IReadBinding binding, IChangeStreamOperation <TDocument> changeStreamOperation, BsonDocument aggregatePostBatchResumeToken, BsonTimestamp initialOperationTime, BsonDocument initialStartAfter, BsonDocument initialResumeAfter, BsonTimestamp initialStartAtOperationTime, SemanticVersion serverVersion) { _cursor = Ensure.IsNotNull(cursor, nameof(cursor)); _documentSerializer = Ensure.IsNotNull(documentSerializer, nameof(documentSerializer)); _binding = Ensure.IsNotNull(binding, nameof(binding)); _changeStreamOperation = Ensure.IsNotNull(changeStreamOperation, nameof(changeStreamOperation)); _postBatchResumeToken = aggregatePostBatchResumeToken; _initialOperationTime = initialOperationTime; _initialStartAfter = initialStartAfter; _initialResumeAfter = initialResumeAfter; _initialStartAtOperationTime = initialStartAtOperationTime; _serverVersion = Ensure.IsNotNull(serverVersion, nameof(serverVersion)); }
public async Task <List <FormControl> > FindByOwner(string email) { IAsyncCursor <BsonDocument> result = await _mongoRepository.FindBy(Keywords.OWNER, email); List <FormControl> formControls = new List <FormControl>(); if (result == null) { return(formControls); } using (IAsyncCursor <BsonDocument> cursor = result) { while (await cursor.MoveNextAsync()) { IEnumerable <BsonDocument> batch = cursor.Current; foreach (BsonDocument document in batch) { formControls.Add(CreateFormControlFromBson(document)); } } } return(formControls); }
public static async Task MainAsync() { dataToSave.Clear(); Console.WriteLine("connecting"); var client = new MongoClient( "mongodb+srv://lukas:[email protected]/test?retryWrites=true&w=majority" ); IMongoDatabase db = client.GetDatabase("bear_witness"); var collection = db.GetCollection <BsonDocument>("user_info"); using (IAsyncCursor <BsonDocument> cursor = await collection.FindAsync(new BsonDocument())) { while (await cursor.MoveNextAsync()) { IEnumerable <BsonDocument> batch = cursor.Current; foreach (BsonDocument document in batch) { try { Data account = JsonConvert.DeserializeObject <Data>(JsonConvert.SerializeObject(BsonTypeMapper.MapToDotNetValue(document))); dataToSave.Add(account); } catch (Exception ex) { } } sortData(dataToSave); } } System.Threading.Thread.Sleep(300000); Task task = MainAsync(); task.Wait(); }
public static async ETTask Query(this DBComponent self, long id, List <string> collectionNames, List <Entity> result) { if (collectionNames == null || collectionNames.Count == 0) { return; } using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, id % DBComponent.TaskCount)) { foreach (string collectionName in collectionNames) { IAsyncCursor <Entity> cursor = await self.GetCollection(collectionName).FindAsync(d => d.Id == id); Entity e = await cursor.FirstOrDefaultAsync(); if (e == null) { continue; } result.Add(e); } } }
/// <inheritdoc/> public async Task <bool> MoveNextAsync(CancellationToken cancellationToken = default(CancellationToken)) { bool hasMore; while (true) { try { hasMore = await _cursor.MoveNextAsync(cancellationToken).ConfigureAwait(false); break; } catch (Exception ex) when(RetryabilityHelper.IsResumableChangeStreamException(ex, _serverVersion)) { var newCursor = await ResumeAsync(cancellationToken).ConfigureAwait(false); _cursor.Dispose(); _cursor = newCursor; } } ProcessBatch(hasMore); return(hasMore); }
public async Task <IActionResult> CreateEntity(DynamicEntity input) { MongoDbContext mongoDbContext = new MongoDbContext(); string dbName = "Db_1234"; var mongoDb = mongoDbContext.GetDatabase(dbName); // IAsyncCursor <DynamicEntity> cc = await mongoDb.GetCollection <DynamicEntity>("master").FindAsync(o => o.Name == input.Name); if (cc.FirstOrDefault() != null) { return(await Task.FromResult(BadRequest())); } foreach (var fld in input.Fields.OrderByDescending(z => z.IsKey)) { } //Insert collection schema in master collection of service database await mongoDb.GetCollection <DynamicEntity>("master").InsertOneAsync(input); //Creating collection itself with validation and index CreateCollectionOptions opt = new CreateCollectionOptions <BsonDocument> { Validator = input.GetValidationExp(), ValidationAction = DocumentValidationAction.Error, ValidationLevel = DocumentValidationLevel.Strict }; await mongoDb.CreateCollectionAsync(input.Name, opt); return(Ok()); }
public IEnumerable <TField> Distinct <TField, TCollection>(Expression <Func <TCollection, TField> > fieldSelector, FilterDefinition <TCollection> filterDefinition, Collation collation = null) where TCollection : DataEntityBase { IMongoCollection <TCollection> collection = GetCollection <TCollection>(); Logger.Trace($"{nameof(MongoStore)}.{nameof(Distinct)}", new LogItem("Event", "Get distinct"), new LogItem("FieldType", typeof(TField).ToString), new LogItem("CollectionType", typeof(TCollection).ToString), new LogItem("FieldSelector", fieldSelector.ToString), new LogItem("FilterDefinition", filterDefinition.ToString)); DistinctOptions distinctOptions = new DistinctOptions() { Collation = collation }; using (IAsyncCursor <TField> cursor = collection.Distinct(fieldSelector, filterDefinition, distinctOptions)) foreach (TField p in IterateCursor(cursor)) { yield return(p); } }
/** Get an updated type of heroes array */ public static async void GetCurrentHeroes() { try { /* Get all docs from collection */ IMongoCollection <BsonDocument> mainCollection = DB.mainCollection; using (IAsyncCursor <BsonDocument> task = await mainCollection.FindAsync(Builders <BsonDocument> .Filter.Empty)) { List <BsonDocument> docs = await task.ToListAsync(); /* Retrieve heroes document and deserialize it into array */ BsonDocument heroesDocument = docs.FirstOrDefault(); BsonValue heroesValue = heroesDocument["heroes"]; List <Hero> heroesObj = BsonSerializer.Deserialize <List <Hero> >(heroesValue.ToJson()); Hero[] currHeroes = heroesObj.ToArray(); heroes = currHeroes; DB_Changed = false; } } catch (Exception exception) { Console.WriteLine(exception.Message); } }
static async Task MainAsync() { var collection = silcoDB.GetCollection <BsonDocument>("VehWeapons"); using (IAsyncCursor <BsonDocument> cursor = await collection.FindAsync(new BsonDocument())) { while (await cursor.MoveNextAsync()) { IEnumerable <BsonDocument> batch = cursor.Current; availWeapList.Clear(); foreach (BsonDocument x in batch) { VehWeapon nWeapon = new VehWeapon(ret(x, 1), ret(x, 2), ret(x, 3), ret(x, 4), ret(x, 5), ret(x, 6), ret(x, 7), ret(x, 8), ret(x, 9), ret(x, 10), (Int32)x.GetValue(11), (Int32)x.GetValue(12)); availWeapList.Add(nWeapon); //VehWeapon x = new VehWeapon(); // MessageBox.Show(nWeapon.name + " " + nWeapon.range); } } } String ret(BsonDocument doc, int input) { String r = doc.GetValue(input).ToString(); return(r); } }
public AsyncCursorEnumerator(IAsyncCursor <T> cursor) => _cursor = cursor;
/// <summary> /// Calls a delegate for each document returned by the cursor. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> /// <param name="source">The source.</param> /// <param name="processor">The processor.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A Task that completes when all the documents have been processed.</returns> public static Task ForEachAsync <TDocument>(this IAsyncCursor <TDocument> source, Func <TDocument, Task> processor, CancellationToken cancellationToken = default(CancellationToken)) { return(ForEachAsync(source, (doc, _) => processor(doc), cancellationToken)); }
private async Task GetFirstBatchAsync(CancellationToken cancellationToken) { var operation = CreateFirstBatchOperation(); _cursor = await operation.ExecuteAsync(Binding, cancellationToken).ConfigureAwait(false); await GetNextBatchAsync(cancellationToken).ConfigureAwait(false); }
private void GetFirstBatch(CancellationToken cancellationToken) { var operation = CreateFirstBatchOperation(); _cursor = operation.Execute(Binding, cancellationToken); GetNextBatch(cancellationToken); }
private async Task<IEnumerable<IEvent>> CollectEventsAsync(int limit, IAsyncCursor<BsonDocument> cursor) { var result = new List<IEvent>(); while (await cursor.MoveNextAsync()) { var currentDocuments = cursor.Current; foreach (var currentDocument in currentDocuments) { var commit = _commitSerializer.Deserialize(currentDocument); foreach (var eventId in commit.EventIds) { var eventDocument = await _eventDao.GetByAsync(eventId); var eventContainer = _eventContainerSerializer.Deserialize(eventDocument); result.Add(eventContainer.Event); if (result.Count >= limit) return result; } } } return result; }
/// <summary> /// Setup the oplog tailing cursor. /// </summary> /// <param name="startOplog">The oplog to start at.</param> /// <returns>A task.</returns> public virtual async Task Tail(Oplog startOplog = null) { if(m_cursor != null) { throw new MongoRiverException("We're already talking to the oplog"); } FilterDefinition<Oplog> filter = new BsonDocument(); if(startOplog != null) { filter = Builders<Oplog>.Filter.Gt(o => o.Timestamp, startOplog.Timestamp); } var options = new FindOptions<Oplog, Oplog> { CursorType = CursorType.TailableAwait, NoCursorTimeout = true }; m_cursor = await m_oplogCollection.FindAsync<Oplog>(filter, options); }
// constructors public AsyncCursorEnumerableOneTimeAdapter(IAsyncCursor <TDocument> cursor, CancellationToken cancellationToken) { _cursor = Ensure.IsNotNull(cursor, nameof(cursor)); _cancellationToken = cancellationToken; }
/// <summary> /// Clean up. /// </summary> public virtual void Dispose() { if(m_cursor != null) { m_cursor.Dispose(); m_cursor = null; } m_stopped = false; }
/// <summary> /// Wraps a cursor in an IEnumerable that can be enumerated one time. /// </summary> /// <typeparam name="TItem">The type of the item.</typeparam> /// <param name="cursor">The cursor.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An IEnumerable</returns> public static IEnumerable <TItem> ToEnumerable <TItem>(this IAsyncCursor <TItem> cursor, CancellationToken cancellationToken = default(CancellationToken)) { return(new AsyncCursorEnumerableAdapter <TItem>(cursor, cancellationToken)); }
//public async Task AddItemAsync(MyItem item) //{ // await this._container.CreateItemAsync<MyItem>(item, new PartitionKey(item.Id)); //} //public async Task DeleteItemAsync(string id) //{ // await this._container.DeleteItemAsync<MyItem>(id, new PartitionKey(id)); //} //public async Task<MyItem> GetItemAsync(string id) //{ // try // { // ItemResponse<MyItem> response = await this._container.ReadItemAsync<MyItem>(id, new PartitionKey(id)); // return response.Resource; // } // catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) // { // return null; // } //} public async Task <IEnumerable <MyItem> > GetItemsAsync() { IAsyncCursor <MyItem> result = await _collection.FindAsync(FilterDefinition <MyItem> .Empty).ConfigureAwait(false); return(result.ToList()); }
// constructor public AsyncCursorEnumeratorAdapter(IAsyncCursor <TDocument> cursor, CancellationToken cancellationToken) { _cursor = Ensure.IsNotNull(cursor, "cursor"); _cancellationToken = cancellationToken; }
/// <summary> /// Calls a delegate for each item returned by the cursor. /// </summary> /// <remarks> /// If your delegate is going to take a long time to execute or is going to block /// consider using a different overload of ForEachAsync that uses a delegate that /// returns a Task instead. /// </remarks> /// <typeparam name="TItem">The type of the item.</typeparam> /// <param name="source">The source.</param> /// <param name="processor">The processor.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A Task that completes when all the items have been processed.</returns> public static Task ForEachAsync <TItem>(this IAsyncCursor <TItem> source, Action <TItem> processor, CancellationToken cancellationToken = default(CancellationToken)) { return(ForEachAsync(source, (doc, _) => processor(doc), cancellationToken)); }
// constructor public AsyncCursorEnumeratorAdapter(IAsyncCursor <TDocument> cursor) { _cursor = Ensure.IsNotNull(cursor, "cursor"); }
private IAsyncCursor <string> CreateDatabaseNamesCursor(IAsyncCursor <BsonDocument> cursor) { return(new BatchTransformingAsyncCursor <BsonDocument, string>( cursor, databases => databases.Select(database => database["name"].AsString))); }
public async Task <IActionResult> GetDeclarations(Guid taskID, [FromServices] IMongoCollection <PersonTaskCompletionDeclaration> mongoCollection) { IAsyncCursor <PersonTaskCompletionDeclaration> cursor = await mongoCollection.FindAsync(x => x.Task == taskID); return(new JsonResult(await cursor.ToListAsync())); }
public async Task <IActionResult> GetTasksAsync(Guid taskListID, [FromServices] IMongoCollection <DataModels.TaskLists.Task> mongoCollection) { IAsyncCursor <DataModels.TaskLists.Task> cursor = await mongoCollection.FindAsync(x => x.OwnerID == taskListID); return(new JsonResult(new { Type = "Success", Details = await cursor.ToListAsync() })); }
public async Task <AirplaneEntity> Get(string regNo) { IAsyncCursor <AirplaneEntity> _Results = await _AirplanesCollection.FindAsync(plane => plane.RegNo == regNo); return(await _Results.FirstOrDefaultAsync()); }
public async Task <List <AirplaneEntity> > Get() { IAsyncCursor <AirplaneEntity> _Results = await _AirplanesCollection.FindAsync(plane => true); return(await _Results.ToListAsync()); }
// private methods private async Task GetFirstBatchAsync(CancellationToken cancellationToken) { var chunksCollectionNamespace = Bucket.GetChunksCollectionNamespace(); var messageEncoderSettings = Bucket.GetMessageEncoderSettings(); #pragma warning disable 618 var filter = new BsonDocument("files_id", FilesCollectionDocument.IdAsBsonValue); #pragma warning restore var sort = new BsonDocument("n", 1); var operation = new FindOperation<BsonDocument>( chunksCollectionNamespace, BsonDocumentSerializer.Instance, messageEncoderSettings) { Filter = filter, Sort = sort }; _cursor = await operation.ExecuteAsync(Binding, cancellationToken).ConfigureAwait(false); await GetNextBatchAsync(cancellationToken).ConfigureAwait(false); }