Ejemplo n.º 1
0
        private Task ProcessEvent(IEvent e, CancellationToken token)
        {
            // do we have an error.
            if (e.Error != EventError.None)
            {
                return(OnErrorAsync != null?Task.Run(() => OnErrorAsync?.Invoke(new utils.EventError(e.Error, e.DateTimeUtc), token), token) : Task.FromResult(false));
            }

            switch (e.Action)
            {
            case EventAction.Added:
                return(OnAddedAsync != null?Task.Run(() => OnAddedAsync?.Invoke(new FileSystemEvent(e), token), token) : Task.FromResult(false));

            case EventAction.Removed:
                return(OnRemovedAsync != null?Task.Run(() => OnRemovedAsync?.Invoke(new FileSystemEvent(e), token), token) : Task.FromResult(false));

            case EventAction.Touched:
                return(OnTouchedAsync != null?Task.Run(() => OnTouchedAsync?.Invoke(new FileSystemEvent(e), token), token) : Task.FromResult(false));

            case EventAction.Renamed:
                return(OnRenamedAsync != null?Task.Run(() => OnRenamedAsync?.Invoke(new RenamedFileSystemEvent(e), token), token) : Task.FromResult(false));

            default:
                throw new NotSupportedException($"Received an unknown Action: {e.Action:G}");
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <param name="bypassQueue"></param>
        /// <param name="serializerOptions"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        public async ValueTask SendAsync <T>(T data, bool bypassQueue = false,
                                             JsonSerializerOptions serializerOptions = default)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data), "Provided data was null.");
            }

            if (_webSocket.State != WebSocketState.Open)
            {
                throw new InvalidOperationException(
                          $"WebSocket is not in open state. Current state: {_webSocket.State}");
            }

            try {
                var serializedData = JsonSerializer.SerializeToUtf8Bytes(data, serializerOptions);
                if (bypassQueue)
                {
                    _messageQueue.Enqueue(serializedData);
                }
                else
                {
                    await _webSocket.SendAsync(serializedData, WebSocketMessageType.Text,
                                               true, _connectionTokenSource.Token);
                }
            }
            catch (Exception exception) {
                await OnErrorAsync.Invoke(new ErrorEventArgs(exception));
            }
        }
Ejemplo n.º 3
0
        private async Task ReceiveAsync()
        {
            try {
                var buffer      = new byte[_lavaConfig.BufferSize];
                var finalBuffer = default(byte[]);

                var offset = 0;
                do
                {
                    var receiveResult = await _webSocket.ReceiveAsync(buffer, _cancellationToken.Token);

                    if (!receiveResult.EndOfMessage)
                    {
                        finalBuffer = new byte[_lavaConfig.BufferSize * 2];
                        buffer.CopyTo(finalBuffer, offset);
                        offset += receiveResult.Count;
                        buffer  = new byte[_lavaConfig.BufferSize];
                        continue;
                    }

                    switch (receiveResult.MessageType)
                    {
                    case WebSocketMessageType.Text:
                        await OnDataAsync.Invoke(RemoveTrailingNulls(finalBuffer ?? buffer));

                        finalBuffer = default;
                        buffer      = new byte[_lavaConfig.BufferSize];
                        offset      = 0;
                        break;

                    case WebSocketMessageType.Close:
                        await DisconnectAsync();

                        break;
                    }
                } while (_webSocket.State == WebSocketState.Open &&
                         !_cancellationToken.IsCancellationRequested);
            }
            catch (Exception exception) {
                if (exception is TaskCanceledException ||
                    exception is OperationCanceledException ||
                    exception is ObjectDisposedException)
                {
                    return;
                }

                await OnErrorAsync.Invoke(exception);
                await RetryConnectionAsync();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes instance of <see cref="ClientWebSocket"/> and connects to server.
        /// </summary>
        public async Task ConnectAsync()
        {
            if (_webSocket.State == WebSocketState.Open)
            {
                throw new InvalidOperationException(
                          $"WebSocket is already in open state. Current state: {_webSocket.State}");
            }

            async Task VerifyConnectionAsync(Task task)
            {
                if (task.Exception != null)
                {
                    await OnErrorAsync.Invoke(task.Exception);
                    await RetryConnectionAsync();

                    return;
                }

                _isConnected        = true;
                _connectionAttempts = 0;
                _reconnectInterval  = TimeSpan.Zero;
                _cancellationToken  = new CancellationTokenSource();
                await OnOpenAsync.Invoke();

                await ReceiveAsync();
            }

            try {
                await _webSocket
                .ConnectAsync(_url, CancellationToken.None)
                .ContinueWith(VerifyConnectionAsync);
            }
            catch (Exception exception) {
                if (!(exception is ObjectDisposedException))
                {
                    return;
                }

                await RetryConnectionAsync();
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Closes connection to websocket server.
        /// </summary>
        /// <returns></returns>
        public async Task DisconnectAsync(WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure,
                                          string closeReason = "Normal closure.")
        {
            if (_webSocket.State != WebSocketState.Open)
            {
                throw new InvalidOperationException(
                          $"WebSocket is not in open state. Current state: {_webSocket.State}");
            }

            try {
                await _webSocket.CloseAsync(closeStatus, closeReason, _cancellationToken.Token);
            }
            catch (Exception exception) {
                await OnErrorAsync.Invoke(exception);
            }
            finally {
                _isConnected = false;
                _cancellationToken.Cancel(false);
                await OnCloseAsync.Invoke(closeReason);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// A method to submitting a form in a modal.
        /// </summary>
        /// <returns>An instance of <see cref="Task"/>.</returns>
        public async Task SubmitAsync()
        {
            try
            {
                await _loaderService.CreateAsync();  // Show the loader

                await OnSubmitAsync.Invoke();        // Submit the form.

                await DisposeAsync();                // Remove the modal.

                await _loaderService.DisposeAsync(); // Remove the loader.
            }
            catch (Exception exception)
            {
                await DisposeAsync();                 // Remove the modal.

                await _loaderService.DisposeAsync();  // Remove the loader.

                await OnErrorAsync.Invoke(exception); // Invoke the fact that there is an error.
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Used to send data to websocket server.
        /// </summary>
        /// <param name="value">Value of <typeparamref name="T"/></param>
        /// <typeparam name="T">Type of data to set.</typeparam>
        /// <exception cref="InvalidOperationException">Throws if not connected to websocket.</exception>
        public async Task SendAsync <T>(T value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value), "Provided data was null.");
            }

            if (_webSocket.State != WebSocketState.Open)
            {
                throw new InvalidOperationException(
                          $"WebSocket is not in open state. Current state: {_webSocket.State}");
            }

            try {
                var rawBytes = JsonSerializer.SerializeToUtf8Bytes(value, VictoriaExtensions.JsonOptions);
                await _webSocket.SendAsync(rawBytes, WebSocketMessageType.Text, true, _cancellationToken.Token)
                .ConfigureAwait(false);
            }
            catch (Exception exception) {
                await OnErrorAsync.Invoke(exception);
            }
        }