/// <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();
              }
        }
Example #2
0
        public static List <SeedItem> BuildTargetSeeds(ITargetBuilderOptions options, List <string> seeds, IProgressCallback progress)
        {
            List <SeedItem> result = new List <SeedItem>();

            var mapped = GetTargetCoverageRegion(options, progress);

            progress.SetMessage("Building seeds ...");
            progress.SetRange(0, mapped.Count);
            progress.SetPosition(0);
            foreach (var l in mapped)
            {
                progress.Increment(1);
                foreach (var seed in seeds)
                {
                    var curseq  = l.Strand == '+' ? l.ReverseComplementedSequence : l.Sequence;
                    int lastpos = -1;
                    while (true)
                    {
                        int pos = curseq.IndexOf(seed, lastpos + 1);
                        if (pos == -1)
                        {
                            break;
                        }

                        if (l.Strand == '+')
                        {
                            result.Add(GetSeed(l, curseq.Length - pos - options.MinimumSeedLength, options.MinimumSeedLength, options.MinimumCoverage));
                        }
                        else
                        {
                            result.Add(GetSeed(l, pos, options.MinimumSeedLength, options.MinimumCoverage));
                        }
                        lastpos = pos;
                    }
                }
            }
            progress.End();
            progress.SetMessage("Total {0} {1}mers seeds were built.", result.Count, options.MinimumSeedLength);

            return(result);
        }
Example #3
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();
            }
        }
Example #4
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 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;
            }
        }
        public bool GenerateSortedSolutionList(IProgressCallback callback, out List <ImpositionSolution> solutions)
        {
            // get applicable pattern list
            List <ImpositionPattern> patternList = GetPatternList();
            // need to compute orthogonal positions ?
            bool processOrthogonalImposition = AllowOrthogonalImposition;

            /*_allowOrthogonalImposition && (_cardboardFormat.Width != _cardboardFormat.Height);*/
            // compute number of expected solutions
            if (null != callback)
            {
                callback.Begin(0, patternList.Count * (processOrthogonalImposition ? 4 : 2));
            }
            // instantiate solution list
            solutions = new List <ImpositionSolution>();
            // process pattern list
            foreach (ImpositionPattern pattern in patternList)
            {
                // generate pattern
                try
                {
                    pattern.GeneratePattern(InitialEntities, SpaceBetween, ImpositionOffset, false);
                }
                catch (Exception ex)
                {
                    _log.Error(ex.Message);
                    continue;
                }

                // default orientation
                ImpositionSolution solution = GenerateSolution(pattern);
                if (null != solution && solution.IsValid)
                {
                    solution.UnitLengthCut  = _unitLengthCut;
                    solution.UnitLengthFold = _unitLengthFold;
                    solution.UnitArea       = _unitArea;
                    solutions.Add(solution);
                }
                // increment progress dialog?
                if (null != callback)
                {
                    callback.Increment(solutions.Count);
                }

                // orthogonal direction
                if (processOrthogonalImposition)
                {
                    // generate pattern
                    try
                    {
                        pattern.GeneratePattern(InitialEntities, SpaceBetween, ImpositionOffset, true);
                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex.Message);
                        continue;
                    }
                    solution = GenerateSolution(pattern);
                    if (null != solution && solution.IsValid)
                    {
                        solution.UnitLengthCut  = _unitLengthCut;
                        solution.UnitLengthFold = _unitLengthFold;
                        solution.UnitArea       = _unitArea;
                        solutions.Add(solution);
                    }
                }
                // increment progress dialog?
                if (null != callback)
                {
                    callback.Increment(solutions.Count);
                }
            }

            // generate thumbnails
            foreach (ImpositionSolution sol in solutions)
            {
                sol.GenerateThumbnail();
                // increment progress dialog?
                if (null != callback)
                {
                    callback.Increment(solutions.Count);
                }
            }

            // sort solution list
            solutions.Sort(new SolutionComparerFormat());

            if (null != callback)
            {
                callback.End();
            }

            return(solutions.Count > 0);
        }
Example #7
0
        // The heart of GEDmill is here.
        public void Create()
        {
            fLogger.WriteInfo("Website::Create()");

            // 1 means the process was aborted, for signalling back to calling thread. 2 means file nError.
            ThreadError threaderror = new ThreadError(1, "No error");

            try {
                // The value to indicate in the progress bar to show how much of the website creation is complete.
                int progress = 0;

                int[] gfstats = fTree.GetRecordStats();

                // The maximum value of the progress bar, i.e. when website creation is fully complete.
                int progressMax =
                    1    // Site-wide multimedia files
                    + 1  // W3C Sticker
                    + 1  // Background image
                    + 1  // Style sheet
                    + gfstats[(int)GDMRecordType.rtIndividual]
                    + 1  // Individuals Index
                    + gfstats[(int)GDMRecordType.rtSource]
                    + 1  // Front page
                    + 1  // CD ROM (Doesn't matter here that CD ROM autorun might not be included.)
                    + 1; // Scripts (Doesn't matter here that scripts might not be included.)

                // The paintbox with which to draw the mini tree
                var paintbox = new Paintbox(GMConfig.Instance);
                paintbox.SetBackgroundImage(GMConfig.Instance.BackgroundImage);

                // Object to keep count of number of files created etc.
                var stats = new Stats();

                // Here goes....

                // Start the progress indicator.
                fProgressWindow.Begin(0, progressMax);
                if (fProgressWindow.IsAborting)
                {
                    return;
                }
                // Copy the images to use in place of non-pic multimedia files.
                fProgressWindow.SetText("Copying multimedia");
                CopyIcons();
                if (fProgressWindow.IsAborting)
                {
                    return;
                }
                fProgressWindow.StepTo(++progress);

                // Copy the W3C sticker file.
                fProgressWindow.SetText("Copying W3C sticker");
                string sW3CFilename = "";
                if (GMConfig.Instance.IncludeValiditySticker)
                {
                    sW3CFilename = CopyW3CSticker();
                }
                if (fProgressWindow.IsAborting)
                {
                    return;
                }
                fProgressWindow.StepTo(++progress);

                // Create the index creator for use by the individuals records creator.
                var indiIndexCreator = new CreatorIndexIndividuals(fTree, fProgressWindow, sW3CFilename);

                // Copy the image for the background of the webpages.
                fProgressWindow.SetText("Copying background image");
                string backgroundImageFilename = CopyBackgroundImage();
                if (fProgressWindow.IsAborting)
                {
                    return;
                }
                fProgressWindow.StepTo(++progress);

                // Create the style sheet
                fProgressWindow.SetText("Creating style sheet");
                string cssFilename = string.Concat(GMConfig.Instance.OutputFolder, "\\", GMConfig.Instance.StylesheetFilename, ".css");
                if (GMConfig.Instance.StylesheetFilename.Length > 0 && (!GMConfig.Instance.PreserveStylesheet || !File.Exists(cssFilename)))
                {
                    var csc = new CreatorStylesheet(fTree, fProgressWindow, sW3CFilename, cssFilename, backgroundImageFilename);
                    csc.Create();
                }

                if (fProgressWindow.IsAborting)
                {
                    return;
                }

                fProgressWindow.StepTo(++progress);

                // Create the pages for the individual records.
                fProgressWindow.SetText("Creating individual pages");
                var indiList = fTree.GetRecords <GDMIndividualRecord>();
                foreach (GDMIndividualRecord ir in indiList)
                {
                    var ipc = new CreatorRecordIndividual(fTree, fProgressWindow, sW3CFilename, ir, indiIndexCreator, paintbox);
                    if (ipc.Create(stats))
                    {
                        stats.Individuals++;
                    }
                    if (fProgressWindow.IsAborting)
                    {
                        return;
                    }

                    fProgressWindow.StepTo(++progress);
                }

                // Create the index for the individual records pages.
                fProgressWindow.SetText("Creating individuals index");
                indiIndexCreator.Create();
                if (fProgressWindow.IsAborting)
                {
                    return;
                }

                fProgressWindow.StepTo(++progress);

                // Clear list of copied files, so that source images get copied afresh
                // and so get resized differently to any indi images based on the same file.
                Creator.ClearCopiedFilesList();

                // Create the pages for the source records.
                fProgressWindow.SetText("Creating source pages");
                var sourList = fTree.GetRecords <GDMSourceRecord>();
                foreach (GDMSourceRecord sr in sourList)
                {
                    var spc = new CreatorRecordSource(fTree, fProgressWindow, sW3CFilename, sr);
                    if (spc.Create(stats))
                    {
                        stats.Sources++;
                    }

                    if (fProgressWindow.IsAborting)
                    {
                        return;
                    }

                    fProgressWindow.StepTo(++progress);
                }

                if (fProgressWindow.IsAborting)
                {
                    return;
                }

                // Create the front page
                fProgressWindow.SetText("Creating front page");
                string front_page_filename = string.Concat(GMConfig.Instance.OutputFolder, "\\", GMConfig.Instance.FrontPageFilename, ".", GMConfig.Instance.HtmlExtension);
                if (GMConfig.Instance.FrontPageFilename.Length > 0 && (!GMConfig.Instance.PreserveFrontPage || !File.Exists(front_page_filename)))
                {
                    CreatorFrontPage fpc = new CreatorFrontPage(fTree, fProgressWindow, sW3CFilename, stats);
                    fpc.Create();
                }
                fProgressWindow.StepTo(++progress);
                if (fProgressWindow.IsAborting)
                {
                    return;
                }

                // Copy the CD ROM autorun file
                fProgressWindow.SetText("Creating CD-ROM files");
                if (GMConfig.Instance.CreateCDROMFiles)
                {
                    CreateCDROMFiles();
                }
                if (fProgressWindow.IsAborting)
                {
                    return;
                }

                fProgressWindow.StepTo(++progress);

                // Copy the Javascript
                fProgressWindow.SetText("Creating Javascript file");
                // Currently (10Dec08) the only thing that uses javascript is the multiple images feature.
                if (GMConfig.Instance.AllowMultipleImages)
                {
                    CreateJavascriptFiles();
                }
                if (fProgressWindow.IsAborting)
                {
                    return;
                }

                fProgressWindow.StepTo(++progress);

                // Done
                fLogger.WriteInfo("Website::CreateFinished");
                fProgressWindow.SetText("Done");
                threaderror.Error   = 0;
                threaderror.Message = "";
            } catch (ArgumentException e) {
                fLogger.WriteError("Caught Argument Exception : ", e);
                threaderror.Error   = 2; // 2 => abnormal abort.
                threaderror.Message = "";
            } catch (IOException e) {
                fLogger.WriteError("Caught IO Exception : ", e);
                threaderror.Error   = 2; // 2 => abnormal abort.
                threaderror.Message = "";
            } catch (NullReferenceException e) {
                fLogger.WriteError("Caught NullReference Exception : ", e);
                threaderror.Error   = 2; // 2 => abnormal abort.
                threaderror.Message = "";
            } catch (HTMLException e) {
                threaderror.Error   = 2; // 2 => abnormal abort.
                threaderror.Message = e.Message;
            } catch (Exception e) {
                fLogger.WriteError("Caught Exception : ", e);
                threaderror.Error   = 2; // 2 => abnormal abort.
                threaderror.Message = "";
            } finally {
                fLogger.WriteInfo("Thread ending...");
                if (fProgressWindow != null)
                {
                    fProgressWindow.End(threaderror);
                }
            }
        }
Example #8
0
        private void DoSomeWork(object status)
        {
            errorList = new StringBuilder();
            errorMail = false;
            string sSource = "MultiMail";
            string sLog    = "Application";

            errorList.AppendLine("Email not sent to:");
            IProgressCallback callback = status as IProgressCallback;

            try
            {
                callback.Begin(0, clbLeden.CheckedItems.Count + clbExtraEmail.CheckedItems.Count);

                SmtpClientExt client = new SmtpClientExt(param.STMPserver, param.STMPport, param.EmailUserId, param.EmailPassword,
                                                         EmailLogFile, chkLogEmail.Checked, ckbDoNotSendEmail.Checked, callback.SetText);

                MailMessage message = new MailMessage();
                message.Subject = txtSubject.Text;
                message.From    = new MailAddress(param.EmailReturnAdress);
                message.ReplyToList.Add(param.EmailReturnAdress);
                message.IsBodyHtml = ckbHtml.Checked;
                string messid = string.Format("<{0}@{1}>", Guid.NewGuid().ToString(), "wwww.ttvn.nl");
                message.Headers.Add("Message-Id", messid);

                string strBody = string.Empty;
                if (ckbHtml.Checked)
                {
                    strBody = string.Format(@"<html><head><meta http-equiv=Content-Type content=""text/html; charset=us-ascii""></head>{0}</html>", htmlTextbox1.Text);
                }
                else
                {
                    strBody = htmlTextbox1.PlainText;
                }

                if (txtBijlage1.Text != string.Empty)
                {
                    //emailer.Attachments.Add(new SmtpAttachment(txtBijlage1.Text));
                    message.Attachments.Add(new Attachment(txtBijlage1.Text));
                }
                if (txtBijlage2.Text != string.Empty)
                {
                    //emailer.Attachments.Add(new SmtpAttachment(txtBijlage2.Text));
                    message.Attachments.Add(new Attachment(txtBijlage2.Text));
                }
                if (txtBijlage3.Text != string.Empty)
                {
                    //emailer.Attachments.Add(new SmtpAttachment(txtBijlage3.Text));
                    message.Attachments.Add(new Attachment(txtBijlage3.Text));
                }

                for (int i = 0; i < clbLeden.Items.Count; i++)
                {
                    if (!clbLeden.GetItemChecked(i))
                    {
                        continue;
                    }

                    message.To.Clear();
                    message.To.Add(clbLeden.Items[i].ToString());
                    message.Body = MailRoutines.ReplaceKeyWords(strBody, ledenSchaduwlijst[i], param);



                    //emailer.To.Clear();
                    //emailer.To.Add(clbLeden.Items[i].ToString());
                    //emailer.Body = MailRoutines.ReplaceKeyWords(strBody, ledenSchaduwlijst[i], param);
                    try
                    {
                        //emailer.SendMessage();
                        client.Send(message);
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            if (!EventLog.SourceExists("MultiMail"))
                            {
                                EventLog.CreateEventSource(sSource, sLog);
                            }

                            EventLog.WriteEntry(sSource, ex.Message + @"/n" + message.Body,
                                                EventLogEntryType.Warning, 001);
                        }
                        catch (Exception ex2)
                        {
                            GuiRoutines.ExceptionMessageBox(this, ex);
                            Console.WriteLine(ex2.ToString());
                        }
                        errorMail = true;
                        errorList.AppendLine(clbLeden.Items[i].ToString());
                    }
                    callback.Increment(1);
                    callback.SetText(clbLeden.Items[i].ToString());
                    System.Threading.Thread.Sleep(50);
                    if (callback.IsAborting)
                    {
                        return;
                    }
                }


                for (int i = 0; i < clbExtraEmail.Items.Count; i++)
                {
                    if (!clbExtraEmail.GetItemChecked(i))
                    {
                        continue;
                    }

                    message.To.Clear();
                    message.To.Add(clbExtraEmail.Items[i].ToString());
                    message.Body = MailRoutines.ReplaceKeyWords(strBody, new tblLid(), param);

                    try
                    {
                        client.Send(message);
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            if (!EventLog.SourceExists("MultiMail"))
                            {
                                EventLog.CreateEventSource(sSource, sLog);
                            }
                            EventLog.WriteEntry(sSource, ex.Message,
                                                EventLogEntryType.Warning, 001);
                        }
                        catch { }

                        errorMail = true;
                        errorList.AppendLine(clbExtraEmail.Items[i].ToString());
                    }
                    callback.Increment(1);
                    callback.SetText(clbExtraEmail.Items[i].ToString());
                    System.Threading.Thread.Sleep(50);
                    if (callback.IsAborting)
                    {
                        return;
                    }
                }

                callback.WaitOK();
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                // We want to exit gracefully here (if we're lucky)
                try
                {
                    if (!EventLog.SourceExists("MultiMail"))
                    {
                        EventLog.CreateEventSource(sSource, sLog);
                    }
                    EventLog.WriteEntry(sSource, ex.Message,
                                        EventLogEntryType.Warning, 001);
                }
                catch { }
            }
            catch (System.Threading.ThreadInterruptedException ex)
            {
                // And here, if we can
                try
                {
                    if (!EventLog.SourceExists("MultiMail"))
                    {
                        EventLog.CreateEventSource(sSource, sLog);
                    }
                    EventLog.WriteEntry(sSource, ex.Message,
                                        EventLogEntryType.Warning, 001);
                }
                catch { }
            }
            catch (Exception ex)
            {
                try
                {
                    if (!EventLog.SourceExists("MultiMail"))
                    {
                        EventLog.CreateEventSource(sSource, sLog);
                    }
                    EventLog.WriteEntry(sSource, ex.Message,
                                        EventLogEntryType.Warning, 001);
                }
                catch { }

                GuiRoutines.ExceptionMessageBox(this, ex);
            }
            finally
            {
                if (callback != null)
                {
                    callback.End();
                }
            }
        }
Example #9
0
        /// <summary>
        /// The execute task.
        /// </summary>
        /// <param name="title">
        /// The title.
        /// </param>
        /// <param name="text">
        /// The text.
        /// </param>
        /// <param name="threadName">
        /// The thread name.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <param name="logger">
        /// The logger.
        /// </param>
        /// <param name="action">
        /// The action.
        /// </param>
        /// <param name="exceptionHandler">
        /// The exception handler.
        /// </param>
        /// <param name="finalHandler">
        /// The final handler.
        /// </param>
        /// <param name="notifyError">
        /// The notify error.
        /// </param>
        /// <returns>
        /// The <see cref="ThreadResult"/>.
        /// </returns>
        public static ThreadResult ExecuteTask(
            string title,
            string text,
            string threadName,
            IProgressCallback callback,
            ILogger logger,
            CallbackDelegate action,
            CallbackExceptionDelegate exceptionHandler,
            CallbackExceptionDelegate finalHandler,
            bool notifyError)
        {
            var result = DoWork(
                delegate
                    {
                        threadName = string.IsNullOrEmpty(threadName) ? title.Replace(" ", string.Empty) : threadName;
                        AppUtil.NameCurrentThread(threadName);
                        Exception actionException = null;

                        try
                        {
                            action(callback);
                        }
                        catch (Exception ex)
                        {
                            actionException = ex;
                            if (!callback.IsAborting)
                            {
                                if (logger != null)
                                {
                                    string currentTitle = callback.Title;
                                    logger.Error((string.IsNullOrEmpty(currentTitle) ? null : currentTitle + ": ") + ex);
                                    if (notifyError)
                                    {
                                        callback.Inform(callback, "An error occured: " + ex.Message, currentTitle, NotificationType.Error);
                                    }
                                }

                                if (exceptionHandler != null)
                                {
                                    exceptionHandler(callback, ex);
                                }
                            }
                        }
                        finally
                        {
                            if (callback != null)
                            {
                                callback.End();
                            }

                            if (finalHandler != null)
                            {
                                finalHandler(callback, actionException);
                            }
                        }
                    },
                int.MaxValue,
                threadName,
                logger);

            return result;
        }
Example #10
0
    public static List<SeedItem> BuildTargetSeeds(ITargetBuilderOptions options, Func<SeedItem, bool> acceptSeed, IProgressCallback progress)
    {
      List<SeedItem> seeds = new List<SeedItem>();

      var mapped = GetTargetCoverageRegion(options, progress);

      progress.SetMessage("Building seeds ...");
      progress.SetRange(0, mapped.Count);
      progress.SetPosition(0);
      foreach (var l in mapped)
      {
        progress.Increment(1);
        for (int i = 0; i < l.Sequence.Length - options.MinimumSeedLength; i++)
        {
          SeedItem si = GetSeed(l, i, options.MinimumSeedLength, options.MinimumCoverage);

          if (si != null && acceptSeed(si))
          {
            seeds.Add(si);
          }
        }
      }
      progress.End();
      progress.SetMessage("Total {0} {1}mers seeds were built.", seeds.Count, options.MinimumSeedLength);

      return seeds;
    }
Example #11
0
    public static List<SeedItem> BuildTargetSeeds(ITargetBuilderOptions options, List<string> seeds, IProgressCallback progress)
    {
      List<SeedItem> result = new List<SeedItem>();

      var mapped = GetTargetCoverageRegion(options, progress);

      progress.SetMessage("Building seeds ...");
      progress.SetRange(0, mapped.Count);
      progress.SetPosition(0);
      foreach (var l in mapped)
      {
        progress.Increment(1);
        foreach (var seed in seeds)
        {
          var curseq = l.Strand == '+' ? l.ReverseComplementedSequence : l.Sequence;
          int lastpos = -1;
          while (true)
          {
            int pos = curseq.IndexOf(seed, lastpos + 1);
            if (pos == -1)
            {
              break;
            }

            if (l.Strand == '+')
            {
              result.Add(GetSeed(l, curseq.Length - pos - options.MinimumSeedLength, options.MinimumSeedLength, options.MinimumCoverage));
            }
            else
            {
              result.Add(GetSeed(l, pos, options.MinimumSeedLength, options.MinimumCoverage));
            }
            lastpos = pos;
          }
        }
      }
      progress.End();
      progress.SetMessage("Total {0} {1}mers seeds were built.", result.Count, options.MinimumSeedLength);

      return result;
    }
Example #12
0
        /// <summary>
        /// Load all the components form the component definition file, nominally components.xml.
        /// </summary>
        /// <param name="status">An <see cref="IProgressCallback"/> used for updating the progress dialog.</param>
        /// <remarks>
        /// This is run in a worker thread and therefore has no direct access to the UI/user.
        /// </remarks>
        private void LoadComponents(object status)
        {
            IProgressCallback callback = status as IProgressCallback;

            // blank the component data
            components = new ConcurrentDictionary <string, Component>();

            XmlDocument xmldoc      = new XmlDocument();
            bool        waitForFile = false;
            double      waitTime    = 0; // seconds

            do
            {
                try
                {
                    using (FileStream componentFileStream = new FileStream(saveFilePath, FileMode.Open, FileAccess.Read))
                    {
                        xmldoc.Load(componentFileStream);

                        XmlNode xmlnode = xmldoc.DocumentElement;

                        int nodesLoaded = 0;
                        while (xmlnode != null)
                        {
                            // Report.Information("node name = '" + xmlnode.Name + "'");
                            if (xmlnode.Name == "ROOT")
                            {
                                callback.Begin(0, xmlnode.ChildNodes.Count);

                                xmlnode = xmlnode.FirstChild;
                            }
                            else if (xmlnode.Name == "Component")
                            {
                                ++nodesLoaded;
                                callback.SetText(string.Format("Loading component: {0}", nodesLoaded));
                                callback.StepTo(nodesLoaded);
                                Component newComponent = new Component(xmlnode);
                                components[newComponent.Name] = newComponent;
                                xmlnode = xmlnode.NextSibling;
                            }
                            else
                            {
                                xmlnode = xmlnode.NextSibling;
                            }

                            // check for user Cancel
                            if (callback.IsAborting)
                            {
                                return;
                            }
                        }
                    }
                    waitForFile = false;

                    callback.Success = true;
                }
                catch (System.IO.IOException)
                {
                    // IOException. Is the file locked? Try waiting.
                    if (waitTime < Global.TotalFileWaitTime)
                    {
                        waitForFile = true;
                        System.Threading.Thread.Sleep(Global.FileWaitRetryTime);
                        waitTime += 0.1;
                    }
                    else
                    {
                        // Give up, maybe something else is wrong?
                        throw;
                    }
                }
                catch (System.Threading.ThreadAbortException)
                {
                    // We want to exit gracefully here (if we're lucky)
                    Report.Error("AllComponents: LoadComponents() - Thread Abort Exception.");
                }
                catch (System.Threading.ThreadInterruptedException)
                {
                    // And here, if we can
                    Report.Error("AllComponents: LoadComponents() - Thread Interrupted Exception.");
                }
                catch (Exception e)
                {
                    Report.Error("Failed to load file: \r\n" + e.Message);
                }
                finally
                {
                    if (callback != null)
                    {
                        callback.End();
                    }
                }
            }while (waitForFile);
        }
Example #13
0
        /// <summary>
        /// 加载缓存 zhangdahang 2013-11-15
        /// 算法思路:
        /// 1、从服务器获得需要更新的表(表名,版本)列表
        /// 2、对比本地对应表的版本,决定是否需要更新
        /// 3、对需要更新的表,获取其表中的所有记录(ID,版本)列表
        /// 4、对比本地其表中的记录和版本,统计需要更新的记录集
        /// 5、对需要更新的记录集中的记录进行更新,如有需要,分批更新。
        /// </summary>
        /// <param name="status"></param>
        public static void LoadCache_Update(object status)
        {
            //修复Bug307
            #region 准备

            float             step     = 1;
            String            Msg      = "系统正在更新...";
            IProgressCallback callBack = status as IProgressCallback;

            if (Yqun.Common.ContextCache.ApplicationContext.Current.ISLocalService)
            {
                if (callBack != null)
                {
                    callBack.End();
                }
                return;
            }

            DataTable ServerDataCache = null;
            DataTable LocalDataCache  = null;

            //栓查版本列,如没有版本列,添加“Stcs_1”列,目前以时间作为记录版本
            CompareField();
            #endregion

            callBack.SetText(Msg);
            callBack.Begin(0, 100);

            Thread.Sleep(500);
            //获取服务器表集,
            try
            {
                ServerDataCache = GetServerDataCache();
                LocalDataCache  = GetLocalDataCache();
            }
            catch (Exception ex)
            {
                Msg = string.Format("更新缓存失败,原因:“{0}”,请及时联系管理员!", ex.Message);
                logger.Error(Msg);
                if (callBack != null)
                {
                    callBack.End();
                }
                return;
            }
            step = ProgressGo(callBack, step);
            DataTable updateTable = GetUpdateDateTable(ServerDataCache, LocalDataCache);

            if (updateTable.Rows.Count == 0)
            {
                if (callBack != null)
                {
                    callBack.End();
                }
                return;
            }


            logger.Error("共有" + updateTable.Rows.Count + "表需要更新");

            DataSet UpdateDB = new DataSet();
            foreach (DataRow cacheRow in updateTable.Rows)
            {
                string tableName = cacheRow["tableName"].ToString();
                callBack.SetText("分析表:" + tableName + "需要更新的记录");

                DataTable ServerTable = GetServerDataTalbe("select ID,Scts_1 from " + tableName);
                if (LocalDataCache.Select("tableName ='" + tableName + "'").Length == 0)
                {
                    DataRow newCacheRow = LocalDataCache.NewRow();
                    newCacheRow.ItemArray = cacheRow.ItemArray;
                    LocalDataCache.Rows.Add(newCacheRow);
                    callBack.SetText("添加新表:" + tableName);
                    UpdateTableData(LocalDataCache.TableName, LocalDataCache);
                }
                DataTable LocalTable        = GetLocalDataTable("select ID,Scts_1 from " + tableName);
                DataTable updateRecordTable = GetUpdateDateTable(ServerTable, LocalTable);
                lock (ProcessInfoList)
                {
                    if (!ProcessInfoList.ContainsKey(tableName.ToLower().Trim()))
                    {
                        ProcessInfo pi = new ProcessInfo();
                        pi.CompletedRowsCount = 0;
                        pi.TableRowsCount     = updateRecordTable.Rows.Count;
                        ProcessInfoList.Add(tableName.ToLower().Trim(), pi);
                    }
                }
                UpdateDB.Tables.Add(updateRecordTable);
            }

            //更新
            foreach (DataTable table in UpdateDB.Tables)
            {
                string tableName = table.TableName;

                #region 可以更新
                if (table.Rows.Count == 0)
                {
                    DataTable cacheTalbe = GetServerDataTalbe("select * from sys_biz_Cache where tableName='" + tableName + "'");
                    UpdateTableData("sys_biz_Cache", cacheTalbe);
                    continue;
                }
                #endregion



                callBack.SetText("开始更新,表:" + tableName);

                string IDStr    = "";
                int    index    = 0;
                Int32  pageSize = GetPageSize(tableName);

                for (; index < table.Rows.Count; index++)
                {
                    IDStr += "'" + table.Rows[index]["ID"].ToString() + "',";
                    if ((index != 0 && index % pageSize == 0) || index == table.Rows.Count - 1)
                    {
                        try
                        {
                            IDStr = IDStr.Substring(IDStr.Length - 1) == "," ? IDStr.Remove(IDStr.Length - 1) : IDStr;
                            string sqlStr = "select * from " + tableName + " where ID in (" + IDStr + ")";
                            IDStr = "";

                            object[] parameterArr = new object[] {
                                tableName,
                                sqlStr,
                                callBack,
                                table,
                                ServerDataCache
                            };
                            //启动一个线程 ,更新本地数据据
                            System.Threading.Thread process = GetOneThread();
                            process.Start(parameterArr);
                        }
                        catch (Exception e)
                        {
                            logger.Error(e.ToString());
                        }
                    }
                }
            }
            bool HasRunningThread = true;
            while (HasRunningThread)
            {
                HasRunningThread = false;
                lock (RunningThreads)
                {
                    foreach (Thread t in RunningThreads)
                    {
                        if (t.ThreadState == ThreadState.Running)
                        {
                            HasRunningThread = true;
                            break;
                        }
                    }
                }
                Thread.Sleep(50);
            }

            logger.Error("更新完成");
            callBack.SetText("更新成功!");
            callBack.StepTo(100);
            Thread.Sleep(1000);
            if (callBack != null)
            {
                callBack.End();
            }
        }
Example #14
0
        /// <summary>
        /// 加载缓存  寇志凯  2013-10-18
        /// </summary>
        public static void LoadCache(object status)
        {
            //修复Bug307
            Thread.Sleep(500);
            int               step     = 1;
            String            Msg      = "系统正在更新...";
            IProgressCallback callBack = status as IProgressCallback;

            if (Yqun.Common.ContextCache.ApplicationContext.Current.ISLocalService)
            {
                if (callBack != null)
                {
                    callBack.End();
                }
                return;
            }

            callBack.SetText(Msg);
            callBack.Begin(0, 100);

            DataTable DataCache = null;

            object             o  = "";
            List <CacheHelper> ht = new List <CacheHelper>();

            try
            {
                DataCache = GetDataCache();
                step      = ProgressGo(callBack, step);
            }
            catch (Exception ex)
            {
                Msg = string.Format("更新缓存失败,原因:“{0}”,请及时联系管理员!", ex.Message);
                logger.Error(Msg);
                if (callBack != null)
                {
                    callBack.End();
                }
                return;
            }
            CompareField();
            step = ProgressGo(callBack, step);
            Boolean needLoadAgain = true;

            foreach (DataRow Row in DataCache.Rows)
            {
                String      TableName = Row["TableName"].ToString();
                CacheHelper ch        = new CacheHelper();
                ch.TableName     = TableName;
                ch.AlreadyIDList = new List <string>();
                ch.HasData       = true;
                try
                {
                    o = CallLocalService("Yqun.BO.LoginBO.dll", "GetMaxSCTS1", new object[] { TableName });
                    if (o == null || o.ToString() == "")
                    {
                        ch.MaxTime = new DateTime(1900, 1, 1);
                    }
                    else
                    {
                        ch.MaxTime = System.Convert.ToDateTime(o);
                    }
                }
                catch (Exception ex)
                {
                    ch.MaxTime = new DateTime(1900, 1, 1);
                    logger.Error("获取本地最大时间出错:" + ex.Message);
                }
                ht.Add(ch);
            }
            step = ProgressGo(callBack, step);

            while (needLoadAgain)
            {
                try
                {
                    List <String> sqls = GetCacheSqls(ht);
                    DataSet       ds   = GetNewData(sqls);

                    needLoadAgain = ds.Tables.Count > 0;
                    Thread.Sleep(50);
                    foreach (var ch in ht)
                    {
                        ch.HasData = false;
                    }

                    foreach (DataTable dt in ds.Tables)
                    {
                        needLoadAgain = UpdateTableData(dt.TableName, dt);

                        if (!needLoadAgain)
                        {
                            break;
                        }
                        CacheHelper ch = GetCacheHelperByTableName(ht, dt.TableName);
                        if (ch != null)
                        {
                            ch.HasData = true;
                            foreach (DataRow row in dt.Rows)
                            {
                                ch.AlreadyIDList.Add(row["ID"].ToString());
                                logger.Error(row["ID"].ToString() + "被更新");
                            }
                        }
                        step = ProgressGo(callBack, step);
                    }
                }
                catch (Yqun.Bases.Exceptions.ServiceAccessException sae)
                {
                    logger.Error("服务端内存溢出,请稍后再试:" + sae.Message);
                    needLoadAgain = false;
                }
                catch (Exception ex)
                {
                    Msg = string.Format("更新数据失败,原因:“{0}”,请及时联系管理员!", ex.Message);
                    logger.Error(Msg);
                    needLoadAgain = false;
                }
            }

            callBack.SetText("更新成功!");
            callBack.StepTo(100);
            Thread.Sleep(2000);
            if (callBack != null)
            {
                callBack.End();
            }
        }
Example #15
0
        private void ProcessAddOrder(object objCallback)
        {
            IProgressCallback callback = (IProgressCallback)objCallback;

            ExecutionEngine.EventLogger.Write("FileOrderStorage:AddOrder");

            if (callback != null)
            {
                if (callback.IsAborted)
                {
                    return;
                }

                callback.SetRange(0, _order.OrderItems.Count);
            }

            CreateStoreFolder();

            if (!string.IsNullOrEmpty(_currentOrderPath))
            {
                LockOrderFolder(_currentOrderPath);

                try
                {
                    foreach (OrderItem item in _order.OrderItems)
                    {
                        if (callback != null)
                        {
                            if (callback.IsAborted)
                            {
                                throw new InvalidOperationException();
                            }

                            callback.Increment();
                        }

                        try
                        {
                            item.OrderStoreFileName = VerifyFileName(_currentOrderPath, item.SourcePhotoItem.SourceFileNameWithoutPath);
                            ExecutionEngine.EventLogger.Write(string.Format(CultureInfo.InvariantCulture, "Copying file from: {0} to: {1}", item.SourcePhotoItem.ActualFileName, _currentOrderPath + "\\" + item.OrderStoreFileName));
                            File.Copy(item.SourcePhotoItem.ActualFileName, _currentOrderPath + "\\" + item.OrderStoreFileName);
                        }
                        catch (Exception e)
                        {
                            ExecutionEngine.EventLogger.Write(string.Format(CultureInfo.InvariantCulture, "File copy error {0}. Message: {1}", item.SourcePhotoItem.ActualFileName, e.Message));
                            ExecutionEngine.EventLogger.WriteExceptionInfo(e);
                        }
                    }

                    SaveOrderInfoToFile(_order, _currentOrderPath + "\\" + Constants.OrderInfoXmlFileName);
                    UnlockOrderFolder(_currentOrderPath);
                    IncreaseOrderId();

                    if (callback != null)
                    {
                        callback.IsComplete = true;
                    }
                }
                catch (InvalidOperationException)
                {
                    callback.IsComplete = false;

                    ExecutionEngine.EventLogger.Write(string.Format(CultureInfo.InvariantCulture, "Order process was cancelled"));
                    ExecutionEngine.EventLogger.Write(string.Format(CultureInfo.InvariantCulture, "Remove Folder: {0}", _currentOrderPath));
                    try
                    {
                        Directory.Delete(_currentOrderPath, true);
                        ExecutionEngine.EventLogger.Write(string.Format(CultureInfo.InvariantCulture, "Folder {0} removed succesfully", _currentOrderPath));
                    }
                    catch (Exception e)
                    {
                        ExecutionEngine.EventLogger.Write(string.Format(CultureInfo.InvariantCulture, "Uneble to remove folder {0}. {1}", _currentOrderPath, e.Message));
                    }
                }

                callback.End();
            }
        }