public static void LogRunMessage(string runMessage,ApplicationLog applicationSection)
        {
            if (string.IsNullOrWhiteSpace(runMessage))
              {
            return;
              }

              if (applicationSection == ApplicationLog.None)
              {
            return;
              }

              string messageToLog = string.Format(CultureInfo.InvariantCulture, "{0}:runMessage",applicationSection.ToString(),runMessage);

              OnLogMessage(messageToLog);
        }
        public void Broadcast(PGIServer server, string applicationName, DBLoggingEventArgs loggingInfo)
        {
            if (_entMgr == null)
            {
                _entMgr = AuthenticationUtils.GetSqlEntityManager(
                    LoginTypeEnum.WindowsActiveDirectory,
                    applicationName,
                    server, PGIDB.SmartBase
                    );
            }

            if (AppLog == null)
            {
                AppLog = UIUtils.LogApplicationOpen(_entMgr, applicationName, _entMgr.CurrentStaff);
            }
            //%d [%thread] %-5level %logger [%ndc] - %message%newline%exception
            AppLog.Comments += loggingInfo.FormattedMessage + "|";
            AppLog.Save();
        }
        public void Insert(Guid Guid, string Host, DateTime Timestamp, string LogLevel, string Thread, string Message,
                           string Exception)
        {
            var item = new ApplicationLog();

            item.Guid = Guid;

            item.Host = Host;

            item.Timestamp = Timestamp;

            item.LogLevel = LogLevel;

            item.Thread = Thread;

            item.Message = Message;

            item.Exception = Exception;


            item.Save(UserName);
        }
Esempio n. 4
0
        /// <summary>
        /// 申报借阅
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <CommonResponse <BorrowRegisterResult> > BorrowRegister(BorrowRegisterRequest request)
        {
            var response = new CommonResponse <BorrowRegisterResult>();

            if (request == null)
            {
                response.Message = "参数不能为空";
                return(response);
            }
            if (string.IsNullOrEmpty(request.Phone))
            {
                response.Message = "手机不能为空";
                return(response);
            }
            if (string.IsNullOrEmpty(request.Borrower))
            {
                response.Message = "借阅人不能为空";
                return(response);
            }
            if (request.ReturnDate < DateTime.Now)
            {
                response.Message = "归还日期不能早于今天";
                return(response);
            }

            var regEntity = new dal.Entity.BorrowRegister
            {
                Borrower       = request.Borrower,
                Phone          = request.Phone,
                ReturnDate     = request.ReturnDate,
                SignPhoto      = request.SignPhoto,
                Status         = BorrowRegisterStatus.Registered,
                Company        = request.Company,
                Department     = request.Department,
                CreateTime     = DateTime.Now,
                Deleted        = false,
                UpdateTime     = DateTime.Now,
                ReturnNotified = false
            };

            using (var trans = await _db.Database.BeginTransactionAsync())
            {
                try
                {
                    var archives = await _db.ArchivesInfo.AsNoTracking().Where(c => request.ArchivesId.Contains(c.Id) && !c.Deleted).ToListAsync();

                    if (archives.Count != request.ArchivesId.Count)
                    {
                        throw new BizException("请求档案数目与数据库可用档案不一致,可能是数据已删除,请重新查询后再提交");
                    }

                    var borrowedArchives = archives.Where(c => c.Status == ArchivesStatus.Borrowed);
                    if (borrowedArchives.Any())
                    {
                        throw new BizException($"请求档案:{string.Join(",", borrowedArchives.Select(c => c.ArchivesNumber))} 当前状态为已借阅");
                    }

                    await _db.BorrowRegister.AddAsync(regEntity);

                    await _db.SaveChangesAsync();

                    response.Data = new BorrowRegisterResult {
                        BorrowRegisterId = regEntity.Id
                    };

                    await _db.BorrowRegisterDetail.AddRangeAsync(request.ArchivesId.Select(c => new dal.Entity.BorrowRegisterDetail
                    {
                        ArchivesId       = c,
                        BorrowRegisterId = regEntity.Id,
                        CreateTime       = DateTime.Now
                    }));

                    await _db.SaveChangesAsync();

                    trans.Commit();
                    response.Success = true;
                }
                catch (BizException ex)
                {
                    trans.Rollback();
                    response.Message = ex.Message;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    response.Message = "提交申请借阅发生异常";
                    ApplicationLog.Error("BorrowRegister", ex);
                }
            }

            return(response);
        }
Esempio n. 5
0
        void ValidateParseFormatGeneralTestCases(string nodeName)
        {
            // Gets the expected sequence from the Xml
            string filePath = utilityObj.xmlUtil.GetTextValue(nodeName,
                                                              Constants.FilePathNode);
            string alphabet = utilityObj.xmlUtil.GetTextValue(nodeName,
                                                              Constants.AlphabetNameNode);

            Assert.IsTrue(File.Exists(filePath));

            // Logs information to the log file
            ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                   "FastA Formatter : File Exists in the Path '{0}'.",
                                                   filePath));
            string filepathTmp = "tmp.ffn";

            using (FastAParser parserObj = new FastAParser(filePath))
            {
                using (FastAFormatter formatter = new FastAFormatter(filepathTmp))
                {
                    // Read the original file
                    IEnumerable <ISequence> seqsOriginal = null;
                    parserObj.Alphabet = Utility.GetAlphabet(alphabet);
                    seqsOriginal       = parserObj.Parse();
                    Assert.IsNotNull(seqsOriginal);

                    // Use the formatter to write the original sequences to a temp file
                    ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                           "FastA Formatter : Creating the Temp file '{0}'.",
                                                           filepathTmp));
                    foreach (Sequence s in seqsOriginal)
                    {
                        formatter.Write(s);
                    }
                    formatter.Close();

                    using (FastAParser parserObjNew = new FastAParser(filepathTmp))
                    {
                        // Read the new file, then compare the sequences
                        IEnumerable <ISequence> seqsNew = null;
                        parserObjNew.Alphabet = Utility.GetAlphabet(alphabet);
                        seqsNew = parserObjNew.Parse();
                        Assert.IsNotNull(seqsNew);

                        char[] seqString   = seqsNew.ElementAt(0).Select(a => (char)a).ToArray();
                        string newSequence = new string(seqString);

                        ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                               "FastA Formatter : New Sequence is '{0}'.",
                                                               newSequence));

                        // Now compare the sequences.
                        int countOriginal = seqsOriginal.Count();
                        int countNew      = seqsNew.Count();
                        Assert.AreEqual(countOriginal, countNew);
                        ApplicationLog.WriteLine("FastA Formatter :The Number of sequences are matching.");

                        int i;
                        for (i = 0; i < countOriginal; i++)
                        {
                            Assert.AreEqual(seqsOriginal.ElementAt(i).ID, seqsNew.ElementAt(i).ID);
                            string orgSeq = new string(seqsOriginal.ElementAt(i).Select(a => (char)a).ToArray());
                            string newSeq = new string(seqsNew.ElementAt(i).Select(a => (char)a).ToArray());
                            Assert.AreEqual(orgSeq, newSeq);
                            Console.WriteLine(
                                string.Format((IFormatProvider)null,
                                              "FastA Formatter : The FASTA sequences '{0}' are matching with Format() method and is as expected.",
                                              seqsNew.ElementAt(i).ID));
                            ApplicationLog.WriteLine(
                                string.Format((IFormatProvider)null, "FastA Formatter : The FASTA sequences '{0}' are matching with Format() method.",
                                              seqsNew.ElementAt(i).ID));
                        }

                        // Passed all the tests, delete the tmp file. If we failed an Assert,
                        // the tmp file will still be there in case we need it for debugging.
                        parserObjNew.Close();
                    }
                    File.Delete(filepathTmp);
                    ApplicationLog.WriteLine("Deleted the temp file created.");
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Assemble the input sequences into the largest possible contigs.
        /// </summary>
        /// <remarks>
        /// The algorithm is:
        /// 1.  initialize list of contigs to empty list. List of seqs is passed as argument.
        /// 2.  compute pairwise overlap scores for each pair of input seqs (with reversal and
        ///     complementation as appropriate).
        /// 3.  choose best overlap score. the “merge items” (can be seqs or contigs) are the
        ///     items with that score. If best score is less than threshold, assembly is finished.
        /// 4.  merge the merge items into a single contig and remove them from their list(s)
        /// 5.  compute the overlap between new item and all existing items
        /// 6.  go to step 3
        /// </remarks>
        /// <param name="inputSequences">The sequences to assemble.</param>
        /// <returns>Returns the OverlapDeNovoAssembly instance which contains list of
        /// contigs and list of unmerged sequences which are result of this assembly.</returns>
        public IDeNovoAssembly Assemble(IEnumerable <ISequence> inputSequences)
        {
            if (null == inputSequences)
            {
                throw new ArgumentNullException(Properties.Resource.ParameterNameInputSequences);
            }

            // Initializations
            if (inputSequences.Count() > 0)
            {
                _sequenceAlphabet = inputSequences.First().Alphabet;

                if (ConsensusResolver == null)
                {
                    ConsensusResolver = new SimpleConsensusResolver(_sequenceAlphabet);
                }
                else
                {
                    ConsensusResolver.SequenceAlphabet = _sequenceAlphabet;
                }
            }

            OverlapDeNovoAssembly sequenceAssembly = null;

            // numbering convention: every pool item (whether sequence or contig)
            // gets a fixed number.
            // sequence index = index into inputs (which we won't modify)
            // contig index = nSequences + index into contigs
            List <PoolItem> pool = new List <PoolItem>();

            foreach (ISequence seq in inputSequences)
            {
                pool.Add(new PoolItem(seq));
            }

            // put all the initial sequences into the pool, and generate the pair scores.
            // there are no contigs in the pool yet.
            // to save an iteration, we'll also find the best global score as we go.
            ItemScore globalBest            = new ItemScore(-1, -1, false, false, 0, 0);
            int       globalBestLargerIndex = -1;
            int       unconsumedCount       = inputSequences.Count();

            // Compute alignment scores for all combinations between input sequences
            // Store these scores in the poolItem correspodning to each sequence
            for (int newSeq = 0; newSeq < pool.Count; ++newSeq)
            {
                PoolItem newItem = pool[newSeq];
                for (int oldSeq = 0; oldSeq < newSeq; ++oldSeq)
                {
                    PoolItem  oldItem = pool[oldSeq];
                    ItemScore score   = AlignSequence(oldItem.SequenceOrConsensus, newItem.SequenceOrConsensus, oldSeq, newSeq);
                    newItem.Scores.Add(score);
                    if (score.OverlapScore > globalBest.OverlapScore)
                    {
                        globalBest            = new ItemScore(score);
                        globalBestLargerIndex = newSeq;
                    }
                }
            }

            // Merge sequence if best score is above threshold
            // and add new contig to pool
            if (globalBest.OverlapScore >= MergeThreshold)
            {
                if (Trace.Want(Trace.AssemblyDetails))
                {
                    ApplicationLog.WriteLine("Merging (overlap score {0}):", globalBest.OverlapScore);
                }

                PoolItem mergeItem1 = pool[globalBest.OtherItem];
                PoolItem mergeItem2 = pool[globalBestLargerIndex];
                Contig   newContig  = new Contig();
                if (Trace.Want(Trace.AssemblyDetails))
                {
                    ApplicationLog.WriteLine(
                        "new pool item {0} will merge old items {1} and {2}",
                        pool.Count,
                        globalBest.OtherItem,
                        globalBestLargerIndex);
                }

                MergeLowerIndexedSequence(newContig, globalBest, mergeItem1.Sequence);
                MergeHigherIndexedSequence(newContig, globalBest, mergeItem2.Sequence);

                MakeConsensus(newContig);

                // Set ConsumedBy value and
                // free memory as these sequences are no longer used
                mergeItem1.ConsumedBy = pool.Count;
                mergeItem2.ConsumedBy = pool.Count;
                mergeItem1.FreeSequences();
                mergeItem2.FreeSequences();
                pool.Add(new PoolItem(newContig));
                unconsumedCount--;

                while (unconsumedCount > 1)
                {
                    // Compute scores for each unconsumed sequence with new contig
                    globalBest            = new ItemScore(-1, -1, false, false, 0, 0);
                    globalBestLargerIndex = -1;
                    int      newSeq  = pool.Count - 1;
                    PoolItem newItem = pool[newSeq];
                    for (int oldSeq = 0; oldSeq < pool.Count - 1; ++oldSeq)
                    {
                        PoolItem oldItem = pool[oldSeq];
                        if (oldItem.ConsumedBy >= 0)
                        {
                            // already consumed - just add dummy score to maintain correct indices
                            newItem.Scores.Add(new ItemScore());
                        }
                        else
                        {
                            ItemScore score = AlignSequence(oldItem.SequenceOrConsensus, newItem.SequenceOrConsensus, oldSeq, newSeq);
                            newItem.Scores.Add(score);
                        }
                    }

                    // find best global score in the modified pool.
                    globalBest            = new ItemScore(-1, -1, false, false, 0, 0);
                    globalBestLargerIndex = -1;
                    for (int current = 0; current < pool.Count; ++current)
                    {
                        PoolItem curItem = pool[current];
                        if (curItem.ConsumedBy < 0)
                        {
                            for (int other = 0; other < current; ++other)
                            {
                                if (pool[other].ConsumedBy < 0)
                                {
                                    ItemScore itemScore = curItem.Scores[other];
                                    if (itemScore.OverlapScore > globalBest.OverlapScore)
                                    {
                                        globalBest            = new ItemScore(itemScore); // copy the winner so far
                                        globalBestLargerIndex = current;
                                    }
                                }
                            }
                        }
                    }

                    if (globalBest.OverlapScore >= MergeThreshold)
                    {
                        // Merge sequences / contigs if above threshold
                        mergeItem1 = pool[globalBest.OtherItem];
                        mergeItem2 = pool[globalBestLargerIndex];
                        newContig  = new Contig();

                        if (mergeItem1.IsContig)
                        {
                            if (Trace.Want(Trace.AssemblyDetails))
                            {
                                ApplicationLog.WriteLine(
                                    "item {0} is a contig (reversed = {1}, complemented = {2}, offset = {3}",
                                    globalBest.OtherItem,
                                    globalBest.Reversed,
                                    globalBest.Complemented,
                                    globalBest.FirstOffset);
                            }

                            MergeLowerIndexedContig(newContig, globalBest, mergeItem1.Contig);
                        }
                        else
                        {
                            if (Trace.Want(Trace.AssemblyDetails))
                            {
                                ApplicationLog.WriteLine(
                                    "item {0} is a sequence (reversed = {1}, complemented = {2}, offset = {3}",
                                    globalBest.OtherItem,
                                    globalBest.Reversed,
                                    globalBest.Complemented,
                                    globalBest.FirstOffset);
                            }

                            MergeLowerIndexedSequence(newContig, globalBest, mergeItem1.Sequence);
                        }

                        if (mergeItem2.IsContig)
                        {
                            if (Trace.Want(Trace.AssemblyDetails))
                            {
                                ApplicationLog.WriteLine(
                                    "item {0} is a contig (offset = {1}",
                                    globalBestLargerIndex,
                                    globalBest.SecondOffset);
                            }

                            MergeHigherIndexedContig(newContig, globalBest, mergeItem2.Contig);
                        }
                        else
                        {
                            if (Trace.Want(Trace.AssemblyDetails))
                            {
                                ApplicationLog.WriteLine(
                                    "item {0} is a sequence (offset = {1}",
                                    globalBestLargerIndex,
                                    globalBest.SecondOffset);
                            }

                            MergeHigherIndexedSequence(newContig, globalBest, mergeItem2.Sequence);
                        }

                        MakeConsensus(newContig);
                        if (Trace.Want(Trace.AssemblyDetails))
                        {
                            Dump(newContig);
                        }

                        // Set ConsumedBy value for these poolItems and
                        // free memory as these sequences are no longer used
                        mergeItem1.ConsumedBy = pool.Count;
                        mergeItem2.ConsumedBy = pool.Count;
                        mergeItem1.FreeSequences();
                        mergeItem2.FreeSequences();

                        pool.Add(new PoolItem(newContig));
                        unconsumedCount--;
                    }
                    else
                    {
                        // None of the alignment scores cross threshold
                        // No more merges possible. So end iteration.
                        break;
                    }
                }
            }

            // no further qualifying merges, so we're done.
            // populate contigs and unmergedSequences
            sequenceAssembly = new OverlapDeNovoAssembly();
            foreach (PoolItem curItem in pool)
            {
                if (curItem.ConsumedBy < 0)
                {
                    if (curItem.IsContig)
                    {
                        sequenceAssembly.Contigs.Add(curItem.Contig);
                    }
                    else
                    {
                        sequenceAssembly.UnmergedSequences.Add(curItem.Sequence);
                    }
                }
            }

            return(sequenceAssembly);
        }
Esempio n. 7
0
        public async Task <CommonSearchResponse <List <SearchBorrowRegisterResult> > > SearchBorrowRegister(SearchBorrowRegisterRequest request)
        {
            var response = new CommonSearchResponse <List <SearchBorrowRegisterResult> >();

            try
            {
                var query = _db.BorrowRegister.AsNoTracking().Where(c => !c.Deleted);
                if (!string.IsNullOrEmpty(request.Keyword))
                {
                    query = query.Where(c => c.Phone.Contains(request.Keyword.Trim()) || c.Borrower.Contains(request.Keyword.Trim()) || c.Company.Contains(request.Keyword.Trim()) || c.Department.Contains(request.Keyword.Trim()));
                }
                var list = await query.OrderBy(c => c.Status).ThenBy(c => c.Id)
                           .Skip(request.PageNumber * request.PageSize)
                           .Take(request.PageSize)
                           .Select(c => new SearchBorrowRegisterResult
                {
                    Id            = c.Id,
                    Borrower      = c.Borrower,
                    Company       = c.Company,
                    Department    = c.Company,
                    Phone         = c.Phone,
                    ReturnDate    = c.ReturnDate,
                    SignPhoto     = c.SignPhoto,
                    Status        = c.Status,
                    CreateTime    = c.CreateTime,
                    CreateTimeStr = c.CreateTime.ToString("yyyy-MM-dd")
                }).ToListAsync();

                var ids = list.Select(c => c.Id);

                var archivesList = await(from brd in _db.BorrowRegisterDetail.AsNoTracking()
                                         join a in _db.ArchivesInfo.AsNoTracking() on brd.ArchivesId equals a.Id
                                         where ids.Contains(brd.BorrowRegisterId)
                                         select new ArchivesSimple
                {
                    BorrowRegisterId = brd.BorrowRegisterId,
                    ArchivesNumber   = a.ArchivesNumber,
                    CatalogNumber    = a.CatalogNumber,
                    CategoryId       = a.CategoryId,
                    FileNumber       = a.FileNumber,
                    OrderNumber      = a.OrderNumber
                }).ToListAsync();

                list.ForEach(c =>
                {
                    var arlist      = archivesList.Where(j => j.BorrowRegisterId == c.Id).ToList();
                    c.ArchivesList  = arlist;
                    c.ArchivesStr   = string.Join(",", arlist.Select(j => $"{j.ArchivesNumber}/{j.FileNumber}/{j.OrderNumber}"));
                    c.ReturnDateStr = c.ReturnDate.ToString("yyyy-MM-dd");
                });

                response.Data    = list;
                response.Success = true;
            }
            catch (Exception ex)
            {
                response.Message = "获取借阅列表失败";
                ApplicationLog.Error("SearchBorrowRegister", ex);
            }

            return(response);
        }
Esempio n. 8
0
        /// <summary>
        /// Validate general http request status by
        /// differnt parameters for Ebi web service..
        /// <param name="nodeName">different alphabet node name</param>
        /// </summary>
        static void ValidateEbiGeneralGetRequestStatusMethod(string nodeName)
        {
            if (_IsWebServiceAvailable)
            {
                // Gets the search query parameter and their values.
                string alphabetName = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.AlphabetNameNode);
                string querySequence = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.QuerySequency);
                string queryDatabaseValue = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.DatabaseValue);
                string queryProgramValue = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.ProgramValue);
                string queryDatabaseParameter = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.DatabaseParameter);
                string queryProgramParameter = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.ProgramParameter);
                string emailParameter = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.Emailparameter);
                string email = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.EmailAdress);
                string reqId = string.Empty;

                // Create a sequence.
                Sequence seq = new Sequence(Utility.GetAlphabet(alphabetName),
                                            querySequence);

                // Set Service confiruration parameters true.
                IBlastServiceHandler ebiBlastService = new EbiWuBlastHandler();

                ConfigParameters configParameters = new ConfigParameters();
                configParameters.UseBrowserProxy = true;
                ebiBlastService.Configuration    = configParameters;

                // Create search parameters object.
                BlastParameters queryParams = new BlastParameters();

                // Add mandatory parameter values to search query parameters.
                queryParams.Add(queryDatabaseParameter, queryDatabaseValue);
                queryParams.Add(queryProgramParameter, queryProgramValue);
                queryParams.Add(emailParameter, email);

                // Create a request
                reqId = ebiBlastService.SubmitRequest(seq, queryParams);

                // validate request identifier.
                Assert.IsNotNull(reqId);

                // submit request identifier and get the status
                ServiceRequestInformation reqInfo = ebiBlastService.GetRequestStatus(reqId);

                // Validate job status.
                if (reqInfo.Status != ServiceRequestStatus.Waiting &&
                    reqInfo.Status != ServiceRequestStatus.Ready)
                {
                    string error = ApplicationLog.WriteLine(string.Format(
                                                                null, "Unexpected error", reqInfo.Status));
                    Assert.Fail(error);
                    Console.WriteLine(string.Format(null,
                                                    "Unexpected error", reqInfo.Status));
                }
                else
                {
                    Console.WriteLine(string.Format(null,
                                                    "Request status {0} ", reqInfo.Status));
                }
            }
            else
            {
                Assert.Ignore("The test case ignored due to connection failure");
            }
        }
Esempio n. 9
0
        public void TestSimpleSequenceAssemblerWithSemiRandomSequence()
        {
            // test parameters
            int        matchScore          = 1;
            int        mismatchScore       = -8;
            int        gapCost             = -8;
            double     mergeThreshold      = 4;
            double     consensusThreshold  = 66;
            const int  MasterLength        = 30;
            const int  ReadLength          = 10;
            const int  NumReads            = 5;
            const bool AssumeOrientedReads = false;

            // if this is uncommented, assembly details appear in log.
            // this is extremely verbose.
            Trace.Set(Trace.AssemblyDetails);

            // make random master sequence
            // (use seed for repeatability, or omit seed for
            // different test each time)
            // Random randGen = new Random();
            Random randGen = new Random(654321);

            StringBuilder randSeq = new StringBuilder();

            for (int i = 0; i < MasterLength; ++i)
            {
                int randm = randGen.Next(8);
                if (randm < 2)
                {
                    randSeq.Append('A');
                }
                else if (randm < 4)
                {
                    randSeq.Append('C');
                }
                else if (randm < 6)
                {
                    randSeq.Append('G');
                }
                else
                {
                    randSeq.Append('T');
                }
            }

            Sequence master = new Sequence(Alphabets.DNA, randSeq.ToString());

            // create the reads
            List <ISequence> inputs = new List <ISequence>();

            for (int i = 0; i < NumReads; ++i)
            {
                int       pos     = 5 * i;
                string    data    = master.ToStrings().Substring(pos, ReadLength);
                bool      revcomp = randGen.Next(2) > 0;
                bool      reverse = randGen.Next(2) > 0 && !AssumeOrientedReads;
                ISequence read;
                if (reverse && revcomp)
                {
                    Sequence tmp = new Sequence(Alphabets.DNA, data);
                    read = new Sequence(Alphabets.DNA, tmp.GetReversedSequence().ToStrings());
                }
                else if (revcomp)
                {
                    Sequence tmp = new Sequence(Alphabets.DNA, data);
                    read = new Sequence(Alphabets.DNA, tmp.GetReverseComplementedSequence().ToStrings());
                }
                else
                {
                    read = new Sequence(Alphabets.DNA, data);
                }

                inputs.Add(read);
            }

            OverlapDeNovoAssembler assembler = new OverlapDeNovoAssembler();

            assembler.MergeThreshold   = mergeThreshold;
            assembler.OverlapAlgorithm = new PairwiseOverlapAligner();
            ((IPairwiseSequenceAligner)assembler.OverlapAlgorithm).SimilarityMatrix = new DiagonalSimilarityMatrix(matchScore, mismatchScore);
            ((IPairwiseSequenceAligner)assembler.OverlapAlgorithm).GapOpenCost      = gapCost;
            assembler.ConsensusResolver         = new SimpleConsensusResolver(consensusThreshold);
            assembler.AssumeStandardOrientation = AssumeOrientedReads;

            IOverlapDeNovoAssembly seqAssembly = (IOverlapDeNovoAssembly)assembler.Assemble(inputs);

            Assert.AreEqual(0, seqAssembly.UnmergedSequences.Count);
            Assert.AreEqual(1, seqAssembly.Contigs.Count);
            Contig contig0 = seqAssembly.Contigs[0];

            ApplicationLog.WriteLine("master sequence and contig 0 consensus:");
            ApplicationLog.WriteLine(master.ToStrings());
            ApplicationLog.WriteLine(contig0.Consensus.ToStrings());

            // note that this is tricky, esp. without oriented reads - consensus
            // could be reversed and/or complemented relative to original
            Assert.AreEqual(master.ToStrings(), contig0.Consensus.ToStrings());
        }
        private void LoadData()
        {
            string act = Request["Action"] + "";;
            string functionStructureCode = Request["FunctionStructureCode"] + "";;

            if (act != "Modify")
            {
                this.tableList.Visible      = false;
                this.TableSQLScript.Visible = false;                    //SQL Script
                return;
            }

            try
            {
                EntityData entity = DAL.EntityDAO.SystemManageDAO.GetFunctionStructureByCode(functionStructureCode);
                if (entity.HasRecord())
                {
                    this.txtFunctionStructureCode.Value     = functionStructureCode;
                    this.txtFunctionStructureName.Value     = entity.GetString("FunctionStructureName");
                    this.txtDescription.Value               = entity.GetString("Description");
                    this.txtProjectSpecialDescription.Value = entity.GetString("ProjectSpecialDescription");
                    this.txtOtherSpecialDescription.Value   = entity.GetString("OtherSpecialDescription");
                    this.chkRight.Checked       = (!(entity.GetInt("IsRightControlPoint").ToString() == "1"));
                    this.chkRole.Checked        = (!(entity.GetInt("IsRoleControlPoint").ToString() == "1"));
                    this.chkIsAvailable.Checked = (!(entity.GetInt("IsAvailable").ToString() == "1"));
                    this.chkSystemClass.Checked = (entity.GetInt("IsSystemClass").ToString() == "1");

                    #region 显示功能点 SQL Script
                    string strSQLScript   = "";
                    string strColumnName  = "";
                    string strColumnValue = "";

                    // ******************************************************************************
                    //排除字段,因为 enttiy 中有字段并不存在实际 DataTable 中
                    ArrayList arrDebarColumn = new ArrayList();
                    arrDebarColumn.Add("ChildCount");
                    // ******************************************************************************

                    int ic = entity.CurrentTable.Columns.Count;
                    for (int i = 0; i < ic; i++)
                    {
                        string tempName  = entity.CurrentTable.Columns[i].ColumnName;
                        object tempValue = entity.CurrentRow[tempName];

                        if (arrDebarColumn.Contains(tempName))
                        {
                            continue;
                        }

                        if (0 != i)
                        {
                            strColumnName  += ",";
                            strColumnValue += ",";
                        }
                        strColumnName += "[" + tempName + "]";
                        if (DBNull.Value == tempValue)
                        {
                            strColumnValue += "Null";
                        }
                        else
                        {
                            strColumnValue += "'" + tempValue.ToString() + "'";
                        }
                    }
                    strSQLScript += "\r\n\r\n";
                    strSQLScript += "-- Start 新增 当前功能点";
                    strSQLScript += "\r\n";
                    strSQLScript += "Insert Into [FunctionStructure]";
                    strSQLScript += " (";
                    strSQLScript += strColumnName;
                    strSQLScript += ") Values (";
                    strSQLScript += strColumnValue;
                    strSQLScript += ")";
                    strSQLScript += "\r\n";
                    strSQLScript += "-- End 新增 当前功能点";
                    strSQLScript += "\r\n\r\n";

                    this.txtSQLScript.Value = strSQLScript;
                    #endregion

                    EntityData child = DAL.EntityDAO.SystemManageDAO.GetFunctionStructureByParentCode(functionStructureCode);
                    this.repeatList.DataSource = child.CurrentTable;
                    this.repeatList.DataBind();
                    child.Dispose();
                }
                entity.Dispose();
            }
            catch (Exception ex)
            {
                ApplicationLog.WriteLog(this.ToString(), ex, "");
                Response.Write(JavaScript.Alert(true, "显示出错:" + ex.Message));
            }
        }
Esempio n. 11
0

        
Esempio n. 12
0
        void ValidateFormatterGeneralTestCases(string nodeName)
        {
            using (FastAFormatter formatter = new FastAFormatter(Constants.FastaTempFileName))
            {
                // Gets the actual sequence and the alphabet from the Xml
                string actualSequence = utilityObj.xmlUtil.GetTextValue(nodeName,
                                                                        Constants.ExpectedSequenceNode);
                string formattedActualSequence = actualSequence.Replace("\r", "").Replace("\n", "").Replace(" ", "");

                string alphabet = utilityObj.xmlUtil.GetTextValue(nodeName,
                                                                  Constants.AlphabetNameNode);

                // Logs information to the log file
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                       "FastA Formatter : Validating with Sequence '{0}' and Alphabet '{1}'.",
                                                       actualSequence, alphabet));

                // Replacing all the empty characters, Paragraphs and null entries added
                // while formatting the xml.
                Sequence seqOriginal = new Sequence(Utility.GetAlphabet(alphabet),
                                                    encodingObj.GetBytes(actualSequence.Replace("\r", "").Replace("\n", "").Replace(" ", "")));
                seqOriginal.ID = "";
                Assert.IsNotNull(seqOriginal);

                // Use the formatter to write the original sequences to a temp file
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                       "FastA Formatter : Creating the Temp file '{0}'.",
                                                       Constants.FastaTempFileName));
                formatter.Write(seqOriginal);
                formatter.Close();

                // Read the new file, then compare the sequences
                IEnumerable <ISequence> seqsNew = null;
                using (FastAParser parserObj = new FastAParser(Constants.FastaTempFileName))
                {
                    parserObj.Alphabet = Utility.GetAlphabet(alphabet);
                    seqsNew            = parserObj.Parse();

                    char[] seqString   = seqsNew.ElementAt(0).Select(a => (char)a).ToArray();
                    string newSequence = new string(seqString);

                    Assert.IsNotNull(seqsNew);
                    ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                           "FastA Formatter : New Sequence is '{0}'.",
                                                           newSequence));

                    // Now compare the sequences.
                    int countNew = seqsNew.Count();
                    Assert.AreEqual(1, countNew);

                    ApplicationLog.WriteLine("The Number of sequences are matching.");
                    Assert.AreEqual(seqOriginal.ID, seqsNew.ElementAt(0).ID);
                    Assert.AreEqual(formattedActualSequence, newSequence);

                    Console.WriteLine(string.Format((IFormatProvider)null,
                                                    "FastA Formatter : The FASTA sequences '{0}' are matching with Format() method and is as expected.",
                                                    newSequence));
                    ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                           "FastA Formatter : The FASTA sequences '{0}' are matching with Format() method.",
                                                           newSequence));
                }

                // Passed all the tests, delete the tmp file. If we failed an Assert,
                // the tmp file will still be there in case we need it for debugging.
                File.Delete(Constants.FastaTempFileName);
                ApplicationLog.WriteLine("Deleted the temp file created.");
            }
        }
Esempio n. 13
0
        public void GenBankFormatterWithParseValidateFormatFilePath()
        {
            InitializeXmlVariables();
            // parse
            ISequenceParser   parserObj = new GenBankParser();
            IList <ISequence> seqList   = parserObj.Parse(FilePath);

            ISequence seq = seqList[0];

            ISequenceFormatter formatter = new GenBankFormatter();

            formatter.Format(seq, Constants.GenBankTempFileName);

            // parse
            parserObj = new GenBankParser();
            seqList   = parserObj.Parse(Constants.GenBankTempFileName);

            seq = seqList[0];

            // test the non-metadata properties
            if (0 == string.Compare(IsSequenceReadOnly, "true",
                                    false, CultureInfo.CurrentCulture))
            {
                Assert.IsTrue(seq.IsReadOnly);
                ApplicationLog.WriteLine("Successfully validated the ReadOnly Property");
            }

            Assert.AreEqual(Utility.GetAlphabet(AlphabetName), seq.Alphabet);
            Assert.AreEqual(Utility.GetMoleculeType(MolType), seq.MoleculeType);
            Assert.AreEqual(SeqId, seq.DisplayID);
            Assert.AreEqual(SeqId, seq.ID);
            ApplicationLog.WriteLine(
                "GenBank Formatter BVT: Successfully validated the Alphabet, Molecular type, Sequence ID and Display ID");

            // test the metadata that is tricky to parse, and will not be tested implicitly by
            // testing the formatting
            GenBankMetadata metadata =
                (GenBankMetadata)seq.Metadata["GenBank"];

            if (metadata.Locus.Strand != SequenceStrandType.None)
            {
                Assert.AreEqual(StrandType,
                                metadata.Locus.Strand.ToString());
            }
            Assert.AreEqual(StrandTopology.ToUpper(CultureInfo.CurrentCulture),
                            metadata.Locus.StrandTopology.ToString().ToUpper(CultureInfo.CurrentCulture));
            Assert.AreEqual(Div, metadata.Locus.DivisionCode.ToString());
            Assert.AreEqual(DateTime.Parse(SequenceDate, null),
                            metadata.Locus.Date);
            Assert.AreEqual(Version, metadata.Version.Version.ToString((IFormatProvider)null));
            Assert.AreEqual(PrimaryId, metadata.Version.GINumber);
            ApplicationLog.WriteLine(
                "GenBank Formatter BVT: Successfully validated the StrandType, StrandTopology, Division, Date, Version, PrimaryID Properties");

            // test the sequence string
            Assert.AreEqual(ExpectedSequence, seq.ToString());
            ApplicationLog.WriteLine(
                "GenBank Formatter BVT: Successfully validated the Sequence");
            Console.WriteLine(string.Format((IFormatProvider)null,
                                            "GenBank Formatter BVT: Successfully validated the Sequence '{0}'",
                                            ExpectedSequence));

            File.Delete(Constants.GenBankTempFileName);
        }
Esempio n. 14
0
        void ValidateParseGeneralTestCases(string nodeName)
        {
            string filePath = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.FilePathNode);
            string alphabet = utilityObj.xmlUtil.GetTextValue(nodeName,
                                                              Constants.AlphabetNameNode);

            Assert.IsTrue(File.Exists(filePath));
            // Logs information to the log file
            ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                   "FastA Parser : File Exists in the Path '{0}'.", filePath));

            IEnumerable <ISequence> seqs = null;

            using (FastAParser parserObj = new FastAParser(filePath))
            {
                parserObj.Alphabet = Utility.GetAlphabet(alphabet);
                seqs = parserObj.Parse();

                Assert.IsNotNull(seqs);
                Assert.AreEqual(1, seqs.Count());
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                       "FastA Parser: Number of Sequences found are '{0}'.",
                                                       seqs.Count()));

                // Gets the expected sequence from the Xml
                string expectedSequence = utilityObj.xmlUtil.GetTextValue(
                    nodeName, Constants.ExpectedSequenceNode);

                Sequence seq = (Sequence)seqs.ElementAt(0);
                Assert.IsNotNull(seq);
                char[] seqString   = seqs.ElementAt(0).Select(a => (char)a).ToArray();
                string newSequence = new string(seqString);
                Assert.AreEqual(expectedSequence, newSequence);
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                       "FastA Parser: Sequence is '{0}' and is as expected.",
                                                       newSequence));
                // Logs to the NUnit GUI (Console.Out) window
                Console.WriteLine(string.Format((IFormatProvider)null,
                                                "FastA Parser: Sequence is '{0}' and is as expected.", newSequence));

                byte[] tmpEncodedSeq = new byte[seq.Count];
                (seq as IEnumerable <byte>).ToArray().CopyTo(tmpEncodedSeq, 0);
                Assert.AreEqual(expectedSequence.Length, tmpEncodedSeq.Length);
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                       "FastA Parser: Sequence Length is '{0}' and is as expected.",
                                                       expectedSequence.Length));

                Assert.IsNotNull(seq.Alphabet);
                Assert.AreEqual(seq.Alphabet.Name.ToLower(CultureInfo.CurrentCulture),
                                utilityObj.xmlUtil.GetTextValue(nodeName,
                                                                Constants.AlphabetNameNode).ToLower(CultureInfo.CurrentCulture));
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                       "FastA Parser: The Sequence Alphabet is '{0}' and is as expected.",
                                                       seq.Alphabet.Name));

                Assert.AreEqual(utilityObj.xmlUtil.GetTextValue(
                                    nodeName, Constants.SequenceIdNode), seq.ID);
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                       "FastA Parser: Sequence ID is '{0}' and is as expected.",
                                                       seq.ID));
                // Logs to the NUnit GUI (Console.Out) window
                Console.WriteLine(string.Format((IFormatProvider)null,
                                                "FastA Parser: Sequence ID is '{0}' and is as expected.",
                                                seq.ID));
            }
        }
Esempio n. 15
0
        public void FastaParserValidateParseWithMediumSizeSequence()
        {
            string filePath = utilityObj.xmlUtil.GetTextValue(
                Constants.MediumSizeFastaNodeName, Constants.FilePathNode);
            string alphabet = utilityObj.xmlUtil.GetTextValue(Constants.MediumSizeFastaNodeName,
                                                              Constants.AlphabetNameNode);

            Assert.IsTrue(File.Exists(filePath));
            // Logs information to the log file
            ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                   "FastA Parser : File Exists in the Path '{0}'.", filePath));

            IEnumerable <ISequence> seqs = null;

            using (FastAParser parserObj = new FastAParser(filePath))
            {
                parserObj.Alphabet = Utility.GetAlphabet(alphabet);
                seqs = parserObj.Parse();

                Assert.IsNotNull(seqs);
                Assert.AreEqual(1, seqs.Count());
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                       "FastA Parser: Number of Sequences found are '{0}'.",
                                                       seqs.Count()));

                // Gets the expected sequence from the Xml
                string expectedSequence = utilityObj.xmlUtil.GetTextValue(
                    Constants.MediumSizeFastaNodeName, Constants.ExpectedSequenceNode);

                Sequence seq         = (Sequence)seqs.ElementAt(0);
                char[]   seqString   = seqs.ElementAt(0).Select(a => (char)a).ToArray();
                string   newSequence = new string(seqString);
                Assert.IsNotNull(seq);

                // Replace all the empty spaces, paragraphs and new line for validation
                string updatedExpSequence =
                    expectedSequence.Replace("\r", "").Replace("\n", "").Replace(" ", "");
                string updatedActualSequence =
                    newSequence.Replace("\r", "").Replace("\n", "").Replace(" ", "");
                Assert.AreEqual(updatedExpSequence, updatedActualSequence);
                ApplicationLog.WriteLine(
                    string.Format((IFormatProvider)null, "FastA Parser: Sequence is '{0}' and is as expected.",
                                  updatedActualSequence));
                // Logs to the NUnit GUI (Console.Out) window
                Console.WriteLine(
                    string.Format((IFormatProvider)null, "FastA Parser: Sequence is '{0}' and is as expected.",
                                  updatedActualSequence));

                Assert.AreEqual(updatedExpSequence.Length, updatedActualSequence.Length);
                ApplicationLog.WriteLine(
                    string.Format((IFormatProvider)null, "FastA Parser: Sequence Length is '{0}' and is as expected.",
                                  updatedActualSequence.Length));

                Assert.IsNotNull(seq.Alphabet);
                Assert.AreEqual(seq.Alphabet.Name.ToLower(CultureInfo.CurrentCulture),
                                utilityObj.xmlUtil.GetTextValue(Constants.MediumSizeFastaNodeName,
                                                                Constants.AlphabetNameNode).ToLower(CultureInfo.CurrentCulture));
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                       "FastA Parser: The Sequence Alphabet is '{0}' and is as expected.",
                                                       seq.Alphabet.Name));

                Assert.AreEqual(utilityObj.xmlUtil.GetTextValue(
                                    Constants.MediumSizeFastaNodeName, Constants.SequenceIdNode), seq.ID);
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                                                       "FastA Parser: Sequence ID is '{0}' and is as expected.", seq.ID));
                // Logs to the NUnit GUI (Console.Out) window
                Console.WriteLine(string.Format((IFormatProvider)null,
                                                "FastA Parser: Sequence ID is '{0}' and is as expected.", seq.ID));
            }
        }
Esempio n. 16
0
        private void LoadGrid()
        {
            try
            {
                string ProjectCode = this.txtProjectCode.Value;
                int    IYear       = BLL.ConvertRule.ToInt(this.txtYear.Value);
                int    IMonth      = BLL.ConvertRule.ToInt(this.txtMonth.Value);

                DataTable tb = BLL.CashFlowRule.GenerateRptCostList(ProjectCode, IYear, IMonth);

                tb.Columns.Add("TrHtml");
                foreach (DataRow dr in tb.Rows)
                {
                    string ItemName   = BLL.ConvertRule.ToString(dr["ItemName"]);
                    string ItemDesc   = BLL.ConvertRule.ToString(dr["ItemDesc"]);
                    string FieldName  = BLL.ConvertRule.ToString(dr["FieldName"]);
                    int    Deep       = BLL.ConvertRule.ToInt(dr["Deep"]);
                    string CostCode   = BLL.ConvertRule.ToString(dr["CostCode"]);
                    string CostName   = BLL.ConvertRule.ToString(dr["CostName"]);
                    string ParentCode = BLL.ConvertRule.ToString(dr["ParentCode"]);

                    string ClassName = "";

                    string id = FieldName + "_" + CostCode;

                    string html = "";
                    html += "<tr id='mytr" + id + "' CostCode='" + CostCode + "' ParentCode='" + ParentCode + "' Deep='" + Deep + "' FieldName='" + FieldName + "'>";

                    if (Deep == 0)                     //产品类型根结点
                    {
                        /*
                         * if (IsAct == 0)  //计划
                         * {
                         *      //计划的子结点数
                         *      int AllCountPlan = tb.Select(string.Format("ItemName='{0}' and IsAct={1}", ItemName, IsAct)).Length;
                         *      int rowspanPlan = AllCountPlan + 1;
                         *
                         *      //实际的子结点数
                         *      int AllCountAct = tb.Select(string.Format("ItemName='{0}' and IsAct=1", ItemName)).Length;
                         *      int rowspanAct = AllCountAct + 1;
                         *
                         *      html += "<td align='center' class='list-c' nowrap rowspan='" + (rowspanPlan + rowspanAct).ToString() + "'>" + ItemDesc + "</td>"
                         + "<td align='center' class='list-c' nowrap rowspan='" + rowspanPlan.ToString() + "'>" + IsActName + "</td>"
                         +              ;
                         + }
                         + else  //实际
                         + {
                         +      int AllCount = tb.Select(string.Format("ItemName='{0}' and IsAct={1}", ItemName, IsAct)).Length;
                         +      int rowspan = AllCount + 1;
                         +
                         +      html += "<td align='center' class='list-c' nowrap rowspan='" + rowspan.ToString() + "'>" + IsActName + "</td>"
                         +              ;
                         + }
                         */

                        int AllCount = tb.Select(string.Format("ItemName='{0}'", ItemName)).Length;
                        int rowspan  = AllCount + 1;

                        html += "<td align='center' class='list-c' nowrap rowspan='" + rowspan.ToString() + "'>" + ItemDesc + "</td>"
                        ;
                    }
                    else
                    {
                    }

                    //费用项是否有子结点
                    int ChildCount;
                    if (Deep == 0)
                    {
                        ChildCount = tb.Select(string.Format("ItemName='{0}' and ParentCode='' and Deep > 0", ItemName)).Length;
                    }
                    else
                    {
                        ChildCount = tb.Select(string.Format("ItemName='{0}' and ParentCode='{1}'", ItemName, CostCode)).Length;
                    }

                    //展开、折叠
                    string image = "";

                    /*
                     * string image = "<span style=\"width:15px\">";
                     * if (ChildCount > 0)
                     * {
                     *      image += "<img exp=1 id='myimg" + id + "' src=\"../Images/Minus.gif\" CostCode='" + CostCode + "' Deep='" + Deep.ToString() + "' FieldName='" + FieldName + "' IsAct='" + IsAct.ToString() + "' onclick=\"TreeExpand(this);\">";
                     * }
                     * else
                     * {
                     * }
                     * image += "</span>";
                     */

                    //缩进
                    string space = "";
                    for (int i = 0; i < Deep; i++)
                    {
                        space += "&nbsp;&nbsp;&nbsp;";
                    }

                    if (Deep == 0)                     //费用项根结点
                    {
                        html     += "<td nowrap class='sum-item'>" + space + image + ItemName + "</td>";
                        ClassName = "sum";
                    }
                    else
                    {
                        html += "<td nowrap class='list-c'>" + space + image + CostName + "</td>";
                    }

                    //本月实际
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["CurrAct"], FieldName) + "</td>";

                    //本月计划
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["CurrPlan"], FieldName) + "</td>";

                    //本月对比
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.StringRule.AddUnit(BLL.CashFlowRule.FormatSalListValue(dr["CurrPercent"], "PERCENT"), "%") + "</td>";

                    //后期预测
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["AfterPlanM1"], FieldName) + "</td>";
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["AfterPlanM3"], FieldName) + "</td>";

                    //当年累计实际
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["CurrYAct"], FieldName) + "</td>";

                    //当年累计计划
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["CurrYPlan"], FieldName) + "</td>";

                    //当年累计对比
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.StringRule.AddUnit(BLL.CashFlowRule.FormatSalListValue(dr["CurrYPercent"], "PERCENT"), "%") + "</td>";

                    //项目累计实际
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["ProjectAct"], FieldName) + "</td>";

                    //项目累计计划
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["ProjectPlan"], FieldName) + "</td>";

                    //项目累计对比
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.StringRule.AddUnit(BLL.CashFlowRule.FormatSalListValue(dr["ProjectPercent"], "PERCENT"), "%") + "</td>";

                    html += "</tr>";

                    /*
                     * if (Deep == 0) //费用项根结点
                     * {
                     *      //占预计销售总额百分比
                     *      html += "<tr>";
                     *
                     *      html += "</tr>";
                     * }
                     */


                    dr["TrHtml"] = html;
                }

                BindGrid(tb);
            }
            catch (Exception ex)
            {
                ApplicationLog.WriteLog(this.ToString(), ex, "");
                Response.Write(Rms.Web.JavaScript.Alert(true, "显示成本出错:" + ex.Message));
            }
        }
Esempio n. 17
0
        private void LoadGridCashFlow()
        {
            try
            {
                string ProjectCode = this.txtProjectCode.Value;
                int    IYear       = BLL.ConvertRule.ToInt(this.txtYear.Value);
                int    IMonth      = BLL.ConvertRule.ToInt(this.txtMonth.Value);

                DataTable tb = BLL.CashFlowRule.GenerateRptCostListCashFlow(ProjectCode, IYear, IMonth);

                tb.Columns.Add("TrHtml");
                foreach (DataRow dr in tb.Rows)
                {
                    string ItemName = BLL.ConvertRule.ToString(dr["ItemName"]);
                    string ItemDesc = BLL.ConvertRule.ToString(dr["ItemDesc"]);
                    int    Deep     = BLL.ConvertRule.ToInt(dr["Deep"]);

                    string ClassName = "";

                    string html = "";
                    html += "<tr>";

                    if (Deep == 0)                     //根结点
                    {
                        int AllCount = tb.Rows.Count;
                        int rowspan  = AllCount + 1;

                        html += "<td align='center' class='list-c' nowrap rowspan='" + rowspan.ToString() + "'>" + "现金流量" + "</td>"
                        ;
                    }
                    else
                    {
                    }

                    //缩进
                    string space = "";
                    for (int i = 0; i < Deep; i++)
                    {
                        space += "&nbsp;&nbsp;&nbsp;";
                    }

                    if (Deep == 0)                     //根结点
                    {
                        html     += "<td nowrap class='sum-item'>" + space + ItemDesc + "</td>";
                        ClassName = "sum";
                    }
                    else
                    {
                        html += "<td nowrap class='list-c'>" + space + ItemName + "</td>";
                    }

                    //本月实际
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["CurrAct"], "") + "</td>";

                    //本月计划
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["CurrPlan"], "") + "</td>";

                    //本月对比
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.StringRule.AddUnit(BLL.CashFlowRule.FormatSalListValue(dr["CurrPercent"], "PERCENT"), "%") + "</td>";

                    //后期预测
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["AfterPlanM1"], "") + "</td>";
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["AfterPlanM3"], "") + "</td>";

                    //当年累计实际
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["CurrYAct"], "") + "</td>";

                    //当年累计计划
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["CurrYPlan"], "") + "</td>";

                    //当年累计对比
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.StringRule.AddUnit(BLL.CashFlowRule.FormatSalListValue(dr["CurrYPercent"], "PERCENT"), "%") + "</td>";

                    //项目累计实际
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["ProjectAct"], "") + "</td>";

                    //项目累计计划
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.CashFlowRule.FormatSalListValue(dr["ProjectPlan"], "") + "</td>";

                    //项目累计对比
                    html += "<td nowrap align='right' class='" + ClassName + "'>" + BLL.StringRule.AddUnit(BLL.CashFlowRule.FormatSalListValue(dr["ProjectPercent"], "PERCENT"), "%") + "</td>";

                    html += "</tr>";

                    dr["TrHtml"] = html;
                }

                BindGridCashFlow(tb);
            }
            catch (Exception ex)
            {
                ApplicationLog.WriteLog(this.ToString(), ex, "");
                Response.Write(Rms.Web.JavaScript.Alert(true, "显示现金流出错:" + ex.Message));
            }
        }
        /// <summary>
        /// You can either specify the logging server and application name here or set it up in the log4net config file
        /// </summary>
        /// <param name="server"></param>
        /// <param name="applicationName"></param>
        public void Start(PGIServer server, string applicationName)
        {
            _entMgr = AuthenticationUtils.GetSqlEntityManager(
                    LoginTypeEnum.WindowsActiveDirectory,
                    applicationName,
                    server, PGIDB.SmartBase
                    );

            AppLog = UIUtils.LogApplicationOpen(_entMgr, applicationName, _entMgr.CurrentStaff);
        }
        private void SavaData()
        {
            string act = Request["Action"] + "";;
            string functionStructureCode = Request["FunctionStructureCode"] + "";

            if (this.txtFunctionStructureName.Value.Trim().Length == 0)
            {
                Response.Write(Rms.Web.JavaScript.Alert(true, "请填写名称 !"));
                return;
            }

            if (this.txtFunctionStructureCode.Value.Trim().Length == 0)
            {
                Response.Write(Rms.Web.JavaScript.Alert(true, "请填写编号 !"));
                return;
            }

            try
            {
                string currentCode = "";
                int    deep        = 0;

                string parentCode = "";
                int    parentDeep = 0;

                EntityData entity = null;
                DataRow    dr     = null;

                if (act == "AddChild")
                {
                    parentCode = functionStructureCode;
                    if (parentCode != "")
                    {
                        EntityData parent = DAL.EntityDAO.SystemManageDAO.GetFunctionStructureByCode(parentCode);
                        parentDeep = parent.GetInt("Deep");
                        parent.Dispose();
                    }

                    currentCode = this.txtFunctionStructureCode.Value;

                    entity = new EntityData("FunctionStructure");
                    dr     = entity.GetNewRecord();
                    dr["FunctionStructureCode"] = currentCode;
                    dr["ParentCode"]            = parentCode;

                    deep       = parentDeep + 1;
                    dr["Deep"] = deep;

                    entity.AddNewRecord(dr);
                }
                else if (act == "Modify")
                {
                    entity = DAL.EntityDAO.SystemManageDAO.GetFunctionStructureByCode(functionStructureCode);
                    dr     = entity.CurrentRow;
                }

                dr["FunctionStructureName"]     = this.txtFunctionStructureName.Value;
                dr["Description"]               = this.txtDescription.Value;
                dr["ProjectSpecialDescription"] = this.txtProjectSpecialDescription.Value;
                dr["OtherSpecialDescription"]   = this.txtOtherSpecialDescription.Value;

                if (this.chkRight.Checked)
                {
                    dr["IsRightControlPoint"] = 0;
                }
                else
                {
                    dr["IsRightControlPoint"] = 1;
                }

                if (this.chkRole.Checked)
                {
                    dr["IsRoleControlPoint"] = 0;
                }
                else
                {
                    dr["IsRoleControlPoint"] = 1;
                }

                if (this.chkIsAvailable.Checked)
                {
                    dr["IsAvailable"] = 0;
                }
                else
                {
                    dr["IsAvailable"] = 1;
                }

                if (this.chkSystemClass.Checked)
                {
                    dr["IsSystemClass"] = 1;
                }
                else
                {
                    dr["IsSystemClass"] = 0;
                }

                DAL.EntityDAO.SystemManageDAO.SubmitAllFunctionStructure(entity);
                entity.Dispose();

                // 对该节点以下的子节点做处理
                if ((act == "Modify") && (!this.chkIsAvailable.Checked))
                {
                    EntityData eee = DAL.EntityDAO.SystemManageDAO.GetAllFunctionStructure();
                    foreach (DataRow dr1 in eee.CurrentTable.Select(String.Format("FunctionStructureCode like '{0}%' ", functionStructureCode)))
                    {
                        dr1["IsAvailable"] = 1;
                    }
                    DAL.EntityDAO.SystemManageDAO.SubmitAllFunctionStructure(eee);
                    eee.Dispose();
                }

                CloseWindow();
            }
            catch (Exception ex)
            {
                ApplicationLog.WriteLog(this.ToString(), ex, "");
                Response.Write(JavaScript.Alert(true, "保存出错:" + ex.Message));
            }
        }
Esempio n. 20
0
        public void InitPlugin(Guid key)
        {
            if (PluginStates.ContainsKey(key))
            {
                return;
            }

            String pluginPath = _pluginPaths[key];

            ApplicationLog.BaseLog.Info("Initializing plugin at {0} - {1}'", pluginPath, key);

            try
            {
                IPlugin plugin = Plugins[key];
                if (plugin.Name == "Dedicated Server Essentials")
                {
                    FieldInfo memberInfo = plugin.GetType().GetField("StableBuild", BindingFlags.Static | BindingFlags.Public);
                    if (memberInfo != null)
                    {
                        bool pluginStable = (bool)memberInfo.GetValue(null);
                        if (!pluginStable && IsStable)
                        {
                            ApplicationLog.Error("WARNING: This version of Essentials is NOT compatible with \"stable\" branch!");
                            ApplicationLog.Error("Aborting plugin initialization!");
                            if (SystemInformation.UserInteractive)
                            {
                                MessageBox.Show("WARNING: This version of Essentials is NOT compatible with \"stable\" branch!\r\n" +
                                                "Essentials will not load!",
                                                "FATAL ERROR", MessageBoxButtons.OK);
                            }
                            return;
                        }
                        else if (pluginStable && !IsStable)
                        {
                            ApplicationLog.Error("WARNING: This version of Essentials is NOT compatible with \"dev\" branch!");
                            ApplicationLog.Error("Aborting plugin initialization!");
                            if (SystemInformation.UserInteractive)
                            {
                                MessageBox.Show("WARNING: This version of Essentials is NOT compatible with \"dev\" branch!\r\n" +
                                                "Essentials will not load!",
                                                "FATAL ERROR", MessageBoxButtons.OK);
                            }
                            return;
                        }
                    }
                }

                FieldInfo logField = plugin.GetType( ).GetField("Log");
                if (logField != null)
                {
                    logField.SetValue(plugin, ApplicationLog.PluginLog, BindingFlags.Static, null, CultureInfo.CurrentCulture);
                }
                MethodInfo initMethod = plugin.GetType( ).GetMethod("InitWithPath");
                if (initMethod != null)
                {
                    initMethod.Invoke(plugin, new object[] { pluginPath });
                }
                if (initMethod == null)
                {
                    initMethod = plugin.GetType( ).GetMethod("Init");
                    initMethod.Invoke(plugin, new object[] { });
                }

                PluginStates.Add(key, true);
            }
            catch (Exception ex)
            {
                ApplicationLog.BaseLog.Error(ex);
            }
        }
Esempio n. 21
0
        void ValidateNUCmerAlignSimpleGeneralTestCases(string nodeName)
        {
            string[]         referenceSequences = null;
            string[]         searchSequences    = null;
            List <ISequence> refSeqList         = new List <ISequence>();
            List <ISequence> searchSeqList      = new List <ISequence>();

            // Gets the reference & search sequences from the configurtion file
            referenceSequences = utilityObj.xmlUtil.GetTextValues(nodeName,
                                                                  Constants.ReferenceSequencesNode);
            searchSequences = utilityObj.xmlUtil.GetTextValues(nodeName,
                                                               Constants.SearchSequencesNode);

            IAlphabet seqAlphabet = Utility.GetAlphabet(
                utilityObj.xmlUtil.GetTextValue(nodeName,
                                                Constants.AlphabetNameNode));

            for (int i = 0; i < referenceSequences.Length; i++)
            {
                ISequence referSeq = new Sequence(seqAlphabet,
                                                  encodingObj.GetBytes(referenceSequences[i]));
                refSeqList.Add(referSeq);
            }

            for (int i = 0; i < searchSequences.Length; i++)
            {
                ISequence searchSeq = new Sequence(seqAlphabet,
                                                   encodingObj.GetBytes(searchSequences[i]));
                searchSeqList.Add(searchSeq);
            }

            // Gets the mum length from the xml
            string mumLength = utilityObj.xmlUtil.GetTextValue(nodeName,
                                                               Constants.MUMAlignLengthNode);

            NucmerPairwiseAligner nucmerObj = new NucmerPairwiseAligner();

            // Update other values for NUCmer object
            nucmerObj.MaximumSeparation = int.Parse
                                              (utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MUMAlignLengthNode), (IFormatProvider)null);
            nucmerObj.MinimumScore = int.Parse(
                utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MUMAlignLengthNode), (IFormatProvider)null);
            nucmerObj.SeparationFactor = int.Parse(
                utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MUMAlignLengthNode), (IFormatProvider)null);
            nucmerObj.BreakLength = int.Parse(
                utilityObj.xmlUtil.GetTextValue(nodeName, Constants.MUMAlignLengthNode), (IFormatProvider)null);
            nucmerObj.LengthOfMUM = long.Parse(mumLength, null);

            IList <ISequenceAlignment> alignSimple = null;
            IList <ISequence>          seqList     = new List <ISequence>();

            foreach (ISequence seq in refSeqList)
            {
                seqList.Add(seq);
            }

            foreach (ISequence seq in searchSeqList)
            {
                seqList.Add(seq);
            }

            alignSimple = nucmerObj.AlignSimple(seqList);

            string expectedSequences = string.Empty;

            expectedSequences = utilityObj.xmlUtil.GetTextValue(nodeName,
                                                                Constants.ExpectedSequencesNode);

            string[] expSeqArray = expectedSequences.Split(',');

            int j = 0;

            // Gets all the aligned sequences in comma seperated format
            foreach (IPairwiseSequenceAlignment seqAlignment in alignSimple)
            {
                foreach (PairwiseAlignedSequence alignedSeq in seqAlignment)
                {
                    Assert.AreEqual(expSeqArray[j], new string(alignedSeq.FirstSequence.Select(a => (char)a).ToArray()));
                    ++j;
                    Assert.AreEqual(expSeqArray[j], new string(alignedSeq.SecondSequence.Select(a => (char)a).ToArray()));
                    j++;
                }
            }

            Console.WriteLine(
                "NUCmer P2 : Successfully validated all the aligned sequences.");
            ApplicationLog.WriteLine(
                "NUCmer P2 : Successfully validated all the aligned sequences.");
        }
    /// ****************************************************************************
    /// <summary>
    /// 流程意见控件数据保存
    /// 世茂特殊要求(2个项目总监会签)
    /// </summary>
    /// ****************************************************************************
    override protected Boolean OpinionDataSubmit(StandardEntityDAO dao, bool flag)
    {
        Boolean ReturnValue;

        ReturnValue = base.OpinionDataSubmit(dao, flag);

        try
        {
            if (ReturnValue)
            {
                foreach (RepeaterItem ud_rptItem in rptMeetSign.Items)
                {
                    RmsPM.Web.WorkFlowControl.WorkFlowFormOpinion ud_wfoControl;

                    switch (ud_rptItem.ItemType)
                    {
                    case ListItemType.Item:
                        ud_wfoControl = (RmsPM.Web.WorkFlowControl.WorkFlowFormOpinion)ud_rptItem.FindControl("wfoItemOpinion");
                        break;

                    case ListItemType.AlternatingItem:
                        ud_wfoControl = (RmsPM.Web.WorkFlowControl.WorkFlowFormOpinion)ud_rptItem.FindControl("wfoAlternatingItemOpinion");
                        break;

                    default:
                        continue;
                    }

                    if (ud_wfoControl.State == ModuleState.Operable)
                    {
                        ud_wfoControl.ApplicationCode = wftToolbar.ApplicationCode;
                        if (!flag)
                        {
                            if (ud_wfoControl.ControlType == "TextArea")
                            {
                                ud_wfoControl.TextOpinion = this.up_wftToolbar.FlowOpinion;
                            }

                            ud_wfoControl.AuditValue = this.up_wftToolbar.AuditValue;
                        }
                        else
                        {
                            if (ud_wfoControl.ControlType == "TextArea")
                            {
                                this.up_wftToolbar.FlowOpinion = ud_wfoControl.TextOpinion;
                            }

                            this.up_wftToolbar.AuditValue = ud_wfoControl.OpinionConfirm;
                        }

                        ud_wfoControl.dao        = dao;
                        ud_wfoControl.AuditValue = this.up_wftToolbar.AuditValue;
                        ud_wfoControl.CaseCode   = wftToolbar.CaseCode;
                        ud_wfoControl.SubmitData();
                    }
                }
            }

            return(ReturnValue);
        }
        catch (Exception ex)
        {
            ApplicationLog.WriteLog(this.ToString(), ex, "");
            Response.Write(Rms.Web.JavaScript.Alert(true, "审批意见保存出错:" + ex.Message));
            throw ex;
        }
    }
Esempio n. 23
0
        /// <summary>
        /// Validate general fetching results.by passing
        /// differnt parameters for Ebi web service..
        /// <param name="nodeName">xml node name.</param>
        /// <param name="isFetchSynchronous">Is Fetch Synchronous?</param>
        /// </summary>
        static void ValidateEBIWuBlastResultsFetch(
            string nodeName,
            bool isFetchSynchronous)
        {
            if (_IsWebServiceAvailable)
            {
                // Gets the search query parameter and their values.
                string alphabetName = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.AlphabetNameNode);
                string querySequence = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.QuerySequency);
                string queryDatabaseValue = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.DatabaseValue);
                string emailParameter = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.Emailparameter);
                string email = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.EmailAdress);
                string queryProgramValue = Utility._xmlUtil.GetTextValue(
                    Constants.EbiAsynchronousResultsNode, Constants.ProgramValue);
                string queryDatabaseParameter = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.DatabaseParameter);
                string queryProgramParameter = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.ProgramParameter);
                string expectedHitId = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.HitID);
                string expectedAccession = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.HitAccession);
                string expectedResultCount = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.ResultsCount);
                string expectedHitsCount = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.HitsCount);
                string expectedEntropyStatistics = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.EntropyStatistics);
                string expectedKappaStatistics = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.KappaStatistics);
                string expectedLambdaStatistics = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.LambdaStatistics);
                string expectedLength = Utility._xmlUtil.GetTextValue(
                    nodeName, Constants.Length);

                object   responseResults = null;
                Sequence seq             = new Sequence(Utility.GetAlphabet(alphabetName),
                                                        querySequence);

                // create Ebi Blast service object.
                IBlastServiceHandler service      = new EbiWuBlastHandler();
                ConfigParameters     configParams = new ConfigParameters();
                configParams.UseBrowserProxy = true;
                service.Configuration        = configParams;

                BlastParameters searchParams = new BlastParameters();

                // Set Request parameters.
                searchParams.Add(queryDatabaseParameter, queryDatabaseValue);
                searchParams.Add(queryProgramParameter, queryProgramValue);
                searchParams.Add(emailParameter, email);

                // Create a request without passing sequence.
                string reqId = service.SubmitRequest(seq, searchParams);

                // validate request identifier.
                Assert.IsNotNull(reqId);

                // query the status
                ServiceRequestInformation info = service.GetRequestStatus(reqId);
                if (info.Status != ServiceRequestStatus.Waiting &&
                    info.Status != ServiceRequestStatus.Ready)
                {
                    string err =
                        ApplicationLog.WriteLine("Unexpected status: '{0}'", info.Status);
                    Assert.Fail(err);
                }

                // get async results, poll until ready
                int maxAttempts = 20;
                int attempt     = 1;
                while (attempt <= maxAttempts &&
                       info.Status != ServiceRequestStatus.Error &&
                       info.Status != ServiceRequestStatus.Ready)
                {
                    if (isFetchSynchronous)
                    {
                        info = service.GetRequestStatus(reqId);
                        Thread.Sleep(info.Status == ServiceRequestStatus.Waiting ||
                                     info.Status == ServiceRequestStatus.Queued
                            ? 20000 * attempt : 0);
                    }
                    else
                    {
                        Thread.Sleep(info.Status == ServiceRequestStatus.Waiting ? 20000 : 0);
                        info = service.GetRequestStatus(reqId);
                    }
                    ++attempt;
                }

                IBlastParser blastXmlParser = new BlastXmlParser();
                responseResults = blastXmlParser.Parse(
                    new StringReader(service.GetResult(reqId, searchParams)));

                // Validate blast results.
                Assert.IsNotNull(responseResults);
                List <BlastResult> eBlastResults = responseResults as List <BlastResult>;
                Assert.IsNotNull(eBlastResults);
                Assert.AreEqual(eBlastResults.Count.ToString(
                                    (IFormatProvider)null), expectedResultCount);
                Assert.AreEqual(eBlastResults[0].Records.Count.ToString((
                                                                            IFormatProvider)null), expectedResultCount);
                BlastSearchRecord record = eBlastResults[0].Records[0];
                Assert.AreEqual(record.Statistics.Kappa.ToString(
                                    (IFormatProvider)null), expectedKappaStatistics);
                Assert.AreEqual(record.Statistics.Lambda.ToString(
                                    (IFormatProvider)null), expectedLambdaStatistics);
                Assert.AreEqual(record.Statistics.Entropy.ToString(
                                    (IFormatProvider)null), expectedEntropyStatistics);
                Assert.AreEqual(record.Hits.Count.ToString(
                                    (IFormatProvider)null), expectedHitsCount);
                Hit hit = record.Hits[0];
                Assert.AreEqual(hit.Accession, expectedAccession);
                Assert.AreEqual(hit.Length.ToString(), expectedLength);
                Assert.AreEqual(hit.Id.ToString((IFormatProvider)null), expectedHitId);
                Assert.AreEqual(hit.Hsps.Count.ToString((IFormatProvider)null),
                                expectedResultCount);
                Console.WriteLine(string.Format(null,
                                                "Ebi Blast BVT: Hits count '{0}'.", eBlastResults.Count));
                Console.WriteLine(string.Format(null,
                                                "Ebi Blast BVT: Accession '{0}'.", hit.Accession));
                Console.WriteLine(string.Format(null,
                                                "Ebi Blast BVT: Hit Id '{0}'.", hit.Id));
                Console.WriteLine(string.Format(null,
                                                "Ebi Blast BVT: Hits Count '{0}'.", hit.Hsps.Count));

                // Validate the results Synchronously with the results got earlier.
                if (isFetchSynchronous)
                {
                    IList <BlastResult> syncBlastResults =
                        service.FetchResultsSync(reqId, searchParams) as List <BlastResult>;
                    Assert.IsNotNull(syncBlastResults);
                    if (null != eBlastResults[0].Records[0].Hits &&
                        0 < eBlastResults[0].Records[0].Hits.Count &&
                        null != eBlastResults[0].Records[0].Hits[0].Hsps &&
                        0 < eBlastResults[0].Records[0].Hits[0].Hsps.Count)
                    {
                        Assert.AreEqual(eBlastResults[0].Records[0].Hits[0].Hsps[0].QuerySequence,
                                        syncBlastResults[0].Records[0].Hits[0].Hsps[0].QuerySequence);
                    }
                    else
                    {
                        ApplicationLog.WriteLine(
                            "No significant hits found with the these parameters.");
                        Console.WriteLine("No significant hits found with the these parameters.");
                    }
                }
            }
            else
            {
                Assert.Ignore("The test case ignored due to connection failure");
            }
        }
Esempio n. 24
0
        /// <summary>
        /// 显示要导入的厂商材料列表
        /// </summary>
        private void ShowImportList()
        {
            try
            {
                if (Session["tbImportSupplierMaterialStream"] == null)
                {
                    throw new Exception("超时,请重新导入");
                }

                DataTable tbStream = (DataTable)Session["tbImportSupplierMaterialStream"];

                BLL.SupplierMaterialImport imp = new SupplierMaterialImport();
//				EntityData entity = new EntityData("SupplierMaterial");
                EntityData entity = DAL.EntityDAO.MaterialDAO.GetAllSupplierMaterial();

                //增加预导入结果列
                entity.CurrentTable.Columns.Add("GroupFullName");
                entity.CurrentTable.Columns.Add("SupplierName");
                entity.CurrentTable.Columns.Add("rowid", typeof(int));
                entity.CurrentTable.Columns.Add("text");
                entity.CurrentTable.Columns.Add("ImportHint");
                entity.CurrentTable.Columns.Add("ImportResult", typeof(int));
                entity.CurrentTable.Columns.Add("ImportResultName");
                entity.CurrentTable.Columns.Add("IsImport", typeof(int));

                int add_count  = 0;
                int edit_count = 0;
                int err_count  = 0;

                foreach (DataRow drStream in tbStream.Rows)
                {
                    string s = BLL.ConvertRule.ToString(drStream["text"]);
                    int    r = BLL.ConvertRule.ToInt(drStream["rowid"]);

                    string  hint          = "";
                    string  SupplierName  = "";
                    string  GroupFullName = "";
                    DataRow dr            = imp.ImportSupplierMaterialSingle(s, entity, ref hint, ref SupplierName, ref GroupFullName, true, (DataTable)Session["tbAllSystemGroup"]);

                    if (dr == null)
                    {
                        //出错
                        err_count++;
                        dr = entity.CurrentTable.NewRow();
                        dr["SupplierMaterialCode"] = "ERR_" + r.ToString();
                        dr["ImportHint"]           = hint;
                        dr["ImportResult"]         = -1;
                        dr["ImportResultName"]     = "有错";
                        entity.CurrentTable.Rows.Add(dr);
                    }
                    else
                    {
                        //成功
                        if (dr.RowState == DataRowState.Added)
                        {
                            add_count++;
                            dr["ImportResult"]     = 1;
                            dr["ImportResultName"] = "新增";
                        }
                        else
                        {
                            edit_count++;
                            dr["ImportResult"]     = 2;
                            dr["ImportResultName"] = "修改";
                        }
                    }

                    dr["GroupFullName"] = GroupFullName;
                    dr["SupplierName"]  = SupplierName;
                    dr["rowid"]         = r;
                    dr["text"]          = s;
                    dr["IsImport"]      = 1;
                }

                this.lblCountAdd.Text  = add_count.ToString();
                this.lblCountEdit.Text = edit_count.ToString();
                this.lblCountErr.Text  = err_count.ToString();

                Session["entityImportSupplierMaterial"] = entity;
                BindImportList();
//				entity.Dispose();
            }
            catch (Exception ex)
            {
                ApplicationLog.WriteLog(this.ToString(), ex, "");
                Response.Write(JavaScript.Alert(true, "显示要导入的厂商材料列表出错:" + ex.Message));
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Validate if the connection is successful
        /// </summary>
        /// <returns>True, if connection is successful</returns>
        static bool ValidateWebServiceConnection()
        {
            // Gets the search query parameter and their values.
            string alphabetName = Utility._xmlUtil.GetTextValue(
                Constants.EbiAsynchronousResultsNode, Constants.AlphabetNameNode);
            string querySequence = Utility._xmlUtil.GetTextValue(
                Constants.EbiAsynchronousResultsNode, Constants.QuerySequency);
            string queryDatabaseValue = Utility._xmlUtil.GetTextValue(
                Constants.EbiAsynchronousResultsNode, Constants.DatabaseValue);
            string emailParameter = Utility._xmlUtil.GetTextValue(
                Constants.EbiAsynchronousResultsNode, Constants.Emailparameter);
            string email = Utility._xmlUtil.GetTextValue(
                Constants.EbiAsynchronousResultsNode, Constants.EmailAdress);
            string queryProgramValue = Utility._xmlUtil.GetTextValue(
                Constants.EbiAsynchronousResultsNode, Constants.ProgramValue);
            string queryDatabaseParameter = Utility._xmlUtil.GetTextValue(
                Constants.EbiAsynchronousResultsNode, Constants.DatabaseParameter);
            string queryProgramParameter = Utility._xmlUtil.GetTextValue(
                Constants.EbiAsynchronousResultsNode, Constants.ProgramParameter);

            Sequence seq = new Sequence(Utility.GetAlphabet(alphabetName),
                                        querySequence);

            // create Ebi Blast service object.
            IBlastServiceHandler service      = new EbiWuBlastHandler();
            ConfigParameters     configParams = new ConfigParameters();

            configParams.UseBrowserProxy = true;
            service.Configuration        = configParams;

            BlastParameters searchParams = new BlastParameters();

            // Set Request parameters.
            searchParams.Add(queryDatabaseParameter, queryDatabaseValue);
            searchParams.Add(queryProgramParameter, queryProgramValue);
            searchParams.Add(emailParameter, email);

            try
            {
                // Create a request without passing sequence.
                string reqId = service.SubmitRequest(seq, searchParams);

                if (string.IsNullOrEmpty(reqId))
                {
                    Console.WriteLine(
                        "Ebi Blast Bvt : Connection not successful with no Request ID");
                    ApplicationLog.WriteLine(
                        "Ebi Blast Bvt : Connection not successful with no Request ID");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format(
                                      "Ebi Blast Bvt : Connection not successful with error '{0}'", ex.Message));
                ApplicationLog.WriteLine(string.Format(
                                             "Ebi Blast Bvt : Connection not successful with error '{0}'", ex.Message));
                return(false);
            }

            Console.WriteLine("Ebi Blast BVT : Connection Successful");
            return(true);
        }
Esempio n. 26
0
        /// <summary>
        /// 完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnComplete_ServerClick(object sender, System.EventArgs e)
        {
            try
            {
                int step = 9;

                this.txtStep.Value = step.ToString();

                int succ_count     = 0;
                int err_count      = 0;
                int succ_add_count = 0;

                try
                {
                    this.txtResult.Value = "";

                    if (Session["tbImportSupplierMaterialStream"] == null)
                    {
                        throw new Exception("超时,请重新导入");
                    }

                    DataTable tbStream = (DataTable)Session["tbImportSupplierMaterialStream"];

                    BLL.SupplierMaterialImport imp = new SupplierMaterialImport();
                    EntityData entity = DAL.EntityDAO.MaterialDAO.GetAllSupplierMaterial();

                    foreach (DataRow drStream in tbStream.Rows)
                    {
                        string s = BLL.ConvertRule.ToString(drStream["text"]);
                        int    r = BLL.ConvertRule.ToInt(drStream["rowid"]);

                        string  hint          = "";
                        string  SupplierName  = "";
                        string  GroupFullName = "";
                        DataRow dr            = imp.ImportSupplierMaterialSingle(s, entity, ref hint, ref SupplierName, ref GroupFullName, false, (DataTable)Session["tbAllSystemGroup"]);

                        if (dr == null)
                        {
                            //出错
                            err_count++;
                            this.txtResult.Value = this.txtResult.Value + string.Format("第 {0} 行 {1}:", r, "") + hint + "\n";
                        }
                        else
                        {
                            //成功
                            succ_count++;

                            if (dr.RowState == DataRowState.Added)                             //新增
                            {
                                succ_add_count++;
                            }
                        }
                    }

                    DAL.EntityDAO.MaterialDAO.SubmitAllSupplierMaterial(entity);
                }
                catch (Exception ex)
                {
                    ApplicationLog.WriteLog(this.ToString(), ex, "");
                    Response.Write(JavaScript.Alert(true, "导入出错:" + ex.Message));
                    return;
                }

                int succ_edit_count = succ_count - succ_add_count;

                if (err_count > 0)
                {
                    this.txtResult.Value = string.Format("导入完成,{0}条成功(新增{1}条、修改{2}条),{3}条出错:", succ_count, succ_add_count, succ_edit_count, err_count) + "\n" + this.txtResult.Value;
                }
                else
                {
                    this.txtResult.Value = string.Format("导入完成,{0}条导入成功(新增{1}条、修改{2}条)", succ_count, succ_add_count, succ_edit_count);
                }

                //导入有错时记日志
                ApplicationLog.WriteFile("厂商材料导入.log", this.ToString(), this.txtResult.Value);

                RefreshParent();
            }
            catch (Exception ex)
            {
                ApplicationLog.WriteLog(this.ToString(), ex, "");
                Response.Write(JavaScript.Alert(true, "完成出错:" + ex.Message));
            }
        }
Esempio n. 27
0
        public void TestSimpleSequenceAssemblerWithRandomSequence()
        {
            // Test parameters.
            //
            // In theory, as long as all positions in the master sequence are
            // covered by at least one read, we should be able to pass this test.
            // But some parameter settings will make the test fail, for
            // various reasons, including:
            // 1. Short reads, caused by the strategy used to ensure full coverage
            //  at the ends, might not score well enough to merge.
            // 2. Uncovered positions are always possible due to the random
            //  generation of reads. (Increasing the number of reads helps with this)
            // 3. The assembler might construct the reverse or complement (or both)
            //  of the master sequence.
            // 4. Too low a merge threshold could cause incorrect merges, which
            //  the algorithm will not repair.
            int        matchScore          = 1;
            int        mismatchScore       = -8;
            int        gapCost             = -8;
            double     mergeThreshold      = 3;
            double     consensusThreshold  = 99;
            const int  MasterLength        = 100;
            const int  MinReadLength       = 10;
            const int  MaxReadLength       = 30;
            const int  NumReads            = 200;
            const bool AssumeOrientedReads = true;

            // if this is uncommented, assembly details appear in log.
            // this is extremely verbose.
            // Trace.Set(Trace.AssemblyDetails);

            // make random master sequence
            // (use seed for repeatability, or omit seed for
            // different test each time)
            // Random randGen = new Random();
            Random randGen = new Random(654321);

            StringBuilder randSeq = new StringBuilder();

            for (int i = 0; i < MasterLength; ++i)
            {
                int randm = randGen.Next(8);
                if (randm < 2)
                {
                    randSeq.Append('A');
                }
                else if (randm < 4)
                {
                    randSeq.Append('C');
                }
                else if (randm < 6)
                {
                    randSeq.Append('G');
                }
                else
                {
                    randSeq.Append('T');
                }
            }

            Sequence master = new Sequence(Alphabets.AmbiguousDNA, randSeq.ToString());

            // create the reads
            List <ISequence> inputs = new List <ISequence>();

            for (int i = 0; i < NumReads; ++i)
            {
                // try for uniform coverage clear to the ends (this can lead to short reads, though)
                int       rndPos  = Math.Max(0, randGen.Next(-MinReadLength, MasterLength - 1));
                int       rndLen  = Math.Min(MasterLength - rndPos, randGen.Next(MinReadLength, MaxReadLength + 1));
                string    data    = master.ToStrings().Substring(Math.Max(0, rndPos), rndLen);
                bool      revcomp = randGen.Next(2) > 0;
                bool      reverse = randGen.Next(2) > 0 && !AssumeOrientedReads;
                ISequence read;
                if (reverse && revcomp)
                {
                    Sequence tmp = new Sequence(Alphabets.DNA, data);
                    read = new Sequence(Alphabets.DNA, tmp.GetReversedSequence().ToStrings());
                }
                else if (revcomp)
                {
                    Sequence tmp = new Sequence(Alphabets.DNA, data);
                    read = new Sequence(Alphabets.DNA, tmp.GetReverseComplementedSequence().ToStrings());
                }
                else
                {
                    read = new Sequence(Alphabets.DNA, data);
                }

                ApplicationLog.WriteLine("read {0}: {1}", i, read);
                inputs.Add(read);
            }

            OverlapDeNovoAssembler assembler = new OverlapDeNovoAssembler();

            assembler.MergeThreshold   = mergeThreshold;
            assembler.OverlapAlgorithm = new PairwiseOverlapAligner();
            ((IPairwiseSequenceAligner)assembler.OverlapAlgorithm).SimilarityMatrix = new DiagonalSimilarityMatrix(matchScore, mismatchScore);
            ((IPairwiseSequenceAligner)assembler.OverlapAlgorithm).GapOpenCost      = gapCost;
            assembler.ConsensusResolver         = new SimpleConsensusResolver(consensusThreshold);
            assembler.AssumeStandardOrientation = AssumeOrientedReads;

            IOverlapDeNovoAssembly seqAssembly = (IOverlapDeNovoAssembly)assembler.Assemble(inputs);

            ApplicationLog.WriteLine(
                "Assembly finished. Contigs: {0}. Unmerged sequences: {1}.",
                seqAssembly.Contigs.Count,
                seqAssembly.UnmergedSequences.Count);
            Contig contig0 = seqAssembly.Contigs[0];

            ApplicationLog.WriteLine("master sequence and contig 0 consensus:");
            ApplicationLog.WriteLine(master.ToStrings());
            ApplicationLog.WriteLine(contig0.Consensus.ToStrings());

            Assert.AreEqual(2, seqAssembly.UnmergedSequences.Count);
            Assert.AreEqual(1, seqAssembly.Contigs.Count);

            // note that this is tricky, esp. without oriented reads - consensus
            // could be reversed and/or complemented relative to original
            Assert.AreEqual(master.ToStrings(), contig0.Consensus.ToStrings());
        }
Esempio n. 28
0
        /// <summary>
        /// 另存为csv
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDownloadCsv_ServerClick(object sender, System.EventArgs e)
        {
            try
            {
                if (Session["entityImportSupplierMaterial"] == null)
                {
                    throw new Exception("超时,请重新导入");
                }

                EntityData entity = (EntityData)Session["entityImportSupplierMaterial"];
                DataView   dv     = new DataView(entity.CurrentTable, "IsImport = 1", "rowid", DataViewRowState.CurrentRows);

                RmsPM.BLL.FileIO io = new FileIO(Response, Request, Server, Session);
                io.SaveFileName = "SupplierMaterialImportPrepare.csv";

                StreamWriter w = new StreamWriter(io.SaveFileNamePhy, false, System.Text.Encoding.Default);
                try
                {
                    BLL.SupplierMaterialImport imp = new SupplierMaterialImport();
                    string s;

                    //第1行是列标题
                    s  = imp.GetDefineFieldDesc();
                    s += ",预导入结果,错误提示";
                    w.WriteLine(s);

                    int count = imp.tbDefine.Rows.Count;

                    //数据
                    foreach (DataRowView drv in dv)
                    {
                        DataRow dr = drv.Row;
                        s = "";

                        s = BLL.ConvertRule.ToString(dr["text"]);
                        string[] arr = BLL.ImportRule.SplitCsvLine(s);

                        //用“,”补足列数
                        for (int k = arr.Length; k < count; k++)
                        {
                            s += ",";
                        }

                        /*
                         * //按字段定义重新写入
                         * for (int i=0;i<count;i++)
                         * {
                         *      DataRow drDefine = imp.tbDefine.Rows[i];
                         *      string FieldName = drDefine["FieldName"].ToString();
                         *
                         *      if (i > 0)
                         *              s += ",";
                         *
                         *      if (FieldName != "")
                         *      {
                         *              s += BLL.ConvertRule.ToString(dr[FieldName]);
                         *      }
                         * }
                         */

                        //写入预导入结果
                        s += "," + BLL.ConvertRule.ToString(dr["ImportResultName"]);

                        s += "," + BLL.ConvertRule.ToString(dr["ImportHint"]);

                        w.WriteLine(s);
                    }
                }
                finally
                {
                    w.Close();
                }

                io.ShowClient();
            }
            catch (Exception ex)
            {
                ApplicationLog.WriteLog(this.ToString(), ex, "");
                Response.Write(JavaScript.Alert(true, "另存为csv出错:" + ex.Message));
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Alignes the two input sequence
        /// Updates best score, if necessary
        /// </summary>
        /// <param name="sequence1">First Sequence to be aligned</param>
        /// <param name="sequence2">Second Sequence to be aligned</param>
        /// <param name="reversed">Is first sequence reversed?</param>
        /// <param name="complement">Is first sequence complemented?</param>
        /// <param name="bestScore">Structure to track best score</param>
        /// <param name="sequence1PoolIndex">Index of first sequence in pool.
        /// Used in printing for debug purpose.</param>
        /// <param name="sequence2PoolIndex">Index of second sequence in pool.
        /// Used in printing for debug purpose.</param>
        /// <param name="message">Message to be printed for debug purpose</param>
        /// <returns>Updated best score</returns>
        private ItemScore AlignAndUpdateBestScore(
            ISequence sequence1,
            ISequence sequence2,
            bool reversed,
            bool complement,
            ItemScore bestScore,
            int sequence1PoolIndex,
            int sequence2PoolIndex,
            string message)
        {
            // we will look for the best (largest) overlap score. Note that
            // lower-index items are already in place, so can do this in same pass
            IList <ISequenceAlignment> alignment = RunAlignSimple(sequence1, sequence2);

            if (Trace.Want(Trace.AssemblyDetails))
            {
                ApplicationLog.WriteLine("{0} {1} and {2}", message, sequence1PoolIndex, sequence2PoolIndex);
                Dump(alignment);
            }

            if (alignment.Count > 0 &&
                alignment[0].AlignedSequences.Count > 0)
            {
                long score = 0;
                try
                {
                    score = (long)alignment[0].AlignedSequences[0].Metadata["Score"];
                }
                catch
                {
                    // no impl.
                }

                if (score > bestScore.OverlapScore)
                {
                    bestScore.OverlapScore = score;
                    bestScore.Reversed     = reversed;
                    bestScore.Complemented = complement;
                    long offsets = 0;
                    try
                    {
                        offsets = (long)alignment[0].AlignedSequences[0].Metadata["FirstOffset"];
                    }
                    catch
                    {
                        // no impl.
                    }

                    bestScore.FirstOffset = offsets;
                    offsets = 0;
                    try
                    {
                        offsets = (long)alignment[0].AlignedSequences[0].Metadata["SecondOffset"];
                    }
                    catch
                    {
                        // no impl.
                    }

                    bestScore.SecondOffset = offsets;
                }
            }

            return(bestScore);
        }
Esempio n. 30
0
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOK_ServerClick(object sender, System.EventArgs e)
        {
            if (this.txtFile.PostedFile.FileName == "")
            {
                Response.Write(Rms.Web.JavaScript.Alert(true, "请选择文件"));
                return;
            }

            int succ_count = 0;
            int err_count  = 0;

            try
            {
                this.txtResult.Value = "";
                StreamReader m_sr = new StreamReader(this.txtFile.PostedFile.InputStream, System.Text.Encoding.Default);
                int          r    = 0;

                //第1行是标题
                if (m_sr.Peek() >= 0)
                {
                    m_sr.ReadLine();
                    r++;
                }

                BLL.SupplierMaterialImport imp = new SupplierMaterialImport();
                EntityData entity = DAL.EntityDAO.MaterialDAO.GetAllSupplierMaterial();

                while (m_sr.Peek() >= 0)
                {
                    string s = m_sr.ReadLine();
                    r++;

                    string  hint         = "";
                    string  SupplierName = "";
                    string  SupplierMaterialGroupFullName = "";
                    DataRow dr = imp.ImportSupplierMaterialSingle(s, entity, ref hint, ref SupplierName, ref SupplierMaterialGroupFullName, false, (DataTable)Session["tbAllSystemGroup"]);

                    if (dr == null)
                    {
                        //出错
                        err_count++;
                        this.txtResult.Value = this.txtResult.Value + string.Format("第 {0} 行 {1}:", r, "") + hint + "\n";
                    }
                    else
                    {
                        //成功
                        succ_count++;
                    }
                }

                DAL.EntityDAO.MaterialDAO.SubmitAllSupplierMaterial(entity);
            }
            catch (Exception ex)
            {
                ApplicationLog.WriteLog(this.ToString(), ex, "");
                Response.Write(JavaScript.Alert(true, "导入出错:" + ex.Message));
                return;
            }

            if (err_count > 0)
            {
                this.txtResult.Value = string.Format("导入完成,{0}条成功, {1}条出错:", succ_count, err_count) + "\n" + this.txtResult.Value;
            }
            else
            {
                this.txtResult.Value = string.Format("{0}条导入成功", succ_count);
            }

            //导入有错时记日志
            ApplicationLog.WriteFile("厂商材料导入.log", this.ToString(), this.txtResult.Value);

            RefreshParent();
            //			Response.Write(JavaScript.WinClose(false));
        }
Esempio n. 31
0
        /// <summary>
        /// 续借
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <CommonResponse <string> > RenewBorrow(RenewBorrowRequest request)
        {
            var response = new CommonResponse <string>();

            try
            {
                if (request == null)
                {
                    throw new BizException("参数不能为空");
                }

                if (request.RenewDate < DateTime.Now)
                {
                    throw new BizException("续借日期不能小于当天");
                }

                var borrowRegister = await _db.BorrowRegister.FirstOrDefaultAsync(c => c.Id == request.BorrowRegisterId && !c.Deleted);

                if (borrowRegister == null)
                {
                    throw new BizException("借阅登记不存在");
                }

                if (!(borrowRegister.Status == BorrowRegisterStatus.Renewed || borrowRegister.Status == BorrowRegisterStatus.Overdue || borrowRegister.Status == BorrowRegisterStatus.Borrowed))
                {
                    throw new BizException("借阅登记状态为:已借出、延期、逾期 才能续借");
                }

                borrowRegister.ReturnDate     = request.RenewDate;
                borrowRegister.Status         = BorrowRegisterStatus.Renewed;
                borrowRegister.UpdateTime     = DateTime.Now;
                borrowRegister.ReturnNotified = false;
                await _db.SaveChangesAsync();

                response.Success = true;

                try
                {
                    var archivesFirst = await _db.ArchivesInfo.AsNoTracking().Join(_db.BorrowRegisterDetail.AsNoTracking().Where(j => j.BorrowRegisterId == borrowRegister.Id).Take(1),
                                                                                   a => a.Id, b => b.ArchivesId, (a, b) => new { a, b })
                                        .Select(c => new
                    {
                        c.a.ProjectName
                    }).FirstOrDefaultAsync();

                    ApplicationLog.Info("SMS_171116665." + borrowRegister.Phone + "." + borrowRegister.Id);
                    var msgRes = OssHelper.SendSms("SMS_171116665", borrowRegister.Phone, $"{{\"name\":\"{borrowRegister.Borrower}\", \"PtName\":\"{(archivesFirst.ProjectName)}\", \"RDate\":\"{borrowRegister.ReturnDate.ToString("yyyy-MM-dd")}\" }}");
                }
                catch (Exception ex1)
                {
                    ApplicationLog.Error("RenewBorrow notice exception", ex1);
                }
            }
            catch (BizException ex)
            {
                response.Message = ex.Message;
            }
            catch (Exception ex)
            {
                response.Message = "提交续借发生异常";
                ApplicationLog.Error("RenewBorrow", ex);
            }
            return(response);
        }
Esempio n. 32
0
        public void GenBankParserValidateParseOneWithSpecificFormats()
        {
            InitializeXmlVariables();
            // Initialization of xml strings.
            FilePath = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.FilePathNode);
            AlphabetName = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.AlphabetNameNode);
            MolType = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.MoleculeTypeNode);
            IsSequenceReadOnly = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.IsReadOnlyNode);
            SeqId = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.SequenceIdNode);
            StrandTopology = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.StrandTopologyNode);
            StrandType = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.StrandTypeNode);
            Div = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.DivisionNode);
            Version = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.VersionNode);
            SequenceDate = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.DateNode);
            PrimaryId = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.PrimaryIdNode);
            ExpectedSequence = _utilityObj._xmlUtil.GetTextValue(
                Constants.SimpleGenBankPrimaryNode,
                Constants.ExpectedSequenceNode);

            // parse
            BasicSequenceParser parserObj = new GenBankParser();

            parserObj.Alphabet = Alphabets.Protein;
            parserObj.Encoding = NcbiEAAEncoding.Instance;
            ISequence seq = parserObj.ParseOne(FilePath);

            Assert.AreEqual(Utility.GetAlphabet(AlphabetName),
                            seq.Alphabet);
            Assert.AreEqual(Utility.GetMoleculeType(MolType),
                            seq.MoleculeType);
            Assert.AreEqual(SeqId, seq.DisplayID);
            Assert.AreEqual(SeqId, seq.ID);
            ApplicationLog.WriteLine(
                "GenBank Parser BVT: Successfully validated the Alphabet, Molecular type, Sequence ID and Display ID");

            // test the metadata that is tricky to parse, and will not be tested implicitly by
            // testing the formatting
            GenBankMetadata metadata = (GenBankMetadata)seq.Metadata["GenBank"];

            if (metadata.Locus.Strand != SequenceStrandType.None)
            {
                Assert.AreEqual(StrandType,
                                metadata.Locus.Strand.ToString());
            }
            Assert.AreEqual(StrandTopology.ToUpper(CultureInfo.CurrentCulture),
                            metadata.Locus.StrandTopology.ToString().ToUpper(
                                CultureInfo.CurrentCulture));
            Assert.AreEqual(Div, metadata.Locus.DivisionCode.ToString());
            Assert.AreEqual(DateTime.Parse(SequenceDate, null),
                            metadata.Locus.Date);
            Assert.AreEqual(Version, metadata.Version.Version.ToString((IFormatProvider)null));
            Assert.AreEqual(PrimaryId, metadata.Version.GINumber);
            ApplicationLog.WriteLine(
                "GenBank Parser BVT: Successfully validated the StrandType, StrandTopology, Division, Date, Version, PrimaryID Properties");

            // test the sequence string
            Assert.AreEqual(ExpectedSequence, seq.ToString());
            ApplicationLog.WriteLine(
                "GenBank Parser BVT: Successfully validated the Sequence");
            Console.WriteLine(string.Format((IFormatProvider)null,
                                            "GenBank Parser BVT: Successfully validated the Sequence '{0}'",
                                            ExpectedSequence));
        }
Esempio n. 33
0
        public async Task <CommonResponse <string> > ConfirmBorrowed(ConfirmBorrowedRequest request)
        {
            var response = new CommonResponse <string>();

            using (var trans = await _db.Database.BeginTransactionAsync())
            {
                try
                {
                    if (request == null)
                    {
                        throw new BizException("参数不能为空");
                    }

                    var borrowRegister = await _db.BorrowRegister.FirstOrDefaultAsync(c => c.Id == request.BorrowRegisterId && !c.Deleted);

                    if (borrowRegister == null)
                    {
                        throw new BizException("借阅登记不存在");
                    }

                    if (borrowRegister.Status == BorrowRegisterStatus.Borrowed)
                    {
                        //response.Message = "当前状态已经借出";
                        //response.ErrorCode = 1;
                        //response.Success = true;
                        //return response;
                        throw new BizException("当前借阅的状态为已借出");
                    }

                    if (borrowRegister.Status != BorrowRegisterStatus.Registered)
                    {
                        throw new BizException("借阅登记状态为:已登记 才能确认借出");
                    }

                    var archives = await _db.ArchivesInfo.Join(_db.BorrowRegisterDetail, a => a.Id, b => b.ArchivesId, (a, b) => new { a, b })
                                   .Where(j => j.b.BorrowRegisterId == borrowRegister.Id)
                                   .Select(c => c.a).ToListAsync();

                    //如果当前状态为init,将档案改为
                    archives.ForEach(c =>
                    {
                        switch (c.Status)
                        {
                        case ArchivesStatus.Init:
                        case ArchivesStatus.Normal:
                            c.Status = ArchivesStatus.Borrowed;
                            break;

                        case ArchivesStatus.Borrowed:
                            throw new BizException("您选择的档案可能已借出,无法再次借阅");

                        default:
                            throw new BizException("您选择的档案档案当前状态出错,无法确认借出");
                        }
                    });
                    borrowRegister.UpdateTime = DateTime.Now;
                    borrowRegister.Status     = BorrowRegisterStatus.Borrowed;
                    borrowRegister.UpdateTime = DateTime.Now;

                    await _db.SaveChangesAsync();

                    trans.Commit();
                    response.Success = true;
                    ApplicationLog.Info("SMS_171116670." + borrowRegister.Phone + "." + borrowRegister.Id);
                    var msgRes = OssHelper.SendSms("SMS_171116670", borrowRegister.Phone, $"{{\"name\":\"{borrowRegister.Borrower}\", \"PtName\":\"{(archives[0].ProjectName)}\", \"RDate\":\"{borrowRegister.ReturnDate.ToString("yyyy-MM-dd")}\" }}");
                }
                catch (BizException ex)
                {
                    trans.Rollback();
                    response.Message = ex.Message;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    response.Message = "提交续借发生异常";
                    ApplicationLog.Error("ConfirmBorrowed", ex);
                }
            }

            return(response);
        }
Esempio n. 34
0
        public void GenBankFormatterValidateFormatTextWriter()
        {
            InitializeXmlVariables();
            // Create a Sequence with all attributes.
            // parse and update the properties instead of parsing entire file.
            ISequenceParser   parser1  = new GenBankParser();
            IList <ISequence> seqList1 = parser1.Parse(FilePath);

            string expectedUpdatedSequence =
                ExpectedSequence.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            Sequence orgSeq =
                new Sequence(Utility.GetAlphabet(AlphabetName), expectedUpdatedSequence);

            orgSeq.Metadata.Add("GenBank",
                                (GenBankMetadata)seqList1[0].Metadata["GenBank"]);
            orgSeq.ID           = seqList1[0].ID;
            orgSeq.DisplayID    = seqList1[0].DisplayID;
            orgSeq.MoleculeType = seqList1[0].MoleculeType;

            ISequenceFormatter formatter = new GenBankFormatter();

            using (TextWriter writer =
                       new StreamWriter(Constants.GenBankTempFileName))
            {
                formatter.Format(orgSeq, writer);
            }

            // parse
            GenBankParser     parserObj = new GenBankParser();
            IList <ISequence> seqList   = parserObj.Parse(Constants.GenBankTempFileName);

            ISequence seq = seqList[0];

            // test the non-metadata properties
            if (0 == string.Compare(IsSequenceReadOnly, "true",
                                    false, CultureInfo.CurrentCulture))
            {
                Assert.IsTrue(seq.IsReadOnly);
                ApplicationLog.WriteLine(
                    "GenBank Formatter BVT: Successfully validated the ReadOnly Property");
            }

            Assert.AreEqual(Utility.GetAlphabet(AlphabetName), seq.Alphabet);
            Assert.AreEqual(Utility.GetMoleculeType(MolType), seq.MoleculeType);
            Assert.AreEqual(SeqId, seq.DisplayID);
            Assert.AreEqual(SeqId, seq.ID);
            ApplicationLog.WriteLine(
                "GenBank Formatter BVT: Successfully validated the Alphabet, Molecular type, Sequence ID and Display ID");

            // test the metadata that is tricky to parse, and will not be tested implicitly by
            // testing the formatting
            GenBankMetadata metadata = (GenBankMetadata)seq.Metadata["GenBank"];

            if (metadata.Locus.Strand != SequenceStrandType.None)
            {
                Assert.AreEqual(StrandType, metadata.Locus.Strand.ToString());
            }
            Assert.AreEqual(StrandTopology.ToUpper(CultureInfo.CurrentCulture), metadata.Locus.StrandTopology.ToString().ToUpper(CultureInfo.CurrentCulture));
            Assert.AreEqual(Div, metadata.Locus.DivisionCode.ToString());
            Assert.AreEqual(DateTime.Parse(SequenceDate, null), metadata.Locus.Date);
            Assert.AreEqual(Version, metadata.Version.Version.ToString((IFormatProvider)null));
            Assert.AreEqual(PrimaryId, metadata.Version.GINumber);
            ApplicationLog.WriteLine(
                "GenBank Formatter BVT: Successfully validated the StrandType, StrandTopology, Division, Date, Version, PrimaryID Properties");

            // test the sequence string
            Assert.AreEqual(ExpectedSequence, seq.ToString());
            ApplicationLog.WriteLine("GenBank Formatter BVT: Successfully validated the Sequence");
            Console.WriteLine(string.Format((IFormatProvider)null, "GenBank Formatter BVT: Successfully validated the Sequence '{0}'", ExpectedSequence));

            File.Delete(Constants.GenBankTempFileName);
        }