Esempio n. 1
0
        public static async Task BaseModuleTest <T1, T2>(
            string name1,
            string name2,
            Func <ExceptionsBag, T1, T2, CancellationToken, Task> testFunc)
            where T1 : class, IModule
            where T2 : class, IModule
        {
            using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15));
            var cancellationToken = cancellationTokenSource.Token;

            var exceptions = new ExceptionsBag();

            await using var manager = new ModuleManager <IModule>(
                            Path.Combine(Path.GetTempPath(), $"H.Containers.Tests_{name1}_{name2}"));
            manager.ExceptionOccurred += (_, exception) =>
            {
                Console.WriteLine($"ExceptionOccurred: {exception}");
                exceptions.OnOccurred(exception);

                // ReSharper disable once AccessToDisposedClosure
                cancellationTokenSource.Cancel();
            };

            using var instance1 = await manager.AddModuleAsync <T1>(
                      CreateContainer (name1),
                      name1,
                      name1,
                      ResourcesUtilities.ReadFileAsBytes($"{name1}.zip"),
                      cancellationToken);

            using var instance2 = await manager.AddModuleAsync <T2>(
                      CreateContainer (name2),
                      name2,
                      name2,
                      ResourcesUtilities.ReadFileAsBytes($"{name2}.zip"),
                      cancellationToken);

            Assert.IsNotNull(instance1);
            Assert.IsNotNull(instance2);

            foreach (var instance in new IModule[] { instance1, instance2 })
            {
                instance.EnableLog();
            }

            await testFunc(exceptions, instance1, instance2, cancellationToken);

            try
            {
                await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
            }
            catch (OperationCanceledException)
            {
            }

            exceptions.EnsureNoExceptions();
        }
        public static ExceptionsBag EnableLogging(
            this IEnumerable <IServiceBase> services,
            CancellationTokenSource?source = null)
        {
            var exceptions = new ExceptionsBag();

            foreach (var service in services)
            {
                service.EnableLogging(exceptions, source);
            }

            return(exceptions);
        }
Esempio n. 3
0
        public async Task SimpleTest()
        {
            using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
            var cancellationToken = cancellationTokenSource.Token;

            await using var service = new HookService();
            using var exceptions    = new ExceptionsBag();
            service.EnableLogging(exceptions, cancellationTokenSource);

            await service.InitializeAsync(cancellationToken);

            await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
        }
Esempio n. 4
0
        private async void StartButton_Click(object sender, RoutedEventArgs e)
        {
            Dispatcher?.Invoke(() =>
            {
                StartButton.IsEnabled = false;
                StopButton.IsEnabled  = true;
                OutputTextBox.Text   += $"{DateTime.Now:h:mm:ss.fff} Started {Environment.NewLine}";
            });

            try
            {
                using var recorder   = new NAudioRecorder();
                using var recognizer = RecognizerComboBox.Text switch
                      {
                          nameof(YandexRecognizer) => new YandexRecognizer
                          {
                              OAuthToken = OAuthTokenTextBox.Text,
                              FolderId   = FolderIdTextBox.Text,
                              Lang       = "ru-RU",
                          },
                          nameof(WitAiRecognizer) or _ => (IRecognizer) new WitAiRecognizer
                          {
                              Token = !string.IsNullOrWhiteSpace(OAuthTokenTextBox.Text)
                            ? OAuthTokenTextBox.Text
                            : "KATWBG4RQCFNBLQTY6QQUKB2SH6EIELG",
                          },
                      };
                var exceptions = new ExceptionsBag();
                exceptions.ExceptionOccurred += (_, exception) => OnException(exception);

                Recognition = await recognizer.StartStreamingRecognitionAsync(recorder, exceptions).ConfigureAwait(false);

                Recognition.PreviewReceived += (_, value) => Dispatcher?.Invoke(() =>
                {
                    OutputTextBox.Text += $"{DateTime.Now:h:mm:ss.fff} Preview: {value}{Environment.NewLine}";
                });
                Recognition.Stopped += (_, value) => Dispatcher?.Invoke(() =>
                {
                    OutputTextBox.Text += $"{DateTime.Now:h:mm:ss.fff} Final: {value}{Environment.NewLine}";
                });
            }
            catch (Exception exception)
            {
                OnException(exception);
            }
        }
Esempio n. 5
0
        public async Task SilenceDetectionTest()
        {
            using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
            var cancellationToken = cancellationTokenSource.Token;

            CheckDevices();

            var source = new TaskCompletionSource <bool>();

            using var exceptions   = new ExceptionsBag();
            using var registration = cancellationToken.Register(() => source.TrySetCanceled(cancellationToken));

            using var recorder  = new NAudioRecorder();
            using var recording = await recorder.StartWithPlaybackAsync(null, cancellationToken);

            recording.Stopped += (_, _) => source.TrySetResult(true);
            recording.StopWhenSilence(exceptions: exceptions);

            await source.Task;
        }
Esempio n. 6
0
        public static async Task <ExceptionsBag> StartStreamingRecognitionTest_RealTimeAsync(
            IRecorder recorder,
            IRecognizer recognizer,
            CancellationToken cancellationToken = default)
        {
            var exceptions = new ExceptionsBag();

            using var recognition = await recognizer.StartStreamingRecognitionAsync(recorder, exceptions, cancellationToken);

            recognition.PreviewReceived += (_, value) =>
            {
                Console.WriteLine($"{DateTime.Now:h:mm:ss.fff} {nameof(recognition.PreviewReceived)}: {value}");
            };
            recognition.Stopped += (_, value) =>
            {
                Console.WriteLine($"{DateTime.Now:h:mm:ss.fff} {nameof(recognition.Stopped)}: {value}");
            };

            await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);

            await recognition.StopAsync(cancellationToken);

            return(exceptions);
        }
Esempio n. 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="process"></param>
        /// <param name="cancellationToken"></param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        /// <returns></returns>
        public async Task <Rectangle> SelectAsync(
            IProcess <ICommand> process,
            CancellationToken cancellationToken = default)
        {
            process = process ?? throw new ArgumentNullException(nameof(process));

            if (Window == null)
            {
                await InitializeAsync(cancellationToken).ConfigureAwait(false);
            }

            Window = Window ?? throw new InvalidOperationException("Window is null.");

            var scaleFactor = await Dispatcher.InvokeAsync(
                () => Window.GetDpi(),
                DispatcherPriority.Normal,
                cancellationToken);

            var startPoint   = new Point();
            var endPoint     = new Point();
            var currentPoint = new Point();

            using var exceptions = new ExceptionsBag();
            using var hook       = new LowLevelMouseHook
                  {
                      GenerateMouseMoveEvents = true,
                  };
            hook.ExceptionOccurred += (_, exception) =>
            {
                // ReSharper disable once AccessToDisposedClosure
                exceptions.OnOccurred(exception);
            };

            var isInitialized = false;

            hook.Move += (_, args) =>
            {
                currentPoint = args.Position;
                if (isInitialized)
                {
                    return;
                }

                startPoint    = currentPoint.ToApp(scaleFactor);
                endPoint      = startPoint;
                isInitialized = true;
            };
            hook.Start();

            using var timer = new Timer(15);
            timer.Elapsed  += (_, _) =>
            {
                if (!isInitialized)
                {
                    return;
                }

                endPoint = currentPoint.ToApp(scaleFactor);

                Dispatcher.Invoke(() =>
                {
                    ApplyRectangle(
                        Window,
                        startPoint,
                        endPoint);
                });
            };
            timer.Start();

            await Dispatcher.InvokeAsync(() =>
            {
                ApplyRectangle(
                    Window,
                    startPoint,
                    endPoint);
                Window.Border.Visibility = Visibility.Visible;
            }, DispatcherPriority.Normal, cancellationToken);

            await process.WaitAsync(cancellationToken).ConfigureAwait(false);

            timer.Dispose();
            hook.Dispose();

            await Dispatcher.InvokeAsync(() =>
            {
                Window.Border.Visibility = Visibility.Hidden;
            }, DispatcherPriority.Normal, cancellationToken);

            return(startPoint
                   .ToRectangle(endPoint)
                   .Normalize()
                   .ToPhysical(scaleFactor));
        }