Ejemplo n.º 1
0
        /// <summary>
        /// Асинхронная смена сценария
        /// </summary>
        /// <returns></returns>
        private async Task ChangeScenarioAsync(string fileName, bool isQuickLoad)
        {
            if (isQuickLoad)
            {
                mFileName = fileName;
                await ProgressDialogService.ExecuteAsync(LoadAsync).ConfigureAwait(false);
            }
            else
            {
                await TaskExtension.Delay(1).ConfigureAwait(false);

                var dialog = new OpenFileDialog {
                    Filter = "Файл с описанием сценария (xmlinfo)|*.xmlinfo"
                };
                if (!string.IsNullOrEmpty(DataHolder.Instance.FullFolderPath))
                {
                    dialog.InitialDirectory = DataHolder.Instance.FullFolderPath;
                    dialog.FileName         = Path.Combine(DataHolder.Instance.FullFolderPath, Constants.cScenarioDescriptor);
                }

                if (dialog.ShowDialog() == true)
                {
                    mFileName = dialog.FileName;
                    await ProgressDialogService.ExecuteAsync(LoadAsync).ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 2
0
        async Task TrySendKeepAliveMessagesAsync(CancellationToken cancellationToken)
        {
            try
            {
                _logger.Verbose("Start sending keep alive packets.");

                var keepAlivePeriod = Options.KeepAlivePeriod;

                while (!cancellationToken.IsCancellationRequested)
                {
                    // Values described here: [MQTT-3.1.2-24].
                    var waitTime = keepAlivePeriod - _sendTracker.Elapsed;

                    if (waitTime <= TimeSpan.Zero)
                    {
                        await SendAndReceiveAsync <MqttPingRespPacket>(new MqttPingReqPacket(), cancellationToken).ConfigureAwait(false);
                    }

                    // Wait a fixed time in all cases. Calculation of the remaining time is complicated
                    // due to some edge cases and was buggy in the past. Now we wait half a second because the
                    // min keep alive value is one second so that the server will wait 1.5 seconds for a PING
                    // packet.
                    await TaskExtension.Delay(TimeSpan.FromMilliseconds(100), cancellationToken).ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                if (_cleanDisconnectInitiated)
                {
                    return;
                }

                if (exception is OperationCanceledException)
                {
                }
                else if (exception is MqttCommunicationException)
                {
                    _logger.Warning(exception, "Communication error while sending/receiving keep alive packets.");
                }
                else
                {
                    _logger.Error(exception, "Error exception while sending/receiving keep alive packets.");
                }

                if (!DisconnectIsPending())
                {
                    await DisconnectInternalAsync(_keepAlivePacketsSenderTask, exception, null).ConfigureAwait(false);
                }
            }
            finally
            {
                _logger.Verbose("Stopped sending keep alive packets.");
            }
        }
Ejemplo n.º 3
0
        private async Task CreateNewScenarioAsync(CancellationToken token)
        {
            await await Task.Factory.StartNew(async() =>
            {
                if (MessageBox.Show(Constants.cInsureCreateScenarioText, Constants.cAttention, MessageBoxButton.YesNo) == MessageBoxResult.No)
                {
                    await TaskExtension.Delay(1);
                    return;
                }
                await DataHolder.Instance.ReleaseMedia(false, null, token);
                await DataHolder.Instance.ClearAllData().ConfigureAwait(false);
                await UnselectCurrentScenario();
                await DataHolder.Instance.CreateStartUpData().ConfigureAwait(false);
            }, token, TaskCreationOptions.AttachedToParent, TaskScheduler.FromCurrentSynchronizationContext());

            IndicatorCreate = Indicators.Warn.GetColor();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Асинхронная загрузка сценария
        /// </summary>
        /// <param name="cancellation"></param>
        /// <param name="progress"></param>
        /// <returns></returns>
        private async Task LoadAsync(CancellationToken cancellation, IProgress <string> progress)
        {
            await await Task.Factory.StartNew(async() =>
            {
                await DataHolder.Instance.ReleaseMedia(false, progress, cancellation);
                progress.Report("Загрузка данных");
                Thread.Sleep(3000);
                if (DataHolder.Instance.LoadAllData(mFileName, progress, cancellation))
                {
                    Debug.Assert(Path.GetDirectoryName(mFileName) != null, "Path.GetDirectoryName(mFileName) != null");
                }
                else
                {
                    while (true)
                    {
                        if (cancellation.IsCancellationRequested)
                        {
                            break;
                        }
                        Thread.Sleep(100);
                    }
                }
                if (cancellation.IsCancellationRequested)
                {
                    await DataHolder.Instance.ClearAllData();
                    return(TaskExtension.Delay(1));
                }

                DispatcherServices.BeginInvoke(() =>
                {
                    DynamicText                 = Constants.cChangeScenarioText;
                    IndicatorLoad               = Indicators.Warn.GetColor();
                    IndicatorCreate             = Indicators.Warn.GetColor();
                    IndicatorSave               = Indicators.Accept.GetColor();
                    ScenarioItem loadedScenario = Scenarios.FirstOrDefault(s => s.ScenarioInfo.Key.Equals(mFileName));
                    if (loadedScenario == null)
                    {
                        loadedScenario            = new ScenarioItem(new KeyValuePair <string, string>(mFileName, DataHolder.Instance.ScenarioProperties.ScenarioName));
                        loadedScenario.Selecting += NewScenatioItemOnSelecting;
                        Scenarios.Add(loadedScenario);
                    }
                    loadedScenario.SelecteItem();
                });
                return(TaskExtension.Delay(1));
            }, cancellation).ConfigureAwait(false);
        }
Ejemplo n.º 5
0
        private static async Task Main(string[] args)
        {
            try
            {
                Program.config = new ConfigService();
                Startup.Configure(Program.config);

                Program.services = new ServiceCollection();
                Program.services.AddSingleton <ConfigService>(Program.config);

                Program.services.AddSingleton <App>();
                Startup.ConfigureServices(Program.services, Program.config);

                Program.provider = Program.services.BuildServiceProvider();

                Program.app          = provider.GetRequiredService <App>();
                Program.logger       = provider.GetService <Logger>();
                Program.cancellation = provider.GetService <CancellationTokenSource>();

                Console.CancelKeyPress += (_, eventArgs) =>
                {
                    eventArgs.Cancel = true;
                    Program.cancellation?.Cancel();
                };

                await Program.app.RunAsync();

                await TaskExtension.Delay(-1, Program.cancellation);
            }
            catch (TaskCanceledException ex)
            {
                Program.Out(LogEventLevel.Debug, ex.Message);
            }
            catch (Exception ex)
            {
                Program.Out(LogEventLevel.Fatal, ex);
            }
            finally
            {
                Log.CloseAndFlush();
            }

            Program.Out(LogEventLevel.Information, "The End!");
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Асинхронная выгрузка сценария
        /// </summary>
        /// <param name="path">путь к выгрузки</param>
        /// <param name="cancellation"></param>
        /// <param name="progress"></param>
        /// <param name="rewrite">True-перезаписать старые данные</param>
        /// <returns></returns>
        private async Task UploadScenarioAsync(string path, CancellationToken cancellation, IProgress <string> progress, bool rewrite = true)
        {
            await Task.Factory.StartNew(async() =>
            {
                progress.Report("Сохранение сценария");
                Thread.SpinWait(1000);
                DataHolder.Instance.TargetDirectory = path;
                if (rewrite)
                {
                    progress.Report("Очистка старых данных");
                    DataHolder.Instance.PrepareForRewriteScenario();
                }
                if (!DataHolder.Instance.UpLoadData(path, progress, cancellation))
                {
                    //    DataHolder.Instance.ScenarioProperties.Folder = Path.GetDirectoryName(mFileName);
                    //else
                    while (true)
                    {
                        if (cancellation.IsCancellationRequested)
                        {
                            break;
                        }
                        Thread.Sleep(100);
                    }
                }
                if (cancellation.IsCancellationRequested)
                {
                    await DataHolder.Instance.ClearAllData();
                    return(TaskExtension.Delay(1));
                }

                DispatcherServices.BeginInvoke(() =>
                {
                    DynamicText     = Constants.cChangeScenarioText;
                    IndicatorLoad   = Indicators.Warn.GetColor();
                    IndicatorCreate = Indicators.Warn.GetColor();
                    IndicatorSave   = Indicators.Accept.GetColor();
                });
                return(TaskExtension.Delay(1));
            }, cancellation).Unwrap().ConfigureAwait(false);
        }
Ejemplo n.º 7
0
        public async Task RunAsync()
        {
            using IConnection connection = this.connectionFactory.CreateConnection();
            using IModel channel         = connection.CreateModel();

            try
            {
                AsyncEventingBasicConsumer consumer = new AsyncEventingBasicConsumer(channel);

                consumer.Received += async(_, eventArgs) =>
                {
                    await this.Callback?.Invoke(eventArgs) !;

                    await Task.Yield();
                };

                channel.BasicConsume(
                    queue: this.configService.QueueConfig.Rabbit.Queue,
                    autoAck: true,
                    consumer: consumer
                    );

                this.logger?.Debug("Subscribed to {queue}", this.configService.QueueConfig.Rabbit.Queue);

                await TaskExtension.Delay(-1, this.cancellationTokenSource);
            }
            catch (OperationCanceledException ex)
            {
                this.logger?.Debug(ex.Message);
            }
            catch (Exception ex)
            {
                this.logger?.Error(ex, ex.Message);
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 8
0
        async Task RunAsync(int keepAlivePeriod, CancellationToken cancellationToken)
        {
            try
            {
                _lastPacketReceivedTracker.Restart();

                while (!cancellationToken.IsCancellationRequested)
                {
                    // Values described here: [MQTT-3.1.2-24].
                    // If the client sends 5 sec. the server will allow up to 7.5 seconds.
                    // If the client sends 1 sec. the server will allow up to 1.5 seconds.
                    if (!_isPaused && _lastPacketReceivedTracker.Elapsed.TotalSeconds >= keepAlivePeriod * 1.5D)
                    {
                        _logger.Warning(null, "Client '{0}': Did not receive any packet or keep alive signal.", _clientId);
                        await _keepAliveElapsedCallback().ConfigureAwait(false);

                        return;
                    }

                    // The server checks the keep alive timeout every 50 % of the overall keep alive timeout
                    // because the server allows 1.5 times the keep alive value. This means that a value of 5 allows
                    // up to 7.5 seconds. With an interval of 2.5 (5 / 2) the 7.5 is also affected. Waiting the whole
                    // keep alive time will hit at 10 instead of 7.5 (but only one time instead of two times).
                    await TaskExtension.Delay(TimeSpan.FromSeconds(keepAlivePeriod * 0.5D), cancellationToken).ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException)
            {
            }
            catch (Exception exception)
            {
                _logger.Error(exception, "Client '{0}': Unhandled exception while checking keep alive timeouts.", _clientId);
            }
            finally
            {
                _logger.Verbose("Client '{0}': Stopped checking keep alive timeout.", _clientId);
            }
        }
Ejemplo n.º 9
0
#pragma warning disable 4014
        async Task AcceptClientConnectionsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var clientSocket = await _socket.AcceptAsync().ConfigureAwait(false);

                    if (clientSocket == null)
                    {
                        continue;
                    }
#if NET40
                    TaskExtension.Run(() => TryHandleClientConnectionAsync(clientSocket).Wait(), cancellationToken).Forget(_logger);
#else
                    TaskExtension.Run(() => TryHandleClientConnectionAsync(clientSocket), cancellationToken).Forget(_logger);
#endif
                }
                catch (OperationCanceledException)
                {
                }
                catch (Exception exception)
                {
                    if (exception is SocketException socketException)
                    {
                        if (socketException.SocketErrorCode == SocketError.ConnectionAborted ||
                            socketException.SocketErrorCode == SocketError.OperationAborted)
                        {
                            continue;
                        }
                    }

                    _logger.Error(exception, $"Error while accepting connection at TCP listener {_localEndPoint} TLS={_tlsCertificate != null}.");
                    await TaskExtension.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Проверка параметров загрузки сценария
        /// </summary>
        /// <param name="param"></param>
        /// <param name="fileName"></param>
        /// <param name="loadingMode"></param>
        /// <returns></returns>
        private async Task <bool> CheckLoadParameter(object param, string fileName, bool loadingMode)
        {
            bool result = false;

            if (IndicatorLoad.IsEqual(Indicators.Warn.GetColor()))
            {
                if (MessageBox.Show(Constants.cInsureChangeScenarioText, Constants.cAttention, MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    await ChangeScenarioAsync(fileName, loadingMode).ConfigureAwait(false);

                    result = true;
                }
            }
            else if (IndicatorLoad.IsEqual(Indicators.Accept.GetColor()))
            {
                await ChangeScenarioAsync(fileName, loadingMode).ConfigureAwait(false);

                result = true;
            }
            await TaskExtension.Delay(1);

            CommandManager.InvalidateRequerySuggested();
            return(await TaskExtension.FromResult(result));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Асинхронное сохранение сценария
        /// </summary>
        /// <returns></returns>
        private async Task SaveScenarioHandlerAsync(object param)
        {
            if (IndicatorSave.IsEqual(Indicators.Accept.GetColor()))
            {
                if (!DataHolder.Instance.SlideDataHolders.Any(x => (x as ISaveValidator).With(valid => valid.OwnScenarioTypes.Contains(DataHolder.Instance.ScenarioProperties.ScenarioType) && !valid.IsValid)))
                {
                    var dialog = new FolderBrowserDialog
                    {
                        SelectedPath = DataHolder.Instance.FullFolderPath
                    };
                    if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        await DataHolder.Instance.ReleaseMedia(true, null, new CancellationToken());

                        string directoryName = dialog.SelectedPath;
                        IEnumerable <string> scenarioInfos = Directory.GetFiles(directoryName)
                                                             .ToList()
                                                             .Where(x => x.Contains(".xmlinfo"))
                                                             .Select(Path.GetFileName)
                                                             .ToList();
                        if (!scenarioInfos.Any())
                        {
                            await ProgressDialogService.ExecuteAsync((cancellation, progress) => UploadScenarioAsync(dialog.SelectedPath, cancellation, progress)).ConfigureAwait(false);
                        }
                        else if (scenarioInfos.Any(x => x == Constants.cScenarioDescriptor))
                        {
                            switch (MessageBox.Show(Application.Current.MainWindow, Constants.cInsureRewriteScenario, "Сохранение сценария", MessageBoxButton.YesNo))
                            {
                            case MessageBoxResult.Yes:
                                await ProgressDialogService.ExecuteAsync(async (cancellation, progress) => await UploadScenarioAsync(dialog.SelectedPath, cancellation, progress)).ConfigureAwait(false);

                                break;

                            case MessageBoxResult.No:
                                await TaskExtension.Delay(1);

                                return;
                            }
                        }
                        else
                        {
                            await ProgressDialogService.ExecuteAsync((cancellation, progress) => UploadScenarioAsync(dialog.SelectedPath, cancellation, progress)).ConfigureAwait(false);
                        }
                    }
                }
                else
                {
                    MessageBox.Show(string.Format("Данный Сценарий нельзя сохранить. Проверьте правильность запонения следующих вкладок для корректного сохранения \n{0}",
                                                  DataHolder.Instance.SlideDataHolders.Where(x => (x as ISaveValidator).With(valid => valid.OwnScenarioTypes.Contains(DataHolder.Instance.ScenarioProperties.ScenarioType) && !valid.IsValid)).Select(x => x.Name).EnumerableToString("{0}\n")), Constants.cScenarioEditorTitle,
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                throw new NotImplementedException("ScenarioEditor.ViewModel.ViewModels.StartPageViewModelsSaveScenarioHandlerAsync");
            }

            await TaskExtension.Delay(1);

            CommandManager.InvalidateRequerySuggested();
        }