private async Task<IList<JsonDocument>> GetNextBatch(IAsyncEnumerator<JsonDocument> documentsStream, CancellationToken token) { var documents = new List<JsonDocument>(); var count = 0; while (await documentsStream.MoveNextAsync().ConfigureAwait(false) && count < BatchSize) { documents.Add(documentsStream.Current); count++; token.ThrowIfCancellationRequested(); } return documents; }
public async Task <UserRole> AssignRole(Guid userId, Guid roleId, Guid currentUser) { if (Guid.Empty == userId) { throw new AppException("UserId is required"); } if (Guid.Empty == roleId) { throw new AppException("RoleId is required"); } if (Guid.Empty == currentUser) { throw new AppException("Current user is required"); } IAsyncEnumerator <Data.Entities.Role> _role = GetRolesByUserId(userId).GetAsyncEnumerator(); while (await _role.MoveNextAsync()) { if (_role.Current.Id == roleId) { throw new AppException("User already assigned this role."); } } Data.Entities.User user = _context.Users.Find(userId); Data.Entities.Role role = _context.Roles.Find(roleId); Guid newUserRoleId = Guid.NewGuid(); UserRole userRole = new UserRole { Id = newUserRoleId, User = user, Role = role, CreatedBy = currentUser != Guid.Empty ? currentUser : userId, CreatedDate = DateTime.Now, DeletedBy = null, DeletedDate = null, }; _context.UserRoles.Add(userRole); _context.SaveChanges(); return(userRole); }
private async Task StreamResultsAsync(string invocationId, HubConnectionContext connection, IAsyncEnumerator <object> enumerator, IServiceScope scope, IHubActivator <THub> hubActivator, THub hub, CancellationTokenSource streamCts) { string error = null; using (scope) { try { while (await enumerator.MoveNextAsync()) { // Send the stream item await connection.WriteAsync(new StreamItemMessage(invocationId, enumerator.Current)); } } catch (ChannelClosedException ex) { // If the channel closes from an exception in the streaming method, grab the innerException for the error from the streaming method error = ErrorMessageHelper.BuildErrorMessage("An error occurred on the server while streaming results.", ex.InnerException ?? ex, _enableDetailedErrors); } catch (Exception ex) { // If the streaming method was canceled we don't want to send a HubException message - this is not an error case if (!(ex is OperationCanceledException && connection.ActiveRequestCancellationSources.TryGetValue(invocationId, out var cts) && cts.IsCancellationRequested)) { error = ErrorMessageHelper.BuildErrorMessage("An error occurred on the server while streaming results.", ex, _enableDetailedErrors); } } finally { (enumerator as IDisposable)?.Dispose(); hubActivator.Release(hub); // Dispose the linked CTS for the stream. streamCts.Dispose(); await connection.WriteAsync(CompletionMessage.WithError(invocationId, error)); if (connection.ActiveRequestCancellationSources.TryRemove(invocationId, out var cts)) { cts.Dispose(); } } } }
public async Task <SharedDocumentData[]> getSharedDocument(string email) { int sharedDocumentCount = 0; Boolean connectionResult = connectToFirebase(); DocumentReference documentReference = db.Collection("SharedDocuments").Document(email); IAsyncEnumerable <CollectionReference> collectionRefrences = documentReference.ListCollectionsAsync(); IAsyncEnumerator <CollectionReference> enumerator = collectionRefrences.GetAsyncEnumerator(); while (await enumerator.MoveNextAsync()) { CollectionReference collectionReference = enumerator.Current; Query allDocumentsQuery = documentReference.Collection(collectionReference.Id); QuerySnapshot snaps = await allDocumentsQuery.GetSnapshotAsync(); foreach (DocumentSnapshot snap in snaps) { sharedDocumentCount++; } } SharedDocumentData[] sharedDocuments = new SharedDocumentData[sharedDocumentCount]; IAsyncEnumerator <CollectionReference> enumerator1 = collectionRefrences.GetAsyncEnumerator(); int i = 0; while (await enumerator1.MoveNextAsync()) { CollectionReference collectionReference = enumerator1.Current; Query allDocumentsQuery = documentReference.Collection(collectionReference.Id); QuerySnapshot snaps = await allDocumentsQuery.GetSnapshotAsync(); foreach (DocumentSnapshot snap in snaps) { DBSharedDocumentData dBSharedDocumentData = snap.ConvertTo <DBSharedDocumentData>(); sharedDocuments[i] = new SharedDocumentData(); sharedDocuments[i].fileName = dBSharedDocumentData.fileName; sharedDocuments[i].fileLink = dBSharedDocumentData.fileLink; sharedDocuments[i].sharedBy = dBSharedDocumentData.sharedBy; i++; } } return(sharedDocuments); }
public async Task <IActionResult> Index() { var productList = new List <ProductModel>(); var productServiceClient = new ProductServiceClient(); IAsyncEnumerator <ProductModel> products = productServiceClient.GetAllProducts(); while (await products.MoveNextAsync()) { productList.Add(products.Current); } await products.DisposeAsync(); if (productList != null) { productList = productList.OrderByDescending(x => x.DateAdded).Take(3).ToList(); } return(View(productList)); // var productEntities = new List<ProductModel>(); // productEntities.Add(new ProductModel(){ // Id = 1, // Name = "Laptop", // Price = 25000, // OldPrice = 3000, // Description = "Laptop", // ProductImage = "/Images/asus gtx 1070 strix.png", // Rating = 5, // ReviewCount = 2, // Category = "Hardware", // Manufacturers = "Azus" // }); // productEntities.Add(new ProductModel(){ // Id = 2, // Name = "Mobile", // Price = 10000, // OldPrice = 10000, // Description = "Mobile", // ProductImage = "/Images/asus gtx 1070 strix.png", // Rating = 5, // ReviewCount = 4, // Category = "Mobile", // Manufacturers = "Azus" // }); }
public async Task Test429sWithContinuationsAsync() { int numItems = 100; IDocumentContainer inMemoryCollection = await this.CreateDocumentContainerAsync( numItems, new FlakyDocumentContainer.FailureConfigs( inject429s: true, injectEmptyPages: false)); IAsyncEnumerator <TryCatch <TPage> > enumerator = this.CreateEnumerator(inMemoryCollection); HashSet <string> identifiers = new HashSet <string>(); TState state = default; while (await enumerator.MoveNextAsync()) { TryCatch <TPage> tryGetPage = enumerator.Current; if (tryGetPage.Failed) { Exception exception = tryGetPage.Exception; while (exception.InnerException != null) { exception = exception.InnerException; } if (!((exception is CosmosException cosmosException) && (cosmosException.StatusCode == (System.Net.HttpStatusCode) 429))) { throw tryGetPage.Exception; } // Create a new enumerator from that state to simulate when the user want's to start resume later from a continuation token. enumerator = this.CreateEnumerator(inMemoryCollection, state); } else { IReadOnlyList <Record> records = this.GetRecordsFromPage(tryGetPage.Result); foreach (Record record in records) { identifiers.Add(record.Identifier); } state = tryGetPage.Result.State; } } Assert.AreEqual(numItems, identifiers.Count); }
private static async Task Main() { // await foreach await foreach (var i in RunAsync()) { Console.WriteLine(i); } // Equals to this, nothing runs on parallel IAsyncEnumerator <int> asyncEnumerator = RunAsync().GetAsyncEnumerator(); // Move next is not blocking, unlike normal IEnumerable<T> while (await asyncEnumerator.MoveNextAsync()) { Console.WriteLine(asyncEnumerator.Current); } }
static async Task AwaitAndYieldReturnMain() { await foreach (int item in AwaitAndYieldReturn()) { Console.WriteLine($"Got {item}"); } // same as: await using (IAsyncEnumerator <int> enumerator = AwaitAndYieldReturn().GetAsyncEnumerator()) { while (await enumerator.MoveNextAsync()) { int item = enumerator.Current; Console.WriteLine($"Got {item}"); } } }
/// <summary> /// Converts an async enumerable into a dictionary. /// </summary> /// <typeparam name="T">The type of the objects to iterate.</typeparam> /// <typeparam name="TKey">The type of keys</typeparam> /// <param name="source">The source enumerable to iterate.</param> /// <param name="keySelector">Function of T which creates a key</param> /// <param name="cancellationToken">The cancellation token to use.</param> /// <returns>Dictionary of T with TKey keys</returns> public static async Task <Dictionary <TKey, T> > ToDictionaryAsync <T, TKey>(this IAsyncEnumerable <T> source, Func <T, TKey> keySelector, CancellationToken cancellationToken = default) { if (source == null) { throw new ArgumentNullException(nameof(source)); } Dictionary <TKey, T> dic = new Dictionary <TKey, T>(); await using (IAsyncEnumerator <T> e = source.GetAsyncEnumerator(cancellationToken)) while (await e.MoveNextAsync()) { dic.Add(keySelector(e.Current), e.Current); } return(dic); }
/// <summary> /// Returns true if all the elements of the source sequence match the predicate. /// </summary> public static async Task <bool> AllAsync <TSource>(this IAsyncEnumerator <TSource> source, Func <TSource, bool> predicate) { while (true) { bool success; var value = source.TryGetNext(out success); if (success && !predicate(value)) { return(false); } if (!(await source.MoveNextAsync().ConfigureAwait(false))) { return(true); } } }
/// <summary> /// Returns the first element of the source sequence, or default if empty. /// </summary> public static async Task <TSource> FirstOrDefaultAsync <TSource>(this IAsyncEnumerator <TSource> source) { while (true) { bool success; var value = source.TryGetNext(out success); if (success) { return(value); } if (!(await source.MoveNextAsync().ConfigureAwait(false))) { return(default(TSource)); } } }
private async Task StreamResultsAsync(string invocationId, HubConnectionContext connection, IAsyncEnumerator <object> enumerator) { try { while (await enumerator.MoveNextAsync()) { // Send the stream item await SendMessageAsync(connection, new StreamItemMessage(invocationId, enumerator.Current)); } await SendMessageAsync(connection, CompletionMessage.Empty(invocationId)); } catch (Exception ex) { await SendMessageAsync(connection, CompletionMessage.WithError(invocationId, ex.Message)); } }
private async Task FinishRemovalOfSubscriptions(IReliableDictionary <string, string> subscriptions) { using (ITransaction tx = this.StateManager.CreateTransaction()) { var unregisteredServices = new List <string>(); IAsyncEnumerable <KeyValuePair <string, string> > asyncEnumerable = await subscriptions.CreateEnumerableAsync(tx).ConfigureAwait(false); using (IAsyncEnumerator <KeyValuePair <string, string> > asyncEnumerator = asyncEnumerable.GetAsyncEnumerator()) { while (await asyncEnumerator.MoveNextAsync(CancellationToken.None).ConfigureAwait(false)) { string subscriber = asyncEnumerator.Current.Key; string topic = asyncEnumerator.Current.Value; try { // https://social.msdn.microsoft.com/Forums/en-US/ce8aff1d-6246-4b53-9075-13b738a24b13/best-way-to-determine-if-a-service-already-exists?forum=AzureServiceFabric // treat as "Desired state management" // "Instead treat this more like desired state management - create the service until you are told it already exists." Uri serviceUri = this.Context.CreateSubscriptionUri(topic, subscriber); var description = new DeleteServiceDescription(serviceUri); using (var fabric = new FabricClient()) { await fabric.ServiceManager.DeleteServiceAsync(description); } } catch (FabricElementNotFoundException) { await UnregisterSubscriberFromTopic(subscriber, topic); unregisteredServices.Add(subscriber); } } } // do after enumerator is complete. foreach (var sub in unregisteredServices) { await subscriptions.TryRemoveAsync(tx, sub); } await tx.CommitAsync(); } }
public async Task AsyncPageableLoop() { // create a client var client = new SecretClient(new Uri("http://example.com"), new DefaultAzureCredential()); #region Snippet:AsyncPageableLoop // call a service method, which returns AsyncPageable<T> AsyncPageable <SecretProperties> response = client.GetPropertiesOfSecretsAsync(); IAsyncEnumerator <SecretProperties> enumerator = response.GetAsyncEnumerator(); while (await enumerator.MoveNextAsync()) { SecretProperties secretProperties = enumerator.Current; Console.WriteLine(secretProperties.Name); } #endregion }
public async Task <IActionResult> SearchDevicesHistory(string deviceId = null, long searchIntervalStart = 86400000, long searchIntervalEnd = 0, int limit = 0) { List <DeviceMessage> deviceMessages = new List <DeviceMessage>(); IReliableDictionary <DateTimeOffset, DeviceMessage> storeCompletedMessages = storeCompletedMessages = await this.stateManager.GetOrAddAsync <IReliableDictionary <DateTimeOffset, DeviceMessage> >(TargetSolution.Names.EventHistoryDictionaryName); if (storeCompletedMessages != null) { DateTimeOffset intervalToSearchStart = DateTimeOffset.UtcNow.AddMilliseconds(searchIntervalStart * (-1)); DateTimeOffset intervalToSearchEnd = DateTimeOffset.UtcNow.AddMilliseconds(searchIntervalEnd * (-1)); float selectInterval = 1F; if (limit != 0) { int totalCount = await SearchDevicesHistoryCountInternal(intervalToSearchStart.ToString("u"), intervalToSearchEnd.ToString("u"), deviceId); if (totalCount > limit) { selectInterval = totalCount / limit; } } using (ITransaction tx = this.stateManager.CreateTransaction()) { IAsyncEnumerable <KeyValuePair <DateTimeOffset, DeviceMessage> > enumerable = await storeCompletedMessages.CreateEnumerableAsync( tx, key => (key.CompareTo(intervalToSearchStart) > 0) && (key.CompareTo(intervalToSearchEnd) <= 0), EnumerationMode.Ordered); IAsyncEnumerator <KeyValuePair <DateTimeOffset, DeviceMessage> > enumerator = enumerable.GetAsyncEnumerator(); int index = 0; int itemsAdded = 0; while (await enumerator.MoveNextAsync(appLifetime.ApplicationStopping)) { if (index >= (itemsAdded * selectInterval)) { itemsAdded++; deviceMessages.Add(enumerator.Current.Value); } index++; } await tx.CommitAsync(); } } return(this.Ok(deviceMessages)); }
/// <summary> /// Counts the number of items that pass the given predicate. /// </summary> /// <typeparam name="TSource"></typeparam> /// <param name="source"></param> /// <param name="predicate"></param> /// <returns></returns> public static async Task <int> CountAsync <TSource>(this IAsyncEnumerable <TSource> source, Func <TSource, bool> predicate) { int count = 0; using (IAsyncEnumerator <TSource> asyncEnumerator = source.GetAsyncEnumerator()) { while (await asyncEnumerator.MoveNextAsync(CancellationToken.None).ConfigureAwait(false)) { if (predicate(asyncEnumerator.Current)) { count++; } } } return(count); }
public async Task <bool> MoveNextAsync() { var n = remaining; if (n <= 0) { return(false); } remaining = n - 1; if (await enumerator.MoveNextAsync()) { current = enumerator.Current; return(true); } current = default; return(false); }
public async ValueTask <bool> MoveNextAsync() { for (; ;) { if (await _source.MoveNextAsync()) { if (_collection.Add(_keySelector(_source.Current))) { return(true); } } else { return(false); } } }
public static async Task <List <T> > ToList <T>(this IAsyncEnumerable <T> collection) { IAsyncEnumerator <T> enumerator = collection.GetAsyncEnumerator(); try { List <T> list = new List <T>(); while (await enumerator.MoveNextAsync()) { list.Add(enumerator.Current); } return(list); } finally { await enumerator.DisposeAsync(); } }
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Global public static async ValueTask AssertResult <T>(this IAsyncEnumerator <T> source, params T[] values) { var main = default(Exception); var dispose = default(Exception); var idx = 0; try { while (await source.MoveNextAsync()) { Assert.True(idx < values.Length, "Source has more than the expected " + values.Length + " items"); Assert.Equal(values[idx], source.Current); idx++; } Assert.True(values.Length == idx, "Source has less items than expected: " + values.Length + ", actual: " + idx); } catch (Exception ex) { main = ex; } finally { try { await source.DisposeAsync(); } catch (Exception ex) { dispose = ex; } } if (main != null && dispose != null) { throw new AggregateException(main, dispose); } if (main != null) { throw main; } if (dispose != null) { throw dispose; } }
private async System.Threading.Tasks.Task <List <JobModel> > ListJobsAsync() { List <JobModel> results = new List <JobModel>(); var detailLevel = new ODATADetailLevel() { SelectClause = "name,state,creationTime" }; IEnumerableAsyncExtended <ICloudJob> jobList = this.WorkItem.ListJobs(detailLevel); IAsyncEnumerator <ICloudJob> asyncEnumerator = jobList.GetAsyncEnumerator(); while (await asyncEnumerator.MoveNextAsync()) { results.Add(new JobModel(this, asyncEnumerator.Current)); } return(results); }
public static async ValueTask <int> CountAsync <TSource>(this IAsyncEnumerable <TSource> source) { int count = 0; await using (IAsyncEnumerator <TSource> e = source.GetAsyncEnumerator()) { checked { while (await e.MoveNextAsync()) { count++; } } } return(count); }
/// <summary> /// Converts an async enumerable into a list. /// </summary> /// <typeparam name="T">The type of the objects to iterate.</typeparam> /// <param name="source">The source enumerable to iterate.</param> /// <param name="cancellationToken">The cancellation token to use.</param> /// <returns>List of T</returns> public static async Task <List <T> > ToListAsync <T>(this IAsyncEnumerable <T> source, CancellationToken cancellationToken = default) { if (source == null) { throw new ArgumentNullException(nameof(source)); } List <T> l = new List <T>(); await using (IAsyncEnumerator <T> e = source.GetAsyncEnumerator(cancellationToken)) while (await e.MoveNextAsync()) { l.Add(e.Current); } return(l); }
public override async Task <bool> WaitForNextAsync() { switch (_state) { case 1: _enumerator = _source.GetAsyncEnumerator(); _state = 2; goto case 2; case 2: _hasNext = await _enumerator.MoveNextAsync().ConfigureAwait(false); return(_hasNext); } return(false); }
/// <summary> /// Enumerates over all elements in the collection asynchronously /// </summary> /// <param name="enumerator">The collection of elements which can be enumerated asynchronously</param> /// <param name="action">A synchronous action to perform for every single item in the collection</param> /// <returns>Returns a Task which does enumeration over elements in the collection</returns> public static async Task ForEachAsync(this IAsyncEnumerator enumerator, Action <object> action) { try { while (await enumerator.MoveNextAsync().ConfigureAwait(false)) { action(enumerator.Current); } } catch (ForEachAsyncBreakException) { } finally { await enumerator.DisposeAsync().ConfigureAwait(false); } }
protected async Task <bool> LoadFromEnumeratorAsync() { if (await _enumerator.MoveNextAsync().ConfigureAwait(false)) { _current = _enumerator.Current; return(true); } if (_enumerator != null) { await _enumerator.DisposeAsync().ConfigureAwait(false); _enumerator = null; } return(false); }
public async ValueTask <bool> MoveNextAsync() { for (; ;) { if (await _source.MoveNextAsync()) { if (_predicate(_source.Current)) { return(true); } } else { return(false); } } }
protected override async ValueTask <bool> MoveNextCore() { switch (_state) { case AsyncIteratorState.Allocated: _enumerator = _source.GetAsyncEnumerator(_cancellationToken); _hasSkipped = false; _taken = 0; _state = AsyncIteratorState.Iterating; goto case AsyncIteratorState.Iterating; case AsyncIteratorState.Iterating: if (!_hasSkipped) { if (!await SkipBeforeFirstAsync(_enumerator).ConfigureAwait(false)) { // Reached the end before we finished skipping. break; } _hasSkipped = true; } if ((!HasLimit || _taken < Limit) && await _enumerator.MoveNextAsync().ConfigureAwait(false)) { if (HasLimit) { // If we are taking an unknown number of elements, it's important not to increment _state. // _state - 3 may eventually end up overflowing & we'll hit the Dispose branch even though // we haven't finished enumerating. _taken++; } _current = _enumerator.Current; return(true); } break; } await DisposeAsync().ConfigureAwait(false); return(false); }
public async Task <string> DisconfigureService(string serviceName, string primaryCluster, string secondaryCluster) { List <String> keysToRemove = new List <String>(); IReliableDictionary <String, PartitionWrapper> myDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <String, PartitionWrapper> >("partitionDictionary"); using (ITransaction tx = this.StateManager.CreateTransaction()) { IAsyncEnumerable <KeyValuePair <String, PartitionWrapper> > enumerable = await myDictionary.CreateEnumerableAsync(tx); IAsyncEnumerator <KeyValuePair <String, PartitionWrapper> > asyncEnumerator = enumerable.GetAsyncEnumerator(); while (await asyncEnumerator.MoveNextAsync(CancellationToken.None)) { PartitionWrapper secondaryPartition = asyncEnumerator.Current.Value; String partitionAccessKey = asyncEnumerator.Current.Key; if (Utility.isPartitionFromPrimarySecondaryCombination(partitionAccessKey, primaryCluster, secondaryCluster)) { if (secondaryPartition.serviceName.ToString().Equals(serviceName)) { keysToRemove.Add(asyncEnumerator.Current.Key); } } } await tx.CommitAsync(); } bool allPartitionsRemoved = true; using (ITransaction tx = this.StateManager.CreateTransaction()) { foreach (String key in keysToRemove) { ConditionalValue <PartitionWrapper> value = myDictionary.TryRemoveAsync(tx, key).Result; if (!value.HasValue) { allPartitionsRemoved = false; } } await tx.CommitAsync(); } if (allPartitionsRemoved) { return(serviceName); } return(null); }
public async Task <bool> MoveNextAsync() { _prev?.Dispose(); // dispose the previous instance while (true) { if (await _enumerator.MoveNextAsync().WithCancellation(_token).ConfigureAwait(false) == false) { return(false); } _prev = _enumerator.Current; _query?.InvokeAfterStreamExecuted(_enumerator.Current); Current = CreateStreamResult(_enumerator.Current); return(true); } }
public bool MoveNext() { _enumerator ??= _enumeratorFunc.Invoke(); if (_index < _buffer.Count - 1) { ++_index; return(true); } if (_enumerator.MoveNextAsync().Result) { _buffer.Add(_enumerator.Current); ++_index; return(true); } return(false); }