public async Task <long> GetCountAsync(ITransaction tx)
        {
            if (reliableDictionary == null)
            {
                await InitializeReliableDictionary();
            }

            return(await reliableDictionary.GetCountAsync(tx));
        }
Esempio n. 2
0
        public async Task <IHttpActionResult> Get(int countyId)
        {
            IReliableDictionary <Guid, CountyDoctorStats> countyHealth =
                await this.stateManager.GetOrAddAsync <IReliableDictionary <Guid, CountyDoctorStats> >(string.Format(Service.CountyHealthDictionaryName, countyId));

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                if (await countyHealth.GetCountAsync(tx) > 0)
                {
                    IList <KeyValuePair <Guid, CountyDoctorStats> > doctorStats = new List <KeyValuePair <Guid, CountyDoctorStats> >();

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

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

                    return(this.Ok(this.indexCalculator.ComputeAverageIndex(doctorStats.Select(x => x.Value.AverageHealthIndex))));
                }
                else
                {
                    return(this.Ok(-1));
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// The platform calls this method when an instance of your service is placed and ready to execute.
        /// </summary>
        /// <param name="cancellationToken">
        /// The system uses a cancellation token to signal your service when it's time to stop running.
        /// </param>
        /// <returns></returns>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            IReliableDictionary <int, CustomObject> dictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <int, CustomObject> >("dictionary1");

            int i = 1;

            while (!cancellationToken.IsCancellationRequested)
            {
                using (ITransaction tx = this.StateManager.CreateTransaction())
                {
                    await dictionary.AddOrUpdateAsync(tx, i, new CustomObject()
                    {
                        Data = i
                    }, (k, v) => new CustomObject()
                    {
                        Data = v.Data + 1
                    });

                    await tx.CommitAsync();
                }

                ServiceEventSource.Current.ServiceMessage(
                    this,
                    "Total Custom Objects: {0}. Data Average: {1}",
                    await dictionary.GetCountAsync(),
                    dictionary.Average(item => item.Value.Data));

                i = i % 10 == 0 ? 1 : i + 1;

                await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
            }
        }
Esempio n. 4
0
        // Maps the paritions of the applications from primary cluster and secondary cluster
        public async Task MapPartitionsOfApplication(Uri applicationName, ClusterDetails primaryCluster, ClusterDetails secondaryCluster, String reliableDictionary)
        {
            FabricClient primaryFabricClient   = new FabricClient(primaryCluster.address + ':' + primaryCluster.clientConnectionEndpoint);
            FabricClient secondaryFabricClient = new FabricClient(secondaryCluster.address + ':' + secondaryCluster.clientConnectionEndpoint);

            IReliableDictionary <Guid, PartitionWrapper> myDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <Guid, PartitionWrapper> >(reliableDictionary);

            ServiceList services = await primaryFabricClient.QueryManager.GetServiceListAsync(applicationName);

            foreach (Service service in services)
            {
                ServicePartitionList primaryPartitions = await primaryFabricClient.QueryManager.GetPartitionListAsync(service.ServiceName);

                ServicePartitionList secondaryPartitions = await secondaryFabricClient.QueryManager.GetPartitionListAsync(service.ServiceName);
                await MapPartitions(applicationName, service.ServiceName, primaryCluster, primaryPartitions, secondaryCluster, secondaryPartitions, reliableDictionary);

                using (var tx = this.StateManager.CreateTransaction())
                {
                    var result = await myDictionary.GetCountAsync(tx);

                    ServiceEventSource.Current.ServiceMessage(this.Context, "The number of items in dictionary are : {0}", result);
                    await tx.CommitAsync();
                }
            }
        }
        // PRIVATE Methods
        public async Task <long> GetQueueLengthAsyncInternal()
        {
            long count = -1;
            IReliableDictionary <DateTimeOffset, DeviceEventSeries> storeCompletedMessages = await this.stateManager.GetOrAddAsync <IReliableDictionary <DateTimeOffset, DeviceEventSeries> >(TargetSolution.Names.EventHistoryDictionaryName);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                try
                {
                    count = await storeCompletedMessages.GetCountAsync(tx);

                    await tx.CommitAsync();
                }
                catch (TimeoutException te)
                {
                    // transient error. Could Retry if one desires .
                    ServiceEventSource.Current.ServiceMessage(this.context, $"DataService - GetQueueLengthAsync - TimeoutException : Message=[{te.ToString()}]");
                    tx.Abort();
                }
                catch (Exception ex)
                {
                    ServiceEventSource.Current.ServiceMessage(this.context, $"DataService - GetQueueLengthAsync - General Exception - Message=[{0}]", ex);
                    tx.Abort();
                }
            }

            return(count);
        }
Esempio n. 6
0
        private async Task <long> ExecuteCountAsync(IReliableDictionary <string, Order> orders)
        {
            long count = 0;

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                count = await orders.GetCountAsync(tx);

                await tx.CommitAsync();
            }
            return(count);
        }
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            TimeSpan timeSpan = new TimeSpan(0, 0, 30);

            ServiceEventSource.Current.ServiceMessage(
                this,
                "Partition {0} started processing messages.",
                this.Context.PartitionId);

            IReliableDictionary <DateTime, Message> messagesDictionary =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <DateTime, Message> >("messages");

            //Use this method to periodically clean up messages in the messagesDictionary
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    IEnumerable <KeyValuePair <DateTime, Message> > messagesEnumerable = await GetMessagesAsync();

                    // Remove all the messages that are older than 30 seconds keeping the last 50 messages
                    IEnumerable <KeyValuePair <DateTime, Message> > oldMessages = from t in messagesEnumerable
                                                                                  where t.Key < (DateTime.Now - timeSpan)
                                                                                  orderby t.Key ascending
                                                                                  select t;

                    using (ITransaction tx = this.StateManager.CreateTransaction())
                    {
                        int messagesCount = (int)await messagesDictionary.GetCountAsync(tx);

                        foreach (KeyValuePair <DateTime, Message> item in oldMessages.Take(messagesCount - MessagesToKeep))
                        {
                            await messagesDictionary.TryRemoveAsync(tx, item.Key);
                        }
                        await tx.CommitAsync();
                    }
                }
                catch (Exception e)
                {
                    if (!this.HandleException(e))
                    {
                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Partition {0} stopped processing because of error {1}",
                            this.Context.PartitionId,
                            e);
                        break;
                    }
                }

                await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken);
            }
        }
Esempio n. 8
0
        public async Task <IActionResult> GetPlayerStats()
        {
            try
            {
                if (!PlayerManager.IsActive)
                {
                    return new ContentResult {
                               StatusCode = 500, Content = "Service is still starting up. Please retry."
                    }
                }
                ;

                IReliableDictionary <string, PlayerPackage> playdict =
                    await this.stateManager.GetOrAddAsync <IReliableDictionary <string, PlayerPackage> >(PlayersDictionaryName);

                PlayerStats stats = new PlayerStats(0, 0, 0, 0);

                //Go through the player dictionary gathering data and averaging or summing as you go.
                using (ITransaction tx = this.stateManager.CreateTransaction())
                {
                    stats.NumAccounts = await playdict.GetCountAsync(tx);

                    IAsyncEnumerable <KeyValuePair <string, PlayerPackage> > enumerable = await playdict.CreateEnumerableAsync(tx);

                    IAsyncEnumerator <KeyValuePair <string, PlayerPackage> > enumerator = enumerable.GetAsyncEnumerator();

                    while (await enumerator.MoveNextAsync(CancellationToken.None))
                    {
                        //Averaging
                        if (enumerator.Current.Value.State == LogState.LoggedIn)
                        {
                            stats.NumLoggedIn++;
                        }

                        stats.AvgNumLogins  += (float)enumerator.Current.Value.NumLogins / stats.NumAccounts;
                        stats.AvgAccountAge += (double)DateTime.Now.ToUniversalTime().Subtract(enumerator.Current.Value.FirstLogin).Seconds /
                                               stats.NumAccounts;
                    }
                    await tx.CommitAsync();
                }

                return(this.Json(stats));
            }
            catch (Exception e)
            {
                return(exceptionHandler(e));
            }
        }
Esempio n. 9
0
        // Maps the paritions of the applications from primary cluster and secondary cluster
        public async Task MapPartitionsOfApplication(Uri applicationName, ClusterDetails primaryCluster, ClusterDetails secondaryCluster, String reliableDictionary)
        {
            FabricClient primaryFabricClient   = GetSecureFabricClient(primaryCluster.address + ':' + primaryCluster.clientConnectionEndpoint, primaryCluster.certificateThumbprint);
            FabricClient secondaryFabricClient = GetSecureFabricClient(secondaryCluster.address + ':' + secondaryCluster.clientConnectionEndpoint, secondaryCluster.certificateThumbprint);

            IReliableDictionary <Guid, PartitionWrapper> myDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <Guid, PartitionWrapper> >(reliableDictionary);

            ServiceList services = await primaryFabricClient.QueryManager.GetServiceListAsync(applicationName);

            foreach (Service service in services)
            {
                ServicePartitionList primaryPartitions;
                ServicePartitionList secondaryPartitions;

                if (service.ServiceKind == ServiceKind.Stateless)
                {
                    continue;
                }

                try
                {
                    primaryPartitions = await primaryFabricClient.QueryManager.GetPartitionListAsync(service.ServiceName);
                }
                catch (Exception ex)
                {
                    ServiceEventSource.Current.Message("Restore Service: Exception getting primary partitions {0}", ex);
                    throw;
                }
                try
                {
                    secondaryPartitions = await secondaryFabricClient.QueryManager.GetPartitionListAsync(service.ServiceName);
                }
                catch (Exception ex)
                {
                    ServiceEventSource.Current.Message("Restore Service: Exception getting secondary partitions {0}", ex);
                    throw;
                }
                await MapPartitions(applicationName, service.ServiceName, primaryCluster, primaryPartitions, secondaryCluster, secondaryPartitions, reliableDictionary);

                using (var tx = this.StateManager.CreateTransaction())
                {
                    var result = await myDictionary.GetCountAsync(tx);

                    ServiceEventSource.Current.ServiceMessage(this.Context, "The number of items in dictionary are : {0}", result);
                    await tx.CommitAsync();
                }
            }
        }
Esempio n. 10
0
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            int hourlyLimit = (int)Math.Round(3600D / HourlyInterval.TotalSeconds);

            IReliableDictionary <DateTimeOffset, Dictionary <string, long> > dictionary = await
                                                                                          this.StateManager.GetOrAddAsync <IReliableDictionary <DateTimeOffset, Dictionary <string, long> > >($"history:/hourly");

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    ClusterLoadInformation capacities = await this.query.GetClusterLoadAsync();

                    DateTimeOffset            utcnow    = DateTimeOffset.UtcNow;
                    DateTimeOffset            timestamp = new DateTimeOffset(utcnow.Year, utcnow.Month, utcnow.Day, utcnow.Hour, utcnow.Minute, utcnow.Second, utcnow.Offset);
                    Dictionary <string, long> values    = new Dictionary <string, long>();

                    foreach (var capacity in capacities.LoadMetricInformationList)
                    {
                        values[capacity.Name] = capacity.ClusterLoad;
                    }

                    using (ITransaction tx = this.StateManager.CreateTransaction())
                    {
                        long count = await dictionary.GetCountAsync(tx);

                        if (count >= hourlyLimit)
                        {
                            var min = await(await dictionary.CreateLinqAsyncEnumerable(tx)).Min(x => x.Key);
                            await dictionary.TryRemoveAsync(tx, min);
                        }

                        await dictionary.SetAsync(tx, timestamp, values);

                        await tx.CommitAsync();
                    }
                }
                catch (FabricTransientException)
                {
                    // retry
                }

                await Task.Delay(HourlyInterval, cancellationToken);
            }
        }
Esempio n. 11
0
        public async Task <long> GetKeyCountAsync(CancellationToken cancellationToken)
        {
            IReliableDictionary <SessionKeyItemId, SessionKeyItem> sessionKeyItems =
                await StateManager
                .GetOrAddAsync <IReliableDictionary <SessionKeyItemId, SessionKeyItem> >(SessionKeyDictionaryName);

            ServiceEventSource.Current.Message($"Method started {nameof(SessionKeys)}->GetKeyCountAsync() at: {DateTime.UtcNow}");

            long sessionKeyCount = 0;

            if (sessionKeyItems != null)
            {
                using (var tx = StateManager.CreateTransaction()) {
                    sessionKeyCount = await sessionKeyItems.GetCountAsync(tx);
                }
            }
            ServiceEventSource.Current.Message($"Method ended {nameof(SessionKeys)}->GetKeyCountAsync() at: {DateTime.UtcNow}");
            return(sessionKeyCount);
        }
Esempio n. 12
0
        private async Task PeriodicInventoryCheck(CancellationToken cancellationToken)
        {
            IReliableDictionary <InventoryItemId, InventoryItem> inventoryItems =
                await this.stateManager.GetOrAddAsync <IReliableDictionary <InventoryItemId, InventoryItem> >(InventoryItemDictionaryName);

            if (this.storageType == StorageTypes.Azure)
            {
                await this.InitializeAsync(cancellationToken);
            }

            while (!cancellationToken.IsCancellationRequested)
            {
                ServiceEventSource.Current.ServiceMessage(this, "Checking inventory stock for {0} items.", await inventoryItems.GetCountAsync());

                foreach (InventoryItem item in inventoryItems.Select(x => x.Value))
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    try
                    {
                        //Check if stock is below restockThreshold and if the item is not already on reorder
                        if ((item.AvailableStock <= item.RestockThreshold) && !item.OnReorder)
                        {
                            ServiceUriBuilder builder = new ServiceUriBuilder(RestockRequestManagerServiceName);

                            IRestockRequestManager restockRequestManagerClient = ServiceProxy.Create <IRestockRequestManager>(0, builder.ToUri());

                            // we reduce the quantity passed in to RestockRequest to ensure we don't overorder
                            RestockRequest newRequest = new RestockRequest(item.Id, (item.MaxStockThreshold - item.AvailableStock));

                            InventoryItem updatedItem = new InventoryItem(
                                item.Description,
                                item.Price,
                                item.AvailableStock,
                                item.RestockThreshold,
                                item.MaxStockThreshold,
                                item.Id,
                                true);

                            // TODO: this call needs to be idempotent in case we fail to update the InventoryItem after this completes.
                            await restockRequestManagerClient.AddRestockRequestAsync(newRequest);

                            // Write operations take an exclusive lock on an item, which means we can't do anything else with that item while the transaction is open.
                            // If something blocks before the transaction is committed, the open transaction on the item will prevent all operations on it, including reads.
                            // Once the transaction commits, the lock is released and other operations on the item can proceed.
                            // Operations on the transaction all have timeouts to prevent deadlocking an item,
                            // but we should do as little work inside the transaction as possible that is not related to the transaction itself.
                            using (ITransaction tx = this.stateManager.CreateTransaction())
                            {
                                await inventoryItems.TryUpdateAsync(tx, item.Id, updatedItem, item);

                                await tx.CommitAsync();
                            }

                            ServiceEventSource.Current.ServiceMessage(
                                this,
                                "Restock order placed. Item ID: {0}. Quantity: {1}",
                                newRequest.ItemId,
                                newRequest.Quantity);
                        }
                    }
                    catch (Exception e)
                    {
                        ServiceEventSource.Current.ServiceMessage(this, "Failed to place restock order for item {0}. {1}", item.Id, e.ToString());
                    }

                    if (this.storageType == StorageTypes.Local)
                    {
                        await this.StateManager.BackupAsync(this.BackupCallbackAsync);
                    }
                    else
                    {
                        await this.StateManager.BackupAsync(this.BackupCallbackAzureAsync);
                    }
                }

                await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken);
            }
        }
Esempio n. 13
0
        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);
                }
            }
        }
Esempio n. 14
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);
        }
        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);
                }
            }
        }
Esempio n. 16
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 <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);
        }