/// <summary>
        /// The edit.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task <ActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            SequenceGroup sequenceGroup = await db.SequenceGroup.FindAsync(id);

            if (sequenceGroup == null)
            {
                return(HttpNotFound());
            }

            using (var db = new LibiadaWebEntities())
            {
                var viewDataHelper   = new ViewDataHelper(db);
                var viewData         = viewDataHelper.FillViewData(1, int.MaxValue);
                var matterRepository = new MatterRepository(db);
                var matterIds        = sequenceGroup.Matters.Select(m => m.Id);
                bool Selected(Matter m) => matterIds.Contains(m.Id);

                viewData["matters"]            = matterRepository.GetMatterSelectList(db.Matter, Selected);
                viewData["sequenceGroupTypes"] = EnumExtensions.ToArray <SequenceGroupType>().ToSelectListWithNature();
                ViewBag.data = JsonConvert.SerializeObject(viewData);
            }

            return(View(sequenceGroup));
        }
        public void FillGroupAndSequenceTypeTest(string name, Nature nature, Group group, SequenceType sequenceType)
        {
            var matter = new Matter
            {
                Name   = name,
                Nature = nature
            };

            MatterRepository.FillGroupAndSequenceType(matter);

            Assert.AreEqual(group, matter.Group);
            Assert.AreEqual(sequenceType, matter.SequenceType);
        }
Example #3
0
        public ActionResult Index(long matterId,
                                  Notation notation,
                                  Language?language,
                                  Translator?translator,
                                  PauseTreatment?pauseTreatment,
                                  bool?sequentialTransfer,
                                  int scrambling)
        {
            Matter matter = Cache.GetInstance().Matters.Single(m => m.Id == matterId);
            long   sequenceId;

            switch (matter.Nature)
            {
            case Nature.Literature:
                sequenceId = db.LiteratureSequence.Single(l => l.MatterId == matterId &&
                                                          l.Notation == notation &&
                                                          l.Language == language &&
                                                          l.Translator == translator).Id;
                break;

            case Nature.Music:
                sequenceId = db.MusicSequence.Single(m => m.MatterId == matterId &&
                                                     m.Notation == notation &&
                                                     m.PauseTreatment == pauseTreatment &&
                                                     m.SequentialTransfer == sequentialTransfer).Id;
                break;

            default:
                sequenceId = db.CommonSequence.Single(c => c.MatterId == matterId && c.Notation == notation).Id;
                break;
            }

            BaseChain chain = sequenceRepository.GetLibiadaBaseChain(sequenceId);

            for (int i = 0; i < scrambling; i++)
            {
                int firstIndex  = randomGenerator.Next(chain.Length);
                int secondIndex = randomGenerator.Next(chain.Length);

                IBaseObject firstElement  = chain[firstIndex];
                IBaseObject secondElement = chain[secondIndex];
                chain[firstIndex]  = secondElement;
                chain[secondIndex] = firstElement;
            }

            var resultMatter = new Matter
            {
                Nature = matter.Nature,
                Name   = $"{matter.Name} {scrambling} mixes"
            };
            MatterRepository matterRepository = new MatterRepository(db);

            matterRepository.SaveToDatabase(resultMatter);

            var result = new CommonSequence
            {
                Notation = notation,
                MatterId = resultMatter.Id
            };

            long[] alphabet = elementRepository.ToDbElements(chain.Alphabet, notation, false);

            switch (matter.Nature)
            {
            case Nature.Genetic:
                DnaSequence dnaSequence = db.DnaSequence.Single(c => c.Id == sequenceId);

                dnaSequenceRepository.Create(result, dnaSequence.Partial, alphabet, chain.Building);
                break;

            case Nature.Music:
                musicSequenceRepository.Create(result, alphabet, chain.Building);
                break;

            case Nature.Literature:
                LiteratureSequence sequence = db.LiteratureSequence.Single(c => c.Id == sequenceId);

                literatureSequenceRepository.Create(result, sequence.Original, sequence.Language, sequence.Translator, alphabet, chain.Building);
                break;

            case Nature.MeasurementData:
                dataSequenceRepository.Create(result, alphabet, chain.Building);
                break;

            default:
                throw new InvalidEnumArgumentException(nameof(matter.Nature), (int)matter.Nature, typeof(Nature));
            }

            return(RedirectToAction("Index", "Matters"));
        }
        /// <summary>
        /// The index.
        /// </summary>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult Index()
        {
            using (var db = new LibiadaWebEntities())
            {
                var           matterRepository         = new MatterRepository(db);
                var           dnaSequenceRepository    = new GeneticSequenceRepository(db);
                var           commonSequenceRepository = new CommonSequenceRepository(db);
                var           elementRepository        = new ElementRepository(db);
                var           matterIds = new long[] { 1332, 1333, 1339, 1330, 1337, 1342, 1331, 1338, 1340, 1943, 1945, 1334 };
                DnaSequence[] sequences = db.DnaSequence.Include(d => d.Matter).Where(d => matterIds.Contains(d.MatterId)).ToArray();

                for (int i = 0; i < sequences.Length; i++)
                {
                    var newMatter = new Matter
                    {
                        Name         = $"{sequences[i].Matter.Name} Cleaned of IS110",
                        Description  = sequences[i].Matter.Description,
                        Nature       = sequences[i].Matter.Nature,
                        Group        = sequences[i].Matter.Group,
                        SequenceType = sequences[i].Matter.SequenceType
                    };

                    var newSequence = new CommonSequence
                    {
                        Notation    = sequences[i].Notation,
                        Matter      = newMatter,
                        Description = sequences[i].Description,
                        RemoteDb    = sequences[i].RemoteDb,
                        RemoteId    = sequences[i].RemoteId
                    };
                    var chain = commonSequenceRepository.GetLibiadaChain(sequences[i].Id);

                    matterRepository.CreateOrExtractExistingMatterForSequence(newSequence);
                    dnaSequenceRepository.Create(newSequence, false, elementRepository.ToDbElements(chain.Alphabet, Notation.Nucleotides, false), chain.Building);
                    var sequenceId              = sequences[i].Id;
                    var subsequences            = db.Subsequence.Include(s => s.Position).Include(s => s.SequenceAttribute).Where(s => s.SequenceId == sequenceId).ToList();
                    var subsequenceIds          = subsequences.Select(s => s.Id);
                    var subsequencesIdsToRemove = db.SequenceAttribute
                                                  .Where(sa => subsequenceIds.Contains(sa.SequenceId) && sa.Value.Contains("IS110"))
                                                  .Select(sa => sa.SequenceId)
                                                  .Distinct()
                                                  .ToArray();

                    subsequences.RemoveAll(s => subsequencesIdsToRemove.Contains(s.Id));

                    var newSubsequences       = new Subsequence[subsequences.Count];
                    var newSequenceAttributes = new List <SequenceAttribute>();
                    var newPositions          = new List <Position>();
                    for (int j = 0; j < subsequences.Count; j++)
                    {
                        newSubsequences[j] = new Subsequence
                        {
                            Id         = db.GetNewElementId(),
                            Feature    = subsequences[j].Feature,
                            SequenceId = newSequence.Id,
                            Start      = subsequences[j].Start,
                            Length     = subsequences[j].Length,
                            RemoteId   = subsequences[j].RemoteId,
                            Partial    = subsequences[j].Partial
                        };

                        foreach (SequenceAttribute subsequenceAttribute in subsequences[j].SequenceAttribute.ToArray())
                        {
                            newSequenceAttributes.Add(new SequenceAttribute
                            {
                                SequenceId = newSubsequences[j].Id,
                                Attribute  = subsequenceAttribute.Attribute,
                                Value      = subsequenceAttribute.Value
                            });
                        }

                        foreach (Position position in subsequences[j].Position.ToArray())
                        {
                            newPositions.Add(new Position
                            {
                                SubsequenceId = newSubsequences[j].Id,
                                Length        = position.Length,
                                Start         = position.Start
                            });
                        }
                    }

                    db.Subsequence.AddRange(newSubsequences);
                    db.SequenceAttribute.AddRange(newSequenceAttributes);
                    db.Position.AddRange(newPositions);
                    db.SaveChanges();
                }
            }

            return(View());
        }
        public ActionResult Index(
            string searchQuery,
            bool importGenes,
            bool importPartial,
            bool filterMinLength,
            int minLength,
            bool filterMaxLength,
            int maxLength)
        {
            return(CreateTask(() =>
            {
                string searchResults;
                string[] accessions;
                List <NuccoreObject> nuccoreObjects;

                if (filterMinLength)
                {
                    searchResults = filterMaxLength ?
                                    NcbiHelper.FormatNcbiSearchTerm(searchQuery, minLength, maxLength: maxLength) :
                                    NcbiHelper.FormatNcbiSearchTerm(searchQuery, minLength);
                }
                else
                {
                    searchResults = filterMaxLength ?
                                    NcbiHelper.FormatNcbiSearchTerm(searchQuery, minLength: 1, maxLength: maxLength) :
                                    NcbiHelper.FormatNcbiSearchTerm(searchQuery);
                }
                nuccoreObjects = NcbiHelper.ExecuteESummaryRequest(searchResults, importPartial);
                accessions = nuccoreObjects.Select(no => no.AccessionVersion.Split('.')[0]).Distinct().ToArray();
                var importResults = new List <MatterImportResult>(accessions.Length);

                using (var db = new LibiadaWebEntities())
                {
                    var matterRepository = new MatterRepository(db);
                    var dnaSequenceRepository = new GeneticSequenceRepository(db);

                    var(existingAccessions, accessionsToImport) = dnaSequenceRepository.SplitAccessionsIntoExistingAndNotImported(accessions);

                    importResults.AddRange(existingAccessions.ConvertAll(existingAccession => new MatterImportResult
                    {
                        MatterName = existingAccession,
                        Result = "Sequence already exists",
                        Status = "Exists"
                    }));

                    foreach (string accession in accessionsToImport)
                    {
                        var importResult = new MatterImportResult()
                        {
                            MatterName = accession
                        };

                        try
                        {
                            ISequence bioSequence = NcbiHelper.DownloadGenBankSequence(accession);
                            GenBankMetadata metadata = NcbiHelper.GetMetadata(bioSequence);
                            importResult.MatterName = metadata.Version.CompoundAccession;

                            Matter matter = matterRepository.CreateMatterFromGenBankMetadata(metadata);

                            importResult.SequenceType = matter.SequenceType.GetDisplayValue();
                            importResult.Group = matter.Group.GetDisplayValue();
                            importResult.MatterName = matter.Name;
                            importResult.AllNames = $"Common name = {metadata.Source.CommonName}, "
                                                    + $"Species = {metadata.Source.Organism.Species}, "
                                                    + $"Definition = {metadata.Definition}, "
                                                    + $"Saved matter name = {importResult.MatterName}";

                            var sequence = new CommonSequence
                            {
                                Matter = matter,
                                Notation = Notation.Nucleotides,
                                RemoteDb = RemoteDb.GenBank,
                                RemoteId = metadata.Version.CompoundAccession
                            };
                            bool partial = metadata.Definition.ToLower().Contains("partial");
                            dnaSequenceRepository.Create(sequence, bioSequence, partial);

                            (importResult.Result, importResult.Status) = importGenes ?
                                                                         ImportFeatures(metadata, sequence) :
                                                                         ("Successfully imported sequence", "Success");
                        }
                        catch (Exception exception)
                        {
                            importResult.Status = "Error";
                            importResult.Result = $"Error: {exception.Message}";
                            while (exception.InnerException != null)
                            {
                                exception = exception.InnerException;
                                importResult.Result += $" {exception.Message}";
                            }

                            foreach (var dbEntityEntry in db.ChangeTracker.Entries())
                            {
                                if (dbEntityEntry.Entity != null)
                                {
                                    dbEntityEntry.State = EntityState.Detached;
                                }
                            }
                        }
                        finally
                        {
                            importResults.Add(importResult);
                        }
                    }

                    string[] names = importResults.Select(r => r.MatterName).ToArray();

                    // removing matters for which adding of sequence failed
                    Matter[] orphanMatters = db.Matter
                                             .Include(m => m.Sequence)
                                             .Where(m => names.Contains(m.Name) && m.Sequence.Count == 0)
                                             .ToArray();

                    if (orphanMatters.Length > 0)
                    {
                        db.Matter.RemoveRange(orphanMatters);
                        db.SaveChanges();
                    }
                }

                var result = new Dictionary <string, object> {
                    { "result", importResults }
                };

                return new Dictionary <string, string> {
                    { "data", JsonConvert.SerializeObject(result) }
                };
            }));
        }
Example #6
0
        public void Update(Matter matter)
        {
            MatterRepository repository = new MatterRepository();

            repository.Update(matter);
        }
Example #7
0
        public Matter GetById(int id)
        {
            MatterRepository repository = new MatterRepository();

            return(repository.GetById(id));
        }
Example #8
0
        public int Save(Matter matter)
        {
            MatterRepository repository = new MatterRepository();

            return(repository.Save(matter));
        }
Example #9
0
        public List <Matter> GetAll()
        {
            MatterRepository repository = new MatterRepository();

            return(repository.GetAll());
        }
Example #10
0
        public ActionResult Create(
            [Bind(Include = "Id,Notation,RemoteDb,RemoteId,Description,Matter,MatterId")] CommonSequence commonSequence,
            bool localFile,
            Language?language,
            bool?original,
            Translator?translator,
            bool?partial,
            int?precision)
        {
            return(CreateTask(() =>
            {
                var db = new LibiadaWebEntities();
                try
                {
                    if (!ModelState.IsValid)
                    {
                        throw new Exception("Model state is invalid");
                    }

                    Stream sequenceStream;
                    Nature nature = commonSequence.Notation.GetNature();
                    if (nature == Nature.Genetic && !localFile)
                    {
                        sequenceStream = NcbiHelper.GetFastaFileStream(commonSequence.RemoteId);
                    }
                    else
                    {
                        sequenceStream = FileHelper.GetFileStream(Request.Files[0]);
                    }

                    switch (nature)
                    {
                    case Nature.Genetic:
                        ISequence bioSequence = NcbiHelper.GetFastaSequence(sequenceStream);
                        var dnaSequenceRepository = new GeneticSequenceRepository(db);
                        dnaSequenceRepository.Create(commonSequence, bioSequence, partial ?? false);
                        break;

                    case Nature.Music:
                        var musicSequenceRepository = new MusicSequenceRepository(db);
                        musicSequenceRepository.Create(commonSequence, sequenceStream);
                        break;

                    case Nature.Literature:
                        var literatureSequenceRepository = new LiteratureSequenceRepository(db);
                        literatureSequenceRepository.Create(commonSequence, sequenceStream, language ?? Language.Russian, original ?? true, translator ?? Translator.NoneOrManual);
                        break;

                    case Nature.MeasurementData:
                        var dataSequenceRepository = new DataSequenceRepository(db);
                        dataSequenceRepository.Create(commonSequence, sequenceStream, precision ?? 0);
                        break;

                    case Nature.Image:
                        var matterRepository = new MatterRepository(db);
                        int fileSize = Request.Files[0].ContentLength;
                        var file = new byte[fileSize];
                        Request.Files[0].InputStream.Read(file, 0, fileSize);
                        var matter = new Matter
                        {
                            Nature = Nature.Image,
                            SequenceType = commonSequence.Matter.SequenceType,
                            Name = commonSequence.Matter.Name,
                            Source = file,
                            Group = commonSequence.Matter.Group
                        };
                        matterRepository.SaveToDatabase(matter);
                        break;

                    default:
                        throw new InvalidEnumArgumentException(nameof(nature), (int)nature, typeof(Nature));
                    }
                    string multisequenceName = db.Multisequence.SingleOrDefault(ms => ms.Id == commonSequence.Matter.MultisequenceId).Name;
                    var result = new ImportResult(commonSequence, language, original, translator, partial, precision, multisequenceName);

                    return new Dictionary <string, string> {
                        { "data", JsonConvert.SerializeObject(result) }
                    };
                }
                catch (Exception)
                {
                    long matterId = commonSequence.MatterId;
                    if (matterId != 0)
                    {
                        List <Matter> orphanMatter = db.Matter
                                                     .Include(m => m.Sequence)
                                                     .Where(m => m.Id == matterId && m.Sequence.Count == 0)
                                                     .ToList();

                        if (orphanMatter.Count > 0)
                        {
                            db.Matter.Remove(orphanMatter[0]);
                            db.SaveChanges();
                        }
                    }

                    throw;
                }
                finally
                {
                    Dispose(true);
                }
            }));
        }
Example #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ViewDataHelper"/> class.
 /// </summary>
 /// <param name="db">
 /// The db.
 /// </param>
 public ViewDataHelper(LibiadaWebEntities db)
 {
     this.db          = db;
     matterRepository = new MatterRepository(db);
 }
Example #12
0
        public ActionResult Index(HttpPostedFileBase[] files)
        {
            return(CreateTask(() =>
            {
                var importResults = new List <MatterImportResult>();

                using (var db = new LibiadaWebEntities())
                {
                    Matter[] matters = db.Matter.Where(m => m.Nature == Nature.Image).ToArray();
                    var matterRepository = new MatterRepository(db);

                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        var file = Request.Files[i];
                        string sequenceName = file?.FileName.Substring(0, file.FileName.LastIndexOf('.'));

                        var importResult = new MatterImportResult()
                        {
                            MatterName = sequenceName
                        };

                        try
                        {
                            if (file == null)
                            {
                                throw new FileNotFoundException($"No image file is provided. Iteration: {i}");
                            }

                            if (matters.Any(m => m.Name == sequenceName))
                            {
                                importResult.Result = "Image already exists";
                                continue;
                            }
                            int fileSize = file.ContentLength;
                            var fileBytes = new byte[fileSize];
                            file.InputStream.Read(fileBytes, 0, fileSize);

                            var matter = new Matter
                            {
                                Name = sequenceName,
                                Group = Group.Picture,
                                Nature = Nature.Image,
                                Source = fileBytes,
                                SequenceType = SequenceType.CompleteImage
                            };

                            matterRepository.SaveToDatabase(matter);
                            importResult.Result = "Successfully imported image and created matter";
                            importResult.Status = "Success";
                            importResults.Add(importResult);
                        }
                        catch (Exception exception)
                        {
                            importResult.Result = $"Failed to import image: {exception.Message}";
                            while (exception.InnerException != null)
                            {
                                importResult.Result += $" {exception.InnerException.Message}";

                                exception = exception.InnerException;
                            }

                            importResult.Status = "Error";
                            importResults.Add(importResult);
                        }
                    }

                    var result = new Dictionary <string, object> {
                        { "result", importResults }
                    };

                    return new Dictionary <string, string> {
                        { "data", JsonConvert.SerializeObject(result) }
                    };
                }
            }));
        }
 public Exception GetActiveMattersList(ref ICollection<Matter> matters)
 {
     return MatterRepository.GetInstance().GetActiveMattersList(ref matters);
 }