private async Task <long> SearchDevicesHistoryCountInternal(string startTimestamp, string endTimestamp = null, string deviceId = null)
        {
            long lRet = await GetQueueLengthAsyncInternal();

            IReliableDictionary <DateTimeOffset, DeviceEventSeries> storeCompletedMessages = storeCompletedMessages = await this.stateManager.GetOrAddAsync <IReliableDictionary <DateTimeOffset, DeviceEventSeries> >(TargetSolution.Names.EventHistoryDictionaryName);

            if (storeCompletedMessages != null)
            {
                DateTimeOffset intervalToSearchStart = DateTimeOffset.Parse(startTimestamp).ToUniversalTime();
                DateTimeOffset intervalToSearchEnd   = DateTimeOffset.UtcNow;


                using (ITransaction tx = this.stateManager.CreateTransaction())
                {
                    IAsyncEnumerable <KeyValuePair <DateTimeOffset, DeviceEventSeries> > enumerable = await storeCompletedMessages.CreateEnumerableAsync(tx, EnumerationMode.Ordered);

                    IAsyncEnumerator <KeyValuePair <DateTimeOffset, DeviceEventSeries> > enumerator = enumerable.GetAsyncEnumerator();

                    await enumerator.MoveNextAsync(appLifetime.ApplicationStopping);

                    if (lRet > 0 && enumerator.Current.Key.CompareTo(intervalToSearchStart) < 0)
                    {
                        lRet = 0;
                        if (endTimestamp == null)
                        {
                            enumerable = await storeCompletedMessages.CreateEnumerableAsync(
                                tx, key => (key.CompareTo(intervalToSearchStart) >= 0), EnumerationMode.Ordered);
                        }
                        else
                        {
                            intervalToSearchEnd = DateTimeOffset.Parse(endTimestamp);
                            enumerable          = await storeCompletedMessages.CreateEnumerableAsync(
                                tx, key => (key.CompareTo(intervalToSearchStart) >= 0) && (key.CompareTo(intervalToSearchEnd) <= 0), EnumerationMode.Ordered);
                        }

                        enumerator = enumerable.GetAsyncEnumerator();

                        while (await enumerator.MoveNextAsync(appLifetime.ApplicationStopping))
                        {
                            lRet++;
                        }
                    }
                    await tx.CommitAsync();
                }
            }
            ServiceEventSource.Current.ServiceMessage(this.context, $"DataService - SearchDevicesHistoryCount - Count of[{lRet}] for data range from [{startTimestamp}] to [{endTimestamp ?? "empty"}] - device [{deviceId ?? "All"}]");

            return(lRet);
        }
Пример #2
0
        public async Task <List <VehicleModel> > GetVehicles(CancellationToken cancellationToken)
        {
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                IReliableDictionary <Guid, VehicleModel> vehicleDictionary = await GetVehicleModelsFromReliableStateAsync();

                List <VehicleModel> vehicleModels = new List <VehicleModel>();

                using (ITransaction tx = _stateManager.CreateTransaction())
                {
                    Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <Guid, VehicleModel> > allVehicles =
                        await vehicleDictionary.CreateEnumerableAsync(tx, EnumerationMode.Unordered);

                    using (Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <Guid, VehicleModel> > enumertor =
                               allVehicles.GetAsyncEnumerator())
                    {
                        while (await enumertor.MoveNextAsync(CancellationToken.None))
                        {
                            KeyValuePair <Guid, VehicleModel> current = enumertor.Current;
                            vehicleModels.Add(current.Value);
                        }
                    }
                }

                return(vehicleModels);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task <IEnumerable <Domain.CustomerInformation> > GetCustomerInformationAsync(CancellationToken ct)
        {
            IList <Domain.CustomerInformation> results = new List <Domain.CustomerInformation>();

            IReliableDictionary <string, Domain.CustomerInformation> customers =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, Domain.CustomerInformation> >(CustomerInformationDictionary);

            ServiceEventSource.Current.Message("Called CustomerInformationDictionary to return CustomerInformation");

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ServiceEventSource.Current.Message("Generating item views for {0} items", await customers.GetCountAsync(tx));

                IAsyncEnumerator <KeyValuePair <string, Domain.CustomerInformation> > enumerator =
                    (await customers.CreateEnumerableAsync(tx)).GetAsyncEnumerator();

                while (await enumerator.MoveNextAsync(ct))
                {
                    results.Add(enumerator.Current.Value);
                }
            }


            return(results);
        }
Пример #4
0
        public async Task <IEnumerable <perStoryData> > GetAllStoryPointData()
        {
            IReliableDictionary <Guid, perStoryData> storypointdata =
                await _stateManager.GetOrAddAsync <IReliableDictionary <Guid, perStoryData> >("storypointdata");

            var result = new List <perStoryData>();

            using (ITransaction tx = _stateManager.CreateTransaction())
            {
                Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <Guid, perStoryData> > allstorypointdata =
                    await storypointdata.CreateEnumerableAsync(tx, EnumerationMode.Unordered);

                using (Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <Guid, perStoryData> > enumerator =
                           allstorypointdata.GetAsyncEnumerator())
                {
                    while (await enumerator.MoveNextAsync(CancellationToken.None))
                    {
                        KeyValuePair <Guid, perStoryData> current = enumerator.Current;
                        result.Add(current.Value);
                    }
                }
            }

            return(result);
        }
Пример #5
0
        public async Task <List <KeyValuePair <string, int> > > GetAllVoteCounts()
        {
            ServiceEventSource.Current.Message("VotingData.GetAllVoteCounts start.");
            List <KeyValuePair <string, int> > kvps = new List <KeyValuePair <string, int> >();

            IReliableDictionary <string, int> votesDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, int> >("votes");

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                if (votesDictionary != null)
                {
                    IAsyncEnumerable <KeyValuePair <string, int> > e = await votesDictionary.CreateEnumerableAsync(tx);

                    IAsyncEnumerator <KeyValuePair <string, int> > items = e.GetAsyncEnumerator();

                    while (await items.MoveNextAsync(new CancellationToken()))
                    {
                        kvps.Add(new KeyValuePair <string, int>(items.Current.Key, items.Current.Value));
                    }

                    //kvps.Sort((x, y) => x.Value.CompareTo(y.Value) * -1);  // intentionally commented out!
                }
                await tx.CommitAsync();
            }

            ServiceEventSource.Current.Message($"VotingData.GetAllVoteCounts end. Number of keys: {kvps.Count.ToString()}");
            return(kvps);
        }
Пример #6
0
 public static Task ForeachAsync <TKey, TValue>(
     this IReliableDictionary <TKey, TValue> instance, ITransaction tx, CancellationToken token, EnumerationMode enumMode, Func <TKey, bool> filter,
     Action <KeyValuePair <TKey, TValue> > doSomething)
     where TKey : IEquatable <TKey>, IComparable <TKey>
 {
     return(ForeachAsync <TKey, TValue>(instance.CreateEnumerableAsync(tx, filter, enumMode), token, doSomething));
 }
Пример #7
0
        public async Task <IActionResult> Get()
        {
            try
            {
                CancellationToken ct = new CancellationToken();
                IReliableDictionary <string, string> votesDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, string> >(Enums.StateName.VoterIdVoteForPair.ToString());

                using (ITransaction tx = this.stateManager.CreateTransaction())
                {
                    IAsyncEnumerable <KeyValuePair <string, string> > list = await votesDictionary.CreateEnumerableAsync(tx);

                    IAsyncEnumerator <KeyValuePair <string, string> > enumerator = list.GetAsyncEnumerator();
                    Dictionary <string, int> dictionary = new Dictionary <string, int>();

                    while (await enumerator.MoveNextAsync(ct))
                    {
                        if (dictionary.ContainsKey(enumerator.Current.Value))
                        {
                            dictionary[enumerator.Current.Value] = dictionary[enumerator.Current.Value] + 1;
                        }
                        else
                        {
                            dictionary[enumerator.Current.Value] = 1;
                        }
                    }

                    var result = dictionary.OrderByDescending(d => d.Value);
                    return(Json(result));
                }
            }
            catch (Exception)
            {
                return(Json(new List <KeyValuePair <string, string> >()));
            }
        }
Пример #8
0
        public async Task <CheckoutSummary[]> GetOrderHistoryAsync(string userId)
        {
            List <CheckoutSummary> result = new List <CheckoutSummary>();

            IReliableDictionary <DateTime, CheckoutSummary> history =
                await StateManager.GetOrAddAsync <IReliableDictionary <DateTime, CheckoutSummary> >(HISTORY_COLLECTION);

            using (ITransaction tx = StateManager.CreateTransaction())
            {
                IAsyncEnumerable <KeyValuePair <DateTime, CheckoutSummary> > allCheckoutSummaries =
                    await history.CreateEnumerableAsync(tx, EnumerationMode.Unordered);

                using (IAsyncEnumerator <KeyValuePair <DateTime, CheckoutSummary> > enumerator = allCheckoutSummaries.GetAsyncEnumerator())
                {
                    while (await enumerator.MoveNextAsync(CancellationToken.None))
                    {
                        KeyValuePair <DateTime, CheckoutSummary> current = enumerator.Current;

                        result.Add(current.Value);
                    }
                }
            }

            return(result.ToArray());
        }
Пример #9
0
        public static async Task <IList <KeyValuePair <Guid, T> > > QueryReliableDictionary <T>
            (IReliableStateManager stateManager, string collectionName, Func <T, bool> filter)
        {
            var result = new List <KeyValuePair <Guid, T> >();

            IReliableDictionary <Guid, T> reliableDictionary =
                await stateManager.GetOrAddAsync <IReliableDictionary <Guid, T> >(collectionName);

            using (ITransaction tx = stateManager.CreateTransaction())
            {
                IAsyncEnumerable <KeyValuePair <Guid, T> > asyncEnumerable = await reliableDictionary.CreateEnumerableAsync(tx);

                using (IAsyncEnumerator <KeyValuePair <Guid, T> > asyncEnumerator = asyncEnumerable.GetAsyncEnumerator())
                {
                    while (await asyncEnumerator.MoveNextAsync(CancellationToken.None))
                    {
                        if (filter(asyncEnumerator.Current.Value))
                        {
                            result.Add(asyncEnumerator.Current);
                        }
                    }
                }
            }
            return(result);
        }
Пример #10
0
        public async Task <IActionResult> Get()
        {
            CancellationToken ct = new CancellationToken();

            // (1)Use StateManager to get or add a reliable dictionary called counts.
            IReliableDictionary <string, int> votesDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, int> >("counts");

            //(2) All interactions with values in a reliable dictionary require a transaction, this using statement (2) creates that transaction.
            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                IAsyncEnumerable <KeyValuePair <string, int> > list = await votesDictionary.CreateEnumerableAsync(tx);

                IAsyncEnumerator <KeyValuePair <string, int> > enumerator = list.GetAsyncEnumerator();

                List <KeyValuePair <string, int> > result = new List <KeyValuePair <string, int> >();
                //(3) In the transaction, we then update the value of the relevant key for the voting option and commits the operation.
                //Once the commit method returns, the data is updated in the dictionary and replicated to other nodes in the cluster.
                //The data is now safely stored in the cluster, and the back-end service can fail over to other nodes, still having the data available.

                while (await enumerator.MoveNextAsync(ct))
                {
                    result.Add(enumerator.Current);
                }

                return(this.Json(result));
            }
        }
        public async Task <IEnumerable <BlobId> > ListAsync(ListOptions options, CancellationToken cancellationToken)
        {
            if (options == null)
            {
                options = new ListOptions();
            }

            var result = new List <BlobId>();

            using (ServiceFabricTransaction tx = GetTransaction())
            {
                IReliableDictionary <string, byte[]> coll = await OpenCollectionAsync();

                IAsyncEnumerable <KeyValuePair <string, byte[]> > enumerable =
                    await coll.CreateEnumerableAsync(tx.Tx);

                using (IAsyncEnumerator <KeyValuePair <string, byte[]> > enumerator = enumerable.GetAsyncEnumerator())
                {
                    while (await enumerator.MoveNextAsync(cancellationToken))
                    {
                        KeyValuePair <string, byte[]> current = enumerator.Current;

                        if (options.Prefix == null || current.Key.StartsWith(options.Prefix))
                        {
                            result.Add(new BlobId(current.Key, BlobItemKind.File));
                        }
                    }
                }
            }

            return(result);
        }
Пример #12
0
        public async Task <List <RoomData> > GetAllRoomsAsync(CancellationToken cancellationToken)
        {
            List <RoomData> roomsResult = new List <RoomData>();

            using (var tx = this.StateManager.CreateTransaction())
            {
                var rooms = await roomsDictionary.CreateEnumerableAsync(tx);

                var roomsEnumerator = rooms.GetAsyncEnumerator();
                while (await roomsEnumerator.MoveNextAsync(cancellationToken))
                {
                    roomsResult.Add(roomsEnumerator.Current.Value);
                }

                await tx.CommitAsync();
            }

            foreach (RoomData r in roomsResult)
            {
                try
                {
                    var roomActor = ActorProxy.Create <IRoomActor>(new ActorId(r.Number), new Uri("fabric:/AffittaCamere/RoomActorService"));
                    var info      = await roomActor.GetRoomInfoAsync(cancellationToken);

                    r.IsAvailable = info == null ? true : !info.Reserved;
                    r.User        = info == null ? string.Empty : info.User;
                }
                catch (Exception)
                {
                }
            }

            return(roomsResult);
        }
Пример #13
0
        public async Task <IActionResult> Get()
        {
            CancellationToken ct = new CancellationToken();

            IReliableDictionary <string, int> votesDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, int> >("counts");

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                IAsyncEnumerable <KeyValuePair <string, int> > list = await votesDictionary.CreateEnumerableAsync(tx);

                IAsyncEnumerator <KeyValuePair <string, int> > enumerator = list.GetAsyncEnumerator();

                List <KeyValuePair <string, int> > result = new List <KeyValuePair <string, int> >();

                while (await enumerator.MoveNextAsync(ct))
                {
                    result.Add(enumerator.Current);
                }

                if (!result.Any())
                {
                    result.Add(new KeyValuePair <string, int>("Pizza", 1));
                    result.Add(new KeyValuePair <string, int>("Sushi", 9));
                }

                return(this.Json(result));
            }
        }
        /// <summary>
        /// Enumerates scheduled health checks.
        /// </summary>
        internal async Task EnumerateHealthChecksAsync()
        {
            // Check if the partition is readable/writable.
            if (PartitionAccessStatus.Granted != this._service.ReadStatus || PartitionAccessStatus.Granted != this._service.WriteStatus)
            {
                return;
            }

            // Get the health check schedule items.
            IReliableDictionary <long, WatchdogScheduledItem> scheduleDict = await this.GetHealthCheckScheduleDictionaryAsync();

            // Create a transaction for the enumeration.
            using (ITransaction eTx = this._service.StateManager.CreateTransaction())
            {
                // Create the AsyncEnumerator.
                IAsyncEnumerator <KeyValuePair <long, WatchdogScheduledItem> > ae =
                    (await scheduleDict.CreateEnumerableAsync(eTx, EnumerationMode.Ordered)).GetAsyncEnumerator();
                while (await ae.MoveNextAsync(this._token))
                {
                    // Compare the times, if this item is due for execution
                    if (ae.Current.Value.ExecutionTicks < DateTimeOffset.UtcNow.UtcTicks)
                    {
                        await this.PerformItemHealthCheckAsync(ae.Current.Value);
                    }
                }

                await eTx.CommitAsync();
            }

            this._healthState = HealthState.Ok;
        }
        private async Task PeriodicOldMessageTrimming(CancellationToken cancellationToken)
        {
            IReliableDictionary <CustomerOrderActorMessageId, DateTime> recentRequests =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <CustomerOrderActorMessageId, DateTime> >(ActorMessageDictionaryName);

            IReliableDictionary <CustomerOrderActorMessageId, Tuple <InventoryItemId, int> > requestHistory =
                await
                this.StateManager.GetOrAddAsync <IReliableDictionary <CustomerOrderActorMessageId, Tuple <InventoryItemId, int> > >(RequestHistoryDictionaryName);

            while (!cancellationToken.IsCancellationRequested)
            {
                using (ITransaction tx = this.StateManager.CreateTransaction())
                {
                    IAsyncEnumerator <KeyValuePair <CustomerOrderActorMessageId, DateTime> > enumerator =
                        (await recentRequests.CreateEnumerableAsync(tx)).GetAsyncEnumerator();

                    while (await enumerator.MoveNextAsync(cancellationToken))
                    {
                        //if we have a record of a message that is older than 2 hours from current time, then remove that record
                        //from both of the stale message tracking dictionaries.
                        if (enumerator.Current.Value < (DateTime.UtcNow.AddHours(-2)))
                        {
                            await recentRequests.TryRemoveAsync(tx, enumerator.Current.Key);

                            await requestHistory.TryRemoveAsync(tx, enumerator.Current.Key);
                        }
                    }

                    await tx.CommitAsync();
                }

                //sleep for 5 minutes then scan again
                await Task.Delay(TimeSpan.FromMinutes(5), cancellationToken);
            }
        }
        public async Task <HealthIndex> Get(int countyId)
        {
            IReliableDictionary <Guid, CountyDoctorStats> countyHealth =
                await this.stateManager.GetOrAddAsync <IReliableDictionary <Guid, CountyDoctorStats> >(
                    string.Format(CountyService.CountyHealthDictionaryName, countyId));

            IList <KeyValuePair <Guid, CountyDoctorStats> > doctorStats = new List <KeyValuePair <Guid, CountyDoctorStats> >();

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                var enumerator = (await countyHealth.CreateEnumerableAsync(tx)).GetAsyncEnumerator();

                while (await enumerator.MoveNextAsync(CancellationToken.None))
                {
                    doctorStats.Add(enumerator.Current);
                }
            }

            if (doctorStats.Count > 0)
            {
                return(this.indexCalculator.ComputeAverageIndex(doctorStats.Select(x => x.Value.AverageHealthIndex)));
            }

            return(this.indexCalculator.ComputeIndex(-1));
        }
        /// <summary>
        /// Add CheckoutSummary to the history
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task <CheckoutSummary[]> GetOrderHitoryAsync(string userId)
        {
            //get reference to history transaction
            var result = new List <CheckoutSummary>();
            IReliableDictionary <DateTime, CheckoutSummary> history =
                await StateManager.GetOrAddAsync <IReliableDictionary <DateTime, CheckoutSummary> >("history");

            //go through all items in history collection - return as list of history summary
            using (ITransaction tx = StateManager.CreateTransaction())
            {
                Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <DateTime, CheckoutSummary> > allProducts =
                    await history.CreateEnumerableAsync(tx, EnumerationMode.Unordered);

                using (Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <DateTime, CheckoutSummary> > enumerator = allProducts.GetAsyncEnumerator())
                {
                    while (await enumerator.MoveNextAsync(CancellationToken.None))
                    {
                        KeyValuePair <DateTime, CheckoutSummary> current = enumerator.Current;

                        result.Add(current.Value);
                    }
                }
            }

            return(result.ToArray());
        }
Пример #18
0
        private async Task <IEnumerable <Chunk> > GetChunks_impl(Guid?replicaId)
        {
            using (var tx = ServiceFabricUtils.CreateTransaction())
            {
retry:
                try
                {
                    if (replicaId.HasValue)
                    {
                        var res = await m_chunktable.TryGetValueAsync(tx, replicaId.Value);

                        if (res.HasValue)
                        {
                            return(Utils.Deserialize <Chunk[]>(res.Value));
                        }
                    }
                    else
                    {
                        var res = await m_chunktable.CreateEnumerableAsync(tx, EnumerationMode.Unordered);

                        var          enumerator = res.GetAsyncEnumerator();
                        List <Chunk> chunks     = new List <Chunk>();
                        while (await enumerator.MoveNextAsync(m_cancel))
                        {
                            chunks.AddRange(Utils.Deserialize <Chunk[]>(enumerator.Current.Value));
                        }
                        return(chunks);
                    }
                }
                catch (TimeoutException) { await Task.Delay(1000); goto retry; }
                catch (Exception ex) { Log.WriteLine(LogLevel.Error, "{0}", $"ServiceFabricChunkTable: {ex.ToString()}"); }
                finally { await tx.CommitAsync(); }
            }
            return(null);
        }
        public async Task <IActionResult> Get(string eventId, string topicId)
        {
            try
            {
                List <Feedback> result = new List <Feedback>();

                var tryGetResult = await this.stateManager.TryGetAsync <IReliableDictionary <string, Feedback> >(ValuesDictionaryName);

                if (tryGetResult.HasValue)
                {
                    IReliableDictionary <string, Feedback> dictionary = tryGetResult.Value;

                    using (ITransaction tx = this.stateManager.CreateTransaction())
                    {
                        var enumerable = await dictionary.CreateEnumerableAsync(tx);

                        var enumerator = enumerable.GetAsyncEnumerator();

                        while (await enumerator.MoveNextAsync(CancellationToken.None))
                        {
                            result.Add(enumerator.Current.Value);
                        }
                    }
                }
                return(this.Json(result));
            }
            catch (FabricException)
            {
                return(new ContentResult {
                    StatusCode = 503, Content = "The service was unable to process the request. Please try again."
                });
            }
        }
Пример #20
0
        public async Task <IActionResult> Get()
        {
            ServiceEventSource.Current.Message($"VotingData.Get start. ");
            CancellationToken ct = new CancellationToken();

            IReliableDictionary <string, int> votesDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, int> >("votes");

            IReliableDictionary <string, long> ballotDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, long> >("ballots");

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                IAsyncEnumerable <KeyValuePair <string, int> > list = await votesDictionary.CreateEnumerableAsync(tx);

                IAsyncEnumerator <KeyValuePair <string, int> > enumerator = list.GetAsyncEnumerator();
                List <KeyValuePair <string, int> >             result     = new List <KeyValuePair <string, int> >();

                while (await enumerator.MoveNextAsync(ct))
                {
                    result.Add(enumerator.Current);
                }

                ServiceEventSource.Current.Message($"VotingData.Get end.");
                return(this.Json(result));
            }
        }
        public async Task Clear()
        {
            DateTimeOffset now    = DateTimeOffset.Now;
            var            toKeep = new List <KeyValuePair <Guid, DateTimeOffset> >();

            using (ITransaction tx = this.sm.CreateTransaction())
            {
                var asyncEnumerable = await dictionary.CreateEnumerableAsync(tx);

                using (var asyncEnumerator = asyncEnumerable.GetAsyncEnumerator())
                {
                    while (await asyncEnumerator.MoveNextAsync(CancellationToken.None))
                    {
                        if ((now - asyncEnumerator.Current.Value).TotalSeconds < maxDelaySeconds)
                        {
                            toKeep.Add(asyncEnumerator.Current);
                        }
                    }
                }
                await dictionary.ClearAsync();

                foreach (var pair in toKeep)
                {
                    await dictionary.TryAddAsync(tx, pair.Key, pair.Value);
                }
                await tx.CommitAsync();

                lastClear = DateTimeOffset.Now;
            }
        }
Пример #22
0
        public async Task <IList <Book> > GetBooksAsync(CancellationToken ct)
        {
            IReliableDictionary <Guid, Book> books =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <Guid, Book> >(BooksDictionaryName);

            ServiceEventSource.Current.Message(message: "Called GetBooksAsync to return books");

            IList <Book> results = new List <Book>();

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ServiceEventSource.Current.Message(message: "Generating item views for {0} items", args: new object[] { await books.GetCountAsync(tx) });

                IAsyncEnumerator <KeyValuePair <Guid, Book> > enumerator =
                    (await books.CreateEnumerableAsync(tx)).GetAsyncEnumerator();

                while (await enumerator.MoveNextAsync(ct))
                {
                    results.Add(enumerator.Current.Value);
                }
            }


            return(results);
        }
        public async Task <IReadOnlyCollection <NetCore.Blobs.Blob> > ListAsync(ListOptions options, CancellationToken cancellationToken)
        {
            if (options == null)
            {
                options = new ListOptions();
            }

            var result = new List <NetCore.Blobs.Blob>();

            using (ServiceFabricTransaction tx = GetTransaction())
            {
                IReliableDictionary <string, byte[]> coll = await OpenCollectionAsync().ConfigureAwait(false);

                global::Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <string, byte[]> > enumerable =
                    await coll.CreateEnumerableAsync(tx.Tx).ConfigureAwait(false);

                using (global::Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <string, byte[]> > enumerator = enumerable.GetAsyncEnumerator())
                {
                    while (await enumerator.MoveNextAsync(cancellationToken).ConfigureAwait(false))
                    {
                        KeyValuePair <string, byte[]> current = enumerator.Current;

                        if (options.FilePrefix == null || current.Key.StartsWith(options.FilePrefix))
                        {
                            result.Add(new NetCore.Blobs.Blob(current.Key, BlobItemKind.File));
                        }
                    }
                }
            }

            return(result);
        }
Пример #24
0
        public async Task <IEnumerable <InventoryItemView> > GetCustomerInventoryAsync(CancellationToken ct)
        {
            IReliableDictionary <InventoryItemId, InventoryItem> inventoryItems =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <InventoryItemId, InventoryItem> >(InventoryItemDictionaryName);

            ServiceEventSource.Current.Message("Called GetCustomerInventory to return InventoryItemView");

            await this.PrintInventoryItemsAsync(inventoryItems, ct);

            IList <InventoryItemView> results = new List <InventoryItemView>();

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ServiceEventSource.Current.Message("Generating item views for {0} items", await inventoryItems.GetCountAsync(tx));

                IAsyncEnumerator <KeyValuePair <InventoryItemId, InventoryItem> > enumerator =
                    (await inventoryItems.CreateEnumerableAsync(tx)).GetAsyncEnumerator();

                while (await enumerator.MoveNextAsync(ct))
                {
                    if (enumerator.Current.Value.AvailableStock > 0)
                    {
                        results.Add(enumerator.Current.Value);
                    }
                }
            }


            return(results);
        }
        public async Task <IEnumerable <Product> > GetAllProducts()
        {
            IReliableDictionary <Guid, Product> products =
                await _stateManager.GetOrAddAsync <IReliableDictionary <Guid, Product> >("products");

            var result = new List <Product>();

            using (ITransaction tx = _stateManager.CreateTransaction())
            {
                Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <Guid, Product> > allProducts =
                    await products.CreateEnumerableAsync(tx, EnumerationMode.Unordered);

                using (Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <Guid, Product> > enumerator =
                           allProducts.GetAsyncEnumerator())
                {
                    while (await enumerator.MoveNextAsync(CancellationToken.None))
                    {
                        KeyValuePair <Guid, Product> current = enumerator.Current;
                        result.Add(current.Value);
                    }
                }
            }

            return(result);
        }
Пример #26
0
        public async Task <IActionResult> Get()
        {
            try
            {
                var result = new List <KeyValuePair <string, BookingAggregates> >();

                var tryGetResult = await _stateManager.TryGetAsync <IReliableDictionary <string, BookingAggregates> >(ValuesDictionaryName);

                if (tryGetResult.HasValue)
                {
                    IReliableDictionary <string, BookingAggregates> dictionary = tryGetResult.Value;

                    using (ITransaction tx = _stateManager.CreateTransaction())
                    {
                        var list = await dictionary.CreateEnumerableAsync(tx);

                        var enumerator = list.GetAsyncEnumerator();

                        while (await enumerator.MoveNextAsync(CancellationToken.None))
                        {
                            result.Add(enumerator.Current);
                        }
                    }
                }
                return(Json(result));
            }
            catch (FabricException)
            {
                return(new ContentResult {
                    StatusCode = 503, Content = "The service was unable to process the request. Please try again."
                });
            }
        }
Пример #27
0
        public async Task <List <User> > GetUsersAsync(CancellationToken cancellationToken)
        {
            IReliableDictionary <string, User> users =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, User> >(StateManagerKey);

            var returnList = new List <User>();

            using (var tx = this.StateManager.CreateTransaction())
            {
                var asyncEnumerable = await users.CreateEnumerableAsync(tx);

                var asyncEnumerator = asyncEnumerable.GetAsyncEnumerator();

                try
                {
                    while (await asyncEnumerator.MoveNextAsync(cancellationToken))
                    {
                        returnList.Add(asyncEnumerator.Current.Value);
                    }
                }
                catch (OperationCanceledException)
                {
                    // Ignore
                }

                await tx.CommitAsync();
            }
            return(returnList);
        }
Пример #28
0
        public async Task <IEnumerable <Product> > GetAllProducts()
        {
            IReliableDictionary <Guid, Product> products = await _stateManager
                                                           .GetOrAddAsync <IReliableDictionary <Guid, Product> >("products");

            var results = new List <Product>();

            // Everything is done via transactions
            using (ITransaction tx = _stateManager.CreateTransaction())
            {
                // Get all products from Service Fabric async. (Incurs a call cost)
                // Returns enumerable instead of list because there can be millions of products.
                Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <Guid, Product> > allProducts =
                    await products.CreateEnumerableAsync(tx, EnumerationMode.Unordered);

                // Get product enumerator from Service Fabric async. (Incurs a call cost)
                using (Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <Guid, Product> > enumerator =
                           allProducts.GetAsyncEnumerator())
                {
                    while (await enumerator.MoveNextAsync(CancellationToken.None))
                    {
                        KeyValuePair <Guid, Product> current = enumerator.Current;
                        results.Add(current.Value);
                    }
                }
            }

            return(results);
        }
Пример #29
0
        private async Task EnumerateRemindersAsync(
            IReliableDictionary <string, byte[]> reminderDictionary,
            Dictionary <string, ReminderCompletedData> reminderCompletedDataDict,
            ActorReminderCollection reminderCollection,
            CancellationToken cancellationToken)
        {
            using (var tx = this.stateManager.CreateTransaction())
            {
                var enumerable = await reminderDictionary.CreateEnumerableAsync(tx);

                var enumerator = enumerable.GetAsyncEnumerator();

                while (await enumerator.MoveNextAsync(cancellationToken))
                {
                    var data = enumerator.Current.Value;

                    if (data == null)
                    {
                        continue;
                    }

                    var reminderData = ActorReminderDataSerializer.Deserialize(data);
                    var key          = CreateStorageKey(reminderData.ActorId, reminderData.Name);

                    ReminderCompletedData reminderCompletedData;
                    reminderCompletedDataDict.TryGetValue(key, out reminderCompletedData);

                    reminderCollection.Add(
                        reminderData.ActorId,
                        new ActorReminderState(reminderData, this.logicalTimeManager.CurrentLogicalTime, reminderCompletedData));
                }
            }
        }
Пример #30
0
        public static async Task <IAsyncEnumerable <KeyValuePair <TKey, TValue> > > CreateLinqAsyncEnumerable <TKey, TValue>(
            this IReliableDictionary <TKey, TValue> dictionary, Microsoft.ServiceFabric.Data.ITransaction txn, Func <TKey, bool> filter, EnumerationMode enumerationMode)
            where TKey : IComparable <TKey>, IEquatable <TKey>
        {
            var enumerable = await dictionary.CreateEnumerableAsync(txn, filter, enumerationMode).ConfigureAwait(false);

            return(enumerable.AsAsyncEnumerable());
        }
        /// <summary>
        /// Gets a list of active clusters. Clusters that are new, being created, or ready and not expired are considered active.
        /// </summary>
        /// <param name="clusterDictionary"></param>
        /// <returns></returns>
        private async Task<IEnumerable<KeyValuePair<int, Cluster>>> GetActiveClusters(
            IReliableDictionary<int, Cluster> clusterDictionary, CancellationToken cancellationToken)
        {
            List<KeyValuePair<int, Cluster>> activeClusterList = new List<KeyValuePair<int, Cluster>>();

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                IAsyncEnumerable<KeyValuePair<int, Cluster>> clusterAsyncEnumerable = await clusterDictionary.CreateEnumerableAsync(tx);

                await clusterAsyncEnumerable.ForeachAsync(
                    cancellationToken,
                    x =>
                    {
                        if (x.Value.Status == ClusterStatus.New ||
                            x.Value.Status == ClusterStatus.Creating ||
                            x.Value.Status == ClusterStatus.Ready)
                        {
                            activeClusterList.Add(x);
                        }
                    });
            }

            return activeClusterList;
        }
 async protected override Task RunAsync(CancellationToken cancelServicePartitionReplica)
 {
     _roomsState = await StateManager.GetOrAddAsync<IReliableDictionary<string, RoomData>>("Rooms");
     using (var tx = StateManager.CreateTransaction())
     {
         var roomEnumerable = await _roomsState.CreateEnumerableAsync(tx, EnumerationMode.Unordered);
         using (var roomEnumerator = roomEnumerable.GetAsyncEnumerator())
         {
             while (await roomEnumerator.MoveNextAsync(cancelServicePartitionReplica).ConfigureAwait(false))
             {
                 roomEnumerator.Current.Value.Members = new List<RoomMember>();
                 Rooms.Add(roomEnumerator.Current.Key, roomEnumerator.Current.Value);
             }
         }
     }
     
     ServiceEventSource.Current.ServiceMessage(this, "RunAsync called");
     while (!cancelServicePartitionReplica.IsCancellationRequested)
     {
         await Task.Delay(10000, cancelServicePartitionReplica);
     }
 }
        private async Task PrintInventoryItemsAsync(IReliableDictionary<InventoryItemId, InventoryItem> inventoryItems, CancellationToken cancellationToken)
        {
            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ServiceEventSource.Current.Message("Printing Inventory for {0} items:", await inventoryItems.GetCountAsync(tx));

                IAsyncEnumerator<KeyValuePair<InventoryItemId, InventoryItem>> enumerator =
                    (await inventoryItems.CreateEnumerableAsync(tx)).GetAsyncEnumerator();

                while (await enumerator.MoveNextAsync(cancellationToken))
                {
                    ServiceEventSource.Current.Message("ID:{0}|Item:{1}", enumerator.Current.Key, enumerator.Current.Value);
                }
            }
        }