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 #2
0
        public Converser(Guid convoId)
        {
            ConversationId = convoId;

            Token = CancelSource.Token;
            CancelSource.Cancel();
        }
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?");
         }
     }
 }
        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 #6
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 #7
0
 public UserCancellations()
 {
     Cancel = new Command(() =>
     {
         CancelSource?.Cancel();
         IsEnabled   = false;
         Description = "Canceling...";
     });
 }
Beispiel #8
0
            public void Dispose()
            {
                CancelSource.Cancel();
                Task.ContinueWith(t => {
                    Interlocked.Decrement(ref _activeTaskCount);

                    CancelSource.Dispose();
                    t.Dispose();
                });
            }
 public void Dispose()
 {
     CancelSource.Cancel();
     lock (TaskMonitor)
     {
         Monitor.PulseAll(TaskMonitor);
     }
     LoopTask.Wait();
     CancelSource.Dispose();
 }
Beispiel #10
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 #11
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 #12
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 #14
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 #15
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 #16
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();
            }));
        }
        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 #18
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;
     }
 }
Beispiel #19
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 #20
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 #22
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 #23
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 #24
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 #25
0
        private async Task ReadLogLinesWrapper(ChannelWriter <RawLogLineInfo> writer, string logPath, CancellationToken token, int delayTimeMs = 250)
        {
            Log.Verbose("Writing channel: Reader");
            var startingLineCount = 0;

            var lr = new LogReader(logPath, token);

            lr.StartReading += () =>
            {
                Log.Verbose($"LogReader starting to read the next chunk. {_rawLineCount:N0} read lines, {_sw.Elapsed} elapsed");
                OnStartReading();
            };

            lr.LineRead += line =>
            {
                _rawLineCount++;

                // Filter out the occasional totally blank line (not even a timestamp)
                if (!String.IsNullOrEmpty(line))
                {
                    writer.TryWrite(new RawLogLineInfo()
                    {
                        LogLine = line, LineNumber = _rawLineCount,
                    });

                    // Track so we can print debug message in other channels
                    _lastLineNumber = _rawLineCount;
                }
            };

            // lr.EoFReached += async () => await Delay(delayTimeMs, token);
            lr.EoFReached += async() =>
            {
                var eofLineCount = _rawLineCount - startingLineCount;
                if (eofLineCount > 0)
                {
                    Log.Verbose($"LogReader EOF - waiting to read next chunk. {_rawLineCount:N0} read lines, {_sw.Elapsed} elapsed");
                }

                startingLineCount = _rawLineCount;

                OnEoFReached();

                if (WatchFile)
                {
                    await Task.Delay(delayTimeMs, token);
                }
                else
                {
                    CancelSource.Cancel(); // Not the best way I don't think. Perhaps just a return of 'False'
                }
            };

            Log.Verbose("About to start reading");
            startingLineCount = _rawLineCount;
            var lrTask = lr.StartReadingAsync();

            try
            {
                Log.Verbose("Task'd LR reading");
                await lrTask;
                Log.Verbose("LR reading completed successfully");
            }
            catch (OperationCanceledException)
            {
                Log.Verbose("ReadLogLinesWrapper");
                throw;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "ReadLogLinesWrapper");
                throw;
            }
            finally
            {
                Log.Verbose("Finally done with LR reading");
                DumpTaskInfo(lrTask, "lrTask");
            }
        }
Beispiel #26
0
 public bool Stop()
 {
     CancelSource.Cancel();
     SetMeFreeAsync();
     return(controller.StopController());
 }
Beispiel #27
0
 private void StopProbe(ProbeStatus status)
 {
     CancelSource.Cancel();
     Status   = status;
     IsActive = false;
 }
 protected override void OnStop()
 {
     CancelSource.Cancel();
     ProcessorTask.Wait();
 }
 private void ClosingCommand(object obj)
 {
     CancelSource?.Cancel();
 }
Beispiel #30
0
 /// <summary>
 /// Stops the logger.
 /// </summary>
 public void Stop()
 {
     CancelSource.Cancel();
 }