Beispiel #1
0
        /// <summary>
        /// Get the stats of Mutants and Humans.
        /// </summary>
        /// <returns>DNA stats</returns>
        public async Task <DnaStats> GetDnaStatsAsync()
        {
            //I made both calls in parallel, using memory cache
            Task <int> mutantsTask = _memoryCacheService.GetAsync("mutantsCount", () => _dnaService.GetMutantsCountAsync());
            Task <int> humansTask  = _memoryCacheService.GetAsync("humansCount", () => _dnaService.GetHumansCountAsync());

            //then, I await the results and set the ratio
            int     mutants = await mutantsTask;
            int     humans  = await humansTask;
            decimal ratio   = mutants;

            if (humans > 0)
            {
                ratio /= humans;
            }
            ratio = Math.Round(ratio, 2);

            //finally, I return the results
            return(new DnaStats()
            {
                CountMutantDna = mutants,
                CountHumanDna = humans,
                Ratio = ratio
            });
        }
Beispiel #2
0
        /// <summary>
        /// Detects if a human is a mutant through its dna chain.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown when human parameter is null</exception>
        /// <exception cref="DnaInvalidException">Thrown when dna chain is not valid</exception>
        /// <param name="human">Human being with a Dna chain</param>
        /// <returns>True if it's mutant; false if not.</returns>
        public virtual async Task <bool> IsMutantAsync(Human human)
        {
            //pre-conditions
            if (human == null)
            {
                throw new ArgumentNullException(nameof(human));
            }

            string[] dna      = human.Dna;
            bool     isMutant = false;

            //first at all, I have to validate the dna
            if (IsDnaValid(dna))
            {
                string chainString = string.Join(",", dna);

                Dna savedDna = await _memoryCacheService.GetAsync(chainString, () => _dnaService.GetByChainAsync(dna));

                if (savedDna != null)
                {
                    //I get the saved value
                    isMutant = savedDna.IsMutant;
                }
                else
                {
                    //I save the verified entity
                    isMutant = VerifyIsMutant(dna);

                    Dna dnaEnt = new Dna()
                    {
                        ChainString = chainString,
                        IsMutant    = isMutant
                    };

                    await MemoryCacheService.TriggerSaveActionAsync(dnaEnt, 1, (ICollection <Dna> dnas) => _dnaService.SaveAsync(dnas));
                }
            }

            return(isMutant);
        }