private void IncrementProgress(IProgressCallback progressCallback)
 {
     if (progressCallback != null)
     {
         progressCallback.Increment(1);
     }
 }
Exemplo n.º 2
0
    private static bool DoDownloadFileDirectly(string uri, string targetFile, IProgressCallback callback = null)
    {
      if (!File.Exists(targetFile))
      {
        var tempFile = new FileInfo(targetFile).DirectoryName + "/" + Path.GetFileName(Path.GetTempFileName());
        var webClient = new WebClient()
        {
          Proxy = null
        };

        Console.WriteLine("        " + Path.GetFileName(uri) + " ...");
        webClient.DownloadFile(new Uri(uri), tempFile);

        if (File.Exists(tempFile))
        {
          Console.WriteLine("        " + Path.GetFileName(uri) + " ... done.");
          File.Move(tempFile, targetFile);
        }
        else
        {
          Console.WriteLine("        " + Path.GetFileName(uri) + " ... failed.");
        }
      }

      return File.Exists(targetFile);
    }
Exemplo n.º 3
0
        private static bool DoDownloadFileDirectly(string uri, string targetFile, IProgressCallback callback = null)
        {
            if (!File.Exists(targetFile))
            {
                var tempFile  = new FileInfo(targetFile).DirectoryName + "/" + Path.GetFileName(Path.GetTempFileName());
                var webClient = new WebClient()
                {
                    Proxy = null
                };

                Console.WriteLine("        " + Path.GetFileName(uri) + " ...");
                webClient.DownloadFile(new Uri(uri), tempFile);

                if (File.Exists(tempFile))
                {
                    Console.WriteLine("        " + Path.GetFileName(uri) + " ... done.");
                    File.Move(tempFile, targetFile);
                }
                else
                {
                    Console.WriteLine("        " + Path.GetFileName(uri) + " ... failed.");
                }
            }

            return(File.Exists(targetFile));
        }
Exemplo n.º 4
0
    /// <summary>
    /// Fill reference allele from genome fasta file.
    /// </summary>
    /// <param name="snpItems"></param>
    /// <param name="fastaFile"></param>
    /// <param name="progress"></param>
    public static void FillReferenceAlleleFromFasta(this IEnumerable<SNPItem> snpItems, string fastaFile, IProgressCallback progress = null)
    {
      if (progress == null)
      {
        progress = new ConsoleProgressCallback();
      }

      var dic = snpItems.ToGroupDictionary(m => m.Chrom);

      progress.SetMessage("Filling reference allele from {0} file ...", fastaFile);
      using (var sw = new StreamReader(fastaFile))
      {
        var ff = new FastaFormat();
        Sequence seq;
        while ((seq = ff.ReadSequence(sw)) != null)
        {
          progress.SetMessage("chromosome " + seq.Name + " ...");
          var chr = HumanChromosomeToInt(seq.Name);
          if (dic.ContainsKey(chr))
          {
            var snps = dic[chr];
            foreach (var snp in snps)
            {
              snp.RefChar = char.ToUpper(seq.SeqString[snp.Position - 1]);
            }
          }
        }
      }
      progress.SetMessage("Filling reference allele finished.");
    }
        private void ExportConversationsAsync()
        {
            ExportedFilenameGenerator filenameGenerator = new ExportedFilenameGenerator();
            string folderName = filenameGenerator.CreateExportFolderNameSuggestion();

            string outputPath = System.IO.Path.Combine(folderPathTextBox.Text, folderName);

            BackgroundWorker backgroundWorker = new BackgroundWorker();

            _progressCallback = new ProgressCallback(backgroundWorker);

            backgroundWorker.WorkerReportsProgress      = true;
            backgroundWorker.WorkerSupportsCancellation = true;
            backgroundWorker.DoWork             += OnDoWork;
            backgroundWorker.ProgressChanged    += OnProgressChanged;
            backgroundWorker.RunWorkerCompleted += OnWorkerCompleted;

            ExportMultipleDialogModel.ExportFormat exportFormat = GetExportFormat();

            AsyncExportingProgressParams exportingParams = new AsyncExportingProgressParams(_progressCallback, _model, exportFormat, outputPath);

            SetUiToExportInProgress();

            backgroundWorker.RunWorkerAsync(exportingParams);
        }
Exemplo n.º 6
0
        /// <summary>
        /// 更新本地数据库
        /// </summary>
        /// <param name="parameters"></param>
        private static void UpdateProcess(object parameters)
        {
            object[] parameterArr = parameters as object[];// { tableName, sqlStr, index, updateRecordTable.Rows.Count };

            string            tableName       = parameterArr[0].ToString();
            string            sqlStr          = parameterArr[1].ToString();
            IProgressCallback callBack        = (IProgressCallback)parameterArr[2];
            DataTable         ServerTable     = parameterArr[3] as DataTable;
            DataTable         ServerDataCache = parameterArr[4] as DataTable;
            //从远程获取要更新的记录
            DataTable NewDataTable = GetServerDataTalbe(sqlStr);

            NewDataTable.TableName = tableName;
            //更新dataCache
            parameterArr = new object[] { tableName, NewDataTable, ServerTable, ServerDataCache };
            UpdateDataCache(parameterArr);

            lock (ProcessInfoList)
            {
                if (ProcessInfoList.ContainsKey(tableName.ToLower().Trim()))
                {
                    ProcessInfo pi = ProcessInfoList[tableName];
                    if (NewDataTable.Rows.Count <= pi.TableRowsCount)
                    {
                        pi.CompletedRowsCount     += NewDataTable.Rows.Count;
                        ProcessInfoList[tableName] = pi;
                    }
                    callBack.SetText("正在更新表:" + tableName + "……已完成" + ((int)((double)pi.CompletedRowsCount / pi.TableRowsCount * 100)).ToString() + "%");
                }
            }
            //更新进度条
            Agent_updateProcessEvent(callBack, tableName);
        }
Exemplo n.º 7
0
 private void DoSomeWork(object status)
 {
     errorList = new StringBuilder();
     errorMail = false;
     errorList.AppendLine("Email not sent to:");
     callback = status as IProgressCallback;
     try
     {
         callback.Begin(0, nbrTxtInc);
         SendContributieIncassoAankondiging();
         SendInschrijfIncassoAankondiging();
         callback.WaitOK();
     }
     catch (System.Threading.ThreadAbortException)
     {
         // We want to exit gracefully here (if we're lucky)
     }
     catch (System.Threading.ThreadInterruptedException)
     {
         // And here, if we can
     }
     catch (Exception ex)
     {
         GuiRoutines.ExceptionMessageBox(this, ex);
     }
     finally
     {
         if (callback != null)
         {
             callback.End();
         }
     }
 }
Exemplo n.º 8
0
		public ConditionProcessor(PolicyEngineCache policyEngineCache, IProgressCallback callback)
		{
			if (null == policyEngineCache)
				throw new Exceptions.ArgumentNullException("policyEngineCache", "Invalid policy engine cache");

			m_policyEngineCache = policyEngineCache;
			m_progressCallback = callback;
		}
Exemplo n.º 9
0
 public void Load(IProgressCallback progress)
 {
     for (int i = 0; i < 50; i++)
     {
         System.Threading.Thread.Sleep(10);
         progress.ProgressUpdated(i / 50.0f);
     }
 }
		protected override EnforceResponse CallEnforcer(IProgressCallback callback)
		{
			EnforceResponse er = new EnforceResponse();
			er.Properties = new CustomProperty[] { 
				new CustomProperty("Error.Test", "This is a fake error to test the enforce error handling."),
				new CustomProperty("Error.Test", "Exception in fake enforce handler"),
				new CustomProperty("Error.Test", "Block") };
			return er;
		} 
Exemplo n.º 11
0
		protected override IContentEnforcer GetContentEnforcer(IProgressCallback eventSink)
		{
			if (null == m_factory)
			{
				m_factory = new PolicyEngineFactory();
			}

			return m_factory.CreateContentEnforcer(eventSink);
		}
        public void Submit(VoiceProfileViewModel viewModel, IProgressCallback progressCallback)
        {
            this.progressCallback = progressCallback;
            this.progressCallback.SetText("Initialize");
            this.InitializeKeepAliveService(viewModel);
            this.InitializeTerminalClient(viewModel);

            this.pingService.Send();
            this.telnet.Send(viewModel);
        }
        public AsyncExportingProgressParams(IProgressCallback progressCallback, ExportMultipleDialogModel model, ExportMultipleDialogModel.ExportFormat exportFormat, string exportPath)
        {
            ProgressCallback = progressCallback;

            Model = model;

            ExportFormat = exportFormat;

            ExportPath = exportPath;
        }
        public AsyncExportingProgressParams(IProgressCallback progressCallback, ExportMultipleDialogModel model, ExportMultipleDialogModel.ExportFormat exportFormat, string exportPath)
        {
            ProgressCallback = progressCallback;

            Model = model;

            ExportFormat = exportFormat;

            ExportPath = exportPath;
        }
Exemplo n.º 15
0
		public PolicyEngineCache(IPolicyCache policyCache, IProgressCallback callback)
		{
			if (null == policyCache)
				throw new Workshare.Policy.Exceptions.ArgumentNullException("policyCache", "Invalid policy cache");

			m_policyCache = policyCache;
			m_progressCallback = callback;

			m_policyEngines = new Dictionary<string, Dictionary<string, PolicyEngine>>();
		}
    public IIdentifiedProteinGroupFilter GetNotContaminationDescriptionFilter(IProgressCallback progress)
    {
      var result = GetContaminationDescriptionFilter(progress);

      if (result != null)
      {
        return new IdentifiedProteinGroupNotFilter(result);
      }

      return null;
    }
        private void BuildAnalyses(object status)
        {
            try
            {
                IProgressCallback callback = status as IProgressCallback;
                callback.SetRange(0, CheckedIndices.Count - 1);
                callback.Begin();

                int           expectedCount = uCtrlNumberPerCase.Value.Activated ? uCtrlNumberPerCase.Value.Value : -1;
                PackableBrick packable      = cbBoxes.SelectedType as PackableBrick;

                // build list of analyses
                for (int i = 0; i < CheckedIndices.Count; ++i)
                {
                    try
                    {
                        if (callback.IsAborting)
                        {
                            break;
                        }
                        callback.StepTo(i);
                        callback.SetText(string.Format(Resources.ID_EVALUATINGCASE, i + 1, CheckedIndices.Count));

                        if ((chklbCases.Items[CheckedIndices[i]] as ItemBaseCB).Item is BoxProperties caseProperties)
                        {
                            // build constraint set
                            ConstraintSetBoxCase constraintSet = new ConstraintSetBoxCase(caseProperties);
                            constraintSet.SetAllowedOrientations(uCtrlCaseOrient.AllowedOrientations);
                            if (uCtrlNumberPerCase.Value.Activated)
                            {
                                constraintSet.SetMaxNumber(uCtrlNumberPerCase.Value.Value);
                            }
                            // build solver + get analyses
                            SolverBoxCase solver       = new SolverBoxCase(packable, caseProperties);
                            var           listAnalyses = solver.BuildAnalyses(constraintSet, false);
                            foreach (var analysis in listAnalyses)
                            {
                                if ((-1 == expectedCount) || (expectedCount == analysis.Solution.ItemCount))
                                {
                                    Analyses.Add(analysis);
                                }
                            }
                        }
                    }
                    catch (Exception) {}
                }
                callback.SetText(Resources.ID_SORTINGSOLUTIONS);
                // sort analysis
                Analyses.Sort(new AnalysisComparer());
                callback.End();
            }
            catch (Exception) {}
        }
        public CompositeProcessor <PeakList <Peak> > GetProcessor(string fileName, IProgressCallback callBack)
        {
            CompositeProcessor <PeakList <Peak> > result = new CompositeProcessor <PeakList <Peak> >();

            if (!this.OutputMzXmlFormat)
            {
                AddGeneralProcessor(result);
            }

            if (RemoveIons)
            {
                if (RemoveIsobaricIons)
                {
                    result.Add(GetIsobaricProcessor());
                }

                if (RemoveSpecialIons)
                {
                    var ranges = ParseRemoveMassRange();
                    foreach (var range in ranges)
                    {
                        result.Add(new PeakListRemoveMassRangeProcessor <Peak>(range.From, range.To));
                    }
                }
            }

            if (Deisotopic)
            {
                result.Add(new PeakListDeisotopicByChargeProcessor <Peak>(ProductIonPPM));
            }

            if (PrecursorOptions.RemovePrecursor)
            {
                result.Add(new PeakListRemovePrecursorProcessor <Peak>(this.PrecursorOptions));
            }

            if (ChargeDeconvolution)
            {
                result.Add(new PeakListDeconvolutionByChargeProcessor <Peak>(ProductIonPPM));
                if (Deisotopic)
                {
                    result.Add(new PeakListDeisotopicByChargeProcessor <Peak>(ProductIonPPM));
                }
            }

            if (KeepTopX)
            {
                result.Add(new PeakListTopXProcessor <Peak>(TopX));
            }

            return(result);
        }
        private void CheckForCancel(IProgressCallback progressCallback)
        {
            if (progressCallback == null)
            {
                return;
            }

            if (progressCallback.IsCancelRequested)
            {
                progressCallback.AcceptCancel();
                throw new OperationCanceledException();
            }
        }
        /// <summary>
        /// Thread start. Use in a ThreadStart. No internal checking is done to 
        /// make sure that the model doesn't change during processing so this
        /// must be ensured by the calling code.
        /// </summary>
        /// <param name="status">The IProgressCallback implementation that allows
        /// for progress to be tracked in a gui.</param>
        public void Start(object status)
        {
            mCallback = status as IProgressCallback;

              try
              {
            FFMPEGToVideo();
              }
              finally
              {
            mCallback.End();
              }
        }
Exemplo n.º 21
0
        public static void SlimDocument(XmlDocument xml, IProgressCallback progress)
        {
            var xmlHelper = new XmlHelper(xml);

            List <XmlNode> proteins = xmlHelper.GetChildren(xml.DocumentElement, "protein");

            progress.SetRange(0, proteins.Count);
            int index = 0;

            var reg = new Regex(@"(\S{8,})");

            foreach (XmlNode protein in proteins)
            {
                progress.SetPosition(index++);

                List <XmlNode> peptides = xmlHelper.GetChildren(protein, "peptide");
                foreach (XmlNode peptide in peptides)
                {
                    XmlNode chro = xmlHelper.GetValidChild(peptide, "chro");

                    string   oldValue = chro.InnerText;
                    string[] parts    = oldValue.Split(new[] { ';' });
                    for (int i = 0; i < parts.Length; i++)
                    {
                        parts[i] = reg.Replace(parts[i], new MatchEvaluator(FormatString));
                    }
                    string newValue = StringUtils.Merge(parts, ";");

                    if (oldValue.Equals(newValue)) //不需要进行slim
                    {
                        return;
                    }

                    double lightMass, heavyMass;
                    if (peptide.Attributes["lightMass"] != null)
                    {
                        lightMass = MyConvert.ToDouble(peptide.Attributes["lightMass"].Value);
                        heavyMass = MyConvert.ToDouble(peptide.Attributes["heavyMass"].Value);
                        peptide.Attributes["lightMass"].Value = MyConvert.Format("{0:0.0000}", lightMass);
                        peptide.Attributes["heavyMass"].Value = MyConvert.Format("{0:0.0000}", heavyMass);
                    }
                    else if (peptide.Attributes["lightStartMass"] != null)
                    {
                        lightMass = MyConvert.ToDouble(peptide.Attributes["lightStartMass"].Value);
                        heavyMass = MyConvert.ToDouble(peptide.Attributes["heavyStartMass"].Value);
                        peptide.Attributes["lightStartMass"].Value = MyConvert.Format("{0:0.0000}", lightMass);
                        peptide.Attributes["heavyStartMass"].Value = MyConvert.Format("{0:0.0000}", heavyMass);
                    }
                }
            }
        }
Exemplo n.º 22
0
 public void Output(DEResFolder curResFolder)
 {
     if (curResFolder != null)
     {
         this.curFolder = curResFolder;
         this.InitResInfo();
         this.TotalNum = this.GetResDataCount();
         if (this.TotalNum == 0)
         {
             MessageBoxPLM.Show("资源的记录数为零,不能导出", "资源数据导出", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
         }
         else
         {
             this.TotalPage = ((this.TotalNum % this.showNum) == 0) ? (this.TotalNum / this.showNum) : ((this.TotalNum / this.showNum) + 1);
             this.attrShow  = new PLReference().GetDefAttrLst(this.curFolder.Oid, emTreeType.NodeTree);
             foreach (DEDefAttr attr in this.attrShow)
             {
                 if (!attr.ISVISUAL)
                 {
                     for (int i = this.attrList.Count - 1; i >= 0; i--)
                     {
                         DEMetaAttribute attribute = this.attrList[i] as DEMetaAttribute;
                         if (attribute.Oid == attr.ATTROID)
                         {
                             this.attrList.RemoveAt(i);
                         }
                     }
                 }
             }
             FrmOutputOption option = new FrmOutputOption(this.TotalPage, this.attrList);
             if (option.ShowDialog() == DialogResult.OK)
             {
                 SaveFileDialog dialog;
                 this.StartNum       = option.StartPage;
                 this.EndNum         = option.EndPage;
                 this.IsMultiPageOut = option.IsMultiPage;
                 if (this.saveFile(out dialog))
                 {
                     IProgressCallback progressWindow = ClientData.GetProgressWindow();
                     ArrayList         state          = new ArrayList {
                         progressWindow,
                         dialog.FileName
                     };
                     ThreadPool.QueueUserWorkItem(new WaitCallback(this.outPageExcel), state);
                     progressWindow.ShowWindow();
                 }
             }
         }
     }
 }
Exemplo n.º 23
0
        /// <summary>
        /// 精确控制进度条
        /// </summary>
        /// <param name="callBack"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        private static float ProgressGo(IProgressCallback callBack, float step)
        {
            float newStep = 0;

            if (step < 99)
            {
                newStep = step + 1;
            }
            else
            {
                newStep = step;
            }
            callBack.StepTo((Int32)newStep);
            return(newStep);
        }
Exemplo n.º 24
0
        private static Int32 ProgressGo(IProgressCallback callBack, Int32 step)
        {
            Int32 newStep = 0;

            if (step <= 99)
            {
                newStep = step + 1;
            }
            else
            {
                newStep = step;
            }
            callBack.StepTo(newStep);
            return(newStep);
        }
 protected override EnforceResponse CallEnforcer(IProgressCallback callback)
 {
     EnforceResponse er = new EnforceResponse();
     if (!m_aborted)
     {
         er.Properties = new CustomProperty[] { new CustomProperty("ABORT", "true") };
         m_aborted = true;
         AbortHit = true;
     }
     else
     {
         er.Properties = new CustomProperty[] { new CustomProperty("SUCCESS", "true") };
     }
     return er;
 }
 public MultipleRaw2OneMgfThreadProcessor(DirectoryInfo rawDir, FileInfo saveToFile,
                                          IRawFile2 rawFile, IPeakListWriter <Peak> writer,
                                          double retentionTimeTolerance, double ppmPrecursorTolerance,
                                          double ppmPeakTolerance, IProcessor <PeakList <Peak> > pklProcessor,
                                          IProgressCallback eachProcessorProgress)
 {
     this.rawDir                 = rawDir;
     this.saveToFile             = saveToFile;
     this.rawFile                = rawFile;
     this.writer                 = writer;
     this.retentionTimeTolerance = retentionTimeTolerance;
     this.ppmPrecursorTolerance  = ppmPrecursorTolerance;
     this.ppmPeakTolerance       = ppmPeakTolerance;
     this.pklProcessor           = pklProcessor;
     this.eachProcessorProgress  = eachProcessorProgress;
 }
        public ExportMultipleDialogView(IConversationManager conversationManager, IDisplayOptionsReadOnly displayOptions)
        {
            InitializeComponent();

            IFileSystem exportFileSystem = new OsFileSystem();

            ExportErrorFormatter exportErrorFormatter = new ExportErrorFormatter();

            _model = new ExportMultipleDialogModel(conversationManager, displayOptions, exportFileSystem, exportErrorFormatter);
            _progressCallback = null;

            Loaded += delegate
            {
                folderPathTextBox.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            };
        }
Exemplo n.º 28
0
        /// <summary>
        /// The send data.
        /// </summary>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public string SendData(IList<TravelRoute> data, IProgressCallback callback)
        {
            if (data == null || data.Count < 1)
            {
                return null;
            }

            var newPkg = new DataPackage<TravelRoute>(data);
            var pkgSyncer = this.DataSynchronizer as IPackageSyncer<TravelRoute>;
            if (pkgSyncer != null)
            {
                pkgSyncer.Send(newPkg, callback);
            }

            return newPkg.Id;
        }
        public ExportMultipleDialogView(IConversationManager conversationManager, IDisplayOptionsReadOnly displayOptions)
        {
            InitializeComponent();

            IFileSystem exportFileSystem = new OsFileSystem();

            ExportErrorFormatter exportErrorFormatter = new ExportErrorFormatter();

            _model            = new ExportMultipleDialogModel(conversationManager, displayOptions, exportFileSystem, exportErrorFormatter);
            _progressCallback = null;

            Loaded += delegate
            {
                folderPathTextBox.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            };
        }
        public void ExportConversations(ExportFormat exportFormat, string exportPath, IProgressCallback progressCallback)
        {
            IConversationExporter conversationExporter;
            switch (exportFormat)
            {
                case ExportFormat.Html:
                    conversationExporter = new ConversationExporterHtml(_exportFileSystem);
                    break;
                case ExportFormat.Plaintext:
                    conversationExporter = new ConversationExporterPlaintext(_exportFileSystem);
                    break;
                default:
                    throw new ArgumentException("Unrecognized export format.");
            }

            _exportErrors = conversationExporter.ExportMultipleConversations(_conversationManager, _displayOptions, exportPath, progressCallback);
        }
    public IIdentifiedProteinGroupFilter GetContaminationDescriptionFilter(IProgressCallback progress)
    {
      if (HasContaminationDescriptionFilter())
      {
        if (_contaminationGroupFilter == null)
        {
          var acParser = GetAccessNumberParser();

          var map = IdentifiedResultUtils.GetContaminationAccessNumbers(acParser, Location, ContaminationDescriptionPattern, progress);

          _contaminationGroupFilter = new IdentifiedProteinGroupContaminationMapFilter(acParser, map);
        }
        return _contaminationGroupFilter;
      }

      return null;
    }
Exemplo n.º 32
0
        /// <summary>
        /// The receive packages.
        /// </summary>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>
        /// The <see cref="int"/>.
        /// </returns>
        public int ReceivePackages(IProgressCallback callback)
        {
            var pkgSyncer = this.DataSynchronizer as IPackageSyncer<TravelRoute>;
            int newPackageCount = 0;

            if (pkgSyncer != null)
            {
                var importedPkg = this.GetImportedPackages(callback);
                var newData = pkgSyncer.Receive(importedPkg, callback);
                if (newData != null && newData.Count > 0)
                {
                    this.AddData(newData, callback);
                    newPackageCount = newData.Count;
                }
            }

            return newPackageCount;
        }
Exemplo n.º 33
0
        public static HashSet <string> GetContaminationAccessNumbers(IStringParser <string> acParser, string fastaFilename, string contaminationDescriptionPattern,
                                                                     IProgressCallback progress)
        {
            HashSet <string> result = new HashSet <string>();

            if (progress == null)
            {
                progress = new EmptyProgressCallback();
            }

            Regex reg = new Regex(contaminationDescriptionPattern, RegexOptions.IgnoreCase);

            progress.SetMessage("Get contamination map from database ...");
            var ff = new FastaFormat();

            using (var sr = new StreamReader(fastaFilename))
            {
                progress.SetRange(1, sr.BaseStream.Length);

                Sequence seq;
                while ((seq = ff.ReadSequence(sr)) != null)
                {
                    if (progress.IsCancellationPending())
                    {
                        throw new UserTerminatedException();
                    }

                    progress.SetPosition(sr.GetCharpos());

                    string ac = acParser.GetValue(seq.Name);

                    if (reg.Match(seq.Reference).Success)
                    {
                        result.Add(ac);
                    }
                }
            }

            progress.SetMessage("Get contamination map from database finished.");

            return(result);
        }
 private void OnWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     _progressCallback = null;
     if (e.Cancelled)
     {
         SetUiToExportFailed("Export canceled.");
     }
     else if (e.Error != null)
     {
         SetUiToExportFailed(e.Error.Message);
     }
     else if (!_model.ExportSucceeded)
     {
         SetUiToExportFailed(_model.ErrorMessage);
     }
     else
     {
         SetUiToExportSucceeded();
     }
 }
Exemplo n.º 35
0
        private void outPageExcel(object objs)
        {
            ArrayList         list        = (ArrayList)objs;
            IProgressCallback callback    = list[0] as IProgressCallback;
            string            strFileName = list[1] as string;

            try
            {
                callback.Begin(0, 100);
                callback.SetText("正在生成{'资源'}的导出文件……");
                this.DoOutFile(strFileName);
            }
            catch (Exception exception)
            {
                PrintException.Print(exception);
            }
            finally
            {
                callback.End();
            }
        }
Exemplo n.º 36
0
 /// <summary>
 /// 更新完成后,表总表记录进行更新
 ///
 /// </summary>
 /// <param name="callBack"></param>
 /// <param name="TalbeID"></param>
 /// <param name="tableName"></param>
 /// <param name="CompleteRowsCount"></param>
 private static void Agent_updateProcessEvent(IProgressCallback callBack, string tableName)
 {
     try
     {
         int totalRowsCount         = 0;
         int totalCompleteRowsCount = 0;
         lock (ProcessInfoList)
         {
             foreach (string key in ProcessInfoList.Keys)
             {
                 totalCompleteRowsCount += ProcessInfoList[key].CompletedRowsCount;
                 totalRowsCount         += ProcessInfoList[key].TableRowsCount;
             }
         }
         double completeRate = (double)totalCompleteRowsCount / totalRowsCount;
         ProgressGo(callBack, (Int32)(completeRate * 100));
     }
     catch (Exception e)
     {
         logger.Error(e.Message);
     }
 }
        public List<ExportError> ExportMultipleConversations(IEnumerable<IConversation> conversations, IDisplayOptionsReadOnly displayOptions, string exportPath, IProgressCallback progressCallback)
        {
            List<ExportError> exportErrors = new List<ExportError>();
            string createdFolderPath = FileCreator.CreateNewDirectoryWithRenameAttempts(exportPath, _exportFileSystem, MaxRenameAttempts);

            ExportedFilenameGenerator filenameGenerator = new ExportedFilenameGenerator();

            foreach (IConversation conversation in conversations)
            {
                CheckForCancel(progressCallback);

                //
                // Don't export empty conversations
                //

                if (conversation.MessageCount == 0)
                {
                    IncrementProgress(progressCallback);
                    continue;
                }

                try
                {
                    string filename = filenameGenerator.CreateExportFilenameSuggestion(conversation) + "." + GetExportFileExtension();
                    string exportFilename = Path.Combine(createdFolderPath, filename);

                    List<ExportError> currentErrors = Export(conversation, displayOptions, exportFilename);
                    exportErrors.AddRange(currentErrors);
                }
                catch (Exception ex)
                {
                    exportErrors.Add(new ExportError(conversation, ex));
                }

                IncrementProgress(progressCallback);
            }

            return exportErrors;
        }
        private static void OnDoWork(object sender, DoWorkEventArgs e)
        {
            AsyncExportingProgressParams exportingParams = (AsyncExportingProgressParams)e.Argument;

            ExportMultipleDialogModel model = exportingParams.Model;

            ExportMultipleDialogModel.ExportFormat exportFormat = exportingParams.ExportFormat;
            string            exportPath       = exportingParams.ExportPath;
            IProgressCallback progressCallback = exportingParams.ProgressCallback;

            try
            {
                progressCallback.Begin(model.ConversationCount);

                model.ExportConversations(exportFormat, exportPath, progressCallback);

                progressCallback.End();
            }
            catch (OperationCanceledException)
            {
                e.Cancel = true;
            }
        }
Exemplo n.º 39
0
		protected override EnforceResponse CallEnforcer(IProgressCallback callback)
		{
			// Uncomment to generate new resources...
			//Workshare.PolicyContent.EnforceResponse enforceResponse = base.CallEnforcer(callback);

			string resourceName = string.Format("Workshare.Policy.ClientManager.Tests.Resources.{0}.enforceresponse", m_methodBase.Name);
			Stream stream = GetType().Assembly.GetManifestResourceStream(resourceName);
			XmlSerializer serializer = new XmlSerializer(typeof(EnforceResponse));
			EnforceResponse enforceResponse = (EnforceResponse) serializer.Deserialize(stream);

            foreach (var attachment in enforceResponse.ModifiedRequest.Attachments)
            {
                string tempFile = m_lcofm.GetLocalCopyOfFileTarget(attachment.Name);
                File.WriteAllBytes(tempFile, attachment.Content);
                attachment.FileName = tempFile;
                attachment.File = new FCS.Lite.Interface.File(tempFile, attachment.Name);
            }

			//Stream stream = File.Open(string.Format("{0}.enforceresponse", m_methodBase.Name), FileMode.Create);
			//serializer.Serialize(stream, enforceResponse);
			
			return enforceResponse;
		}
Exemplo n.º 40
0
 public void Downloader(object status)
 {
     try
     {
         IProgressCallback callback = status as IProgressCallback;
         callback.Begin(0, requiredDependancies.Count);
         WebClient web = new WebClient();
         for (int i = 0; i < requiredDependancies.Count; i++)
         {
             if (!File.Exists("Mods/" + requiredDependancies[i]))
             {
                 MelonLogger.Log("Downloading " + requiredDependancies[i]);
                 web.DownloadFileTaskAsync("https://raw.githubusercontent.com/KosmicShovel/BTD6-Mods/master/BTD6.py/DLL/" + requiredDependancies[i], "Mods/" + requiredDependancies[i]).GetAwaiter().GetResult();
                 MelonLogger.Log("Downloaded " + requiredDependancies[i] + "!");
                 Console.WriteLine("");
             }
             callback.StepTo(i);
         }
         callback.End();
         MelonLogger.Log("THE WIZARD WILL NOW RESTART SO YOU CAN USE THE SCRIPT MODS!");
     }
     catch (System.FormatException) {}
 }
        private void ProcessDatasetFromSameEngine(IProgressCallback progress, Action <List <IIdentifiedSpectrum>, IScoreFunction> process, bool hasDuplicatedSpectrum)
        {
            Func <Dataset, Dataset, bool> preFunc = (m1, m2) => m1.Options.SearchEngine == m2.Options.SearchEngine;

            var overlaps = FindOverlap(preFunc);

            if (overlaps.Count > 0)
            {
                progress.SetMessage("Filtering spectra from same engine but different search parameters ...");

                foreach (var dsList in overlaps)
                {
                    var spectra = dsList.GetSpectra();

                    Console.Write(spectra.Count);

                    process(spectra, dsList.First().Options.ScoreFunction);

                    Console.WriteLine(" -> {0}", spectra.Count);

                    ResetClassificationTag(dsList, spectra);

                    dsList[0].Spectra = spectra;
                    dsList[0].HasDuplicatedSpectrum = hasDuplicatedSpectrum;

                    //删除其余dataset。
                    for (int i = 1; i < dsList.Count; i++)
                    {
                        this.Remove(dsList[i]);
                    }


                    //new MascotPeptideTextFormat().WriteToFile(@"U:\sqh\hppp\orbitrap\summary\overlap\new.merged.peptides", spectra);
                }
                progress.SetMessage("Filtering spectra from same engine but different search parameters finished.");
            }
        }
Exemplo n.º 42
0
    private static bool DoDownloadFileAsync(string uri, string targetFile, IProgressCallback callback = null)
    {
      if (!File.Exists(targetFile))
      {
        var tempFile = new FileInfo(targetFile).DirectoryName + "/" + Path.GetFileName(Path.GetTempFileName());
        var webClient = new WebClient()
        {
          Proxy = null,
        };

        Console.WriteLine("        " + Path.GetFileName(uri) + " ...");
        webClient.DownloadFileAsync(new Uri(uri), tempFile);

        while(webClient.IsBusy)
        {
          if (callback != null && callback.IsCancellationPending())
          {
            webClient.CancelAsync();
            return false;
          }
          Thread.Sleep(100);
        }

        if (File.Exists(tempFile))
        {
          Console.WriteLine("        " + Path.GetFileName(uri) + " ... done.");
          File.Move(tempFile, targetFile);
        }
        else
        {
          Console.WriteLine("        " + Path.GetFileName(uri) + " ... failed.");
        }
      }

      return File.Exists(targetFile);
    }
Exemplo n.º 43
0
        private static bool DoDownloadFileAsync(string uri, string targetFile, IProgressCallback callback = null)
        {
            if (!File.Exists(targetFile))
            {
                var tempFile  = new FileInfo(targetFile).DirectoryName + "/" + Path.GetFileName(Path.GetTempFileName());
                var webClient = new WebClient()
                {
                    Proxy = null,
                };

                Console.WriteLine("        " + Path.GetFileName(uri) + " ...");
                webClient.DownloadFileAsync(new Uri(uri), tempFile);

                while (webClient.IsBusy)
                {
                    if (callback != null && callback.IsCancellationPending())
                    {
                        webClient.CancelAsync();
                        return(false);
                    }
                    Thread.Sleep(100);
                }

                if (File.Exists(tempFile))
                {
                    Console.WriteLine("        " + Path.GetFileName(uri) + " ... done.");
                    File.Move(tempFile, targetFile);
                }
                else
                {
                    Console.WriteLine("        " + Path.GetFileName(uri) + " ... failed.");
                }
            }

            return(File.Exists(targetFile));
        }
 public CCreatorStylesheet( CGedcom gedcom, IProgressCallback progress, string sW3cfile, string sCssFilename, string sBackgroundImageFilename )
     : base(gedcom, progress, sW3cfile)
 {
     m_sCssFilename = sCssFilename;
       m_sBackgroundImageFilename = sBackgroundImageFilename;
 }
Exemplo n.º 45
0
        /// <summary>
        /// The reset data.
        /// </summary>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        public void ResetData(IList<TravelRoute> data, IProgressCallback callback)
        {
            if (data == null || data.Count < 1)
            {
                return;
            }

            ProgressDialog.ExecuteTask(
                null,
                "Reset Database",
                "Please wait...",
                "SQLiteDbReset",
                ProgressBarStyle.Marquee,
                this.Logger,
                cb =>
                {
                    cb.Begin();
                    this.Logger.Info("Clear database");
                    this.Reset(cb);
                    this.AddData(data, cb);
                });
        }
Exemplo n.º 46
0
        /// <summary>
        /// Fill dbsnp information. The name of SNPItem will be replaced by dbSNP name and the mapping between dbSNP name and old SNPItem name will be returned.
        /// </summary>
        /// <param name="snpItems"></param>
        /// <param name="dbSnpVcfFile"></param>
        /// <param name="progress"></param>
        /// <returns></returns>
        public static Dictionary <string, string> FillDbsnpIdByPosition(this IEnumerable <SNPItem> snpItems, string dbSnpVcfFile, IProgressCallback progress = null)
        {
            var sourceDbsnpMap = snpItems.ToDictionary(m => m.Name, m => m.Name);

            if (progress == null)
            {
                progress = new  EmptyProgressCallback();
            }

            var dic = snpItems.ToDoubleDictionary(m => m.Chrom, m => m.Position);

            progress.SetMessage("Filling dbSNP id from {0} ...", dbSnpVcfFile);
            using (var sr = new StreamReader(dbSnpVcfFile))
            {
                progress.SetRange(0, sr.BaseStream.Length);

                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (!line.StartsWith("##"))
                    {
                        break;
                    }
                }

                int linecount = 0;
                Dictionary <int, SNPItem> chrMap = null;
                int lastChr = -1;
                while (line != null)
                {
                    linecount++;

                    if (linecount % 10000 == 0)
                    {
                        progress.SetPosition(sr.GetCharpos());
                    }

                    try
                    {
                        //make sure it is SNV
                        if (!line.Contains("VC=SNV"))
                        {
                            continue;
                        }

                        //Even it marked as SNV, it still could be insertion/deletion
                        //2       179658175       rs11537855      C       CC,CT   .       .       RS=11537855;RSPOS=179658175;dbSNPBuildID=120;SSR=0;SAO=0;VP=0x050100001205000002000110;GENEINFO=TTN:7273;WGT=1;VC=SNV;SLO;NSF;REF;ASP;OTHERKG;NOC
                        var parts = line.Split('\t');
                        if (parts[3].Split(',').Any(l => l.Length != 1))
                        {
                            continue;
                        }

                        if (parts[4].Split(',').Any(l => l.Length != 1))
                        {
                            continue;
                        }

                        var chr      = HumanChromosomeToInt(parts[0]);
                        var position = int.Parse(parts[1]);

                        if (lastChr != chr)
                        {
                            if (!dic.TryGetValue(chr, out chrMap))
                            {
                                continue;
                            }
                            lastChr = chr;
                        }

                        SNPItem source;
                        if (!chrMap.TryGetValue(position, out source))
                        {
                            continue;
                        }

                        if (!source.Name.Equals(parts[2]))
                        {
                            sourceDbsnpMap.Remove(source.Name);
                            sourceDbsnpMap[source.Name] = parts[2];
                        }

                        source.DbsnpRefAllele  = parts[3][0];
                        source.DbsnpAltAllele  = parts[4][0];
                        source.DbsnpIsReversed = parts[7].Contains(";RV;");
                    }
                    finally
                    {
                        line = sr.ReadLine();
                    }
                }
            }

            var snpMap = snpItems.ToDictionary(m => m.Name);
            var result = new Dictionary <string, string>();

            foreach (var r in sourceDbsnpMap)
            {
                result[r.Value] = r.Key;
                if (!r.Key.Equals(r.Value))
                {
                    snpMap[r.Key].Name = r.Value;
                }
            }

            progress.SetMessage("Filling dbSNP id finished.");
            return(result);
        }
Exemplo n.º 47
0
 public static void FindAllele2FrequencyFrom1000GomeByName(this IEnumerable <SNPItem> snpItems, string g1000VcfFile, IProgressCallback progress = null)
 {
     DoFillAllele2FrequencyFrom1000Gome(snpItems, g1000VcfFile, m => m.Name, progress);
 }
Exemplo n.º 48
0
		protected virtual EnforceResponse CallEnforcer(IProgressCallback callback)
		{
			try
			{
				return m_factory.CreateContentEnforcer(callback).Enforce(m_request, m_response);
			}
			catch (Exception ex)
			{
				return HandleException(ex, m_request, "Prompt");
			}
		}
Exemplo n.º 49
0
		protected virtual EnforceResponse CallEnforcerForPreview(IProgressCallback callback, Request request, Response response)
		{
			return m_factory.CreateContentEnforcer(callback).Enforce(request, response);
		}
Exemplo n.º 50
0
		private void InitializeEngine()
		{
			m_contentScannerEvents = null;

			if (null == m_factory)
			{
				m_factory = new PolicyContent.PolicyEngineFactory();
			}

            if (!m_bProfilesLoaded)
            {
                LoadDefaultProfile();
                m_bProfilesLoaded = true;
            }
        }
Exemplo n.º 51
0
        /// <summary>
        /// The load data.
        /// </summary>
        /// <param name="journeys">
        /// The journeys.
        /// </param>
        /// <param name="loadHistory">
        /// The load history.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        public void LoadData(IList<Journey> journeys, bool loadHistory, IProgressCallback callback)
        {
            this.Logger.DebugFormat("Load data for {0} journeys [{1}]", journeys.Count, loadHistory ? "H" : null);
            foreach (var j in journeys)
            {
                j.Data.Clear();
            }

            string condition = GenerateCondition(journeys);
            using (var connection = new SQLiteConnection(this._connectionString))
            {
                string selectSql = "SELECT LID, LJOURNEYID, SCURRENCY, BFLIGHT, " + (loadHistory ? "TUPDATE" : "MAX(TUPDATE) TUPDATE")
                                   + " FROM JOURNEY_DATA " + " WHERE " + condition + (loadHistory ? string.Empty : " GROUP BY (LJOURNEYID)");

                using (var getFlightsCmd = new SQLiteCommand(selectSql, connection))
                {
                    connection.Open();

                    using (var reader = getFlightsCmd.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            if (reader.HasRows)
                            {
                                int iId = reader.GetOrdinal("LID");
                                int iJourneyId = reader.GetOrdinal("LJOURNEYID");
                                int iCurrency = reader.GetOrdinal("SCURRENCY");
                                int iUpdate = reader.GetOrdinal("TUPDATE");
                                int iFlight = reader.GetOrdinal("BFLIGHT");

                                while (reader.Read())
                                {
                                    var flights = this._formatter.FromRaw<List<Flight>>((byte[])reader[iFlight]);
                                    if (flights != null && flights.Count > 0)
                                    {
                                        long dataId = reader.GetInt64(iId);
                                        long journeyId = reader.GetInt64(iJourneyId);
                                        string currency = reader.GetString(iCurrency);
                                        string dataDateStr = reader.GetString(iUpdate);
                                        DateTime dataDate = DateTime.ParseExact(
                                            dataDateStr,
                                            DATETIME_FORMAT,
                                            CultureInfo.InvariantCulture,
                                            DateTimeStyles.AssumeUniversal);

                                        var newData = new JourneyData(dataId, currency, dataDate);
                                        newData.AddFlights(flights);

                                        foreach (var j in journeys)
                                        {
                                            if (j.Id == journeyId)
                                            {
                                                j.AddData(newData);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 52
0
 /// <summary>
 /// The load data.
 /// </summary>
 /// <param name="journey">
 /// The journey.
 /// </param>
 /// <param name="loadHistory">
 /// The load history.
 /// </param>
 /// <param name="callback">
 /// The callback.
 /// </param>
 public void LoadData(Journey journey, bool loadHistory, IProgressCallback callback)
 {
     this.LoadData(new List<Journey> { journey }, loadHistory, callback);
 }
Exemplo n.º 53
0
        /// <summary>
        /// The validate database.
        /// </summary>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <returns>
        /// The <see cref="ValidateResult"/>.
        /// </returns>
        public ValidateResult ValidateDatabase(IProgressCallback callback)
        {
            this.Logger.Info("Validate database");
            string error = null;

            using (var connection = new SQLiteConnection(this._connectionString))
            {
                error = string.Empty;
                using (
                    var getFlightCmd = new SQLiteCommand(@"SELECT COUNT(*) FROM FLIGHT WHERE LJOURNEYID NOT IN (SELECT LID FROM JOURNEY)", connection)
                    )
                {
                    connection.Open();
                    object result = getFlightCmd.ExecuteScalar();

                    long orphanCount;
                    if (result == null || result is DBNull)
                    {
                        orphanCount = 0;
                    }
                    else
                    {
                        orphanCount = (long)result;
                    }

                    if (orphanCount > 0)
                    {
                        error = string.Format("There are {0} orphan flights without any assosiated journey detail", orphanCount);
                    }
                }
            }

            var valResult = new ValidateResult(error == null, error);
            return valResult;
        }
 // Constructor
 public CCreatorRecordSource( CGedcom gedcom, IProgressCallback progress, string w3cfile, CSourceRecord sr )
     : base(gedcom, progress, w3cfile)
 {
     m_sr = sr;
 }
Exemplo n.º 55
0
 public static void FindAllele2FrequencyFrom1000GomeByLocus(this IEnumerable <SNPItem> snpItems, string g1000VcfFile, IProgressCallback progress = null)
 {
     DoFillAllele2FrequencyFrom1000Gome(snpItems, g1000VcfFile, m => string.Format("{0}:{1}", m.Chrom, m.Position), progress);
 }
        public static IDisposable Work(IProgressCallback callback, int units)
        {
            if (callback == null)
                throw new ArgumentNullException("callback"); // $NON-NLS-1
            if (units <= 0)
                throw Failure.NegativeOrZero("unit", units);

            return new SimpleContext(callback, units);
        }
Exemplo n.º 57
0
        /// <summary>
        /// Fill reference allele from genome fasta file.
        /// </summary>
        /// <param name="snpItems"></param>
        /// <param name="fastaFile"></param>
        /// <param name="progress"></param>
        public static void FillReferenceAlleleFromFasta(this IEnumerable <SNPItem> snpItems, string fastaFile, IProgressCallback progress = null)
        {
            if (progress == null)
            {
                progress = new ConsoleProgressCallback();
            }

            var dic = snpItems.ToGroupDictionary(m => m.Chrom);

            progress.SetMessage("Filling reference allele from {0} file ...", fastaFile);
            using (var sw = new StreamReader(fastaFile))
            {
                var      ff = new FastaFormat();
                Sequence seq;
                while ((seq = ff.ReadSequence(sw)) != null)
                {
                    progress.SetMessage("chromosome " + seq.Name + " ...");
                    var chr = HumanChromosomeToInt(seq.Name);
                    if (dic.ContainsKey(chr))
                    {
                        var snps = dic[chr];
                        foreach (var snp in snps)
                        {
                            snp.RefChar = char.ToUpper(seq.SeqString[snp.Position - 1]);
                        }
                    }
                }
            }
            progress.SetMessage("Filling reference allele finished.");
        }
 public SimpleContext(IProgressCallback c, int u)
 {
     callback = c; units = u;
 }
Exemplo n.º 59
0
 /// <summary>
 /// The reset.
 /// </summary>
 /// <param name="callback">
 /// The callback.
 /// </param>
 public void Reset(IProgressCallback callback)
 {
     ProgressDialog.ExecuteTask(
         null,
         "Initialize new database",
         "Please wait...",
         "SQLiteDbReset",
         ProgressBarStyle.Marquee,
         this.Logger,
         cb =>
         {
             cb.Begin();
             this.DoResetDatabase(cb);
         });
 }
Exemplo n.º 60
0
 /// <summary>
 /// The repair database.
 /// </summary>
 /// <param name="callback">
 /// The callback.
 /// </param>
 public void RepairDatabase(IProgressCallback callback)
 {
     try
     {
         this.TryOpenDatabase();
         this.Optimize();
     }
     catch (Exception ex)
     {
         this.Logger.Error("Failed to optimize database: " + ex);
         this.Reset(callback);
     }
 }