Example #1
0
 /// <summary>
 /// Raises event 'Aborted'
 /// </summary>
 protected virtual void OnAborted()
 {
     if (Aborted != null)
     {
         Aborted.Invoke(this, System.EventArgs.Empty);
     }
 }
Example #2
0
        /// <summary>
        /// Aborts execution of this script.
        /// </summary>
        public void Abort()
        {
            IsRunning = false;

            waitEvent.Release();

            try
            {
                Aborted?.Invoke(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                ScriptDomain.HandleUnhandledException(this, new UnhandledExceptionEventArgs(ex, true));
            }

            if (thread != null)
            {
                thread.Abort(); thread = null;

                Log.Message(Log.Level.Info, "Aborted script ", Name, ".");
            }

            // Unregister any console commands attached to this script
            var console = AppDomain.CurrentDomain.GetData("Console") as Console;

            console?.UnregisterCommands(ScriptInstance.GetType());
        }
Example #3
0
        //private:
        void ThreadProc()
        {
            try
            {
                bool done = DoWork();
                State = JobState_t.Finished;

                if (done)
                {
                    Succeeded?.Invoke(this);
                }
                else
                {
                    Canceled?.Invoke(this);
                }
            }
            catch (Exception ex)
            {
                State = JobState_t.Finished;
                Aborted?.Invoke(this, ex);
            }

            Aborted  = null;
            Canceled = Succeeded = null;
        }
Example #4
0
 protected void OnAbort(EventArgs e)
 {
     lock (_syncRoot)
     {
         Aborted?.Invoke(this, e);
     }
 }
        private bool StreamFile(HttpWebResponse fileresp, IDownloadable download)
        {
            bool succeeded = true;

            using (Stream dlstream = fileresp.GetResponseStream()) {
                FileStream outputStream;
                while (true)
                {
                    try {
                        outputStream = new FileStream(currentFilepath, FileMode.OpenOrCreate, FileAccess.Write);
                        break;
                    } catch (UnauthorizedAccessException e) {
                        DialogResult res = MessageBox.Show(
                            $"Couldn't get access to local file location at {currentFilepath}. Another program might be using it. Would you like to try again?",
                            "Download Error",
                            MessageBoxButtons.RetryCancel,
                            MessageBoxIcon.Error);
                        if (res == DialogResult.Cancel)
                        {
                            throw e;
                        }
                        Thread.Sleep(1000);
                    }
                }

                int buffersize = 10000;
                try {
                    long bytesRead = 0;
                    int  length    = 1;
                    while (length > 0)
                    {
                        byte[] buffer = new byte[buffersize];
                        length     = dlstream.Read(buffer, 0, buffersize);
                        bytesRead += length;
                        outputStream.Write(buffer, 0, length);
                        UpdateProgress(Convert.ToInt32(100F * bytesRead / fileresp.ContentLength));
                        UpdateProgressText(
                            $"Downloading {download} (Package {downloadQueue.IndexOf(download) + 1}/{downloadQueue.Count}) {bytesRead / 1048576}/{fileresp.ContentLength / 1048576} MB ({Convert.ToInt16(100 * (double)bytesRead / fileresp.ContentLength, Program.Culture)}%)...");
                    }
                } catch (WebException e) {
                    succeeded = false;
                    DialogResult res = MessageBox.Show(
                        "An error has occurred during your download. Please check your network connection and try again.\n" +
                        "If this error persists, please report this issue to the launcher's GitHub page. Click OK to copy the error details to your clipboard or CANCEL to ignore this message.",
                        "Download Error",
                        MessageBoxButtons.OKCancel,
                        MessageBoxIcon.Error);
                    if (res == DialogResult.OK)
                    {
                        Clipboard.SetText(e.ToString());
                    }
                    Aborted?.Invoke(this, new EventArgs());
                    CloseForm();
                } finally {
                    outputStream.Dispose();
                }
            }

            return(succeeded);
        }
Example #6
0
 /// <summary>
 ///     Aborts the thread, instantly stopping execution. If possible always try to cancel over abort
 /// </summary>
 public void Abort(object sender)
 {
     if (thread != null && thread.IsAlive)
     {
         thread?.Abort();
         Aborted?.Invoke(sender, new EventArgs());
     }
 }
Example #7
0
        /// <summary>
        /// Called on algorithm abort.
        /// </summary>
        /// <param name="args"><see cref="EventArgs.Empty"/>.</param>
        protected virtual void OnAborted([NotNull] EventArgs args)
        {
            if (args is null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            Aborted?.Invoke(this, args);
        }
Example #8
0
 public void Abort()
 {
     UnityEvents.Instance.StopCoroutine(ThreadState());
     if (Aborted != null)
     {
         Aborted.Invoke();
     }
     Clear();
 }
 private void DownloadForm_Disposed(object sender, EventArgs e)
 {
     if (dlThread.IsAlive)
     {
         dlThread.Abort();
         if (!finished)
         {
             Aborted?.Invoke(sender, new EventArgs());
         }
     }
 }
        /// <summary>
        /// Main download method.
        /// </summary>
        public void Download()
        {
            try {
                finished = true;
                foreach (IDownloadable download in downloadQueue)
                {
                    string source      = download.Location;
                    string destination = Path.Combine(Config.InstallPath, "Versions", download.ToString());
                    currentFilepath = $"{destination}.zip";

                    Program.Launcher.UpdateStatus($"Downloading {download}");
                    Directory.CreateDirectory(destination);

                    // Download
                    HttpWebResponse fileresp = GetResponse(download.Location);
                    if (fileresp.ContentLength <= 0)
                    {
                        MessageBox.Show($"Could not access file {download}. Package skipped.");
                        continue;
                    }

                    if (!StreamFile(fileresp, download))
                    {
                        finished = false;
                        MessageBox.Show("The download couldn't be completed. Check your internet connection. If you think this is a program error, please report this to the Launcher's GitHub page.");
                        break;
                    }

                    // Extraction
                    if (!ExtractDownload(download, destination))
                    {
                        continue;
                    }

                    // Patching
                    if (!PatchDownload(download, destination))
                    {
                        continue;
                    }
                }

                if (finished)
                {
                    QueueComplete?.Invoke(this, new EventArgs());
                }
            } catch (ThreadAbortException) { } catch (ThreadInterruptedException) { } catch (Exception e) {
                new ErrorCatcher(e).ShowDialog();
                Aborted?.Invoke(this, new EventArgs());
            }
        }
Example #11
0
 protected virtual void OnAborted(object sender, EventArgs e)
 {
     CrossThreadingHelpers.InvokeControl((Control)sender, null, (x) =>
     {
         if (backWorker.IsBusy && !backWorker.CancellationPending)
         {
             if (CanAbort)
             {
                 backWorker.CancelAsync();
                 ProgressBar1.Enabled = false;
                 Aborted?.Invoke(sender, e);
             }
         }
     });
 }
Example #12
0
        private void OnPrepareCompareValue(CancellationToken ct, int maxParallelism)
        {
            var comp = new FileComparison();
            ConcurrentDictionary <string, CompareValue> compare    = new ConcurrentDictionary <string, CompareValue>(CacheCompareValue);
            ConcurrentDictionary <string, CompareValue> newCompare = new ConcurrentDictionary <string, CompareValue>();
            int itemCounter = 0;

            PrepareCompareValuesProgress?.Invoke(this, 0);

            ParallelOptions po = new ParallelOptions
            {
                CancellationToken      = ct,
                MaxDegreeOfParallelism = maxParallelism
            };

            try
            {
                Parallel.For(0, Files.Count, po, (int index) =>
                {
                    itemCounter      += 1;
                    var progressValue = Math.Round(((decimal)itemCounter / (decimal)Files.Count * 100), 2);
                    PrepareCompareValuesProgress?.Invoke(this, progressValue);
                    string currentFile = Files[index]?.ToUpper();
                    if (!compare.ContainsKey(currentFile))
                    {
                        var compareValue = comp.CreateCompareValue(currentFile);
                        if (compareValue != null)
                        {
                            compare.GetOrAdd(currentFile, compareValue);
                            newCompare.GetOrAdd(currentFile, compareValue);
                        }
                    }
                    PrepareCompareValuesProgressWithItems?.Invoke(this, new PrepareComareProgressItem(progressValue, new Dictionary <string, CompareValue>(newCompare)));
                });
                PrepareCompareValuesProgress?.Invoke(this, 100);
                PrepareCompareValuesProgressWithItems?.Invoke(this, new PrepareComareProgressItem(100, new Dictionary <string, CompareValue>(newCompare)));
                CacheCompareValue = new Dictionary <string, CompareValue>(compare);
            }
            catch (Exception ex)
            {
                if (ex is AggregateException || ex is ObjectDisposedException || ex is OperationCanceledException)
                {
                    Aborted?.Invoke(this, EventArgs.Empty);
                    return;
                }
                throw;
            }
        }
Example #13
0
        //private:
        void ThreadProc()
        {
            try
            {
                DoWork();
                State = JobState_t.Finished;
                Succeeded?.Invoke(this);
            }
            catch (Exception ex)
            {
                State = JobState_t.Finished;
                Aborted?.Invoke(this, ex);
            }

            Aborted   = null;
            Succeeded = null;
        }
Example #14
0
        void CoreInvoke(bool beginInvokeBehavior)
        {
            Status = DispatcherOperationStatus.Executing;

            var oldSynchronizationContext = SynchronizationContext.Current;

            try
            {
                SynchronizationContext.SetSynchronizationContext(Dispatcher.DefaultSynchronizationContext);

                try
                {
                    if (method is Action action)
                    {
                        action();
                    }
                    else
                    {
                        Result = method.DynamicInvoke(args);
                    }
                }
                catch (Exception e)
                {
                    exception = e;
                }

                if (beginInvokeBehavior)
                {
                    if (exception is OperationCanceledException)
                    {
                        Status    = DispatcherOperationStatus.Aborted;
                        exception = null;
                        Aborted?.Invoke(this, EventArgs.Empty);
                    }
                    else
                    {
                        Status = DispatcherOperationStatus.Completed;
                        Completed?.Invoke(this, EventArgs.Empty);
                    }
                }
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(oldSynchronizationContext);
            }
        }
 public CoroutineBasedTimer Abort()
 {
     if (current != null)
     {
         target.StopCoroutine(current);
         current = null;
         if (Aborted != null)
         {
             Aborted.Invoke();
         }
         if (Ended != null)
         {
             Ended.Invoke();
         }
     }
     return(this);
 }
Example #16
0
        //private:
        void ThreadProc()
        {
            State = State_t.Running;

            try
            {
                DoWork();
                State = State_t.Finished;
                Succeeded?.Invoke(this);
            }
            catch (ThreadAbortException)
            {
                Thread.ResetAbort();
                State = State_t.Finished;
                Canceled?.Invoke(this);
            }
            catch (Exception ex)
            {
                State = State_t.Finished;
                Aborted?.Invoke(this, ex);
            }
        }
        private HttpWebResponse GetResponse(string source)
        {
            HttpWebRequest  filereq  = (HttpWebRequest)WebRequest.Create(new Uri(source));
            HttpWebResponse fileresp = null;

            try {
                fileresp = (HttpWebResponse)filereq.GetResponse();
                if (filereq.ContentLength > 0)
                {
                    fileresp.ContentLength = filereq.ContentLength;
                }
            } catch (WebException) {
                MessageBox.Show(
                    "Network exception encountered when trying to start your download. You might not have a connection to the internet," +
                    " or access to the download link is restricted. If you think tihs is a program error, please report it to the Launcher's GitHub page.");
                Aborted?.Invoke(this, new EventArgs());
                Downloading = false;
                CloseForm();
            }

            return(fileresp);
        }
Example #18
0
        /// <summary>
        /// Aborts execution of this script.
        /// </summary>
        public void Abort()
        {
            IsRunning = false;

            try
            {
                Aborted?.Invoke(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                ScriptDomain.HandleUnhandledException(this, new UnhandledExceptionEventArgs(ex, true));
            }

            waitEvent.Release();

            if (thread != null)
            {
                Log.Message(Log.Level.Warning, "Aborted script ", Name, ".");

                thread.Abort(); thread = null;
            }
        }
Example #19
0
        /// <summary>
        /// Aborts execution of this <see cref="Script"/>.
        /// </summary>
        public void Abort()
        {
            try
            {
                Aborted?.Invoke(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                ScriptDomain.HandleUnhandledException(this, new UnhandledExceptionEventArgs(ex, true));
            }

            _running = false;
            _waitEvent.Set();

            if (_thread != null)
            {
                _thread.Abort();
                _thread = null;

                ScriptDomain.OnAbortScript(this);
            }
        }
Example #20
0
 private void PerformOperation(Func <IOperation> setup)
 {
     try {
         if (_context.State != XModemStates.Idle)
         {
             throw new XModemProtocolException(new AbortedEventArgs(XModemAbortReason.StateNotIdle));
         }
         _context.State = XModemStates.Initializing;
         if (_context.Communicator is NullCommunicator)
         {
             throw new XModemProtocolException(new AbortedEventArgs(XModemAbortReason.CommunicatorIsNull));
         }
         IOperation operation = setup();
         if (OperationPending != null && OperationPending() == false)
         {
             throw new XModemProtocolException(new AbortedEventArgs(XModemAbortReason.CancelledByOperationPendingEvent));
         }
         _tokenSource   = new CancellationTokenSource();
         _context.Token = _tokenSource.Token;
         _context.Communicator.Flush();
         operation.Go(_context);
         Completed?.Invoke(this, new CompletedEventArgs(_context.Data));
     }
     catch (XModemProtocolException ex) {
         switch (ex.AbortArgs.Reason)
         {
         case XModemAbortReason.Cancelled:
         case XModemAbortReason.ConsecutiveNAKLimitExceeded:
             SendCancel();
             break;
         }
         Aborted?.Invoke(this, new AbortedEventArgs(ex.AbortArgs.Reason));
     }
     finally {
         _context.State = XModemStates.Idle;
     }
 }
Example #21
0
 private void OnAborted()
 {
     Aborted?.Invoke(this, EventArgs.Empty);
 }
 protected virtual void OnAborted(PrinterEventArgs e)
 {
     Aborted?.Invoke(this, e);
 }
Example #23
0
 private void OnAborted()
 {
     Aborted?.Invoke();
 }
Example #24
0
 protected void OnAborted(EventArgs e)
 {
     Aborted?.Invoke(this, e);
 }
Example #25
0
        public async Task <List <DuplicatesResult> > Find(int maxParallelism = 4)
        {
            var ts = new CancellationTokenSource();

            cancellationTokens.Add(ts);
            CancellationToken ct = ts.Token;

            try
            {
                return(await Task.Run(() =>
                {
                    PrepareCompareValues?.Invoke(this, false);
                    OnPrepareCompareValue(ct, maxParallelism);
                    PrepareCompareValues?.Invoke(this, true);
                    var result = new List <DuplicatesResult>();
                    ParallelOptions po = new ParallelOptions
                    {
                        CancellationToken = ct,
                        MaxDegreeOfParallelism = maxParallelism
                    };
                    try
                    {
                        int itemCounter = 0;
                        decimal progressValue = 0;
                        List <string> cacheIndexValues = new List <string>();
                        if (CacheDuplicateResult != null)
                        {
                            result = CacheDuplicateResult.DuplicatesResults;
                            cacheIndexValues = CacheDuplicateResult.IndexCollection;
                        }

                        Parallel.For(0, Files.Count, po, (int index) =>
                        {
                            string file = Files[index];
                            System.Diagnostics.Debug.Print($"INDEX => {index}");
                            if (!cacheIndexValues.Contains(file.ToUpper()))
                            {
                                if (itemCounter == 0)
                                {
                                    ProcessFileProgress?.Invoke(this, 0);
                                    ProcessFileProgressWithItems?.Invoke(this, new ProcessFileProgressItem(0, result, index, itemCounter, cacheIndexValues));
                                }

                                cacheIndexValues.Add(file.ToUpper());
                                ProcessFile?.Invoke(this, file);
                                var dup = OnCompareDuplicates(file, index);
                                if (dup != null)
                                {
                                    result.Add(dup);
                                }
                                var progressValue2 = Math.Round(((decimal)itemCounter / (decimal)Files.Count * 100), 2);
                                if (progressValue2 > progressValue)
                                {
                                    progressValue = progressValue2;
                                }
                                ProcessFileProgress?.Invoke(this, progressValue);
                                ProcessFileProgressWithItems?.Invoke(this, new ProcessFileProgressItem(progressValue, result, index, itemCounter, cacheIndexValues));
                            }
                            else
                            {
                                System.Diagnostics.Debug.Print($"Already collected File:{file}");
                            }
                            itemCounter++;
                        });
                        ProcessFileProgress?.Invoke(this, 100);
                        ProcessFileProgressWithItems?.Invoke(this, new ProcessFileProgressItem(100, result, -1, itemCounter, cacheIndexValues));
                    }
                    catch (Exception ex)
                    {
                        if (ex is AggregateException || ex is ObjectDisposedException || ex is OperationCanceledException)
                        {
                            Aborted?.Invoke(this, EventArgs.Empty);
                            return null;
                        }
                        throw;
                    }
                    cancellationTokens.Remove(ts);
                    return result;
                }, ct));
            }
            catch (Exception ex)
            {
                if (ex is AggregateException || ex is ObjectDisposedException || ex is OperationCanceledException)
                {
                    Aborted?.Invoke(this, EventArgs.Empty);
                    return(null);
                }
                throw;
            }
        }
Example #26
0
        /// <summary>
        /// Abort resource loading.
        /// </summary>
        protected virtual bool OnAbort(PartialResource res, Exception e)
        {
            Aborted?.Invoke(this, e);

            return(false);
        }
Example #27
0
 public void OnAborted(object sender, EventArgs e)
 {
     _moveThread?.Abort();
     Aborted?.Invoke(this, EventArgs.Empty);
 }
Example #28
0
        /// <summary>
        /// Called on algorithm abort.
        /// </summary>
        /// <param name="args"><see cref="EventArgs.Empty"/>.</param>
        protected virtual void OnAborted([NotNull] EventArgs args)
        {
            Debug.Assert(args != null);

            Aborted?.Invoke(this, args);
        }
Example #29
0
 /// <summary>
 /// Raises the <see cref="Aborted"/> event.
 /// </summary>
 /// <param name="e">The event arguments.</param>
 protected virtual void OnAborted(ChaosAbortedEventArgs e) => Aborted?.Invoke(this, e);