Example #1
0
 public ProcessBackground(int Max, DoWorkEventHandler DoWork, ProgressChangedEventHandler worker_ProgressChanged)//最大值和标题
 {
     progressForm = new FrmAutoUpdate();
     progressForm.progressBarDownload.Value = 0;
     progressForm.Show();
     SetbackgroundWorker(DoWork, worker_ProgressChanged);
 }
Example #2
0
        /// <summary>
        /// Creates and dispatches a PageManager to load a search page,
        /// parse, extract, validate and return results using the 
        /// parameter callback EventHandlers
        /// </summary>
        /// <param name="pageNumber">Which search page number to load</param>
        /// <param name="criteria">The user's search criteria</param>
        /// <param name="pageLoadMethod">Supply the method to retrieve html</param>
        /// <param name="updateProgressMethod">Callback for progress updates</param>
        /// <param name="workerCompleteMethod">Callback when work complete</param>
        public PageManager(int pageNumber,
            SearchCriteria criteria,
            Func<int, string, string> pageLoadMethod, // see explanation above
            ProgressChangedEventHandler updateProgressMethod,
            RunWorkerCompletedEventHandler workerCompleteMethod)
        {
            if (pageNumber < 1)
            {
                string msg = "Supplied page number ({0}) was < 0!";
                msg = string.Format(msg,pageNumber);
                throw new ArgumentOutOfRangeException(msg);
            }

            if (pageLoadMethod == null)
            {
                string msg = "Provided a null method to obtain page HTML!";
                throw new InvalidOperationException(msg);
            }

            ProgressChanged += updateProgressMethod; // Callback
            RunWorkerCompleted += workerCompleteMethod;  // Callback
            DoWork += Work;

            _pageLoadMethod = pageLoadMethod;
            _searchCriteria = criteria;
            _pageNumber = pageNumber;

            WorkerReportsProgress = true;
            WorkerSupportsCancellation = true;
        }
Example #3
0
 /// <summary>
 /// Constructor that accepts Event handlers for executing async thread
 /// </summary>
 /// <param name="WorkerProcess">Worker Process Handler</param>
 /// <param name="WorkProgressHandler">Progress Changed Event Handler</param>
 /// <param name="WorkCompletedHandler">Call back method handler which is invoked once the Worker Process is completed</param>
 public WorkerHelper(DoWorkEventHandler WorkerProcess, ProgressChangedEventHandler WorkProgressHandler, RunWorkerCompletedEventHandler WorkCompletedHandler)
 {
     this.DoWork += WorkerProcess;
     this.ProgressChanged += WorkProgressHandler;
     this.RunWorkerCompleted += WorkCompletedHandler;
     this.WorkerReportsProgress = true;
 }
 public BackgroundConnectionHelper(DoWorkEventHandler AsyncDelegate, RunWorkerCompletedEventHandler GUIDelegate, ProgressChangedEventHandler ProgressChanged)
 {
     backgroundWorker = new BackgroundWorker();
     backgroundWorker.DoWork += AsyncDelegate;
     backgroundWorker.RunWorkerCompleted += GUIDelegate;
     backgroundWorker.ProgressChanged += ProgressChanged;
 }
Example #5
0
        public Form1()
        {
            InitializeComponent();

            this.label1.Visible = false;
            this.tableLayoutPanel1.Visible = false;
            this.pictureBox1.MouseHover += this.Control_MouseHover;
            this.pictureBox1.MouseWheel += this.pictureBox1_MouseWheel;
            this.treeView1.MouseHover += this.Control_MouseHover;
            this.treeView1.DragEnter += this.treeView1_DragEnter;
            this.treeView1.DragDrop += this.treeView1_DragDrop;
            this.treeView1.AfterSelect += this.treeView1_AfterSelect;
            this.dataGridView1.MouseHover += this.Control_MouseHover;
            this.dataGridView1.Columns.Add("tagName", "Tag name");
            this.dataGridView1.Columns.Add("tagValue", "Tag value");
            this.dataGridView1.Columns["tagName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            this.dataGridView1.Columns["tagValue"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            this.dataGridView1.RowHeadersWidth = 14;

            this.workerCompleted = (s, e) =>
            {
                this.tableLayoutPanel1.Visible = false;
                this.progressBar1.Value = 0;
            };
            this.progressChanged = (s, e) =>
            {
                this.progressBar1.Value = e.ProgressPercentage;
            };

            this.fileHelper = new FileHelper(this.treeView1);
            this.fileHelper.zipCompleted = this.workerCompleted;
            this.fileHelper.zipProgressChanged = this.progressChanged;

            this.reader = new Reader();
        }
Example #6
0
        /// <summary>
        /// Constructor for the class. Several additional event handlers are hooked up, these are for driving changes in the UI
        /// </summary>
        /// <param name="s_Filename">directory of the MIDI file to play</param>
        /// <param name="extHandleLoadProgressChanged">external event handler for load progress changed</param>
        /// <param name="extHandleLoadCompleted">external event handler for load completed</param>
        /// <param name="extHandleChannelMessagePlayed">external event handler for channel message played</param>
        /// <param name="extHandlePlayingCompleted">external event handler for loading completed</param>
        public MidiPlayer(string s_Filename,
            ProgressChangedEventHandler extHandleLoadProgressChanged,
            EventHandler<AsyncCompletedEventArgs> extHandleLoadCompleted,
            EventHandler<ChannelMessageEventArgs> extHandleChannelMessagePlayed,
            EventHandler extHandlePlayingCompleted)
        {
            sequence.Format = 1;
            sequence.LoadProgressChanged += extHandleLoadProgressChanged;
            sequence.LoadCompleted += HandleLoadCompleted;
            sequence.LoadCompleted += extHandleLoadCompleted;
            sequence.LoadAsync(s_Filename);
            sequencer.Position = 0;
            sequencer.Sequence = sequence;
            sequencer.ChannelMessagePlayed += HandleChannelMessagePlayed;
            sequencer.ChannelMessagePlayed += extHandleChannelMessagePlayed;
            sequencer.Chased += HandleChased;
            sequencer.Stopped += HandleStopped;
            sequencer.PlayingCompleted += HandlePlayingCompleted;
            sequencer.PlayingCompleted += extHandlePlayingCompleted;

            this.extHandleChannelMessagePlayed = extHandleChannelMessagePlayed;
            this.extHandlePlayingCompleted = extHandlePlayingCompleted;

            PlayPersistentChannel = true;
            PlayOtherChannels = true;
        }
Example #7
0
        public byte[] ConvertFrom(byte[] data, int width, int height, ProgressChangedEventHandler progress)
        {
            byte[] result, blockResult, block;
            int step;

            step = Math.Max(width * height / BlockHeight / BlockWidth / 100, 1024);
            result = new byte[width * height << 2];
            block = new byte[BlockStride];

            for (int y = 0, i = 0; y < height; y += BlockHeight)
            {
                for (int x = 0; x < width; x += BlockWidth, i++)
                {
                    Array.Copy(data, i * block.Length, block, 0, block.Length);
                    blockResult = _convertFrom(block);

                    for (int dy = 0; dy < Math.Min(BlockHeight, height - y); dy++)
                    {
                        Array.Copy(blockResult, dy * BlockWidth << 2, result, ((dy + y) * width + x) << 2, Math.Min(BlockWidth, width - x) << 2);
                    }

                    if (i % step == 0 && progress != null)
                        progress(this, new ProgressChangedEventArgs((x + y * width * 100) / (result.Length / 4), null));
                }                
            }

            return result;
        }
Example #8
0
 public pgWorker(int pos, string dsn, 
     ProgressChangedEventHandler onProgress,
     RunWorkerCompletedEventHandler onComplete)
 {
     this.thNo = pos;
     this.pg_conn = new NpgsqlConnection(dsn);
     try
     {
         pg_conn.Open();
         pg_error = "";
     }
     catch (Exception ex)
     {
         pg_conn = null;
         pg_error = ex.Message;
     }
     if (pg_conn != null)
     {
         this.bw = new BackgroundWorker();
         this.bw.WorkerReportsProgress = true;
         this.bw.WorkerSupportsCancellation = true;
         this.bw.DoWork += this.bwDoWork;
         this.bw.ProgressChanged += onProgress;
         this.bw.RunWorkerCompleted += onComplete;
     }
 }
 public static BackgroundWorker InitNewBackgroundWorker(DoWorkEventHandler doWorkEvent, ProgressChangedEventHandler progressChangedEvent, RunWorkerCompletedEventHandler runWorkerCompletedEvent)
 {
     var bw = new BackgroundWorker();
     bw.RegisterDoWork(doWorkEvent);
     bw.RegisterProgressChanged(progressChangedEvent);
     bw.RegisterRunWorkerCompleted(runWorkerCompletedEvent);
     return bw;
 }
Example #10
0
        public virtual void ImportTo(int[] data, int level, ProgressChangedEventHandler progress)
        {
            byte[] rawData;

            rawData = new byte[data.Length << 2];

            Marshal.Copy(Marshal.UnsafeAddrOfPinnedArrayElement(data, 0), rawData, 0, rawData.Length);

            ImportTo(rawData, level, progress);
        }
Example #11
0
        public ImageProcessor()
        {
            processWorkerDelegate = new Action<KeyValuePair<string, string>, IEnumerable<IProcessingPlugin>, IOutputPlugin, AsyncOperation>(ProcessWorker);
            processAsyncProgressChangedDelegate = new SendOrPostCallback(ProcessAsyncProgressChanged);
            processAsyncCompletedDelegate = new SendOrPostCallback(ProcessAsyncCompleted);
            processingPlugin_ProcessProgressChangedDelegate = new ProgressChangedEventHandler(processingPlugin_ProcessProgressChanged);
            getBitmapCompletedDelegate = new EventHandler<GetBitmapCompletedEventArgs>(getBitmapCompleted);

            getBitmapManager.GetBitmapCompleted += getBitmapCompletedDelegate;
        }
Example #12
0
 //把事件传进入
 private void SetbackgroundWorker(DoWorkEventHandler DoWork, ProgressChangedEventHandler worker_ProgressChanged)
 {           
     backgroundWorker.WorkerReportsProgress = true;//有进度条
     backgroundWorker.WorkerSupportsCancellation = true;//是否支持异步取消
     backgroundWorker.DoWork += new DoWorkEventHandler(DoWork);
     backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);//做的事情
     backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(OnProgressChanged);//更新进度条
     backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);//完成事件
     backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnProcessCompleted);
     backgroundWorker.RunWorkerAsync();
 }
Example #13
0
 public PackingProcess(ProgressChangedEventHandler handler, RunWorkerCompletedEventHandler completedHandler)
 {
     this.DoWork += PackingProcess_DoWork;
     this.RunWorkerCompleted += PackingProcess_RunWorkerCompleted;
     this.RunWorkerCompleted += completedHandler;
     this.WorkerReportsProgress = true;
     this.WorkerSupportsCancellation = true;
     this.ProgressChanged += handler;
     IsRunning = false;
     IsError = false;
 }
Example #14
0
        public virtual int[] GetColorData(int level, ProgressChangedEventHandler progress)
        {
            int[] result;
            byte[] data;

            data = GetData(level, progress);
            result = new int[data.Length >> 2];

            Marshal.Copy(data, 0, Marshal.UnsafeAddrOfPinnedArrayElement(result, 0), data.Length);

            return result;
        }
        internal QuadResCombinBackground( MainForm UseForm, QuadResWorkerInfo WInfo )
        {
            MForm = UseForm;

            DoWork += new DoWorkEventHandler( QuadResCombinBackground_DoWork );
            ProgressChanged += new ProgressChangedEventHandler( QuadResCombinBackground_ProgressChanged );
            RunWorkerCompleted += new RunWorkerCompletedEventHandler( QuadResCombinBackground_RunWorkerCompleted );

            WorkerReportsProgress = true;
            WorkerSupportsCancellation = true;

            ProcessName = WInfo.ProcessName;
        }
Example #16
0
        static IBackgroundTask ExecuteOnBackgroundThread(Func<object> backgroundAction, RunWorkerCompletedEventHandler uiCallback, ProgressChangedEventHandler progressChanged)
        {
            var task = new BackgroundTask(backgroundAction);

            if (uiCallback != null)
                task.Completed += uiCallback;

            if (progressChanged != null)
                task.ProgressChanged += progressChanged;

            task.Start(null);

            return task;
        }
Example #17
0
        public ImageProcessingManager()
        {
            processWorkerDelegate = new Action<Queue<KeyValuePair<string, string>>, IEnumerable<IProcessingPlugin>, IOutputPlugin, AsyncOperation>(ProcessWorker);
            processAsyncTaskProgressChangedDelegate = new SendOrPostCallback(ProcessAsyncTaskProgressChanged);
            processAsyncProgressChangedDelegate = new SendOrPostCallback(ProcessAsyncProgressChanged);
            processAsyncStateChangedDelegate = new SendOrPostCallback(ProcessAsyncStateChanged);
            processAsyncCompletedDelegate = new SendOrPostCallback(ProcessAsyncCompleted);
            processingProgressForm_CancelProcessDelegate = new EventHandler<AsyncEventArgs>(processingProgressForm_CancelProcess);

            imageProcessor.ProcessProgressChanged += new ProgressChangedEventHandler(imageProcessor_ProcessProgressChanged);
            imageProcessor.ProcessCompleted += new AsyncCompletedEventHandler(imageProcessor_ProcessCompleted);

            ProcessTaskProgressChanged += new EventHandler<ProcessTaskProgressChangedEventArgs>(ImageProcessingManager_ProcessTaskProgressChanged);
            ProcessProgressChanged += new ProgressChangedEventHandler(ImageProcessingManager_ProcessProgressChanged);
            ProcessStateChanged += new EventHandler<ProcessStateChangedEventArgs>(ImageProcessingManager_ProcessStateChanged);
            ProcessCompleted += new AsyncCompletedEventHandler(ImageProcessingManager_ProcessCompleted);
        }
        /// <summary>
        /// Executes code on the background thread.
        /// </summary>
        /// <param name="backgroundAction">The background action.</param>
        /// <param name="uiCallback">The UI callback.</param>
        /// <param name="progressChanged">The progress change callback.</param>
        public IBackgroundTask ExecuteOnBackgroundThread(Action backgroundAction, RunWorkerCompletedEventHandler uiCallback, ProgressChangedEventHandler progressChanged)
        {
            var task = new BackgroundTask(
                () =>{
                    backgroundAction();
                    return null;
                });

            if(uiCallback != null)
                task.Completed += (s, e) => ExecuteOnUIThread(() => uiCallback(s, e));

            if(progressChanged != null)
                task.ProgressChanged += (s, e) => ExecuteOnUIThread(() => progressChanged(s, e));

            task.Start(null);

            return task;
        }
        private static void RegisterProgressChanged(this BackgroundWorker bw, ProgressChangedEventHandler progressChangedEvent = null)
        {
            bw.WorkerReportsProgress = true;

            //默认实现
            if (progressChangedEvent == null)
            {
                progressChangedEvent = (sender, e) =>
                {
                    var userState = e.UserState;
                    Console.WriteLine("DoWork中传递的执行参数为" + userState);
                    var percentage = e.ProgressPercentage;
                    Console.WriteLine("DoWork中当前的执行进度为" + percentage);
                };
            }

            bw.ProgressChanged += progressChangedEvent;
        }
        public static void Run(DoWorkEventHandler doWork,
                  RunWorkerCompletedEventHandler completed = null,
                  ProgressChangedEventHandler progressChanged = null)
        {
            using (var backgroundWorker = new BackgroundWorker())
            {
                backgroundWorker.DoWork += doWork;

                if (completed != null)
                    backgroundWorker.RunWorkerCompleted += completed;

                if (progressChanged != null)
                {
                    backgroundWorker.WorkerReportsProgress = true;
                    backgroundWorker.ProgressChanged += progressChanged;
                }
                backgroundWorker.RunWorkerAsync();
            }
        }
        public FileMerger(
            MergeInventory inventory,
            ProgressChangedEventHandler progressHandler,
            RunWorkerCompletedEventHandler completedHandler)
        {
            _inventory = inventory;

            _bgWorker = new BackgroundWorker
            {
                WorkerReportsProgress = true
            };
            _bgWorker.ProgressChanged += progressHandler;
            ProgressInfo = new MergeProgressInfo();
            ProgressInfo.PropertyChanged += (sender, e) =>
            {
                _bgWorker.ReportProgress(0, ProgressInfo);
            };
            _bgWorker.RunWorkerCompleted += completedHandler;
        }
Example #22
0
        public void InitialPopulateTreeView(string path, ProgressChangedEventHandler progressChangeEH)
        {
            _folder_inventory.InitializeInventory(path);
            if (_bw == null)
            {
                _bw = new BackgroundWorker();
                _bw.WorkerReportsProgress = true;
                _bw.WorkerSupportsCancellation = true;
                _bw.ProgressChanged += progressChangeEH;
                _bw.DoWork += new DoWorkEventHandler(_folder_inventory.bw_DoWorkEventHandler);
                _bw.RunWorkerCompleted += (e, a) => FinalizeScan();
            }

            _folder_inventory.ReportProgressHandler = _bw.ReportProgress;
            _folder_inventory.UpdateDirectoryLabelHandler = UpdateDirectoryMethod;
            _folder_inventory.CancellationPending = false;
            _bw.RunWorkerAsync();
            _modalForm.StartTimer(this);
            _modalForm.ShowDialog();
        }
Example #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="progressChanged">Callback for errors and notifications</param>
        /// <param name="unloadOnExit">Whetever this DLL should get unloaded on exit</param>
        /// <param name="windowName">Name of the window you wish to inject to</param>
        /// <param name="className">Name of the class you wish to inject to (IFF window name is empty/null)</param>
        /// <param name="dll">Name of the DLL you wish to inject</param>
        public InjectionHelper(BackgroundWorker bw, ProgressChangedEventHandler progressChanged, bool unloadOnExit, string windowName, string className, string dll)
        {
            if (string.IsNullOrEmpty(windowName) && string.IsNullOrEmpty(className))
            {
                throw new ArgumentException("Either window or class name must be specified");
            }
            else if (string.IsNullOrEmpty(dll))
            {
                throw new ArgumentException("DLL name must be specified");
            }

            this._registeredProgressCallback = progressChanged;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.WorkerSupportsCancellation = true;
            bw.WorkerReportsProgress      = true;
            bw.ProgressChanged           += progressChanged;

            _exitArguments = new RunArguments {
                WindowName = windowName,
                ClassName  = className,
                DllName    = dll
            };
            bw.RunWorkerAsync(_exitArguments);
        }
Example #24
0
        public static Task CopyToAsync(this Stream From, Stream To, ProgressChangedEventHandler ProgressHandler)
        {
            return(Task.Run(() =>
            {
                try
                {
                    long TotalBytesRead = 0;
                    long TotalBytesLength = From.Length;

                    byte[] DataBuffer = new byte[2048];

                    while (true)
                    {
                        int bytesRead = From.Read(DataBuffer, 0, DataBuffer.Length);

                        if (bytesRead > 0)
                        {
                            To.Write(DataBuffer, 0, bytesRead);
                            TotalBytesRead += bytesRead;
                        }
                        else
                        {
                            To.Flush();
                            break;
                        }

                        ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32(TotalBytesRead * 100d / TotalBytesLength), null));
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "Could not track the progress of coping the stream");
                    From.CopyTo(To);
                }
            }));
        }
        /// <summary>
        /// Downloads the update from the given Github release, and returns the path to the updater program.
        /// A progress handler can be passed to react when the operation progress (in the range [0, 100]) changes.
        /// Throws an InvalidOperationException if the update is not valid.
        /// </summary>
        /// <param name="release"></param>
        /// <param name="progressHandler"></param>
        /// <returns></returns>
        public static bool UpdateProgram(GithubRelease release, ProgressChangedEventHandler progressHandler)
        {
            string fileName = Path.Combine(Settings.TempFolderPath, "SporeModManagerSetup.exe");
            var    asset    = Array.Find(release.assets, a => a.name.ToLowerInvariant() == "sporemodmanagersetup.exe");

            if (asset == null)
            {
                throw new InvalidOperationException("Invalid update: no 'SporeModManagerSetup.exe' asset");
            }
            using (var client = new WebClient())
            {
                client.DownloadProgressChanged += (s, e) =>
                {
                    if (progressHandler != null)
                    {
                        progressHandler.Invoke(null, e);
                    }
                };

                client.DownloadFile(asset.browser_download_url, fileName);
                client.DownloadFileCompleted += (sneder, args) => UpdateDownloadCompleted?.Invoke(fileName, null);
            }
            return(true);
        }
Example #26
0
 public AnnTestingService(TestingModel testingModel,
                          ProgressChangedEventHandler progressChangedEventHandler)
 {
     _testingModel = testingModel;
     _progressChangedEventHandler = progressChangedEventHandler;
 }
        /// <summary>
        /// 开始处理模板替换
        /// </summary>
        /// <param name="ctx">上下文</param>
        /// <param name="progress">进度汇报</param>
        /// <param name="logger">日志记录</param>
        /// <param name="missMatch">未命中书签事件</param>
        public void Handle(ReplacerContext <T> ctx, ProgressChangedEventHandler progress,
                           Action <string> logger, Action <string> missMatch)
        {
            var filepath     = ctx.SrcFilePath;
            var targetFolder = ctx.DestFolder;

            if (!File.Exists(filepath))
            {
                logger?.Invoke($"{filepath}不存在");
                return;
            }

            var name = Path.GetFileName(filepath);

            if (string.IsNullOrEmpty(name))
            {
                logger?.Invoke($"文件名称{filepath}为空");
                return;
            }

            var targetPath = ctx.DestFilePath;

            try
            {
                File.Copy(filepath, targetPath, true);
            }
            catch (Exception e)
            {
                logger?.Invoke($"拷贝模板文件失败:{e.Message}");
                return;
            }
            progress?.Invoke(this, new ProgressChangedEventArgs(10, "预处理完毕"));
            using (var stream = File.Open(targetPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (var wordprocessingDocument = WordprocessingDocument.Open(stream, true))
                {
                    var mainDocumentPart = wordprocessingDocument.MainDocumentPart;

                    var bookmarkStarts = mainDocumentPart.Document.Body.Descendants <OpenXmlBookmarkStart>().AsQueryable();
                    var bookMarkConfig = ctx.EnsureBookMarkConf(logger);// 加载配置文件
                    var count          = bookmarkStarts.Count();
                    int c = 0;
                    DocumentFormat.OpenXml.Wordprocessing.Table table;
                    foreach (var bookmarkStart in bookmarkStarts)
                    {
                        ++c;
                        progress?.Invoke(this, new ProgressChangedEventArgs(10 + 70 * c / count, $"开始替换书签<{bookmarkStart.Name}>"));
                        ctx.BookmarkName = bookmarkStart.Name;

                        if (bookmarkStart.Name.Value.ToUpper().Equals("_GOBACK"))
                        {
                            logger?.Invoke($"书签[{bookmarkStart.Name.Value}]:处理成表格书签");
                            continue;
                        }

                        if (!_handlerMethods.ContainsKey(bookmarkStart.Name.Value.ToUpper()))
                        {
                            // 处理未知书签
                            UpdateBookMarksByCfg(bookmarkStart, bookMarkConfig, ctx, logger, missMatch);
                            continue;
                        }

                        if (CheckParentTable(bookmarkStart, out table) && null != table)
                        {
                            // 处理表格
                            logger?.Invoke($"书签[{bookmarkStart.Name.Value}]:处理成表格书签");
                            _handlerMethods[bookmarkStart.Name.Value.ToUpper()].Invoke(_handler,
                                                                                       new object[] { table, ctx, logger });

                            continue;
                        }

                        var bookmarkText = bookmarkStart.NextSibling <Run>();
                        if (null != bookmarkText)
                        {
                            var firstChild = bookmarkText.GetFirstChild <Text>();
                            if (firstChild != null)
                            {
                                // 处理文本
                                logger?.Invoke($"书签[{bookmarkStart.Name.Value}]:处理成文本书签");
                                _handlerMethods[bookmarkStart.Name.Value.ToUpper()].Invoke(_handler,
                                                                                           new object[] { firstChild, ctx, logger });

                                continue;
                            }

                            ImagePart imagePart = null;
                            if (CheckPicture(bookmarkStart, ref imagePart))
                            {
                                // 处理图片
                                logger?.Invoke($"书签[{bookmarkStart.Name.Value}]:处理成图片书签");
                                _handlerMethods[bookmarkStart.Name.Value.ToUpper()].Invoke(_handler,
                                                                                           new object[] { imagePart, ctx, logger });
                                continue;
                            }
                        }

                        logger?.Invoke($"书签[{bookmarkStart.Name.Value}]:不是预期类型的书签");
                    }

                    wordprocessingDocument.Close();
                }
            }

            if (!Directory.Exists(targetFolder))
            {
                Directory.CreateDirectory(targetFolder);
            }

            try
            {
                progress?.Invoke(this, new ProgressChangedEventArgs(80, "开始pdf转换"));
                Convert(targetPath, Path.Combine(targetFolder, ctx.SrcFileNameWithoutExt + ".pdf"));
                progress?.Invoke(this, new ProgressChangedEventArgs(90, "pdf转换成功"));
            }
            catch (Exception e)
            {
                logger?.Invoke($"转换pdf失败:{e.Message}");
            }
        }
Example #28
0
 public AutoProcess(ProgressChangedEventHandler ProgressCallBack, RunWorkerCompletedEventHandler WorkCompletedCallBack, ProgressChangedEventHandler StateCallBack, bool CreateFiles = true)
     : base(ProgressCallBack, WorkCompletedCallBack, CreateFiles)
 {
     this.StateCallBack += StateCallBack;
 }
Example #29
0
        public void BuildAsync(
            bool checkScripts, bool checkXml, bool checkBundles,
            ProgressChangedEventHandler progressHandler,
            RunWorkerCompletedEventHandler completedHandler)
        {
            var ignoredModNames = GetIgnoredModNames();
            var modDirPaths     = (Directory.Exists(Paths.ModsDirectory))
              ? Directory.GetDirectories(Paths.ModsDirectory, "mod*", SearchOption.TopDirectoryOnly)
                                  .Where(path => !ignoredModNames.Any(name => name.EqualsIgnoreCase(new DirectoryInfo(path).Name)))
                                  .ToList()
              : new List <string>();

            ModCount = modDirPaths.Count;
            if (ModCount == 0)
            {
                Program.MainForm.ShowMessage("Can't find any mods in the Mods directory.");
            }

            var bgWorker = new BackgroundWorker
            {
                WorkerReportsProgress = true
            };

            bgWorker.DoWork += (sender, e) =>
            {
                var i = 0;
                ScriptCount = XmlCount = BundleCount = 0;
                foreach (var modDirPath in modDirPaths)
                {
                    var modName     = Path.GetFileName(modDirPath);
                    var filePaths   = Directory.GetFiles(modDirPath, "*", SearchOption.AllDirectories);
                    var scriptPaths = filePaths.Where(path => ModFile.IsScript(path));
                    var xmlPaths    = filePaths.Where(path => ModFile.IsXml(path));
                    var bundlePaths = filePaths.Where(path => ModFile.IsBundle(path));

                    ScriptCount += scriptPaths.Count();
                    XmlCount    += xmlPaths.Count();
                    BundleCount += bundlePaths.Count();

                    if (checkScripts)
                    {
                        Files.AddRange(GetModFilesFromPaths(scriptPaths, Categories.Script, modName));
                    }
                    if (checkXml)
                    {
                        Files.AddRange(GetModFilesFromPaths(xmlPaths, Categories.Xml, modName));
                    }
                    if (checkBundles)
                    {
                        foreach (var bundlePath in bundlePaths)
                        {
                            var contentPaths = QuickBms.GetBundleContentPaths(bundlePath);
                            Files.AddRange(GetModFilesFromPaths(contentPaths, Categories.BundleText, modName, bundlePath));
                        }
                    }
                    var progressPct = (int)((float)++i / modDirPaths.Count * 100f);
                    bgWorker.ReportProgress(progressPct, modName as object);
                }
                if (checkBundles)
                {
                    System.Threading.Thread.Sleep(500);  // Wait for progress bar to fill completely
                }
            };
            bgWorker.RunWorkerCompleted += completedHandler;
            bgWorker.ProgressChanged    += progressHandler;
            bgWorker.RunWorkerAsync();
        }
Example #30
0
 /// <summary>
 /// Executes the backgroundAction on a background thread.
 /// </summary>
 /// <param name="backgroundAction">The action.</param>
 /// <param name="progressChanged">The progress change callback.</param>
 public static IBackgroundTask OnBackgroundThread(Func<object> backgroundAction, ProgressChangedEventHandler progressChanged)
 {
     return ExecuteOnBackgroundThread(backgroundAction, null, progressChanged);
 }
Example #31
0
 public static void Run(DoWorkEventHandler doWork, ProgressChangedEventHandler progressChanged, RunWorkerCompletedEventHandler runWorkerCompleted, bool forceEndOnGUIThread = false)
 {
     Run(doWork, progressChanged, runWorkerCompleted, null, forceEndOnGUIThread);
 }
Example #32
0
        private static void GoIPR(NSLinq2SQL.IPRDEV sqledc, ArchiveSettings settings, ProgressChangedEventHandler progress)
        {
            progress(null, new ProgressChangedEventArgs(1, String.Format("Starting IPR archive-{0} delay. It could take several minutes", settings.ArchiveIPRDelay)));
            //Select delete candidates.
            List <int> _invcLib2BeChecked   = new List <int>();
            List <int> _clearance2BeChecked = new List <int>();

            using (NSSPLinq.Entities _spedc = new NSSPLinq.Entities(settings.SiteURL))
            {
                progress(null, new ProgressChangedEventArgs(1, "Buffering IPR entries"));
                foreach (Linq.IPR _iprX in _spedc.IPR.ToList <Linq.IPR>().Where <Linq.IPR>(_iprX => _iprX.AccountClosed.Value == true && _iprX.ClosingDate.IsLatter(settings.ArchiveIPRDelay)))
                {
                    bool _any = false;
                    foreach (NSSPLinq.Disposal _dspx in _iprX.Disposal)
                    {
                        if (_dspx.Disposal2BatchIndex != null && (_dspx.Disposal2BatchIndex.FGQuantityAvailable.Value != 0 || _dspx.Disposal2BatchIndex.BatchStatus.Value != NSSPLinq.BatchStatus.Final))
                        {
                            _any = true;
                            break;
                        }
                    }
                    if (_any)
                    {
                        continue;
                    }
                    List <NSSPLinq.IPR>        _toDeleteIPR                   = new List <NSSPLinq.IPR>();
                    List <IArchival>           _toBeMarkedArchival4IPR        = new List <IArchival>();
                    List <Linq.Disposal>       _toDeletedDisposal             = new List <NSSPLinq.Disposal>();
                    List <IArchival>           _toBeMarkedArchival4Disposal   = new List <IArchival>();
                    List <NSSPLinq.BalanceIPR> _toDeletedBalanceIPR           = new List <NSSPLinq.BalanceIPR>();
                    List <IArchival>           _toBeMarkedArchival4BalanceIPR = new List <IArchival>();
                    _toBeMarkedArchival4IPR.AddIfNotNull(_iprX.ClearenceIndex);
                    foreach (NSSPLinq.Disposal _dspslx in _iprX.Disposal)
                    {
                        _toBeMarkedArchival4Disposal.AddIfNotNull(_dspslx.Disposal2BatchIndex);
                        _toBeMarkedArchival4Disposal.AddIfNotNull(_dspslx.Disposal2ClearenceIndex);
                        _toBeMarkedArchival4Disposal.AddIfNotNull(_dspslx.Disposal2InvoiceContentIndex);
                        _toBeMarkedArchival4Disposal.AddIfNotNull(_dspslx.Disposal2IPRIndex);
                        _toBeMarkedArchival4Disposal.AddIfNotNull(_dspslx.Disposal2MaterialIndex);
                        //_toBeMarkedArchival.Add(_dspslx.Disposal2PCNID);
                        //_toBeMarkedArchival.Add(_dspslx.JSOXCustomsSummaryIndex);
                        _toDeletedDisposal.Add(_dspslx);
                        if (_dspslx.Disposal2InvoiceContentIndex != null)
                        {
                            _invcLib2BeChecked.AddIfNew(_dspslx.Disposal2InvoiceContentIndex.InvoiceIndex.Id.Value);
                        }
                        if (_dspslx.Disposal2ClearenceIndex != null)
                        {
                            _clearance2BeChecked.AddIfNew(_dspslx.Disposal2ClearenceIndex.Id.Value);
                        }
                    }
                    foreach (NSSPLinq.BalanceIPR _biprx in _iprX.BalanceIPR)
                    {
                        //_toBeMarkedArchival4BalanceIPR.AddIfNotNull(_biprx.IPRIndex);
                        //_toBeMarkedArchival4BalanceIPR.AddIfNotNull(_biprx.BalanceIPR2JSOXIndex);
                        _toBeMarkedArchival4BalanceIPR.AddIfNotNull(_biprx.BalanceBatchIndex);
                        _toDeletedBalanceIPR.Add(_biprx);
                    }
                    _toDeleteIPR.Add(_iprX);
                    string _mtmp = "The selected {0} IPR account with {1} Disposal and {2} BalanceIPR entries are to be deleted.";
                    progress(null, new ProgressChangedEventArgs(1, String.Format(_mtmp, _iprX.Title, _toDeletedDisposal.Count, _toDeletedBalanceIPR.Count)));
                    //delete BalanceIPR
                    _spedc.BalanceIPR.Delete <NSSPLinq.BalanceIPR, NSLinq2SQL.History>
                        (_toDeletedBalanceIPR, _toBeMarkedArchival4BalanceIPR, x => sqledc.BalanceIPR.GetAt <NSLinq2SQL.BalanceIPR>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                        settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                    //delete Disposal entries
                    _spedc.Disposal.Delete <NSSPLinq.Disposal, NSLinq2SQL.History>
                        (_toDeletedDisposal, _toBeMarkedArchival4Disposal, x => sqledc.Disposal.GetAt <NSLinq2SQL.Disposal>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                        settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                    //delete IPR
                    _spedc.IPR.Delete <NSSPLinq.IPR, NSLinq2SQL.History>
                        (_toDeleteIPR, _toBeMarkedArchival4IPR, x => sqledc.IPR.GetAt <NSLinq2SQL.IPR>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                        settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                    Link2SQLExtensions.SubmitChanges(_spedc, sqledc, progress);
                }
            }
            //delete InvoiceLib and InvoiceContent
            using (NSSPLinq.Entities _spedc = new NSSPLinq.Entities(settings.SiteURL))
            {
                List <NSSPLinq.InvoiceContent>        _toDeletedInvoiceContent = new List <NSSPLinq.InvoiceContent>();
                List <NSSPLinq.InvoiceLib>            _toDeletedInvoiceLib     = new List <NSSPLinq.InvoiceLib>();
                Dictionary <int, NSSPLinq.InvoiceLib> _allInvcLib = _spedc.InvoiceLibrary.ToDictionary <NSSPLinq.InvoiceLib, int>(x => x.Id.Value);
                int _brokenCleranceLookup = 0;
                foreach (int _ilx in _invcLib2BeChecked)
                {
                    NSSPLinq.InvoiceLib _invcLb = _allInvcLib[_ilx];
                    bool _any = false;
                    foreach (NSSPLinq.InvoiceContent _icx in _invcLb.InvoiceContent)
                    {
                        _any = _icx.Disposal.Count > 0;
                        if (_any)
                        {
                            break;
                        }
                    }
                    if (_any)
                    {
                        continue;
                    }
                    _toDeletedInvoiceLib.Add(_invcLb);
                    _toDeletedInvoiceContent.AddRange(_invcLb.InvoiceContent);
                    if (_invcLb.ClearenceIndex == null)
                    {
                        _brokenCleranceLookup++;
                    }
                    else
                    {
                        _clearance2BeChecked.AddIfNew(_invcLb.ClearenceIndex.Id.Value);
                    }
                }
                if (_brokenCleranceLookup != 0)
                {
                    progress(null, new ProgressChangedEventArgs(1, String.Format("Warning: there are {0} InvoiceLib entries with broken lookup on Clearance", _brokenCleranceLookup)));
                }
                string _mtmp = "The selected: {0} InvoiceLibrary, and {1} InvoiceContent entries are to be deleted.";
                progress(null, new ProgressChangedEventArgs(1, String.Format(_mtmp, _toDeletedInvoiceLib.Count, _toDeletedInvoiceContent.Count)));
                _spedc.InvoiceContent.Delete <NSSPLinq.InvoiceContent, NSLinq2SQL.History>
                    (_toDeletedInvoiceContent, null, x => sqledc.InvoiceContent.GetAt <NSLinq2SQL.InvoiceContent>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                    settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                _spedc.InvoiceLibrary.Delete <NSSPLinq.InvoiceLib, NSLinq2SQL.History>
                    (_toDeletedInvoiceLib, null, x => sqledc.InvoiceLibrary.GetAt <NSLinq2SQL.InvoiceLibrary>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                    settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                _invcLib2BeChecked = null;
                Link2SQLExtensions.SubmitChanges(_spedc, sqledc, progress);
            }
            //Clearance
            List <int> _sad2BeChecked = new List <int>();

            using (NSSPLinq.Entities _spedc = new NSSPLinq.Entities(settings.SiteURL))
            {
                List <NSSPLinq.Clearence>            _toDeletedClearence = new List <NSSPLinq.Clearence>();
                Dictionary <int, NSSPLinq.Clearence> _allClearences      = _spedc.Clearence.ToDictionary <NSSPLinq.Clearence, int>(x => x.Id.Value);
                List <IArchival>           _toBeMarkedArchival4Clearence = new List <IArchival>();
                List <NSSPLinq.InvoiceLib> _allInvcs = _spedc.InvoiceLibrary.ToList <NSSPLinq.InvoiceLib>();
                List <NSSPLinq.IPR>        _allIPR   = _spedc.IPR.ToList <NSSPLinq.IPR>();
                foreach (int _clrncIdx in _clearance2BeChecked)
                {
                    NSSPLinq.Clearence _clrnc = _allClearences[_clrncIdx];
                    if (_clrnc.Disposal.Count == 0 &&
                        !_allInvcs.Where <NSSPLinq.InvoiceLib>(x => x.ClearenceIndex == _clrnc).Any <NSSPLinq.InvoiceLib>() &&
                        !_allIPR.Where <NSSPLinq.IPR>(x => x.ClearenceIndex == _clrnc).Any <NSSPLinq.IPR>())
                    {
                        _toDeletedClearence.Add(_clrnc);
                    }
                    //Debug.Assert(_clrnc.Clearence2SadGoodID != null); - Disposal with 0 belongs may be assigned to closed account but not cleared through custom.
                    if (_clrnc.Clearence2SadGoodID == null)
                    {
                        continue;
                    }
                    _toBeMarkedArchival4Clearence.AddIfNotNull(_clrnc.Clearence2SadGoodID);
                    _sad2BeChecked.AddIfNew(_clrnc.Clearence2SadGoodID.Id.Value);
                }
                _clearance2BeChecked = null;
                string _mtmp = "The selected {0} Clearance entries are to be deleted.";
                progress(null, new ProgressChangedEventArgs(1, String.Format(_mtmp, _toDeletedClearence.Count)));
                _spedc.Clearence.Delete <NSSPLinq.Clearence, NSLinq2SQL.History>
                    (_toDeletedClearence, _toBeMarkedArchival4Clearence, x => sqledc.Clearence.GetAt <NSLinq2SQL.Clearence>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                    settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                Link2SQLExtensions.SubmitChanges(_spedc, sqledc, progress);
            }
            List <int> _sadDocument2BeChecked = new List <int>();

            //SADDocument
            using (NSSPLinq.Entities _spedc = new NSSPLinq.Entities(settings.SiteURL))
            {
                List <NSSPLinq.SADGood> _toDeletedSADGood = new List <NSSPLinq.SADGood>();
                List <NSSPLinq.SADRequiredDocuments> _toDeletedSADRequiredDocuments = new List <NSSPLinq.SADRequiredDocuments>();
                List <NSSPLinq.SADQuantity>          _toDeletedSADQuantity          = new List <NSSPLinq.SADQuantity>();
                List <NSSPLinq.SADPackage>           _toDeletedSADPackage           = new List <NSSPLinq.SADPackage>();
                List <NSSPLinq.SADDuties>            _toDeletedSADDuties            = new List <NSSPLinq.SADDuties>();
                Dictionary <int, NSSPLinq.SADGood>   _allSDGd = _spedc.SADGood.ToDictionary <NSSPLinq.SADGood, int>(x => x.Id.Value);
                foreach (int _sgid in _sad2BeChecked)
                {
                    NSSPLinq.SADGood _SDGd = _allSDGd[_sgid];
                    if (_SDGd.Clearence.Count > 0)
                    {
                        continue;
                    }
                    _sadDocument2BeChecked.AddIfNew(_SDGd.SADDocumentIndex.Id.Value);
                    _toDeletedSADGood.Add(_SDGd);
                    _toDeletedSADRequiredDocuments.AddRange(_SDGd.SADRequiredDocuments);
                    _toDeletedSADDuties.AddRange(_SDGd.SADDuties);
                    _toDeletedSADPackage.AddRange(_SDGd.SADPackage);
                    _toDeletedSADQuantity.AddRange(_SDGd.SADQuantity);
                }
                string _mtmp = "The selected: {0} SADGood, {1} SADRequiredDocuments, {2} SADQuantity, {3} SADPackage, and {4} SADDuties entries are to be deleted.";
                progress(null, new ProgressChangedEventArgs(1, String.Format(_mtmp, _toDeletedSADGood.Count, _toDeletedSADRequiredDocuments.Count, _toDeletedSADQuantity.Count,
                                                                             _toDeletedSADPackage.Count, _toDeletedSADDuties.Count)));
                _spedc.SADDuties.Delete <NSSPLinq.SADDuties, NSLinq2SQL.History>
                    (_toDeletedSADDuties, null, x => sqledc.SADDuties.GetAt <NSLinq2SQL.SADDuties>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                    settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                _spedc.SADPackage.Delete <NSSPLinq.SADPackage, NSLinq2SQL.History>
                    (_toDeletedSADPackage, null, x => sqledc.SADPackage.GetAt <NSLinq2SQL.SADPackage>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                    settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                _spedc.SADQuantity.Delete <NSSPLinq.SADQuantity, NSLinq2SQL.History>
                    (_toDeletedSADQuantity, null, x => sqledc.SADQuantity.GetAt <NSLinq2SQL.SADQuantity>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                    settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                _spedc.SADRequiredDocuments.Delete <NSSPLinq.SADRequiredDocuments, NSLinq2SQL.History>
                    (_toDeletedSADRequiredDocuments, null, x => sqledc.SADRequiredDocuments.GetAt <NSLinq2SQL.SADRequiredDocuments>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                    settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                _spedc.SADGood.Delete <NSSPLinq.SADGood, NSLinq2SQL.History>
                    (_toDeletedSADGood, null, x => sqledc.SADGood.GetAt <NSLinq2SQL.SADGood>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                    settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                Link2SQLExtensions.SubmitChanges(_spedc, sqledc, progress);
                _sad2BeChecked = null;
            }
            using (NSSPLinq.Entities _spedc = new NSSPLinq.Entities(settings.SiteURL))
            {
                List <NSSPLinq.SADDocumentType>            _toDeletedSADDocumentType = new List <NSSPLinq.SADDocumentType>();
                Dictionary <int, NSSPLinq.SADDocumentType> _allSDGd = _spedc.SADDocument.ToDictionary <NSSPLinq.SADDocumentType, int>(x => x.Id.Value);
                foreach (int _sdid in _sadDocument2BeChecked)
                {
                    NSSPLinq.SADDocumentType _SDcumnt = _allSDGd[_sdid];
                    if (_SDcumnt.SADGood.Count > 0)
                    {
                        continue;
                    }
                    _toDeletedSADDocumentType.AddIfNotNull <NSSPLinq.SADDocumentType>(_SDcumnt);
                }
                string _mtmp = "The selected: {0} SADDocument entries are to be deleted.";
                progress(null, new ProgressChangedEventArgs(1, String.Format(_mtmp, _toDeletedSADDocumentType.Count)));
                _spedc.SADDocument.Delete <NSSPLinq.SADDocumentType, NSLinq2SQL.History>
                    (_toDeletedSADDocumentType, null, x => sqledc.SADDocument.GetAt <NSLinq2SQL.SADDocument>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                    settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
                Link2SQLExtensions.SubmitChanges(_spedc, sqledc, progress);
            }
            //Update Activities Log
            progress(null, new ProgressChangedEventArgs(1, "Finished archive operation of IPR related lists"));
        }
Example #33
0
        public static System.ComponentModel.BackgroundWorker Launch(DoWorkEventHandler doWork, ProgressChangedEventHandler progressChange)
        {
            var bw = new System.ComponentModel.BackgroundWorker
            {
                WorkerReportsProgress      = true,
                WorkerSupportsCancellation = true
            };

            bw.DoWork          += doWork;
            bw.ProgressChanged += progressChange;

            bw.RunWorkerCompleted += (s, args) =>
            {
                if (args.Error != null)                     // if an exception occurred during DoWork,
                {
                    MessageBox.Show(args.Error.ToString()); // do your error handling here
                }
            };

            bw.RunWorkerAsync();

            return(bw);
        }
Example #34
0
 private void OnProgressChanged(int percentProgress)
 {
     ProgressChangedEventHandler handler = ProgressChanged;
     if (handler != null)
         handler(percentProgress);
 }
 public StylusAcquisition(PolhemusController controller, SingleShot singleShot, Monitor monitor = null)
 {
     if (controller == null) throw new ArgumentNullException("controller");
     if (singleShot == null) throw new ArgumentNullException("singleShot");
     _controller = controller;
     _singleShot = singleShot;
     _monitor = monitor;
     _continuousMode = false;
     initialization();
     if (monitor != null)
         ProgressChanged += new ProgressChangedEventHandler(sa_StylusProgressChanged);
 }
Example #36
0
        /// <summary>
        /// Generates package content differentials between the source and target snapshots in the specified output path. Note that additional package modifications may be required afterwards to account for content not included in the snapshots.
        /// </summary>
        /// <param name="repo">The initial repository configuration.</param>
        /// <param name="sourcePath">The absolute local source content path.</param>
        /// <param name="targetPath">The absolute localtarget content path.</param>
        /// <param name="deltaPath">The delta content path; these files should be uploaded to the repo.</param>
        /// <param name="settings">The optional package settings.</param>
        /// <param name="progressHandler">The optional handler to report progress to.</param>
        /// <param name="progressStatus">The optional progress status description.</param>
        /// <returns>The created package information.</returns>
        public Package(Repository repo, Path sourcePath, Path targetPath, Path deltaPath, PackageSettings settings = null, ProgressChangedEventHandler progressHandler = null, string progressStatus = null)
        {
            Repository = repo ?? throw new ArgumentNullException(nameof(repo));

            if (!Directory.Exists(sourcePath))
            {
                throw new DirectoryNotFoundException("Source path does not exist.");
            }

            if (!Directory.Exists(targetPath))
            {
                throw new DirectoryNotFoundException("Target path does not exist.");
            }

            if (!Directory.Exists(deltaPath))
            {
                throw new DirectoryNotFoundException("Delta path does not exist.");
            }

            // use the specified settings or initialize with defaults if null
            PackageSettings pkgSettings = settings ?? new PackageSettings();

            // generate the empty package and create it's content directory based on its ID
            Path packagePath = Path.Combine(deltaPath, Id + "\\");

            Directory.CreateDirectory(packagePath);

            // TODO: automatic detection of relative versus absolute paths (absolute should override and not use base path if specified)

            try
            {
                #region Snapshots

                // generate source snapshot, use existing one in repo if content matches
                var sourceSnapshot = new Snapshot(sourcePath, progressHandler, "Generating source snapshot");
                if (repo.Snapshots.Contains(sourceSnapshot))
                {
                    sourceSnapshot = repo.Snapshots[repo.Snapshots.IndexOf(sourceSnapshot)];
                }
                else
                {
                    repo.Snapshots.Add(sourceSnapshot);
                }

                // generate target snapshot, use existing one in repo if content matches
                var targetSnapshot = new Snapshot(targetPath, progressHandler, "Generating target snapshot");
                if (repo.Snapshots.Contains(targetSnapshot))
                {
                    targetSnapshot = repo.Snapshots[repo.Snapshots.IndexOf(targetSnapshot)];
                }
                else
                {
                    repo.Snapshots.Add(targetSnapshot);
                }

                // abort if package already exists
                if (repo.Packages.Any(pkg => Equals(pkg.SourceSnapshot, sourceSnapshot) && Equals(pkg.TargetSnapshot, targetSnapshot)))
                {
                    throw new NotSupportedException("Package already exists for the specified source and target content.");
                }

                // link snapshots to the package
                SourceSnapshot = sourceSnapshot;
                TargetSnapshot = targetSnapshot;

                #endregion

                #region Lookup Tables

                // generate lookup tables
                var sourcePaths  = new Dictionary <Path, FileInformation>();
                var sourceFiles  = new Dictionary <Path, List <FileInformation> >();
                var sourceHashes = new Dictionary <string, List <FileInformation> >();
                foreach (var info in sourceSnapshot.Files)
                {
                    sourcePaths[info.Path] = info;

                    Path fileName = Path.GetFileName(info.Path);
                    if (!sourceFiles.ContainsKey(fileName))
                    {
                        sourceFiles[fileName] = new List <FileInformation>();
                    }
                    sourceFiles[fileName].Add(info);

                    if (info.Hash != null)
                    {
                        var hash = BitConverter.ToString(info.Hash);
                        if (!sourceHashes.ContainsKey(hash))
                        {
                            sourceHashes[hash] = new List <FileInformation>();
                        }
                        sourceHashes[hash].Add(info);
                    }
                }

                var targetPaths  = new Dictionary <Path, FileInformation>();
                var targetFiles  = new Dictionary <Path, List <FileInformation> >();
                var targetHashes = new Dictionary <string, List <FileInformation> >();
                foreach (var info in targetSnapshot.Files)
                {
                    targetPaths[info.Path] = info;

                    Path fileName = Path.GetFileName(info.Path);
                    if (!targetFiles.ContainsKey(fileName))
                    {
                        targetFiles[fileName] = new List <FileInformation>();
                    }
                    targetFiles[fileName].Add(info);

                    if (info.Hash != null)
                    {
                        var hash = BitConverter.ToString(info.Hash);
                        if (!targetHashes.ContainsKey(hash))
                        {
                            targetHashes[hash] = new List <FileInformation>();
                        }
                        targetHashes[hash].Add(info);
                    }
                }

                #endregion

                #region Package Content Generation

                progressHandler?.Invoke(this, new ProgressChangedEventArgs(0, progressStatus));

                // TODO: no good way to get regular progress callbacks from all patchers so just count files processed instead for now
                int processedCount = 0;

                Parallel.ForEach(targetSnapshot.Files, file =>
                {
                    Path sourceFilePath  = Path.Combine(sourcePath, file.Path);
                    Path targetFilePath  = Path.Combine(targetPath, file.Path);
                    bool sourcePathMatch = sourcePaths.ContainsKey(file.Path);

                    // only applicable for files
                    string hash                = !file.Path.IsDirectory && file.Hash != null ? BitConverter.ToString(file.Hash) : null;
                    bool sourceHashMatch       = !file.Path.IsDirectory && file.Hash != null ? sourceHashes.ContainsKey(hash) : false;
                    bool sourceHashSingleMatch = !file.Path.IsDirectory && (sourceHashMatch && sourceHashes[hash].Count == 1);
                    bool targetHashSingleMatch = !file.Path.IsDirectory && file.Hash != null ? targetHashes[hash].Count == 1 : false;

                    // unchanged empty directory
                    if (file.Path.IsDirectory & sourcePathMatch)
                    {
                        // do nothing
                    }

                    // added empty directory
                    else if (file.Path.IsDirectory && !sourcePathMatch)
                    {
                        lock (((ICollection)Actions).SyncRoot)
                        {
                            Actions.Add(new AddAction(file.Path));
                        }
                    }

                    // search for added optional files (target file with a null hash)
                    else if (!file.Path.IsDirectory && file.Hash == null)
                    {
                        var content = new Content(targetFilePath, packagePath, pkgSettings);

                        lock (((ICollection)Actions).SyncRoot)
                        {
                            Actions.Add(new AddAction(file.Path, content, false, true));
                        }
                    }

                    // unchanged file
                    else if (!file.Path.IsDirectory && sourcePathMatch && sourceHashMatch)
                    {
                        // do nothing
                    }

                    // changed files (same path, different hash)
                    else if (!file.Path.IsDirectory && sourcePathMatch && !sourceHashMatch)
                    {
                        Path tempDeltaFile = Utility.GetTempFilePath();

                        try
                        {
                            // patches should already be compressed, no need to do so again
                            PackageSettings pkgSettingsCopy    = (PackageSettings)pkgSettings.Clone(); // deep clone for thread safety
                            pkgSettingsCopy.CompressionEnabled = false;

                            // generate delta patch to temp location and generate content
                            Utility.GetPatcher(pkgSettingsCopy.PatchAlgorithmType).Create(sourceFilePath, targetFilePath, tempDeltaFile);
                            var content = new Content(tempDeltaFile, packagePath, pkgSettingsCopy);
                            lock (((ICollection)Actions).SyncRoot)
                            {
                                Actions.Add(new PatchAction(file.Path, file.Path, pkgSettingsCopy.PatchAlgorithmType, content));
                            }
                        }
                        finally
                        {
                            File.Delete(tempDeltaFile);
                        }
                    }

                    // moved files (different path, single hash match on both sides)
                    else if (!file.Path.IsDirectory && !sourcePathMatch && sourceHashSingleMatch && targetHashSingleMatch)
                    {
                        lock (((ICollection)Actions).SyncRoot)
                        {
                            Actions.Add(new MoveAction(sourceHashes[hash][0].Path, file.Path));
                        }
                    }

                    // search for copied files (multiple hash matches, different paths)
                    else if (!file.Path.IsDirectory && !sourcePathMatch && sourceHashMatch)
                    {
                        lock (((ICollection)Actions).SyncRoot)
                        {
                            Actions.Add(new CopyAction(sourceHashes[hash][0].Path, file.Path));
                        }
                    }

                    // search for added files (path and hash that exists in target but not source)
                    else if (!file.Path.IsDirectory && !sourcePathMatch && !sourceHashMatch)
                    {
                        var content = new Content(targetFilePath, packagePath, pkgSettings);

                        lock (((ICollection)Actions).SyncRoot)
                        {
                            Actions.Add(new AddAction(file.Path, content));
                        }
                    }

                    else
                    {
                        throw new InvalidOperationException("File action not found.");
                    }

                    // propagate current progress upstream
                    int count = Interlocked.Increment(ref processedCount);
                    int progressPercentage = (int)(count / (float)targetSnapshot.Files.Count * 100);
                    progressHandler?.Invoke(this, new ProgressChangedEventArgs(progressPercentage, progressStatus));
                });

                // deleted files & directories (path that exists in source but not target)
                foreach (var file in sourceSnapshot.Files)
                {
                    if (!targetPaths.ContainsKey(file.Path))
                    {
                        Actions.Add(new RemoveAction(file.Path, true));
                    }
                }

                // TODO: handle empty directory deletions caused by files getting deleted within
                // loop through destination directories and delete any that don't exist in source

                // TODO: handle file/directory renames that consist of case-changes only
                // loop through all files (should be 1:1 now) and rename if case mismatches (implies underlying directories are also renamed where applicable)

                #endregion
            }
            catch (Exception ex)
            {
                Directory.Delete(packagePath, true);
            }
        }
Example #37
0
 public SaveWorker(ProgressChangedEventHandler progressChanged, RunWorkerCompletedEventHandler completed)
     : base(progressChanged, completed)
 {
 }
 //monitor only, independent of button state; stops on cancel only
 public StylusAcquisition(PolhemusController controller, Monitor monitor)
 {
     if (controller == null) throw new ArgumentNullException("controller");
     if (monitor == null) throw new ArgumentNullException("monitor");
     _controller = controller;
     _monitor = monitor;
     _continuousMode = true;
     initialization();
     ProgressChanged += new ProgressChangedEventHandler(sa_StylusProgressChanged);
 }
Example #39
0
 private static void GoReports(NSLinq2SQL.IPRDEV sqledc, ArchiveSettings settings, ProgressChangedEventHandler progress)
 {
     progress(null, new ProgressChangedEventArgs(1, String.Format("Starting Reports archive - {0} delay. It could take several minutes", settings.ReportsArchivalDelay)));
     progress(null, new ProgressChangedEventArgs(1, "Buffering JSOXLib and IPR entries"));
     using (NSSPLinq.Entities _spedc = new NSSPLinq.Entities(settings.SiteURL))
     {
         List <NSSPLinq.JSOXLib> _2DeleteJSOXLib = _spedc.JSOXLibrary.ToList <NSSPLinq.JSOXLib>().Where <NSSPLinq.JSOXLib>(x => x.SituationDate.IsLatter(settings.ReportsArchivalDelay)).ToList <NSSPLinq.JSOXLib>();
         foreach (NSSPLinq.JSOXLib _jsoxlx in _2DeleteJSOXLib)
         {
             bool _any = false;
             foreach (NSSPLinq.JSOXCustomsSummary _jcsx in _jsoxlx.JSOXCustomsSummary)
             {
                 if (_jcsx.Disposal.Count != 0)
                 {
                     _any = true;
                     break;
                 }
             }
             if (_any)
             {
                 continue;
             }
             //Start deleting procedure of this branch of lists
             //delete StockEntry
             List <NSSPLinq.StockEntry> _2deleteStockEntry = new List <NSSPLinq.StockEntry>();
             foreach (NSSPLinq.StockLib _slx in _jsoxlx.StockLib)
             {
                 _2deleteStockEntry.AddRange(_slx.StockEntry);
             }
             if (_jsoxlx.BalanceIPR.Count + _jsoxlx.BalanceBatch.Count + _jsoxlx.JSOXCustomsSummary.Count + _2deleteStockEntry.Count == 0)
             {
                 continue;
             }
             String _mstTmp = "The selected {0} JSOXLib report related list are to be deleted: {1} BalanceIPR, {2} BalanceBatch, {3} JSOXCustomsSummary, and {4} StockEntry  entries are to be deleted.";
             progress(null, new ProgressChangedEventArgs(1, String.Format(_mstTmp, _jsoxlx.Title, _jsoxlx.BalanceIPR.Count, _jsoxlx.BalanceBatch.Count, _jsoxlx.JSOXCustomsSummary.Count, _2deleteStockEntry.Count)));
             _spedc.BalanceIPR.Delete <NSSPLinq.BalanceIPR, NSLinq2SQL.History>
                 (_jsoxlx.BalanceIPR, null, x => sqledc.BalanceIPR.GetAt <NSLinq2SQL.BalanceIPR>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                 settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
             _spedc.BalanceBatch.Delete <NSSPLinq.BalanceBatch, NSLinq2SQL.History>
                 (_jsoxlx.BalanceBatch, null, x => sqledc.BalanceBatch.GetAt <NSLinq2SQL.BalanceBatch>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                 settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
             _spedc.JSOXCustomsSummary.Delete <NSSPLinq.JSOXCustomsSummary, NSLinq2SQL.History>
                 (_jsoxlx.JSOXCustomsSummary, null, x => sqledc.JSOXCustomsSummary.GetAt <NSLinq2SQL.JSOXCustomsSummary>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                 settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
             _spedc.StockEntry.Delete <NSSPLinq.StockEntry, NSLinq2SQL.History>
                 (_2deleteStockEntry, null, x => sqledc.StockEntry.GetAt <NSLinq2SQL.StockEntry>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
                 settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
             Link2SQLExtensions.SubmitChanges(_spedc, sqledc, progress);
         }
     }
     progress(null, new ProgressChangedEventArgs(1, "Finished Archive Reports"));
 }
Example #40
0
 public void startSSHD(ProgressChangedEventHandler progressChangedEventHandler, Action <string> dataHandler)
 {
     dataReceivedEventHandler = dataHandler;
     worker.ProgressChanged  += progressChangedEventHandler;
     worker.RunWorkerAsync();
 }
Example #41
0
 private static void GoBatch(NSLinq2SQL.IPRDEV sqledc, ArchiveSettings settings, ProgressChangedEventHandler progress)
 {
     progress(null, new ProgressChangedEventArgs(1, String.Format("Starting Batch archive - {0} delay. It could take several minutes", settings.ArchiveBatchDelay)));
     progress(null, new ProgressChangedEventArgs(1, "Buffering Material entries"));
     using (NSSPLinq.Entities spedc = new NSSPLinq.Entities(settings.SiteURL))
     {
         List <NSSPLinq.Material> _mtrl               = spedc.Material.ToList <NSSPLinq.Material>();
         int _batchArchived                           = 0;
         int _progressBatchArchived                   = 0;
         int _materialArchived                        = 0;
         List <NSSPLinq.Batch>    _allBtchs           = spedc.Batch.ToList <NSSPLinq.Batch>();
         List <NSSPLinq.Batch>    _2BeDeletedBatch    = new List <NSSPLinq.Batch>();
         List <NSSPLinq.Material> _2BeDeletedMaterial = new List <NSSPLinq.Material>();
         foreach (NSSPLinq.Batch _noCig in _allBtchs.Where <NSSPLinq.Batch>(x => x.ProductType.Value != NSSPLinq.ProductType.Cigarette))
         {
             if (_noCig.StockEntry.Count > 0)
             {
                 continue;
             }
             _2BeDeletedBatch.Add(_noCig);
             _2BeDeletedMaterial.AddRange(_noCig.Material);
         }
         string _msg = String.Format("There are {0} Batch and {1} Material entries for no cigarette to be deleted.", _2BeDeletedBatch.Count, _2BeDeletedMaterial.Count);
         progress(null, new ProgressChangedEventArgs(1, _msg));
         IEnumerable <NSSPLinq.Batch> _allBtchCig = _allBtchs.Where <NSSPLinq.Batch>(x => x.ProductType.Value == NSSPLinq.ProductType.Cigarette);
         Dictionary <string, IGrouping <string, NSSPLinq.Batch> > _progressBatch = (from _fbx in _allBtchCig where _fbx.BatchStatus.Value == NSSPLinq.BatchStatus.Progress group _fbx by _fbx.Batch0).ToDictionary(x => x.Key);
         List <NSSPLinq.Batch> _noProgressBatch = (from _fbx in _allBtchCig where _fbx.BatchStatus.Value == NSSPLinq.BatchStatus.Final || _fbx.BatchStatus.Value == NSSPLinq.BatchStatus.Intermediate select _fbx).ToList <NSSPLinq.Batch>();
         _msg = String.Format("There are {0} Progress and {1} not Progress Batch entries for cigarette", _progressBatch.Count, _noProgressBatch.Count);
         progress(null, new ProgressChangedEventArgs(1, _msg));
         foreach (NSSPLinq.Batch _batchX in _noProgressBatch)
         {
             //Deleting progress batches
             if (_progressBatch.Keys.Contains(_batchX.Batch0))
             {
                 Debug.Assert(_batchX.BatchStatus.Value != NSSPLinq.BatchStatus.Progress, "Wrong BatchStatus should be != BatchStatus.Progress");
                 foreach (NSSPLinq.Batch _bpx in _progressBatch[_batchX.Batch0])
                 {
                     Debug.Assert(_bpx.BatchStatus.Value == NSSPLinq.BatchStatus.Progress, "Wrong BatchStatus should be == BatchStatus.Progress");
                     _2BeDeletedBatch.Add(_bpx);
                     _progressBatchArchived++;
                     foreach (NSSPLinq.Material _mpx in _bpx.Material)
                     {
                         Debug.Assert(_mpx.Material2BatchIndex == _bpx, "Wrong Material to Batch link");
                         _materialArchived++;
                         _2BeDeletedMaterial.Add(_mpx);
                     }
                 }
             } //foreach (Batch _batchX ....
             if ((_batchX.FGQuantityAvailable > 0) || (_batchX.BatchStatus.Value == NSSPLinq.BatchStatus.Intermediate))
             {
                 continue;
             }
             Debug.Assert(_batchX.ProductType.Value == NSSPLinq.ProductType.Cigarette);
             bool _2archive = true;
             foreach (NSSPLinq.Material _material in _batchX.Material)
             {
                 if (_material.Disposal.Count > 0)
                 {
                     _2archive = false;
                     break;
                 }
             } // foreach (Material
             if (_2archive)
             {
                 _materialArchived += _batchX.Material.Count;
                 _2BeDeletedMaterial.AddRange(_batchX.Material);
                 if (_batchX.Modified.IsLatter(settings.ArchiveBatchDelay) && _batchX.InvoiceContent.Count == 0 && _batchX.StockEntry.Count == 0 && _batchX.Disposal.Count == 0)
                 {
                     _batchArchived++;
                     _2BeDeletedBatch.Add(_batchX);
                 }
             }
         }// foreach (Batch
         progress(null, new ProgressChangedEventArgs(1, String.Format("The selected {0} Batch final, {1} Batch progress and {2} Material entries are to be deleted.", _batchArchived, _progressBatchArchived, _materialArchived)));
         spedc.Material.Delete <NSSPLinq.Material, NSLinq2SQL.History>
             (_2BeDeletedMaterial, null, x => sqledc.Material.GetAt <NSLinq2SQL.Material>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
             settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
         spedc.Batch.Delete <NSSPLinq.Batch, NSLinq2SQL.History>
             (_2BeDeletedBatch, null, x => sqledc.Batch.GetAt <NSLinq2SQL.Batch>(x), (id, listName) => sqledc.ArchivingLogs.AddLog(id, listName, Extensions.UserName()),
             settings.SiteURL, x => sqledc.History.AddHistoryEntry(x));
         Link2SQLExtensions.SubmitChanges(spedc, sqledc, progress);
     }
     progress(null, new ProgressChangedEventArgs(1, "Finished archival of the Batch and Material lists"));
 }
Example #42
0
 public static void Run(DoWorkEventHandler doWork, ProgressChangedEventHandler progressChanged, RunWorkerCompletedEventHandler runWorkerCompleted)
 {
     Run(doWork, progressChanged, runWorkerCompleted, null);
 }
Example #43
0
		public BackgroundTask(bool runOnUIThread, int runDelay, DoWorkEventHandler doWork, RunWorkerCompletedEventHandler runWorkerCompleted, ProgressChangedEventHandler progressChanged)
			: this(runOnUIThread, runDelay, doWork, runWorkerCompleted)
		{
			if (progressChanged != null)
				base.ProgressChanged += progressChanged;
		}
Example #44
0
        /// <summary>
        /// Get movement samples from the specified image area
        /// </summary>
        /// <param name="x">Position of the upper left corner of the area on the x axis</param>
        /// <param name="y">Position of the upper left corner on of the area the y axis</param>
        /// <param name="width">Width of the area</param>
        /// <param name="height">Height of the area</param>
        /// <param name="maxCycles">Number of cycles to run</param>
        /// <param name="getImg">A delegate returning images to process</param>
        /// <param name="progEv">A delegate specifying code to run when progress of learning changes</param>
        /// <param name="complEv">A delegate specifying code to run when learning is complete</param>
        public void Learn(int x, int y, int width, int height, int maxCycles, Func<Bitmap> getImg, ProgressChangedEventHandler progEv,
            RunWorkerCompletedEventHandler complEv)
        {
            if (samples != null)
            {
                foreach(Bitmap b in samples)
                {
                    b.Dispose();
                }
            }

            ResizeBilinear resize = new ResizeBilinear(70, (int)(70 * ((float)height / width)));
            BackgroundWorker bw = new BackgroundWorker();
            samples = new Bitmap[maxCycles, 10];
            Crop cropFilter;
            Mirror mirror = new Mirror(false,true);
            HomogenityEdgeDetector edgeDetector = new HomogenityEdgeDetector();

            // this allows our worker to report progress during work
            bw.WorkerReportsProgress = true;

            // what to do in the background thread
            bw.DoWork += new DoWorkEventHandler(
            delegate(object o, DoWorkEventArgs args)
            {
                BackgroundWorker b = o as BackgroundWorker;
                //Bitmap img;
                int xSize = 0, ySize = 0;
                int numImages = 0;
                for (int learningPoints = 0; learningPoints < maxCycles; learningPoints++)
                {
                    b.ReportProgress((100 / maxCycles) * learningPoints);
                    for (int tutorialBox = 0; tutorialBox < 100; tutorialBox++)
                    {
                        if (tutorialBox % 10 == 0)
                        {
                            numImages += 1;
                            b.ReportProgress((100 / maxCycles) * learningPoints + (tutorialBox / maxCycles));
                            cropFilter = new Crop(new Rectangle(x - tutorialBox, y, width, height));
                            //img = resize.Apply(maxBlobFilter.Apply(cropFilter.Apply(getImg())));
                            xSize += width;
                            ySize += height;
                            samples[learningPoints, tutorialBox / 10] = resize.Apply(mirror.Apply(cropFilter.Apply(getImg())));
                            samples[learningPoints, tutorialBox / 10].Save("sample" + tutorialBox / 10 + ".bmp");
                        }
                        System.Threading.Thread.Sleep(15);
                    }
                }
                avgSize.x = (float)xSize / numImages;
                avgSize.y = (float)ySize / numImages;
                avgAspectRatio = (float)xSize / ySize;
                b.ReportProgress(100);
                args.Result = samples;
            });

            // what to do when progress changed (update the progress bar for example)
            bw.ProgressChanged += progEv;

            // what to do when worker completes its task (notify the user)
            bw.RunWorkerCompleted += complEv;

            bw.RunWorkerAsync();

        }
Example #45
0
        public static void Run(DoWorkEventHandler doWork, ProgressChangedEventHandler progressChanged, RunWorkerCompletedEventHandler runWorkerCompleted, object argument, bool forceEndOnGUIThread = false)
        {
            var bw = new BackgroundWorker
            {
                WorkerSupportsCancellation = true,
                WorkerReportsProgress      = true
            };

            if (!IsEnabled)
            {
                var       doWorkArgs = new DoWorkEventArgs(null);
                Exception error      = null;
                try
                {
                    doWork(bw, doWorkArgs);
                }
                catch (Exception ex)
                {
                    error = ex;
                }

                var runWorkerCompletedArgs = new RunWorkerCompletedEventArgs(doWorkArgs.Result, error, doWorkArgs.Cancel);
                runWorkerCompleted(bw, runWorkerCompletedArgs);
                return;
            }

            if (doWork != null)
            {
                bw.DoWork += doWork;
            }

            if (progressChanged != null)
            {
                bw.ProgressChanged += progressChanged;
            }

            if (runWorkerCompleted != null)
            {
                bw.RunWorkerCompleted += (sender, e) =>
                {
                    Action complete = () =>
                    {
                        try
                        {
                            runWorkerCompleted(sender, e);
                        }
                        finally
                        {
                            RaiseOnAsyncEnd();
                        }
                    };

                    if (forceEndOnGUIThread)
                    {
                        OnGUI(complete);
                    }
                    else
                    {
                        complete();
                    }
                }
            }
            ;

            RaiseOnAsyncStart();

            if (argument != null)
            {
                bw.RunWorkerAsync(argument);
            }
            else
            {
                bw.RunWorkerAsync();
            }
        }
Example #46
0
 public virtual Task CopyAsync(FileSystemStorageFolder Directory, ProgressChangedEventHandler ProgressHandler = null)
 {
     return(CopyAsync(Directory.Path, ProgressHandler));
 }
Example #47
0
		public BackgroundTask(FrameworkElement optionalRunAsElement, int runDelay, DoWorkEventHandler doWork, RunWorkerCompletedEventHandler runWorkerCompleted, ProgressChangedEventHandler progressChanged)
			: this(optionalRunAsElement, runDelay, doWork, runWorkerCompleted)
		{
			if (progressChanged != null)
				m_worker.ProgressChanged += progressChanged;
		}
Example #48
0
 public void AddProgressChanged(ProgressChangedEventHandler eh)
 {
     mBw.ProgressChanged      += eh;
     mBw.WorkerReportsProgress = true;
 }
        public static async Task <LocationHistory> ExtractJsonAsync(MemoryStream memoryStream, ProgressChangedEventHandler callback)
        {
            using (var zip = new ZipArchive(memoryStream, ZipArchiveMode.Read))
            {
                foreach (var entry in zip.Entries)
                {
                    if (Path.GetExtension(entry.Name) != ".json" || !Names.Contains(Path.GetFileNameWithoutExtension(entry.Name)))
                    {
                        continue;
                    }

                    using (Stream stream = entry.Open())
                    {
                        using (ContainerStream containerStream = new ContainerStream(stream))
                        {
                            containerStream.ProgressChanged += callback;

                            using (StreamReader streamReader = new StreamReader(containerStream))
                            {
                                var jilOptions = new Options(excludeNulls: true);
                                return(await Task.Run(() => JSON.Deserialize <LocationHistory>(streamReader, jilOptions)));
                            }
                        }
                    }
                }
            }

            throw new Exception("Архив не содержит файла с историей местоположений");
        }
        /// <summary>
        /// Executes code on the background thread.
        /// </summary>
        /// <param name="backgroundAction">The background action.</param>
        /// <param name="uiCallback">The UI callback.</param>
        /// <param name="progressChanged">The progress change callback.</param>
        public IBackgroundTask ExecuteOnBackgroundThread(Action backgroundAction, RunWorkerCompletedEventHandler uiCallback, ProgressChangedEventHandler progressChanged)
        {
            var task = new BackgroundTask(
                () => {
                backgroundAction();
                return(null);
            });

            if (uiCallback != null)
            {
                task.Completed += (s, e) => ExecuteOnUIThread(() => uiCallback(s, e));
            }

            if (progressChanged != null)
            {
                task.ProgressChanged += (s, e) => ExecuteOnUIThread(() => progressChanged(s, e));
            }

            task.Start(null);

            return(task);
        }
        public async Task <List <CheckPoint> > ParseLocationHistoryAsync(LocationHistory locationHistory, QueryRequest model, ProgressChangedEventHandler callback)
        {
            var locations         = BorderCrossingHelper.PrepareLocations(locationHistory, model.IntervalType);
            var filteredLocations = locations.Where(l => l.Date >= model.StartDate && l.Date <= model.EndDate).OrderBy(l => l.TimestampMsUnix).ToList();

            var currentLocation = filteredLocations.First();
            var currentCountry  = GetCountryName(currentLocation.Point);

            var i     = 0;
            var count = filteredLocations.Count();

            var checkPoints = new List <CheckPoint>
            {
                BorderCrossingHelper.LocationToCheckPoint(currentLocation, currentCountry)
            };

            foreach (var location in filteredLocations)
            {
                await Task.Run(() =>
                {
                    i++;
                    callback(this, new ProgressChangedEventArgs((int)(100.0 * i / count), null));

                    var countryName = GetCountryName(location.Point);
                    if (currentCountry == countryName)
                    {
                        currentLocation = location;
                        return;
                    }

                    var range      = locationHistory.Locations.Where(lh => lh.TimestampMsUnix >= currentLocation.TimestampMsUnix && lh.TimestampMsUnix <= location.TimestampMsUnix).ToList();
                    var checkPoint = BorderCrossingHelper.FindCheckPoint(range, currentLocation, currentCountry, location, countryName, GetCountryName);

                    checkPoints.Add(checkPoint);
                    currentCountry  = countryName;
                    currentLocation = location;
                });
            }

            var last = filteredLocations.Last();

            checkPoints.Add(BorderCrossingHelper.LocationToCheckPoint(last, GetCountryName(last.Point)));

            return(checkPoints);
        }
Example #52
0
        //========================================================================================
        // Methods
        //========================================================================================
        /// <summary>
        /// This is the worker method for the Librarian background thread.  It implements
        /// a continual loop waiting for scanning tasks to perform.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;

            while (!worker.CancellationPending)
            {
                scanner = queue.Dequeue();

                if (worker.CancellationPending)
                {
                    break;
                }

                if (watcher != null)
                {
                    // Disable the watcher while scanning is active.  This way we won't have
                    // file lock contentions or complex threading issues.
                    watcher.EnableRaisingEvents = false;
                }

                ProgressChangedEventHandler progressHandler =
                    new ProgressChangedEventHandler(DoScannerProgressChanged);

                scanner.ProgressChanged += progressHandler;

                worker.ReportProgress(10,
                    new ScanningProgress(ScannerState.Beginning, scanner.Name));

                try
                {
                    scanner.Execute();
                }
                catch (Exception exc)
                {
                    App.LogException(new SmartException(exc));
                }

                RemoveScanner(scanner);

                if (watcher != null)
                {
                    watcher.EnableRaisingEvents = true;
                }

                worker.ReportProgress(100,
                    new ScanningProgress(ScannerState.Completed, scanner.Name));

                lock (sync)
                {
                    scanner.ProgressChanged -= progressHandler;
                    scanner = null;
                }
            }
        }
        /// <summary>
        /// Processes a TSP and reports errors.
        /// </summary>
        /// <param name="file">File name of TSP being processed.</param>
        private void ProcessTsp(string file)
        {
            System.Diagnostics.Debug.WriteLine($"Loading TSP at path {file} ...\n");

            // Try convert text to TSP
            var success = Interface.TryTextToTsp(file, out var tsp);

            // If conversion was a success
            if (success)
            {
                // Print TSP info to debug console
                tsp.Print();

                // Update name of problem on graph
                this.problemName.Text = tsp.Name;

                // Create solver and event handlers
                Solver solver = null;
                ProgressChangedEventHandler    updateHandler     = null;
                RunWorkerCompletedEventHandler completionHandler = null;
                int drawDelay = 0;

                // Set solvers and event handlers based on the chosen setting
                if (bruteForceRadioButton.IsChecked == true)
                {
                    solver = new BruteForceSolver();

                    MessageBox.Show("Solution method not yet implemented after refactoring.");
                    return;
                }
                else if (bfsRadioButton.IsChecked == true || dfsRadioButton.IsChecked == true)
                {
                    var goal = Convert.ToInt32(searchGoal.Text);

                    if (bfsRadioButton.IsChecked == true)
                    {
                        solver = new BfsSolver();
                    }
                    else
                    {
                        solver = new DfsSolver();
                    }

                    MessageBox.Show("Solution method not yet implemented after refactoring.");
                    return;
                }
                else if (greedyRadioButton.IsChecked == true)
                {
                    solver            = new GreedySolver();
                    updateHandler     = GreedyProgressChanged;
                    completionHandler = GreedyCompletion;
                    drawDelay         = GREEDY_DRAW_DELAY;
                }
                else if (geneticRadioButton.IsChecked == true)
                {
                    solver            = new GeneticSolver();
                    updateHandler     = GeneticProgressChanged;
                    completionHandler = GreedyCompletion;
                    drawDelay         = GREEDY_DRAW_DELAY;
                }
                else
                {
                    MessageBox.Show("No solution method was selected.");
                    return;
                }

                if (progressCheckBox.IsChecked == true)
                {
                    // Update continously
                    solver.ProgressChanged += updateHandler;
                }
                else
                {
                    // Update only at the end
                    solver.RunWorkerCompleted += completionHandler;
                }

                var workerArgs = new Tuple <Tsp, int>(tsp, progressCheckBox.IsChecked == true ? drawDelay : 0);

                // Run solver and draw output
                solver.RunWorkerAsync(workerArgs);
            }
            // If conversion failed
            else
            {
                MessageBox.Show($"Could not convert TSP from text file: \n\n{file}");
            }
        }
        private static void Synchronize <TSQL, TSP>(Table <TSQL> sqlTable, EntityList <TSP> spList, ProgressChangedEventHandler progressChanged, Dictionary <string, string> mapping, bool port2210)
            where TSQL : class, SharePoint.Client.Link2SQL.IItem, INotifyPropertyChanged, new()
            where TSP : Linq.Item, ITrackEntityState, ITrackOriginalValues, INotifyPropertyChanged, INotifyPropertyChanging, new()
        {
            progressChanged(1, new ProgressChangedEventArgs(1, String.Format("Reading the table {0} from SharePoint website.", typeof(TSP).Name)));
            List <TSP> _scrList = spList.ToList <TSP>();

            progressChanged(1, new ProgressChangedEventArgs(1, String.Format("Reading the table {0} from SQL database.", typeof(TSQL).Name)));
            Dictionary <int, IItem> _dictinary = sqlTable.Where <TSQL>(x => !x.OnlySQL).ToDictionary <TSQL, int, IItem>(x => x.ID, y => (SharePoint.Client.Link2SQL.IItem)y);

            progressChanged(1, new ProgressChangedEventArgs(1, String.Format("Synchronization {0} elements in the SharePoint source tables with the {1} element in the SQL table.", _scrList.Count, _dictinary.Count)));
            //create descriptors using reflection
            Dictionary <string, StorageItemsList> _spDscrpt  = StorageItem.CreateStorageDescription(typeof(TSP));
            Dictionary <string, SQLStorageItem>   _sqlDscrpt = SQLStorageItem.CreateStorageDescription(typeof(TSQL), mapping);
            int           _archivalCount    = 0;
            int           _archivalCountOld = 0;
            int           _counter          = 0;
            int           _counterOld       = 0;
            int           _itemChanges      = 0;
            int           _itemChangesOld   = 0;
            bool          _itemChanged;
            Action <TSP>  _port    = x => { };
            List <string> _changes = new List <string>();

            if (port2210 && typeof(IArchival).IsAssignableFrom(typeof(TSP)))
            {
                _port = x => { ((IArchival)x).Archival = false; _archivalCount++; };
                progressChanged(1, new ProgressChangedEventArgs(1, "The table will be updated new software version"));
            }
            int _loopCounter = 0;

            foreach (TSP _spItem in _scrList)
            {
                _port(_spItem);
                SharePoint.Client.Link2SQL.IItem _sqlItem = default(SharePoint.Client.Link2SQL.IItem);
                if (!_dictinary.TryGetValue(_spItem.Id.Value, out _sqlItem))
                {
                    _sqlItem         = new TSQL();
                    _sqlItem.OnlySQL = false;
                    _dictinary.Add(_spItem.Id.Value, _sqlItem);
                    sqlTable.InsertOnSubmit((TSQL)_sqlItem);
                }
                Microsoft.SharePoint.Linq.ContentTypeAttribute _attr = _spItem.GetType().GetContentType();
                _itemChanged = false;
                Synchronize <TSQL, TSP>(
                    (TSQL)_sqlItem,
                    _spItem, _spDscrpt[_attr.Id],
                    _sqlDscrpt, progressChanged,
                    spList.DataContext,
                    (x, y) =>
                {
                    _counter++;
                    _changes.Add(y.PropertyName);
                    _itemChanged = true;
                });
                if (_itemChanged)
                {
                    _itemChanges++;
                }
                _loopCounter++;
                if (_loopCounter > 10000)
                {
                    progressChanged(1, new ProgressChangedEventArgs(1, String.Format("Intermediate: submitting {0} changes on {1} list rows to SQL database", _counter - _counterOld, _itemChanges - _itemChangesOld)));
                    sqlTable.Context.SubmitChanges();
                    if (_archivalCount > 0)
                    {
                        progressChanged(1, new ProgressChangedEventArgs(1, String.Format("Intermediate: update to Rel 2.10 Submitting {0} Archival bit changes", _archivalCount - _archivalCountOld)));
                        spList.DataContext.SubmitChanges();
                    }
                    _loopCounter    = 0;
                    _counterOld     = _counter;
                    _itemChangesOld = _itemChanges;
                }
            }
            progressChanged(1, new ProgressChangedEventArgs(1, String.Format("Submitting total {0} changes on {1} list rows to SQL database", _counter, _itemChanges)));
            sqlTable.Context.SubmitChanges();
            if (_archivalCount > 0)
            {
                progressChanged(1, new ProgressChangedEventArgs(1, String.Format("Update to Rel 2.10 Submitting total {0} Archival bit changes", _archivalCount)));
                spList.DataContext.SubmitChanges();
            }
        }
 /// <summary>
 /// Called when an operation reports progress.
 /// </summary>
 /// <param name="asyncWorker">The async worker.</param>
 /// <param name="worker">The worker.</param>
 /// <param name="progress">The progress.</param>
 /// <param name="userState">State of the user.</param>
 public void ReportProgress(AsyncWorker asyncWorker, DoWorkEventHandler worker, ProgressChangedEventHandler progress, object userState)
 {
     if (this.log.IsInfoEnabled)
     {
         this.log.Info(string.Format(
                      CultureInfo.InvariantCulture,
                      "{0} reports progress for operation {1}.{2}()",
                      asyncWorker,
                      worker.Method.DeclaringType.FullName,
                      worker.Method.Name));
     }
 }
Example #56
0
 /// <summary>
 /// Executes the backgroundAction on a background thread.
 /// </summary>
 /// <param name="backgroundAction">The action.</param>
 /// <param name="uiCallback">The UI callback.</param>
 /// <param name="progressChanged">The progress change callback.</param>
 public static IBackgroundTask OnBackgroundThread(Action backgroundAction, RunWorkerCompletedEventHandler uiCallback, ProgressChangedEventHandler progressChanged)
 {
     return(dispatcher.ExecuteOnBackgroundThread(backgroundAction, uiCallback, progressChanged));
 }
Example #57
0
        //TODO: will need to disable multi-threaded processing of actions during application if specified
        //[JsonProperty(Required = Required.Default)]
        //public bool PreserveActionOrder { get; set; }

        // TODO: when order is not important, perform multi-threaded execution in order of biggest to smallest
        /// <summary>
        /// Applies package actions in-order against the target directory using the contents of the package directory.
        /// </summary>
        /// <param name="packageDirectory">The package contents directory.</param>
        /// <param name="targetDirectory">The target base directory.</param>
        /// <param name="validateBefore">Indicates whether or not the target directory should be validated before package application.</param>
        /// <param name="validateAfter">Indicates whether or not the target directory should be validated after package application.</param>
        /// <param name="progressHandler">The optional handler to report progress to.</param>
        /// <param name="progressStatus">The optional progress status description.</param>
        public void Apply(Path packageDirectory, Path targetDirectory, bool validateBefore = true, bool validateAfter = true, ProgressChangedEventHandler progressHandler = null, string progressStatus = null)
        {
            // validate source content
            if (validateBefore)
            {
                Logger?.Info("Validating package source content");
            }
            if (validateBefore && !new Snapshot(targetDirectory, progressHandler, "Validating source content").Contains(SourceSnapshot))
            {
                throw new DataException("Directory contents do not match the source snapshot.");
            }

            // create temporary directory to contain target backup in case of rollback
            Path backupDirectory = Utility.GetTempDirectory();

            int processedCount = 0;

            // TODO: verify backup/rollback logic
            try
            {
                const string backupStepName = "Performing backup";
                progressHandler?.Invoke(this, new ProgressChangedEventArgs(0, backupStepName));

                // backup content to be modified, skipping NoAction types
                foreach (var action in Actions.Where(a => !(a is NoAction)))
                {
                    Path targetPath = Path.Combine(targetDirectory, action.TargetPath);
                    if (File.Exists(targetPath))
                    {
                        Path backupPath = Path.Combine(backupDirectory, action.TargetPath);
                        Directory.CreateDirectory(Path.GetDirectoryName(backupPath));
                        File.Copy(targetPath, backupPath, true);
                    }

                    // propagate current progress upstream
                    processedCount++;
                    int progressPercentage = (int)(processedCount / (float)Actions.Count * 100);
                    progressHandler?.Invoke(this, new ProgressChangedEventArgs(progressPercentage, backupStepName));
                }

                progressHandler?.Invoke(this, new ProgressChangedEventArgs(0, progressStatus));

                // apply the actions in-order
                processedCount = 0;
                foreach (var action in Actions)
                {
                    action.Run(new ActionContext(targetDirectory, packageDirectory));

                    // propagate current progress upstream
                    processedCount++;
                    int progressPercentage = (int)(processedCount / (float)Actions.Count * 100);
                    progressHandler?.Invoke(this, new ProgressChangedEventArgs(progressPercentage, progressStatus));
                }

                // TODO: selective file validation fed from list of changed files after patch application
                // validate modified content
                if (validateAfter)
                {
                    Logger?.Info("Validating package output content");
                }
                if (validateAfter && !new Snapshot(targetDirectory, progressHandler, "Validating output").Contains(TargetSnapshot))
                {
                    throw new DataException("Directory contents do not match the target snapshot.");
                }
            }
            catch (Exception ex)
            {
                Logger?.Error(ex, "Performing rollback.");

                const string rollbackStepName = "Performing rollback";
                progressHandler?.Invoke(this, new ProgressChangedEventArgs(0, rollbackStepName));
                processedCount = 0;

                // if failure is detected, delete any existing targets and restore any backups
                foreach (var action in Actions.Where(a => !(a is NoAction)))
                {
                    // log any failures encountered during the rollback, keep chugging through regardless
                    try
                    {
                        File.Delete(Path.Combine(targetDirectory, action.TargetPath));
                        Path backupPath = Path.Combine(backupDirectory, action.TargetPath);
                        if (File.Exists(backupPath))
                        {
                            File.Copy(backupPath, Path.Combine(targetDirectory, action.TargetPath), true);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger?.Warn(e, "Unknown package restore failure.");
                    }

                    // propagate current progress upstream
                    processedCount++;
                    int progressPercentage = (int)(processedCount / (float)Actions.Count * 100);
                    progressHandler?.Invoke(this, new ProgressChangedEventArgs(progressPercentage, rollbackStepName));
                }

                // re-throw the original exception
                throw;
            }
            finally
            {
                Directory.Delete(backupDirectory, true);
            }

            // TODO: remove empty directories or leave that up to the package actions?
        }
Example #58
0
 /// <summary>
 /// Executes the backgroundAction on a background thread.
 /// </summary>
 /// <param name="backgroundAction">The action.</param>
 /// <param name="progressChanged">The progress change callback.</param>
 public static IBackgroundTask OnBackgroundThread(Action backgroundAction, ProgressChangedEventHandler progressChanged)
 {
     return(dispatcher.ExecuteOnBackgroundThread(backgroundAction, null, progressChanged));
 }
Example #59
0
        public static bool Move(IEnumerable <KeyValuePair <string, string> > Source, string DestinationPath, ProgressChangedEventHandler Progress, EventHandler <ShellFileOperations.ShellFileOpEventArgs> PostMoveEvent)
        {
            try
            {
                if (!Directory.Exists(DestinationPath))
                {
                    _ = Directory.CreateDirectory(DestinationPath);
                }

                using (ShellFileOperations Operation = new ShellFileOperations
                {
                    Options = ShellFileOperations.OperationFlags.AddUndoRecord | ShellFileOperations.OperationFlags.NoConfirmMkDir | ShellFileOperations.OperationFlags.Silent
                })
                {
                    Operation.UpdateProgress += Progress;
                    Operation.PostMoveItem   += PostMoveEvent;

                    foreach (KeyValuePair <string, string> SourceInfo in Source)
                    {
                        using (ShellItem SourceItem = new ShellItem(SourceInfo.Key))
                            using (ShellFolder DestItem = new ShellFolder(DestinationPath))
                            {
                                Operation.QueueMoveOperation(SourceItem, DestItem, string.IsNullOrEmpty(SourceInfo.Value) ? null : SourceInfo.Value);
                            }
                    }

                    Operation.PerformOperations();

                    Operation.PostMoveItem   -= PostMoveEvent;
                    Operation.UpdateProgress -= Progress;
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #60
0
            public IBackgroundTask ExecuteOnBackgroundThread(Action backgroundAction, RunWorkerCompletedEventHandler uiCallback, ProgressChangedEventHandler progressChanged)
            {
                var task = new ForegroundTask(backgroundAction);

                if (uiCallback != null)
                {
                    task.Completed += uiCallback;
                }

                if (progressChanged != null)
                {
                    task.ProgressChanged += progressChanged;
                }

                task.Start(null);

                return(task);
            }