Example #1
0
        private static ExitCodes ProgramExecution()
        {
            var logger     = new ConsoleLogger();
            var bundle     = DataBundle.GetDataBundle(_inputReferencePath, _inputPrefix);
            int numRefSeqs = bundle.SequenceReader.NumRefSeqs;
            var chromosome = ReferenceNameUtilities.GetChromosome(bundle.SequenceReader.RefNameToChromosome, _referenceName);

            bundle.Load(chromosome);

            string outputStub  = GetOutputStub(chromosome, bundle.Source);
            var    interval    = new ChromosomeInterval(chromosome, _referencePosition, _referenceEndPosition);
            var    transcripts = GetTranscripts(logger, bundle, interval);

            var    sift           = GetPredictionStaging(logger, "SIFT", transcripts, chromosome, bundle.SiftPredictions, bundle.SiftReader, x => x.SiftIndex, numRefSeqs);
            var    polyphen       = GetPredictionStaging(logger, "PolyPhen", transcripts, chromosome, bundle.PolyPhenPredictions, bundle.PolyPhenReader, x => x.PolyPhenIndex, numRefSeqs);
            string referenceBases = GetReferenceBases(logger, bundle.SequenceReader, interval);

            var regulatoryRegionIntervalArrays = GetRegulatoryRegionIntervalArrays(logger, bundle.TranscriptCache, interval, numRefSeqs);
            var transcriptIntervalArrays       = PredictionUtilities.UpdateTranscripts(transcripts, bundle.SiftPredictions,
                                                                                       sift.Predictions, bundle.PolyPhenPredictions, polyphen.Predictions, numRefSeqs);

            var transcriptStaging = GetTranscriptStaging(bundle.TranscriptCacheData.Header, transcriptIntervalArrays, regulatoryRegionIntervalArrays);

            WriteCache(logger, FileUtilities.GetCreateStream(CacheConstants.TranscriptPath(outputStub)), transcriptStaging, "transcript");
            WriteCache(logger, FileUtilities.GetCreateStream(CacheConstants.SiftPath(outputStub)), sift.Staging, "SIFT");
            WriteCache(logger, FileUtilities.GetCreateStream(CacheConstants.PolyPhenPath(outputStub)), polyphen.Staging, "PolyPhen");
            WriteReference(logger, CacheConstants.BasesPath(outputStub), bundle.SequenceReader, chromosome,
                           referenceBases, interval.Start);

            return(ExitCodes.Success);
        }
Example #2
0
        /// <summary>
        /// creates the global database
        /// </summary>
        public void CreateTranscriptCacheFile(string outputPrefix)
        {
            if (!_hasData)
            {
                throw new GeneralException("Data was not loaded before running CreateTranscriptCacheFile");
            }

            Console.Write("- creating transcript cache file... ");
            var createBenchmark = new Benchmark();

            var globalOutputPath = CacheConstants.TranscriptPath(outputPrefix);

            var customHeader = new GlobalCustomHeader(_transcriptReader.Header.VepReleaseTicks,
                                                      _transcriptReader.Header.VepVersion);

            var header = new FileHeader(CacheConstants.Identifier, CacheConstants.SchemaVersion,
                                        CacheConstants.DataVersion, _transcriptReader.Header.TranscriptSource, _currentTimeTicks, _transcriptReader.Header.GenomeAssembly, customHeader);

            var genes = ConvertGenes();

            using (var writer = new GlobalCacheWriter(globalOutputPath, header))
            {
                var cache = new VD.GlobalCache(header, _transcripts.ToArray(), _regulatoryElements.ToArray(),
                                               genes, _introns.ToArray(), _microRnas.ToArray(), _peptideSeqs.ToArray());

                writer.Write(cache);
            }

            Console.WriteLine("{0}", Benchmark.ToHumanReadable(createBenchmark.GetElapsedTime()));
        }
Example #3
0
        public void PolyPhenPath_NominalCase()
        {
            const string expectedResult = "bob.polyphen.ndb";
            var          observedResult = CacheConstants.PolyPhenPath("bob");

            Assert.Equal(expectedResult, observedResult);
        }
Example #4
0
        private void CombinePredictionsCaches()
        {
            Console.WriteLine("Writing combined Sift...");

            var mergedSift = GetMergedPredictions(CacheConstants.SiftPath(_prefix1), CacheConstants.SiftPath(_prefix2));

            using (var writer = new PredictionCacheWriter(CacheConstants.SiftPath(_outPrefix), PredictionCacheHeader.GetHeader(DateTime.Now.Ticks, _genomeAssembly, _numRefSeq)))
            {
                var lookupTableList = new List <Prediction.Entry>();
                foreach (var predictionCach in mergedSift)
                {
                    lookupTableList.AddRange(predictionCach.LookupTable);
                }

                writer.Write(lookupTableList.ToArray(), mergedSift.Select(cache => cache.Predictions).ToArray());
            }
            Console.WriteLine("Done.");

            Console.WriteLine("writing combined polyphen");
            var mergedPolyphen = GetMergedPredictions(CacheConstants.PolyPhenPath(_prefix1), CacheConstants.PolyPhenPath(_prefix2));

            using (var writer = new PredictionCacheWriter(CacheConstants.PolyPhenPath(_outPrefix), PredictionCacheHeader.GetHeader(DateTime.Now.Ticks, _genomeAssembly, _numRefSeq)))
            {
                var lookupTableList = new List <Prediction.Entry>();
                foreach (var predictionCach in mergedPolyphen)
                {
                    lookupTableList.AddRange(predictionCach.LookupTable);
                }

                writer.Write(lookupTableList.ToArray(), mergedPolyphen.Select(cache => cache.Predictions).ToArray());
            }
            Console.WriteLine("Done");
        }
        public TranscriptAnnotationProvider(string pathPrefix, ISequenceProvider sequenceProvider, ProteinConservationProvider conservationProvider)
        {
            Name                  = "Transcript annotation provider";
            _sequence             = sequenceProvider.Sequence;
            _refNameToChromosome  = sequenceProvider.RefNameToChromosome;
            _conservationProvider = conservationProvider;

            using (var stream = PersistentStreamUtils.GetReadStream(CacheConstants.TranscriptPath(pathPrefix)))
            {
                (_transcriptCache, TranscriptIntervalArrays, VepVersion) = InitiateCache(stream, sequenceProvider.RefIndexToChromosome, sequenceProvider.Assembly);
            }

            Assembly           = _transcriptCache.Assembly;
            DataSourceVersions = _transcriptCache.DataSourceVersions;

            // TODO: this is not great. We should not be using IEnumerables if we have to resort to strange stuff like this
            if (conservationProvider != null)
            {
                DataSourceVersions = DataSourceVersions.Concat(new[] { conservationProvider.Version });
            }

            _siftStream = PersistentStreamUtils.GetReadStream(CacheConstants.SiftPath(pathPrefix));
            _siftReader = new PredictionCacheReader(_siftStream, PredictionCacheReader.SiftDescriptions);

            _polyphenStream = PersistentStreamUtils.GetReadStream(CacheConstants.PolyPhenPath(pathPrefix));
            _polyphenReader = new PredictionCacheReader(_polyphenStream, PredictionCacheReader.PolyphenDescriptions);
        }
        private static ExitCodes ProgramExecution()
        {
            using (var writer = GZipUtilities.GetStreamWriter(_outputFileName))
            {
                string cachePath    = CacheConstants.TranscriptPath(_inputPrefix);
                var    sequenceData = SequenceHelper.GetDictionaries(_referencePath);

                // load the cache
                Console.Write("- reading {0}... ", Path.GetFileName(cachePath));
                var cache = TranscriptCacheHelper.GetCache(cachePath, sequenceData.refIndexToChromosome);
                Console.WriteLine("found {0:N0} reference sequences. ", cache.RegulatoryRegionIntervalArrays.Length);

                Console.Write("- writing GFF entries... ");
                foreach (var intervalArray in cache.RegulatoryRegionIntervalArrays)
                {
                    if (intervalArray == null)
                    {
                        continue;
                    }
                    foreach (var interval in intervalArray.Array)
                    {
                        WriteRegulatoryFeature(writer, interval.Value);
                    }
                }
                Console.WriteLine("finished.");
            }

            return(ExitCodes.Success);
        }
Example #7
0
        /// <inheritdoc />
        /// <exception cref="UserNotFoundException">Thrown when user is not found</exception>
        public async Task RemoveUserByIdAsync(string userId)
        {
            var userToRemove = await _userManager.FindByIdAsync(userId);

            if (userToRemove == null)
            {
                throw new UserNotFoundException();
            }
            await _db.Entry(userToRemove).Collection(u => u.Todos).LoadAsync();

            // Clear cached todos owned by the user
            foreach (var todo in userToRemove.Todos)
            {
                _cache.Remove(CacheConstants.GetSingleTodoCacheKey(
                                  todo.Id, userToRemove.Id));
                _cache.Remove(CacheConstants.GetAllTodosForDayCacheKey(
                                  userToRemove.Id, todo.Due.Date));
            }
            _cache.Remove(CacheConstants.GetAllTodosCacheKey(userToRemove.Id));
            _db.RemoveRange(userToRemove.Todos);

            await _userManager.DeleteAsync(userToRemove);

            await _db.SaveChangesAsync();

            // Clear user if cached and all user list.
            _cache.Remove(CacheConstants.GetSingleUserCacheKey(userToRemove.Id));
            _cache.Remove(CacheConstants.AllUsersCacheKey);
        }
Example #8
0
        public void SiftPath_NominalCase()
        {
            const string expectedResult = "bob.sift.ndb";
            var          observedResult = CacheConstants.SiftPath("bob");

            Assert.Equal(expectedResult, observedResult);
        }
Example #9
0
        public void TranscriptPath_NominalCase()
        {
            const string expectedResult = "bob.transcripts.ndb";
            var          observedResult = CacheConstants.TranscriptPath("bob");

            Assert.Equal(expectedResult, observedResult);
        }
        private static ExitCodes ProgramExecution()
        {
            var sequenceData = SequenceHelper.GetDictionaries(_refSequencePath);
            var logger       = new ConsoleLogger();

            var caches = LoadTranscriptCaches(logger, CacheConstants.TranscriptPath(_inputPrefix),
                                              CacheConstants.TranscriptPath(_inputPrefix2), sequenceData.refIndexToChromosome);

            if (caches.Cache.TranscriptIntervalArrays.Length != caches.Cache2.TranscriptIntervalArrays.Length)
            {
                throw new InvalidDataException($"Expected the number of reference sequences in cache 1 ({caches.Cache.TranscriptIntervalArrays.Length}) and cache 2 ({caches.Cache2.TranscriptIntervalArrays.Length}) to be the same.");
            }

            int numRefSeqs                = caches.Cache.TranscriptIntervalArrays.Length;
            var combinedIntervalArrays    = new IntervalArray <ITranscript> [numRefSeqs];
            var siftPredictionsPerRef     = new Prediction[numRefSeqs][];
            var polyphenPredictionsPerRef = new Prediction[numRefSeqs][];

            PredictionHeader siftHeader;
            PredictionHeader polyphenHeader;

            using (var siftReader = new PredictionCacheReader(FileUtilities.GetReadStream(CacheConstants.SiftPath(_inputPrefix)), PredictionCacheReader.SiftDescriptions))
                using (var siftReader2 = new PredictionCacheReader(FileUtilities.GetReadStream(CacheConstants.SiftPath(_inputPrefix2)), PredictionCacheReader.SiftDescriptions))
                    using (var polyphenReader = new PredictionCacheReader(FileUtilities.GetReadStream(CacheConstants.PolyPhenPath(_inputPrefix)), PredictionCacheReader.PolyphenDescriptions))
                        using (var polyphenReader2 = new PredictionCacheReader(FileUtilities.GetReadStream(CacheConstants.PolyPhenPath(_inputPrefix2)), PredictionCacheReader.PolyphenDescriptions))
                        {
                            siftHeader     = siftReader.Header;
                            polyphenHeader = polyphenReader.Header;

                            for (ushort refIndex = 0; refIndex < numRefSeqs; refIndex++)
                            {
                                var chromosome = sequenceData.refIndexToChromosome[refIndex];

                                Console.ForegroundColor = ConsoleColor.Yellow;
                                logger.WriteLine($"\n{chromosome.UcscName}:");
                                Console.ResetColor();

                                var sift = CombinePredictions(logger, chromosome, "SIFT", siftReader, siftReader2);
                                siftPredictionsPerRef[refIndex] = sift.Predictions;

                                var polyphen = CombinePredictions(logger, chromosome, "PolyPhen", polyphenReader, polyphenReader2);
                                polyphenPredictionsPerRef[refIndex] = polyphen.Predictions;

                                var transcriptIntervalArray  = caches.Cache.TranscriptIntervalArrays[refIndex];
                                var transcriptIntervalArray2 = caches.Cache2.TranscriptIntervalArrays[refIndex];

                                combinedIntervalArrays[refIndex] = CombineTranscripts(logger, transcriptIntervalArray,
                                                                                      transcriptIntervalArray2, sift.Offset, polyphen.Offset);
                            }
                        }

            logger.WriteLine();
            WritePredictions(logger, "SIFT", CacheConstants.SiftPath(_outputPrefix), siftHeader, siftPredictionsPerRef);
            WritePredictions(logger, "PolyPhen", CacheConstants.PolyPhenPath(_outputPrefix), polyphenHeader, polyphenPredictionsPerRef);
            WriteTranscripts(logger, CloneHeader(caches.Cache.Header), combinedIntervalArrays,
                             caches.Cache.RegulatoryRegionIntervalArrays);

            return(ExitCodes.Success);
        }
Example #11
0
        private static ExitCodes ProgramExecution()
        {
            var cachePath = CacheConstants.TranscriptPath(_inputPrefix);
            var header    = GetHeaderInformation(cachePath);

            Console.WriteLine($"Versions: Schema: {header.Schema}, Data: {header.Data}, VEP: {header.Vep}");
            return(ExitCodes.Success);
        }
Example #12
0
 public PianoAnnotationProvider(string pathPrefix, ISequenceProvider sequenceProvider)
 {
     Name               = "Transcript annotation provider";
     _sequence          = sequenceProvider.Sequence;
     _transcriptCache   = InitiateCache(FileUtilities.GetReadStream(CacheConstants.TranscriptPath(pathPrefix)), sequenceProvider.GetChromosomeIndexDictionary(), sequenceProvider.GenomeAssembly, sequenceProvider.NumRefSeqs);
     GenomeAssembly     = _transcriptCache.GenomeAssembly;
     DataSourceVersions = _transcriptCache.DataSourceVersions;
 }
Example #13
0
 /// <summary>
 /// constructor
 /// </summary>
 public CacheCombiner(string inputPrefix1, string inputPrefix2, string outputPrefix)
 {
     _prefix1         = inputPrefix1;
     _prefix2         = inputPrefix2;
     _outPrefix       = outputPrefix;
     _cachePath1      = CacheConstants.TranscriptPath(inputPrefix1);
     _cachePath2      = CacheConstants.TranscriptPath(inputPrefix2);
     _outputCachePath = CacheConstants.TranscriptPath(outputPrefix);
 }
        private static void WriteTranscripts(ILogger logger, CacheHeader header,
                                             IntervalArray <ITranscript>[] transcriptIntervalArrays,
                                             IntervalArray <IRegulatoryRegion>[] regulatoryRegionIntervalArrays)
        {
            var staging = TranscriptCacheStaging.GetStaging(header, transcriptIntervalArrays, regulatoryRegionIntervalArrays);

            logger.Write("- writing transcripts... ");
            staging.Write(FileUtilities.GetCreateStream(CacheConstants.TranscriptPath(_outputPrefix)));
            logger.WriteLine("finished.");
        }
Example #15
0
        public void GetSingleUserCacheKey_WithUuid_Matches()
        {
            // Arrange
            const string userId = "31f4a428-33b7-45c3-a886-a63d93543166";

            // Act
            var cacheKey = CacheConstants.GetSingleUserCacheKey(userId);

            // Assert
            Assert.Equal("c_user_31f4a428-33b7-45c3-a886-a63d93543166", cacheKey);
        }
Example #16
0
        public void GetAllTodosCacheKey_WithUuid_Matches()
        {
            // Arrange
            const string id = "79744ca4-c450-40ed-8ea4-daf0569b70e1";

            // Act
            var cacheKey = CacheConstants.GetAllTodosCacheKey(id);

            // Assert
            Assert.Equal("c_todos_79744ca4-c450-40ed-8ea4-daf0569b70e1", cacheKey);
        }
Example #17
0
        public void GetSingleTodoCacheKey_WithUuidAndTodoId_Matches()
        {
            // Arrange
            const string userId = "f7b3d1d1-4c9c-43d3-a929-a6d06d49885c";
            const int    todoId = 55;

            // Act
            var cacheKey = CacheConstants.GetSingleTodoCacheKey(todoId, userId);

            // Assert
            Assert.Equal("c_todo_55_f7b3d1d1-4c9c-43d3-a929-a6d06d49885c", cacheKey);
        }
Example #18
0
        public void GetAllTodosForDayCacheKey_WithUuidAndTodoId_Matches()
        {
            // Arrange
            const string id  = "7d02b709-d300-44e5-90a7-39fc233d0ca9";
            var          day = new DateTime(1999, 2, 10, 4, 22, 1);

            // Act
            var cacheKey = CacheConstants.GetAllTodosForDayCacheKey(id, day);

            // Assert
            Assert.Equal("c_todos_7d02b709-d300-44e5-90a7-39fc233d0ca9_1999_2_10", cacheKey);
        }
Example #19
0
        public static ExitCodes Run(string command, string[] commandArgs)

        {
            var ops = new OptionSet
            {
                {
                    "ref|r=",
                    "compressed reference sequence file",
                    v => _compressedReference = v
                },
                {
                    "cache|c=",
                    "Transcript cache prefix",
                    v => _transcriptCachePrefix = v
                },
                {
                    "gene|g=",
                    "Gene info data file from NCBI",
                    v => _geneInfoFile = v
                },
                {
                    "in|i=",
                    "input VCF file path",
                    v => _inputFile = v
                },
                {
                    "out|o=",
                    "output directory",
                    v => _outputDirectory = v
                }
            };

            string commandLineExample = $"{command} [options]";

            var exitCode = new ConsoleAppBuilder(commandArgs, ops)
                           .Parse()
                           .CheckInputFilenameExists(_compressedReference, "compressed reference sequence file name", "--ref")
                           .HasRequiredParameter(_transcriptCachePrefix, "transcript cache file", "--cache")
                           .CheckInputFilenameExists(CacheConstants.TranscriptPath(_transcriptCachePrefix), "transcript cache prefix", "--cache")
                           .HasRequiredParameter(_inputFile, "SpliceAI VCF file", "--in")
                           .CheckInputFilenameExists(_inputFile, "SpliceAI VCF file", "--in")
                           .HasRequiredParameter(_geneInfoFile, "Gene info data file from NCBI", "--gene")
                           .CheckInputFilenameExists(_geneInfoFile, "Gene info data file from NCBI", "--gene")
                           .HasRequiredParameter(_outputDirectory, "output directory", "--out")
                           .CheckDirectoryExists(_outputDirectory, "output directory", "--out")
                           .SkipBanner()
                           .ShowHelpMenu("Creates a supplementary database containing 1000 Genomes allele frequencies", commandLineExample)
                           .ShowErrors()
                           .Execute(ProgramExecution);

            return(exitCode);
        }
Example #20
0
        public void GetDefaultCacheOptions_HasCorrectExpireTime()
        {
            // Arrange
            const int expecteSeconds = 3600;

            // Act
            var options  = CacheConstants.GetDefaultCacheOptions();
            var lifeSpan = options?.SlidingExpiration?.TotalSeconds;

            // Assert
            Assert.NotNull(lifeSpan);
            Assert.Equal(expecteSeconds, lifeSpan);
        }
        public TranscriptAnnotationProvider(string pathPrefix, ISequenceProvider sequenceProvider)
        {
            Name      = "Transcript annotation provider";
            _sequence = sequenceProvider.Sequence;

            (_transcriptCache, VepVersion) = InitiateCache(FileUtilities.GetReadStream(CacheConstants.TranscriptPath(pathPrefix)),
                                                           sequenceProvider.RefIndexToChromosome, sequenceProvider.GenomeAssembly);

            GenomeAssembly     = _transcriptCache.GenomeAssembly;
            DataSourceVersions = _transcriptCache.DataSourceVersions;

            _siftReader     = new PredictionCacheReader(FileUtilities.GetReadStream(CacheConstants.SiftPath(pathPrefix)), PredictionCacheReader.SiftDescriptions);
            _polyphenReader = new PredictionCacheReader(FileUtilities.GetReadStream(CacheConstants.PolyPhenPath(pathPrefix)), PredictionCacheReader.PolyphenDescriptions);
        }
Example #22
0
        public void Update()
        {
            var objModules = new ModuleController();

            objModules.UpdateTabModuleSetting(_tabModuleId, SettingName.History, History.ToString(CultureInfo.InvariantCulture));
            objModules.UpdateModuleSetting(_moduleId, SettingName.DescriptionLength, DescriptionLength.ToString(CultureInfo.InvariantCulture));
            objModules.UpdateTabModuleSetting(_tabModuleId, SettingName.EditorHeight, EditorHeight.ToString(CultureInfo.InvariantCulture));
            objModules.UpdateTabModuleSetting(_tabModuleId, SettingName.DefaultViewType, Utilities.ViewTypeToString(DefaultViewType));
            objModules.UpdateModuleSetting(_moduleId, SettingName.Legacy, Legacy.ToString(CultureInfo.InvariantCulture));
            objModules.UpdateTabModuleSetting(_tabModuleId, SettingName.TemplateType, TemplateType);
            objModules.UpdateTabModuleSetting(_tabModuleId, SettingName.TemplateName, TemplateName);
            objModules.UpdateTabModuleSetting(_tabModuleId, SettingName.TemplateLocation, TemplateLocation);

            DataCache.RemoveCache(CacheConstants.SettingsCacheKeyFormat(_moduleId, _tabModuleId));
        }
Example #23
0
        static int Main(string[] args)
        {
            var ops = new OptionSet
            {
                {
                    "cache|c=",
                    "input cache {prefix}",
                    v => ConfigurationSettings.InputCachePrefix = v
                },
                {
                    "in|i=",
                    "input VCF {path}",
                    v => ConfigurationSettings.VcfPath = v
                },
                {
                    "out|o=",
                    "output {file path} ",
                    v => ConfigurationSettings.OutputFileName = v
                },
                {
                    "ref|r=",
                    "input compressed reference sequence {path}",
                    v => ConfigurationSettings.RefSequencePath = v
                },
                {
                    "force-mt",
                    "forces to annotate mitochondria variants",
                    v => ConfigurationSettings.ForceMitochondrialAnnotation = v != null
                }
            };

            var commandLineExample = "-i <vcf path> -d <cache dir> -r <ref path> -o <base output filename>";

            var piano    = new Piano();
            var exitCode = new ConsoleAppBuilder(args, ops)
                           .UseVersionProvider(new VersionProvider())
                           .Parse()
                           .CheckInputFilenameExists(ConfigurationSettings.VcfPath, "vcf", "--in", true, "-")
                           .CheckInputFilenameExists(ConfigurationSettings.RefSequencePath, "reference sequence", "--ref")
                           .CheckInputFilenameExists(CacheConstants.TranscriptPath(ConfigurationSettings.InputCachePrefix), "transcript cache", "--cache")
                           .HasRequiredParameter(ConfigurationSettings.OutputFileName, "output file stub", "--out")
                           .ShowBanner(Constants.Authors)
                           .ShowHelpMenu("peptide annotation", commandLineExample)
                           .ShowErrors()
                           .Execute(piano.ProgramExecution);

            return((int)exitCode);
        }
Example #24
0
        public void Create()
        {
            using (var reader = new GlobalCacheReader(CacheConstants.TranscriptPath(_inputPrefix)))
                using (var writer = GZipUtilities.GetStreamWriter(_outPath))
                {
                    WriteVcfHeader(writer);

                    var cache = reader.Read();
                    Console.Write("- found {0} transcripts... ", cache.Transcripts.Length);
                    foreach (var transcript in cache.Transcripts)
                    {
                        CreateVcf(writer, transcript);
                    }
                    Console.WriteLine("finished.");
                }
        }
Example #25
0
        /// <inheritdoc />
        /// <exception cref="TodoNotFoundException">When todo is not found</exception>
        public async Task RemoveTodoByIdAsync(int todoId, string userId)
        {
            var todo = await _db.Todo.SingleOrDefaultAsync(t => t.Id == todoId && t.Owner.Id == userId);

            if (todo == null)
            {
                throw new TodoNotFoundException();
            }
            _db.Remove(todo);
            await _db.SaveChangesAsync();

            // Clear all related caches
            _cache.Remove(CacheConstants.GetSingleTodoCacheKey(todoId, userId));
            _cache.Remove(CacheConstants.GetAllTodosCacheKey(userId));
            _cache.Remove(CacheConstants.GetAllTodosForDayCacheKey(userId, todo.Due));
        }
Example #26
0
        /// <inheritdoc />
        /// <exception cref="UserNotFoundException">Thrown when user is not found</exception>
        public async Task <ApplicationUserDto> GetUserByIdAsync(string userId)
        {
            var cacheKey = CacheConstants.GetSingleUserCacheKey(userId);

            if (!_cache.TryGetValue(cacheKey, out ApplicationUser user))
            {
                user = await _userManager.FindByIdAsync(userId);

                if (user == null)
                {
                    throw new UserNotFoundException();
                }
                _cache.Set(cacheKey, user, CacheConstants.GetDefaultCacheOptions());
            }
            return(new ApplicationUserDto(user));
        }
Example #27
0
        /// <inheritdoc />
        public async Task <IEnumerable <ApplicationUserDto> > GetAllUsersOrderedByNameAsync()
        {
            const string cacheKey = CacheConstants.AllUsersCacheKey;

            if (!_cache.TryGetValue(cacheKey, out List <ApplicationUserDto> users))
            {
                users = await _userManager
                        .Users
                        .Select(u => new ApplicationUserDto(u))
                        .OrderBy(u => u.Name)
                        .ToListAsync();

                _cache.Set(cacheKey, users, CacheConstants.GetDefaultCacheOptions());
            }
            return(users);
        }
Example #28
0
        private static ExitCodes ProgramExecution()
        {
            string cachePath = CacheConstants.TranscriptPath(_inputPrefix);

            var(refIndexToChromosome, _, _) = SequenceHelper.GetDictionaries(_compressedReferencePath);
            var cache            = TranscriptCacheHelper.GetCache(cachePath, refIndexToChromosome);
            var geneToInternalId = InternalGenes.CreateDictionary(cache.Genes);

            using (var writer = new GffWriter(GZipUtilities.GetStreamWriter(_outputFileName)))
            {
                var creator = new GffCreator(writer, geneToInternalId);
                creator.Create(cache.TranscriptIntervalArrays);
            }

            return(ExitCodes.Success);
        }
Example #29
0
        /// <inheritdoc />
        /// <exception cref="TodoNotFoundException">When todo is not found</exception>
        public async Task <TodoDto> GetTodoByIdAsync(int todoId, string userId)
        {
            var cacheKey = CacheConstants.GetSingleTodoCacheKey(todoId, userId);

            if (!_cache.TryGetValue(cacheKey, out Todo todo))
            {
                todo = await _db.Todo.SingleOrDefaultAsync(t =>
                                                           t.Id == todoId && t.Owner.Id == userId);

                if (todo == null)
                {
                    throw new TodoNotFoundException();
                }
                _cache.Set(cacheKey, todo, CacheConstants.GetDefaultCacheOptions());
            }
            return(new TodoDto(todo));
        }
Example #30
0
        /// <summary>
        /// Filters the list by a date (ignoring time).
        /// </summary>
        /// <param name="date">Valid date to filter by</param>
        /// <param name="userId">The id of the token owner</param>
        /// <returns>List of todos</returns>
        private async Task <IEnumerable <TodoDto> > GetAllTodosForDayOrderedByDueAsync(DateTime date, string userId)
        {
            var cacheKey = CacheConstants.GetAllTodosForDayCacheKey(userId, date);

            if (!_cache.TryGetValue(cacheKey, out List <TodoDto> todos))
            {
                todos = await(from t in _db.Todo
                              where t.Due.Date == date && t.Owner.Id == userId
                              orderby t.Due
                              select new TodoDto(t)).ToListAsync();
                if (todos.Any())
                {
                    _cache.Set(cacheKey, CacheConstants.GetDefaultCacheOptions());
                }
            }
            return(todos);
        }