Exemple #1
0
        public async Task <ActionResult <IEnumerable <string> > > Get()
        {
            CancellationToken ct = new CancellationToken();
            IReliableDictionary <string, long> playerDictionary = await this._stateManager.GetOrAddAsync <IReliableDictionary <string, long> >("rulesDictionary");


            using (ITransaction tx = this._stateManager.CreateTransaction())
            {
                Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <string, long> > playerList = await playerDictionary.CreateEnumerableAsync(tx);

                Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <string, long> > enumerator = playerList.GetAsyncEnumerator();

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

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

                return(new JsonResult(result));
            }
        }
        public async Task <IActionResult> Get()
        {
            try
            {
                List <KeyValuePair <string, string> > result = new List <KeyValuePair <string, string> >();

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

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

                    using (ITransaction tx = this.stateManager.CreateTransaction())
                    {
                        Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <string, string> > enumerable = await dictionary.CreateEnumerableAsync(tx);

                        Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <string, string> > enumerator = enumerable.GetAsyncEnumerator();

                        while (await enumerator.MoveNextAsync(CancellationToken.None))
                        {
                            result.Add(enumerator.Current);
                        }
                    }
                }
                return(this.Json(result));
            }
            catch (FabricException)
            {
                return(new ContentResult {
                    StatusCode = 503, Content = "The service was unable to process the request. Please try again."
                });
            }
        }
Exemple #3
0
        private async Task <List <InstallerPkg> > GetInstallerPackagesAsync()
        {
            CancellationToken ct = new CancellationToken();

            IReliableDictionary <string, InstallerPkg> packagesDictionary = await this._statemanager.GetOrAddAsync <IReliableDictionary <string, InstallerPkg> >("packages");

            using (ITransaction tx = this._statemanager.CreateTransaction())
            {
                Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <string, InstallerPkg> > list = await packagesDictionary.CreateEnumerableAsync(tx);

                Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <string, InstallerPkg> > enumerator = list.GetAsyncEnumerator();

                List <InstallerPkg> result = new List <InstallerPkg>();

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

                return(result);
            }
        }
        public async Task <ActionResult <IEnumerable <string> > > Get()
        {
            CancellationToken ct = new CancellationToken();
            IReliableDictionary <int, int> playerDictionary = await this._stateManager.GetOrAddAsync <IReliableDictionary <int, int> >("PlayerMatchStatisticsDictionary");


            using (ITransaction tx = this._stateManager.CreateTransaction())
            {
                Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <int, int> > playerList = await playerDictionary.CreateEnumerableAsync(tx);

                Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <int, int> > enumerator = playerList.GetAsyncEnumerator();


                var stats = new List <UserTeamPlayers>();

                while (await enumerator.MoveNextAsync(ct))
                {
                    stats.Add(new UserTeamPlayers {
                        PlayerId = enumerator.Current.Key, Point = enumerator.Current.Value
                    });
                }

                return(new JsonResult(stats));
            }
        }
        public async Task <IActionResult> Get()
        {
            CancellationToken ct = new CancellationToken();

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

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

                Microsoft.ServiceFabric.Data.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);
                }

                return(this.Json(result));
            }
        }
        private async Task <List <ServiceMessage> > GetResultsAsync()
        {
            var messages = new List <ServiceMessage>();
            var storage  = await this._manager.GetOrAddAsync <IReliableDictionary <string, ServiceMessage> >("storage");

            using (var tx = _manager.CreateTransaction())
            {
                var messageEnumerable = await storage.CreateEnumerableAsync(tx, EnumerationMode.Ordered);

                using (Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <string, ServiceMessage> > enumerator = messageEnumerable.GetAsyncEnumerator())
                {
                    while (await enumerator.MoveNextAsync(CancellationToken.None))
                    {
                        messages.Add(enumerator.Current.Value);
                    }
                }
            }
            return(messages);
        }
Exemple #7
0
        public async Task <IEnumerable <Equipment> > GetAllEquipment()
        {
            // GetorAdd will return empty referene is it's not exist
            IReliableDictionary <Guid, Equipment> equipements = await _stateManager
                                                                .GetOrAddAsync <IReliableDictionary <Guid, Equipment> >("equipements");

            var result = new List <Equipment>();

            using (ITransaction tx = _stateManager.CreateTransaction())
            {
                // Service fabric store all data in replica
                Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <Guid, Equipment> > allEquipments = await equipements.CreateEnumerableAsync(tx, EnumerationMode.Unordered);

                using (Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <Guid, Equipment> > enumerator =
                           allEquipments.GetAsyncEnumerator())
                {
                    // Get all records
                    while (await enumerator.MoveNextAsync(CancellationToken.None))
                    {
                        KeyValuePair <Guid, Equipment> current = enumerator.Current;
                        result.Add(current.Value);
                    }
                }
            }
            return(result);
        }
Exemple #8
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);
        }
        public async Task <IEnumerable <string> > Get()
        {
            var result = new List <string>();

            try
            {
                var dict = await stateManager.GetOrAddAsync <IReliableDictionary <string, VehicleRegistration> >(LicensePlates);

                using (ITransaction tx = stateManager.CreateTransaction())
                {
                    var enu = await dict.CreateEnumerableAsync(tx);

                    using (Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <string, VehicleRegistration> > enumerator = enu.GetAsyncEnumerator())
                    {
                        while (await enumerator.MoveNextAsync(CancellationToken.None))
                        {
                            var value = enumerator.Current;
                            result.Add(value.Key);
                        }
                    }
                }
            }
            catch (TimeoutException)
            {
                return(null);
            }

            return(result);
        }
Exemple #10
0
        private async Task <List <KeyValuePair <string, Order> > > ExecuteGetOrdersAsync()
        {
            List <KeyValuePair <string, Order> > result = new List <KeyValuePair <string, Order> >();

            ConditionalValue <IReliableDictionary <string, Order> > conditionResult =
                await this.stateManager.TryGetAsync <IReliableDictionary <string, Order> >(this.setName);

            if (conditionResult.HasValue)
            {
                IReliableDictionary <string, Order> orders = conditionResult.Value;

                using (var tx = this.stateManager.CreateTransaction())
                {
                    Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <string, Order> > enumerable = await orders.CreateEnumerableAsync(tx);

                    Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <string, Order> > enumerator = enumerable.GetAsyncEnumerator();

                    while (await enumerator.MoveNextAsync(CancellationToken.None))
                    {
                        result.Add(enumerator.Current);
                    }
                    await tx.CommitAsync();
                }
            }
            return(result);
        }
Exemple #11
0
        /// <summary>
        /// Gets a filtered set of MetricCheck items.
        /// </summary>
        /// <param name="application">Optional application filter.</param>
        /// <param name="service">Optional service filter.</param>
        /// <param name="partition">Optional partition filter.</param>
        /// <returns>List containing the set of matching HealthCheck items.</returns>
        /// <remarks>If application is null or empty, the values passed in service and partition will be ignored.
        /// If service is null or empty, the values passed in partition will be ignored.
        /// </remarks>
        public async Task <IList <MetricCheck> > GetMetricsAsync(string application = null, string service = null, Guid?partition = null)
        {
            string             filter = string.Empty;
            List <MetricCheck> items  = new List <MetricCheck>();

            // Get the required dictionaries.
            IReliableDictionary <string, MetricCheck> hcDict = await this.GetMetricCheckDictionaryAsync().ConfigureAwait(false);

            if ((false == string.IsNullOrWhiteSpace(application)) && (false == string.IsNullOrWhiteSpace(service)) && (partition.HasValue))
            {
                filter = $"fabric:/{application}/{service}/{partition}";
            }
            else if ((false == string.IsNullOrWhiteSpace(application)) && (false == string.IsNullOrWhiteSpace(service)))
            {
                filter = $"fabric:/{application}/{service}";
            }
            else if (false == string.IsNullOrWhiteSpace(application))
            {
                filter = $"fabric:/{application}";
            }

            try
            {
                using (ITransaction tx = this._service.StateManager.CreateTransaction())
                {
                    // Query the dictionary for an order list filtered by however much the user specified.
                    Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <string, MetricCheck> > list = null;
                    if (string.IsNullOrWhiteSpace(filter))
                    {
                        list = await hcDict.CreateEnumerableAsync(tx, EnumerationMode.Ordered).ConfigureAwait(false);
                    }
                    else
                    {
                        list = await hcDict.CreateEnumerableAsync(tx, (s) => { return(s.StartsWith(filter)); }, EnumerationMode.Ordered).ConfigureAwait(false);
                    }

                    Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <string, MetricCheck> > asyncEnumerator = list.GetAsyncEnumerator();
                    while (await asyncEnumerator.MoveNextAsync(this._token).ConfigureAwait(false))
                    {
                        if (this._token.IsCancellationRequested)
                        {
                            break;
                        }

                        items.Add(asyncEnumerator.Current.Value);
                    }
                }

                // Update the metric count
                Interlocked.CompareExchange(ref this._metricCount, items.Count, this._metricCount);
            }
            catch (FabricObjectClosedException)
            {
                this._service.RefreshFabricClient();
            }
            catch (TimeoutException ex)
            {
                ServiceEventSource.Current.Exception(ex.Message, ex.GetType().Name, nameof(this.GetMetricsAsync));
            }
            catch (FabricTransientException ex)
            {
                ServiceEventSource.Current.Exception(ex.Message, ex.GetType().Name, nameof(this.GetMetricsAsync));
            }

            // Return the list of HealthCheck items.
            return(items);
        }
Exemple #12
0
        /// <summary>
        /// Enumerates metric requests.
        /// </summary>
        internal async Task EnumerateMetricsAsync()
        {
            // 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 <string, MetricCheck> mDict = await this.GetMetricCheckDictionaryAsync();

            // Create a transaction for the enumeration.
            using (ITransaction tx = this._service.StateManager.CreateTransaction())
            {
                bool result = false;

                // Create the AsyncEnumerator.
                Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <string, MetricCheck> > ae = (await mDict.CreateEnumerableAsync(tx, EnumerationMode.Ordered)).GetAsyncEnumerator();
                while (await ae.MoveNextAsync(this._token))
                {
                    MetricCheck mc = ae.Current.Value;

                    if ((false == string.IsNullOrWhiteSpace(mc.Service)) && (default(Guid) != mc.Partition))
                    {
                        result = await this.ReportPartitionMetricAsync(mc).ConfigureAwait(false);
                    }
                    else if ((false == string.IsNullOrWhiteSpace(mc.Service)) && (default(Guid) == mc.Partition))
                    {
                        result = await this.ReportServiceMetricAsync(mc).ConfigureAwait(false);
                    }
                    else
                    {
                        result = await this.ReportApplicationMetricAsync(mc).ConfigureAwait(false);
                    }
                }
            }

            this._healthState = HealthState.Ok;
        }
Exemple #13
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;
            }
        }
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            // TODO: Replace the following sample code with your own logic
            //       or remove this RunAsync override if it's not needed in your service.
            if (cancellationToken.IsCancellationRequested)
            {
            }
            var playerMatchStatisticsDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <int, int> >("PlayerMatchStatisticsDictionary");

            //while (true)
            //{
            //    cancellationToken.ThrowIfCancellationRequested();

            //    using (var tx = this.StateManager.CreateTransaction())
            //    {
            //        var result = await myDictionary.TryGetValueAsync(tx, "Counter");

            //        ServiceEventSource.Current.ServiceMessage(this.Context, "Current Counter Value: {0}",
            //            result.HasValue ? result.Value.ToString() : "Value does not exist.");

            //        await myDictionary.AddOrUpdateAsync(tx, "Counter", 0, (key, value) => ++value);

            //        // If an exception is thrown before calling CommitAsync, the transaction aborts, all changes are
            //        // discarded, and nothing is saved to the secondary replicas.
            //        await tx.CommitAsync();
            //    }

            //    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
            //}
            while (true)
            {
                List <PlayerMatchStatistics> stats;
                stats = new List <PlayerMatchStatistics>();

                CancellationToken ct = new CancellationToken();

                List <PlayerMatchStatistics> result = new List <PlayerMatchStatistics>();
                using (var tx = this.StateManager.CreateTransaction())
                {
                    var playerlist = await playerMatchStatisticsDictionary.CreateEnumerableAsync(tx);

                    Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <int, int> > enumerator = playerlist.GetAsyncEnumerator();

                    while (await enumerator.MoveNextAsync(ct))
                    {
                        stats.Add(new PlayerMatchStatistics {
                            PlayerId = enumerator.Current.Key, PlayerPoints = enumerator.Current.Value
                        });
                    }
                }
                ////get it from RD this returns instance of PlayerMatchStatistics
                //PlayerMatchStatistics playerMatchStatistics = new PlayerMatchStatistics();
                //playerMatchStatistics.PlayerId = 1;
                //playerMatchStatistics.PlayerPoints = 100;
                //stats.Add(playerMatchStatistics);
                //playerMatchStatistics = new PlayerMatchStatistics();
                //playerMatchStatistics.PlayerId = 2;
                //playerMatchStatistics.PlayerPoints = 100;
                //stats.Add(playerMatchStatistics);
                //playerMatchStatistics = new PlayerMatchStatistics();
                //playerMatchStatistics.PlayerId = 3;
                //playerMatchStatistics.PlayerPoints = 100;
                //stats.Add(playerMatchStatistics);
                //playerMatchStatistics = new PlayerMatchStatistics();
                //playerMatchStatistics.PlayerId = 4;
                //playerMatchStatistics.PlayerPoints = 100;
                //stats.Add(playerMatchStatistics);
                //playerMatchStatistics = new PlayerMatchStatistics();
                //playerMatchStatistics.PlayerId = 5;
                //playerMatchStatistics.PlayerPoints = 100;
                //stats.Add(playerMatchStatistics);
                //playerMatchStatistics = new PlayerMatchStatistics();
                //playerMatchStatistics.PlayerId = 6;
                //playerMatchStatistics.PlayerPoints = 100;
                //stats.Add(playerMatchStatistics);
                //playerMatchStatistics = new PlayerMatchStatistics();
                //playerMatchStatistics.PlayerId = 7;
                //playerMatchStatistics.PlayerPoints = 100;
                //stats.Add(playerMatchStatistics);
                //playerMatchStatistics = new PlayerMatchStatistics();
                //playerMatchStatistics.PlayerId = 8;
                //playerMatchStatistics.PlayerPoints = 100;
                //stats.Add(playerMatchStatistics);

                //Apply rules to the entries from the DB


                var json = "[{'matchPlayerPerformaId':1,'userId':1,'playerId':1,'matchId':1,'strike':4,'isCaughtAndBowled':false,'hasWicketTaken':false,'isStumped':false,'isRunOut':false,'isHalfCentury':false,'isCentury':false,'isFourWickets':false,'isEightWickets':false,'isMaidenOver':false,'isDismissalOnDuck':false,'totalRun':0,'totalWicket':0,'over':0.00},{'matchPlayerPerformaId':2,'userId':1,'playerId':8,'matchId':1,'strike':0,'isCaughtAndBowled':false,'hasWicketTaken':false,'isStumped':false,'isRunOut':true,'isHalfCentury':false,'isCentury':false,'isFourWickets':false,'isEightWickets':false,'isMaidenOver':false,'isDismissalOnDuck':false,'totalRun':0,'totalWicket':0,'over':0.00},{'matchPlayerPerformaId':3,'userId':1,'playerId':2,'matchId':1,'strike':0,'isCaughtAndBowled':false,'hasWicketTaken':false,'isStumped':true,'isRunOut':false,'isHalfCentury':false,'isCentury':false,'isFourWickets':false,'isEightWickets':false,'isMaidenOver':false,'isDismissalOnDuck':false,'totalRun':0,'totalWicket':0,'over':0.00},{'matchPlayerPerformaId':4,'userId':1,'playerId':3,'matchId':1,'strike':0,'isCaughtAndBowled':true,'hasWicketTaken':true,'isStumped':false,'isRunOut':false,'isHalfCentury':false,'isCentury':false,'isFourWickets':false,'isEightWickets':false,'isMaidenOver':false,'isDismissalOnDuck':false,'totalRun':0,'totalWicket':0,'over':0.00},{'matchPlayerPerformaId':5,'userId':1,'playerId':4,'matchId':1,'strike':6,'isCaughtAndBowled':false,'hasWicketTaken':false,'isStumped':false,'isRunOut':false,'isHalfCentury':true,'isCentury':false,'isFourWickets':false,'isEightWickets':false,'isMaidenOver':false,'isDismissalOnDuck':false,'totalRun':0,'totalWicket':0,'over':0.00},{'matchPlayerPerformaId':6,'userId':1,'playerId':5,'matchId':1,'strike':0,'isCaughtAndBowled':false,'hasWicketTaken':true,'isStumped':false,'isRunOut':false,'isHalfCentury':false,'isCentury':false,'isFourWickets':true,'isEightWickets':false,'isMaidenOver':true,'isDismissalOnDuck':false,'totalRun':0,'totalWicket':0,'over':0.00},{'matchPlayerPerformaId':7,'userId':1,'playerId':6,'matchId':1,'strike':0,'isCaughtAndBowled':false,'hasWicketTaken':false,'isStumped':false,'isRunOut':true,'isHalfCentury':false,'isCentury':false,'isFourWickets':false,'isEightWickets':false,'isMaidenOver':false,'isDismissalOnDuck':false,'totalRun':0,'totalWicket':0,'over':0.00},{'matchPlayerPerformaId':8,'userId':1,'playerId':7,'matchId':1,'strike':0,'isCaughtAndBowled':false,'hasWicketTaken':false,'isStumped':false,'isRunOut':false,'isHalfCentury':false,'isCentury':false,'isFourWickets':false,'isEightWickets':false,'isMaidenOver':false,'isDismissalOnDuck':true,'totalRun':0,'totalWicket':0,'over':0.00}]";
                //using (var httpClient = new HttpClient())
                //{


                //   json = httpClient.GetStringAsync(new Uri("http://idtp376.synerzipune.local:8562/api/PlayerPerfoma/")).Result;


                //}
                ValidationContext context = new ValidationContext();
                var playerStatistics      = JsonConvert.DeserializeObject <List <PlayerStatistics> >(json);
                foreach (var point in playerStatistics)
                {
                    //   var point = new PlayerStatistics { Strike = 3 };
                    var wicketpoints = Rule.Create(point,
                                                   entity => entity.Strike > 0 ?
                                                   CalculatePoints.CalculateStrikePoints(point, stats) :
                                                   CalculatePoints.FillEmptyPoints(point));

                    //  point = new PlayerStatistics { HasWicketTaken = true };
                    var strikePoints = Rule.Create(point,
                                                   entity => entity.HasWicketTaken == true ?
                                                   CalculatePoints.CalculateWicketsPoints(entity, stats) :
                                                   CalculatePoints.FillEmptyPoints(entity));

                    //   point = new PlayerStatistics { IsCaughtAndBowled = true };
                    var caughtandBowled = Rule.Create(point,
                                                      entity => entity.IsCaughtAndBowled == true ?
                                                      CalculatePoints.CalculateCaughtAndBowledPoints(entity, stats) :
                                                      CalculatePoints.FillEmptyPoints(entity));



                    //   point = new PlayerStatistics { IsRunout = false };
                    var runoutPoints = Rule.Create(point,
                                                   entity => entity.IsRunout == true ?
                                                   CalculatePoints.CalculateRunoutPoints(entity, stats) :
                                                   CalculatePoints.FillEmptyPoints(entity));


                    //  point = new PlayerStatistics { IsStumped = false };
                    var stumpOutPoints = Rule.Create(point,
                                                     entity => entity.IsStumped == true ?
                                                     CalculatePoints.CalculateStumpedPoints(entity, stats) :
                                                     CalculatePoints.FillEmptyPoints(entity));


                    var maidenOverPoints = Rule.Create(point,
                                                       entity => entity.IsMaidenOver == true ?
                                                       CalculatePoints.CalculateMaidenOverPoints(entity, stats) :
                                                       CalculatePoints.FillEmptyPoints(entity));



                    var eightWicketsPoints = Rule.Create(point,
                                                         entity => entity.IsEightWickets == true ?
                                                         CalculatePoints.CalculateEightWicketsPoints(entity, stats) :
                                                         CalculatePoints.FillEmptyPoints(entity));


                    var fourWicketsPoints = Rule.Create(point,
                                                        entity => entity.IsFourWickets == true ?
                                                        CalculatePoints.CalculateFourWicketsPoints(entity, stats) :
                                                        CalculatePoints.FillEmptyPoints(entity));


                    var halfCenturyWicketsPoints = Rule.Create(point,
                                                               entity => entity.IsHalfCentury == true ?
                                                               CalculatePoints.CalculateHalfCenturyPoints(entity, stats) :
                                                               CalculatePoints.FillEmptyPoints(entity));


                    var centurysPoints = Rule.Create(point,
                                                     entity => entity.IsCentury == true ?
                                                     CalculatePoints.CalculateCenturyPoints(entity, stats) :
                                                     CalculatePoints.FillEmptyPoints(entity));


                    var dismissalOnDuckPoints = Rule.Create(point,
                                                            entity => entity.IsDismissalOnDuck == true ?
                                                            CalculatePoints.CalculateDissmisalOnDuckPoints(entity, stats) :
                                                            CalculatePoints.FillEmptyPoints(entity));
                    context = new ValidationContext(wicketpoints, strikePoints, caughtandBowled, runoutPoints, stumpOutPoints, maidenOverPoints, eightWicketsPoints, fourWicketsPoints, halfCenturyWicketsPoints, centurysPoints, dismissalOnDuckPoints);

                    var totalPoints = context.GetResults();

                    totalPoints.Where(x => x.PlayerId > 0).ToList().ForEach(x => result.Add(new PlayerMatchStatistics {
                        PlayerId = x.PlayerId, PlayerPoints = x.PlayerPoints
                    }));
                }
                var res = result.GroupBy(x => x.PlayerId, (key, group) => group.First()).ToList();

                foreach (var player in res)
                {
                    using (var tx = this.StateManager.CreateTransaction())
                    {
                        var playerdetail = await playerMatchStatisticsDictionary.TryGetValueAsync(tx, player.PlayerId);

                        ServiceEventSource.Current.ServiceMessage(this.Context, "Current Counter Value: {0}",
                                                                  playerdetail.HasValue ? playerdetail.Value.ToString() : "Value does not exist.");

                        await playerMatchStatisticsDictionary.AddOrUpdateAsync(tx, player.PlayerId, player.PlayerPoints, (key, value) => player.PlayerPoints);

                        // If an exception is thrown before calling CommitAsync, the transaction aborts, all changes are
                        // discarded, and nothing is saved to the secondary replicas.
                        await tx.CommitAsync();
                    }
                }
                await Task.Delay(TimeSpan.FromMinutes(1));
            }
        }
Exemple #15
0
        public async Task <ActionResult <List <Employee> > > GetAll()
        {
            CancellationToken ct = new CancellationToken();

            IReliableDictionary <string, Employee> employees = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, Employee> >("employees");

            List <Employee> employeesList = new List <Employee>();

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <string, Employee> > list = await employees.CreateEnumerableAsync(tx);

                Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <string, Employee> > enumerator = list.GetAsyncEnumerator();

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

            return(new ObjectResult(employeesList));
        }
Exemple #16
0
        public async Task <IDictionary <string, string> > GetLARSLearningDeliveriesAsync(IEnumerable <string> learnAimRefs)
        {
            var stopwatch = new Stopwatch();
            var larsLearningDeliveries = await StateManager.GetOrAddAsync <IReliableDictionary <string, string> >("LARS_LearningDelivery");

            var list = new Dictionary <string, string>();

            using (var logger = ESFA.DC.Logging.LoggerManager.CreateDefaultLogger())
                using (var tx = StateManager.CreateTransaction())
                {
                    try
                    {
                        stopwatch.Start();
                        Microsoft.ServiceFabric.Data.IAsyncEnumerator <KeyValuePair <string, string> > enumerator =
                            (await larsLearningDeliveries.CreateEnumerableAsync(tx, (x) => learnAimRefs.Contains(x), EnumerationMode.Ordered)).GetAsyncEnumerator();

                        while (await enumerator.MoveNextAsync(CancellationToken.None))
                        {
                            list.Add(enumerator.Current.Key, enumerator.Current.Value);
                        }

                        logger.LogInfo($"Retrieved LARS LDs in {stopwatch.ElapsedMilliseconds}");
                        await tx.CommitAsync();

                        return(list);
                    }
                    catch (Exception ex)
                    {
                        tx.Abort();
                        logger.LogError("Error while reading from dic", ex);
                        return(null);
                    }
                }
        }
Exemple #17
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())
            {
                Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <string, int> > list = await votesDictionary.CreateEnumerableAsync(tx);

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

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

                while (await enumerator.MoveNextAsync(ct))
                {
                    logger.Debug("Voting Category {VoteCategoryName} and {Count}", enumerator.Current.Key, enumerator.Current.Value);
                    result.Add(enumerator.Current);
                }

                logger.Information("Retrieved list of voting options {@VoteOptions}", result);
                return(Json(result));
            }
        }
Exemple #18
0
        public async Task <CheckoutSummary[]> GetOrderHistoryAsync(string userId)
        {
            var checkoutSummaryRecords = new List <CheckoutSummary>();

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

            using (ITransaction transaction = StateManager.CreateTransaction())
            {
                Microsoft.ServiceFabric.Data.IAsyncEnumerable <KeyValuePair <DateTime, CheckoutSummary> > allProducts =
                    await history.CreateEnumerableAsync(transaction, EnumerationMode.Unordered);

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

            return(checkoutSummaryRecords.ToArray());
        }
        /// <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());
        }
        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);
        }
Exemple #21
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);
        }