Beispiel #1
0
        public Converser(Guid convoId)
        {
            ConversationId = convoId;

            Token = CancelSource.Token;
            CancelSource.Cancel();
        }
        public PolygonManagementViewModel(IEnumerable <IPolygonGenerator> generators, IAreaCalculator?areaCalculator = null, IPolygonClipper?clipper = null)
        {
            Polygons = new ObservableCollection <Polygon>();

            GenerateAndAddPolygonCommand = new DelegateCommand(
                GenerateAndAddPolygon,
                () => SelectedPolygonGenerator != null);

            Clipper             = clipper;
            ClipPolygonsCommand = new DelegateCommand(
                ClipPolygons,
                () => Clipper != null && !IsCalculatingArea && Polygons.Count > 1);

            Calculator = areaCalculator;
            CalculateAreaForSelectedPolygonCommand = new DelegateCommand(
                CalculateAreaForSelectedPolygon,
                () => Calculator != null && SelectedPolygon != null && !IsCalculatingArea);

            CancelAreaCalculationCommand = new DelegateCommand(
                () => CancelSource?.Cancel(),
                () => IsCalculatingArea);

            if (generators != null)
            {
                Generators = GetGeneratorsFromContainer(generators);
                SelectedPolygonGenerator = Generators?.LastOrDefault()?.Generator;
            }
        }
Beispiel #3
0
 private void StopLoop()
 {
     if ((looper != null) && !looper.LoopDone)
     {
         Console.WriteLine("Stopping loop action...");
         looper.LoopDone = true;
         try
         {
             if (theThread.IsAlive && theThread.ThreadState != ThreadState.WaitSleepJoin)
             {
                 theThread.Join();
             }
             else
             {
                 // Just Interrupt
                 theThread.Interrupt();
             }
             CancelSource.Cancel();
         }
         catch (Exception)
         {
             Console.WriteLine("Thread can't join.  Is it started?");
         }
     }
 }
Beispiel #4
0
        private void CreateSingleDumperThread(WzFile file, WzXml wzxml, string fileName)
        {
            IsFinished = false;
            var startTime = DateTime.Now;
            var mainTask  = Task.Factory.StartNew(() => DirectoryDumperThread(file, wzxml, true));

            mainTask.ContinueWith(p => {
                var duration   = DateTime.Now - startTime;
                string message = String.Empty;
                if (CancelSource.Token.IsCancellationRequested)
                {
                    if (Exit)
                    {
                        return;
                    }
                    message = "Canceled dumping " + fileName;
                }
                else if (IsError)
                {
                    message = "An error occurred while dumping " + fileName;
                }
                else
                {
                    message = "Finished dumping " + fileName;
                }
                UpdateToolstripStatus(message);
                UpdateTextBoxInfo(Info, message + ".\r\nElapsed time: " + GetDurationAsString(duration), true);
                IsError    = false;
                IsFinished = true;
                EnableButtons();
                CancelSource.Dispose();
            }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.FromCurrentSynchronizationContext());
        }
        public UdpCommunicator(IPEndPoint endPoint, IMessageConverter converter)
        {
            _endPoint = endPoint;
            Converter = converter;

            Token = CancelSource.Token;
            CancelSource.Cancel();
        }
        public FileAssembler(Content c, ConcurrentDictionary <int, byte[]> data)
        {
            ContentInfo = c;
            DataStore   = data;
            TotalChunks = (int)Math.Ceiling(ContentInfo.ByteSize / 256.0);

            Token = CancelSource.Token;
            CancelSource.Cancel();
        }
Beispiel #7
0
        protected override void Run()
        {
            Log.Debug("Started sender");

            var persistence = new PersistenceManager();

            while (true)
            {
                if (Token.IsCancellationRequested)
                {
                    Log.Debug("Received request to stop");
                    return;
                }

                if (IncomingMessages.Count == 0)
                {
                    continue;
                }

                using (var file = File.Open(Path.Combine(FileInfo.LocalPath, FileInfo.FileName), FileMode.Open))
                    using (var stream = new BinaryReader(file))
                    {
                        while (IncomingMessages.Count > 0)
                        {
                            Message mesg;
                            if (IncomingMessages.TryDequeue(out mesg))
                            {
                                if (mesg.MessageId == MessageType.CHUNK_REQUEST)
                                {
                                    var chunkReq = (ChunkRequest)mesg;

                                    stream.BaseStream.Seek(chunkReq.Size * chunkReq.Index, SeekOrigin.Begin);
                                    var bytes = stream.ReadBytes(chunkReq.Size);

                                    var provider = new RSACryptoServiceProvider();
                                    provider.ImportCspBlob(persistence.ReadContent().KeyInfo);

                                    Log.DebugFormat("Building ChunkReply message for index {0}", chunkReq.Index);
                                    var outMessage = new ChunkReply(Guid.NewGuid(),
                                                                    chunkReq.ConversationId,
                                                                    chunkReq.MessageCount + 1,
                                                                    bytes,
                                                                    chunkReq.Index,
                                                                    MessageVerifier.CreateSignature(bytes, provider.ExportParameters(true)));
                                    RaiseSendMessageEvent(outMessage);
                                }
                                else if (mesg.MessageId == MessageType.ACKNOWLEDGE)
                                {
                                    Log.Info("Client acknowledged that it has received all the data");
                                    CancelSource.Cancel();
                                    RaiseEndConversationEvent();
                                }
                            }
                        }
                    }
            }
        }
Beispiel #8
0
 public UserCancellations()
 {
     Cancel = new Command(() =>
     {
         CancelSource?.Cancel();
         IsEnabled   = false;
         Description = "Canceling...";
     });
 }
 public void Dispose()
 {
     CancelSource.Cancel();
     lock (TaskMonitor)
     {
         Monitor.PulseAll(TaskMonitor);
     }
     LoopTask.Wait();
     CancelSource.Dispose();
 }
Beispiel #10
0
            public void Dispose()
            {
                CancelSource.Cancel();
                Task.ContinueWith(t => {
                    Interlocked.Decrement(ref _activeTaskCount);

                    CancelSource.Dispose();
                    t.Dispose();
                });
            }
Beispiel #11
0
 /// <summary>
 /// Clean up any resources being used.
 /// </summary>
 /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
 protected override void Dispose(bool disposing)
 {
     if (disposing && (components != null))
     {
         components.Dispose();
     }
     if (CancelSource != null)
     {
         CancelSource.Dispose();
     }
     base.Dispose(disposing);
 }
Beispiel #12
0
        /// <summary>
        /// 停止接受消息并清空队列
        /// </summary>
        public void Stop()
        {
            if (!IsRunning)
            {
                throw new Exception("invoker is not start");
            }

            IsRunning = false;
            CancelSource.Cancel();
            MsgSem.Release(InvokerCount);
            Task.WaitAll(InnerTasks);
            Clear();
        }
Beispiel #13
0
 private void CancelOperation(object sender, EventArgs e)
 {
     if (MessageBox.Show("Are you sure you want to cancel the current operation?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
     {
         return;
     }
     if (CancelSource != null)
     {
         CancelSource.Cancel(true);
     }
     CancelOpButton.Enabled = false;
     UpdateTextBoxInfo(Info, "Canceling... Waiting for the current image(s) to finish dumping...", true);
 }
Beispiel #14
0
        public void Dispose()
        {
            if (StatusReportingTask != null)
            {
                CancelSource.Cancel();
                lock (TaskMonitor)
                {
                    Monitor.PulseAll(TaskMonitor);
                }
                StatusReportingTask.Wait();
                CancelSource.Dispose();
            }

            CrashReporterProcessServicer.WriteSlack("CRP stopped");
        }
        protected override void Run()
        {
            Log.Debug("Started receiver");

            var persistence = new PersistenceManager();

            for (var i = 0; i < 3; i++)
            {
                if (Token.IsCancellationRequested)
                {
                    Log.Debug("Received request to stop");
                    break;
                }

                while (IncomingMessages.Count > 0)
                {
                    Message mesg;
                    if (IncomingMessages.TryDequeue(out mesg))
                    {
                        if (mesg.MessageId == MessageType.REGISTER_CONTENT_REQUEST)
                        {
                            var req = (RegisterContentRequest)mesg;

                            Log.Info(string.Format("Registering {0} with host {1} and port {2}", req.Name, req.Host, req.Port));
                            var content = new Content()
                            {
                                ContentHash   = req.Hash,
                                ByteSize      = req.FileSize,
                                FileName      = req.Name,
                                Description   = req.Description,
                                Host          = req.Host,
                                Port          = req.Port,
                                LocalPath     = ".",
                                PublicKeyInfo = req.PublicKeyInfo
                            };
                            persistence.WriteContent(content, PersistenceManager.StorageType.Local);

                            var ack = new Acknowledge(Guid.NewGuid(), ConversationId, req.MessageCount + 1, "Accepted register content request");
                            CancelSource.Cancel();
                            RaiseSendMessageEvent(ack);
                            break;
                        }
                    }
                }
            }

            RaiseEndConversationEvent();
        }
Beispiel #16
0
        protected override void Run()
        {
            Log.Debug("Started sender");

            var persistence = new PersistenceManager();

            // Only try three times
            for (var i = 0; i < 3; i++)
            {
                if (Token.IsCancellationRequested)
                {
                    Log.Debug("Received request to stop");
                    break;
                }

                var req = new ContentListRequest(Guid.NewGuid(), ConversationId, 0, Query);
                RaiseSendMessageEvent(req);

                Thread.Sleep(500);

                while (IncomingMessages.Count > 0)
                {
                    Message mesg;
                    if (IncomingMessages.TryDequeue(out mesg))
                    {
                        if (mesg.MessageId == MessageType.CONTENT_LIST_REPLY)
                        {
                            var reply = (ContentListReply)mesg;

                            foreach (var content in reply.ContentList)
                            {
                                // TODO This is read the file on every call
                                persistence.WriteContent(content, PersistenceManager.StorageType.Remote);
                            }

                            OnSearchResults?.Invoke(reply.ContentList);

                            CancelSource.Cancel();
                            break;
                        }
                    }
                }
            }

            RaiseEndConversationEvent();
        }
Beispiel #17
0
        private void StopProbe(ProbeStatus status)
        {
            CancelSource.Cancel();
            Status   = status;
            IsActive = false;

            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                mutex.WaitOne();
                if (status != ProbeStatus.Error)
                {
                    WriteFinalStatisticsToHistory();
                }
                StatusChangeLog.Add(new StatusChangeLog {
                    Timestamp = DateTime.Now, Hostname = Hostname, Alias = Alias, Status = ProbeStatus.Stop
                });
                mutex.ReleaseMutex();
            }));
        }
Beispiel #18
0
 private void Form1FormClosing(object sender, FormClosingEventArgs e)
 {
     if (IsFinished)
     {
         return;
     }
     if (MessageBox.Show("You can not close the program while it is still dumping. Do you wish to cancel the operation?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
     {
         Exit = true;
         if (CancelSource != null)
         {
             CancelSource.Cancel(true);
         }
     }
     else
     {
         e.Cancel = true;
     }
 }
Beispiel #19
0
 private void Form1FormClosing(object sender, FormClosingEventArgs e)
 {
     if (IsFinished)
     {
         return;
     }
     if (MessageBox.Show("提取中 無法取消本程式. 是否要取消此操作?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
     {
         Exit = true;
         if (CancelSource != null)
         {
             CancelSource.Cancel(true);
         }
     }
     else
     {
         e.Cancel = true;
     }
 }
        protected override void Run()
        {
            Log.Debug("Started sender");

            // Only try three times
            for (var i = 0; i < 3; i++)
            {
                if (Token.IsCancellationRequested)
                {
                    Log.Debug("Received request to stop");
                    break;
                }

                RaiseSendMessageEvent(Request);
                MessageCount++;

                for (int times = 0; times < 10; times++)
                {
                    if (IncomingMessages.Count < 1)
                    {
                        Thread.Sleep(250);
                    }
                }

                while (IncomingMessages.Count > 0)
                {
                    Message mesg;
                    if (IncomingMessages.TryDequeue(out mesg))
                    {
                        if (mesg.MessageId == MessageType.ACKNOWLEDGE)
                        {
                            var ack = (Acknowledge)mesg;

                            Log.Info(string.Format("Recevied acknowledge with status: {0}", ack.StatusInformation));
                            CancelSource.Cancel();
                            break;
                        }
                    }
                }
            }

            RaiseEndConversationEvent();
        }
Beispiel #21
0
        public void Stop()
        {
            FileWatcher.EnableRaisingEvents = false;

            if (DedupTask == null || DedupTask.IsCompleted)
            {
                return;
            }

            CancelSource.Cancel();
            try
            {
                DedupTask?.Wait();
            }
            catch (AggregateException exc)
            {
                exc.Handle(x => x is OperationCanceledException);
            }
            CancelSource?.Dispose();
            OnStopped();
        }
Beispiel #22
0
        protected virtual void Run()
        {
            while (true)
            {
                if (CancelSource.IsCancellationRequested)
                {
                    return;
                }

                if (DataStore.Count >= TotalChunks)
                {
                    try
                    {
                        Log.Info("Received correct chunk count for " + ContentInfo.FileName);

                        var path = Path.Combine(ContentInfo.LocalPath, ContentInfo.FileName);
                        using (var stream = new BinaryWriter(File.Open(path, FileMode.OpenOrCreate)))
                        {
                            foreach (var item in DataStore)
                            {
                                Log.Debug(string.Format("Storing packet {0} of {1}", item.Key, TotalChunks - 1));
                                stream.Seek(item.Key * 256, SeekOrigin.Begin);
                                stream.Write(DataStore[item.Key]);
                            }
                        }

                        Log.Info("Finished downloading " + ContentInfo.FileName);
                        OnDownloadSucess?.Invoke(ContentInfo);
                        CancelSource.Cancel();
                        break;
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.Message);
                    }
                }
            }
        }
        public PolygonManagementViewModel(IUnityContainer container = null, AreaCalculator areaCalculator = null)
        {
            Polygons = new ObservableCollection <Polygon>();

            GenerateAndAddPolygonCommand = new DelegateCommand(
                GenerateAndAddPolygon,
                () => SelectedPolygonGenerator != null);

            Calculator = areaCalculator;
            CalculateAreaForSelectedPolygonCommand = new DelegateCommand(
                CalculateAreaForSelectedPolygon,
                () => Calculator != null && SelectedPolygon != null && !IsCalculatingArea);

            CancelAreaCalculationCommand = new DelegateCommand(
                () => CancelSource?.Cancel(),
                () => IsCalculatingArea);

            if (container != null)
            {
                Generators = GetGeneratorsFromContainer(container);
                SelectedPolygonGenerator = Generators.LastOrDefault()?.Generator;
            }
        }
Beispiel #24
0
        public PolygonManagementViewModel(PolygonGeneratorProvider generatorProvider = null,
                                          IDialogHandler dialogHandler  = null,
                                          PolygonClipper clipper        = null,
                                          AreaCalculator areaCalculator = null)
        {
            Polygons = new ObservableCollection <Polygon>();

            DialogHandler  = dialogHandler;
            Clipper        = clipper;
            AreaCalculator = areaCalculator;

            GenerateAndAddPolygonCommand = new DelegateCommand(
                GenerateAndAddPolygon,
                () => SelectedPolygonGenerator != null);

            ClipPolygonsCommand = new DelegateCommand(
                ClipPolygons,
                () => Polygons.Count == 2 && Clipper != null);
            Polygons.CollectionChanged += (_, __) => ClipPolygonsCommand.RaiseCanExecuteChanged();

            CalculateAreaForSelectedPolygonCommand = new DelegateCommand(
                CalculateAreaForSelectedPolygon,
                () => SelectedPolygon != null && !IsCalculatingArea && AreaCalculator != null);

            CancelAreaCalculationCommand = new DelegateCommand(
                () => CancelSource.Cancel(),
                () => IsCalculatingArea);

            if (generatorProvider != null)
            {
                Generators = GetGeneratorsFromContainer(generatorProvider);
                SelectedPolygonGenerator = Generators.LastOrDefault()?.Generator;
            }

            MouseCommand = new DelegateCommand <Polygon>((x) => SelectedPolygon = x);
        }
Beispiel #25
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    CancelSource.Cancel();
                    try
                    {
                        DedupTask?.Wait();
                    }
                    catch (AggregateException exc)
                    {
                        exc.Handle(x => x is OperationCanceledException);
                    }
                    CancelSource?.Dispose();
                    DedupTask?.Dispose();
                    FileWatcher?.Dispose();
                    // TODO: dispose managed state (managed objects)
                }

                disposedValue = true;
            }
        }
Beispiel #26
0
 /// <summary>
 /// Begins to stop the scanning engine, returns immediately to the caller.
 /// </summary>
 public override void BeginStop()
 {
     CancelSource.Cancel();
     Logger.WriteTraceMessage("Scan engine is shutting down by request.", InstanceID);
 }
Beispiel #27
0
 public bool Stop()
 {
     CancelSource.Cancel();
     SetMeFreeAsync();
     return(controller.StopController());
 }
Beispiel #28
0
 private void StopProbe(ProbeStatus status)
 {
     CancelSource.Cancel();
     Status   = status;
     IsActive = false;
 }
 var model = new NotificationProgressViewModel(out var progressModel, CancelSource, ShowCancelButton, ShowProgress);
 public void Stop()
 {
     Log.Debug("Requesting thread to stop");
     CancelSource.CancelAfter(500);
     WorkerThread.Join();
 }