Ejemplo n.º 1
0
        public async Task InvokeNonExistantClientMethodFromServer(IHubProtocol protocol, TransportType transportType, string path)
        {
            using (StartLog(out var loggerFactory))
            {
                var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + path), transportType, loggerFactory);
                var connection     = new HubConnection(httpConnection, protocol, loggerFactory);
                try
                {
                    await connection.StartAsync().OrTimeout();

                    await connection.InvokeAsync("CallHandlerThatDoesntExist").OrTimeout();

                    await connection.DisposeAsync().OrTimeout();

                    await connection.Closed.OrTimeout();
                }
                finally
                {
                    await connection.DisposeAsync().OrTimeout();
                }
            }
        }
Ejemplo n.º 2
0
        private static HubConnection CreateHubConnection(TestConnection connection, IHubProtocol protocol = null, ILoggerFactory loggerFactory = null)
        {
            var builder = new HubConnectionBuilder();

            var delegateConnectionFactory = new DelegateConnectionFactory(
                connection.StartAsync,
                c => c.DisposeAsync().AsTask());

            builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

            if (loggerFactory != null)
            {
                builder.WithLoggerFactory(loggerFactory);
            }

            if (protocol != null)
            {
                builder.Services.AddSingleton(protocol);
            }

            return(builder.Build());
        }
Ejemplo n.º 3
0
    public void GlobalSetup()
    {
        switch (HubProtocol)
        {
        case Protocol.MsgPack:
            _hubProtocol = new MessagePackHubProtocol();
            break;

        case Protocol.Json:
            _hubProtocol = new JsonHubProtocol();
            break;

        case Protocol.NewtonsoftJson:
            _hubProtocol = new NewtonsoftJsonHubProtocol();
            break;
        }

        switch (Input)
        {
        case Message.NoArguments:
            _hubMessage = new InvocationMessage("Target", Array.Empty <object>());
            break;

        case Message.FewArguments:
            _hubMessage = new InvocationMessage("Target", new object[] { 1, "Foo", 2.0f });
            break;

        case Message.ManyArguments:
            _hubMessage = new InvocationMessage("Target", new object[] { 1, "string", 2.0f, true, (byte)9, new byte[] { 5, 4, 3, 2, 1 }, 'c', 123456789101112L });
            break;

        case Message.LargeArguments:
            _hubMessage = new InvocationMessage("Target", new object[] { new string('F', 10240), new byte[10240] });
            break;
        }

        _binaryInput = _hubProtocol.GetMessageBytes(_hubMessage);
        _binder      = new TestBinder(_hubMessage);
    }
Ejemplo n.º 4
0
        public TestClient(bool synchronousCallbacks = false, IHubProtocol protocol = null, IInvocationBinder invocationBinder = null, bool addClaimId = false)
        {
            var options = new ChannelOptimizations {
                AllowSynchronousContinuations = synchronousCallbacks
            };
            var transportToApplication = Channel.CreateUnbounded <byte[]>(options);
            var applicationToTransport = Channel.CreateUnbounded <byte[]>(options);

            Application = ChannelConnection.Create <byte[]>(input: applicationToTransport, output: transportToApplication);
            _transport  = ChannelConnection.Create <byte[]>(input: transportToApplication, output: applicationToTransport);

            Connection = new DefaultConnectionContext(Guid.NewGuid().ToString(), _transport, Application);

            var claimValue = Interlocked.Increment(ref _id).ToString();
            var claims     = new List <Claim> {
                new Claim(ClaimTypes.Name, claimValue)
            };

            if (addClaimId)
            {
                claims.Add(new Claim(ClaimTypes.NameIdentifier, claimValue));
            }

            Connection.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
            Connection.Metadata["ConnectedTask"] = new TaskCompletionSource <bool>();

            protocol = protocol ?? new JsonHubProtocol();
            _protocolReaderWriter = new HubProtocolReaderWriter(protocol, new PassThroughEncoder());
            _invocationBinder     = invocationBinder ?? new DefaultInvocationBinder();

            _cts = new CancellationTokenSource();

            using (var memoryStream = new MemoryStream())
            {
                NegotiationProtocol.WriteMessage(new NegotiationMessage(protocol.Name), memoryStream);
                Application.Out.TryWrite(memoryStream.ToArray());
            }
        }
Ejemplo n.º 5
0
        public HubConnection(IConnection connection, IHubProtocol protocol, ILoggerFactory loggerFactory)
        {
            if (connection == null)
            {
                throw new ArgumentNullException(nameof(connection));
            }

            if (protocol == null)
            {
                throw new ArgumentNullException(nameof(protocol));
            }

            _connection    = connection;
            _binder        = new HubBinder(this);
            _protocol      = protocol;
            _loggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
            _logger        = _loggerFactory.CreateLogger <HubConnection>();
            _connection.OnReceived((data, state) => ((HubConnection)state).OnDataReceivedAsync(data), this);
            _connection.Closed += e => Shutdown(e);

            // Create the timer for timeout, but disabled by default (we enable it when started).
            _timeoutTimer = new Timer(state => ((HubConnection)state).TimeoutElapsed(), this, Timeout.Infinite, Timeout.Infinite);
        }
Ejemplo n.º 6
0
        public HubConnection(IConnection connection, IHubProtocol protocol, ILoggerFactory loggerFactory)
        {
            if (connection == null)
            {
                throw new ArgumentNullException(nameof(connection));
            }

            if (protocol == null)
            {
                throw new ArgumentNullException(nameof(protocol));
            }

            _connection    = connection;
            _binder        = new HubBinder(this);
            _protocol      = protocol;
            _loggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
            _logger        = _loggerFactory.CreateLogger <HubConnection>();
            _connection.OnReceived((data, state) => ((HubConnection)state).OnDataReceivedAsync(data), this);
            Closed = _connection.Closed.ContinueWith(task =>
            {
                Shutdown(task.Exception);
                return(task);
            }).Unwrap();
        }
Ejemplo n.º 7
0
 private static HubConnection CreateConnection(string url, TransportType transportType, IHubProtocol protocol, ILoggerFactory loggerFactory)
 {
     return(new HubConnectionBuilder()
            .WithUrl(url)
            .WithTransport(transportType)
            .WithHubProtocol(protocol)
            .WithLoggerFactory(loggerFactory)
            .Build());
 }
Ejemplo n.º 8
0
 public HubProtocolReaderWriter(IHubProtocol hubProtocol, IDataEncoder dataEncoder)
 {
     _hubProtocol = hubProtocol;
     _dataEncoder = dataEncoder;
 }
Ejemplo n.º 9
0
        public async Task HubConnectionCanSendAndReceiveGroupMessages(TransportType transportType, IHubProtocol protocol)
        {
            using (StartLog(out var loggerFactory, testName:
                            $"{nameof(HubConnectionCanSendAndReceiveGroupMessages)}_{transportType.ToString()}_{protocol.Name}"))
            {
                var connection       = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, loggerFactory);
                var secondConnection = CreateConnection(_serverFixture.SecondServer.Url + "/echo", transportType, protocol, loggerFactory);

                var tcs = new TaskCompletionSource <string>();
                connection.On <string>("Echo", message => tcs.TrySetResult(message));
                var tcs2 = new TaskCompletionSource <string>();
                secondConnection.On <string>("Echo", message => tcs2.TrySetResult(message));

                await secondConnection.StartAsync().OrTimeout();

                await connection.StartAsync().OrTimeout();

                await connection.InvokeAsync("AddSelfToGroup", "Test").OrTimeout();

                await secondConnection.InvokeAsync("AddSelfToGroup", "Test").OrTimeout();

                await connection.InvokeAsync("EchoGroup", "Test", "Hello, World!").OrTimeout();

                Assert.Equal("Hello, World!", await tcs.Task.OrTimeout());
                Assert.Equal("Hello, World!", await tcs2.Task.OrTimeout());

                await connection.DisposeAsync().OrTimeout();
            }
        }
 public static IHubConnectionBuilder WithHubProtocol(this IHubConnectionBuilder hubConnectionBuilder, IHubProtocol hubProtocol)
 {
     hubConnectionBuilder.Services.AddSingleton(hubProtocol);
     return(hubConnectionBuilder);
 }
Ejemplo n.º 11
0
        public async Task ServerThrowsHubExceptionOnStreamingHubMethodArgumentCountMismatch(IHubProtocol hubProtocol, TransportType transportType, string hubPath)
        {
            using (StartLog(out var loggerFactory))
            {
                loggerFactory.AddConsole(LogLevel.Trace);
                var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + hubPath), transportType, loggerFactory);
                var connection     = new HubConnection(httpConnection, hubProtocol, loggerFactory);
                try
                {
                    await connection.StartAsync().OrTimeout();

                    var channel = await connection.StreamAsync <int>("Stream", 42, 42);

                    var ex = await Assert.ThrowsAsync <HubException>(() => channel.ReadAllAsync().OrTimeout());

                    Assert.Equal("Invocation provides 2 argument(s) but target expects 1.", ex.Message);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test");
                    throw;
                }
                finally
                {
                    await connection.DisposeAsync().OrTimeout();
                }
            }
        }
Ejemplo n.º 12
0
 public HubConnection(IConnectionFactory connectionFactory, IHubProtocol protocol, IServiceProvider serviceProvider, ILoggerFactory loggerFactory)
     : this(connectionFactory, protocol, loggerFactory)
 {
     _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
 }
Ejemplo n.º 13
0
 public static HubProtocol CreateFromConnection(ConnectionContext connection, IHubProtocol hubProtocol, IInvocationBinder invocationBinder, int?maximumMessageSize = null)
 {
     return(new HubProtocol(connection, maximumMessageSize, hubProtocol, invocationBinder));
 }
Ejemplo n.º 14
0
 public static ReadOnlySpan <byte> GetSuccessfulHandshake(IHubProtocol protocol) => _successHandshakeData.Span;
Ejemplo n.º 15
0
 public HubMessageWriter(IHubProtocol hubProtocol)
 {
     _hubProtocol = hubProtocol;
 }
Ejemplo n.º 16
0
 private static HubConnection CreateHubConnection(TestConnection connection, IHubProtocol protocol = null)
 {
     return(new HubConnection(() => connection, protocol ?? new JsonHubProtocol(), new LoggerFactory()));
 }
Ejemplo n.º 17
0
 public HubConnection(Func <IConnection> connectionFactory, IHubProtocol protocol) : this(connectionFactory, protocol, NullLoggerFactory.Instance)
 {
 }
 public BlazorHubProtocolDerivedHttpOptionsConfigurer(IHubProtocol hubProtocol)
 {
     _defaultTransferFormat = hubProtocol.TransferFormat;
 }
Ejemplo n.º 19
0
        private static HubConnection CreateConnection(string url, HttpTransportType transportType, IHubProtocol protocol, ILoggerFactory loggerFactory, string userName = null)
        {
            var hubConnectionBuilder = new HubConnectionBuilder()
                                       .WithLoggerFactory(loggerFactory)
                                       .WithUrl(url, transportType, httpConnectionOptions =>
            {
                if (!string.IsNullOrEmpty(userName))
                {
                    httpConnectionOptions.Headers["UserName"] = userName;
                }
            });

            hubConnectionBuilder.Services.AddSingleton(protocol);

            return(hubConnectionBuilder.Build());
        }
Ejemplo n.º 20
0
 public static IHubConnectionBuilder WithHubProtocol(this IHubConnectionBuilder hubConnectionBuilder, IHubProtocol hubProtocol)
 {
     hubConnectionBuilder.AddSetting(HubConnectionBuilderDefaults.HubProtocolKey, hubProtocol);
     return(hubConnectionBuilder);
 }
Ejemplo n.º 21
0
 public HubConnection(IConnectionFactory connectionFactory, IHubProtocol protocol, EndPoint endPoint, IServiceProvider serviceProvider, ILoggerFactory loggerFactory, IRetryPolicy reconnectPolicy) : base(connectionFactory, protocol, endPoint, serviceProvider, loggerFactory, reconnectPolicy)
 {
     MakeProxy(new ProxyGenerator());
 }
Ejemplo n.º 22
0
        public async Task ServerThrowsHubExceptionIfNonStreamMethodInvokedWithStreamAsync(IHubProtocol hubProtocol, TransportType transportType, string hubPath)
        {
            using (StartLog(out var loggerFactory))
            {
                var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + hubPath), transportType, loggerFactory);
                var connection     = new HubConnection(httpConnection, hubProtocol, loggerFactory);
                try
                {
                    await connection.StartAsync().OrTimeout();

                    var channel = await connection.StreamAsync <int>("HelloWorld").OrTimeout();

                    var ex = await Assert.ThrowsAsync <HubException>(() => channel.ReadAllAsync()).OrTimeout();

                    Assert.Equal("The client attempted to invoke the non-streaming 'HelloWorld' method in a streaming fashion.", ex.Message);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test");
                    throw;
                }
                finally
                {
                    await connection.DisposeAsync().OrTimeout();
                }
            }
        }
Ejemplo n.º 23
0
 public TestHubProtocolResolver(IHubProtocol instance)
 {
     AllProtocols = new[] { instance };
     _instance    = instance;
 }
Ejemplo n.º 24
0
 public SerializedMessage(IHubProtocol protocol, byte[] message)
 {
     Protocol = protocol;
     Message  = message;
 }
Ejemplo n.º 25
0
        public async Task ServerThrowsHubExceptionIfStreamingHubMethodCannotBeResolved(IHubProtocol hubProtocol, TransportType transportType, string hubPath)
        {
            using (StartLog(out var loggerFactory))
            {
                var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + hubPath), transportType, loggerFactory);
                var connection     = new HubConnection(httpConnection, hubProtocol, loggerFactory);
                try
                {
                    await connection.StartAsync().OrTimeout();

                    var channel = await connection.StreamAsync <int>("!@#$%");

                    var ex = await Assert.ThrowsAsync <HubException>(() => channel.ReadAllAsync().OrTimeout());

                    Assert.Equal("Unknown hub method '!@#$%'", ex.Message);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test");
                    throw;
                }
                finally
                {
                    await connection.DisposeAsync().OrTimeout();
                }
            }
        }
Ejemplo n.º 26
0
        public async Task HubConnectionCanSendAndReceiveMessages(TransportType transportType, IHubProtocol protocol)
        {
            using (StartLog(out var loggerFactory, testName:
                            $"{nameof(HubConnectionCanSendAndReceiveMessages)}_{transportType.ToString()}_{protocol.Name}"))
            {
                var connection = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, loggerFactory);

                await connection.StartAsync().OrTimeout();

                var str = await connection.InvokeAsync <string>("Echo", "Hello, World!").OrTimeout();

                Assert.Equal("Hello, World!", str);

                await connection.DisposeAsync().OrTimeout();
            }
        }
Ejemplo n.º 27
0
        public async Task ServerThrowsHubExceptionOnStreamingHubMethodArgumentTypeMismatch(IHubProtocol hubProtocol, TransportType transportType, string hubPath)
        {
            using (StartLog(out var loggerFactory))
            {
                var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + hubPath), transportType, loggerFactory);
                var connection     = new HubConnection(httpConnection, hubProtocol, loggerFactory);
                try
                {
                    await connection.StartAsync().OrTimeout();

                    var channel = await connection.StreamAsync <int>("Stream", "xyz");

                    var ex = await Assert.ThrowsAsync <HubException>(() => channel.ReadAllAsync().OrTimeout());

                    Assert.StartsWith("Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked.", ex.Message);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test");
                    throw;
                }
                finally
                {
                    await connection.DisposeAsync().OrTimeout();
                }
            }
        }
Ejemplo n.º 28
0
        private static HubConnection CreateConnection(string url, HttpTransportType transportType, IHubProtocol protocol, ILoggerFactory loggerFactory)
        {
            var hubConnectionBuilder = new HubConnectionBuilder()
                                       .WithLoggerFactory(loggerFactory)
                                       .WithUrl(url, transportType);

            hubConnectionBuilder.Services.AddSingleton(protocol);

            return(hubConnectionBuilder.Build());
        }
Ejemplo n.º 29
0
        public async Task ServerThrowsHubExceptionIfBuildingAsyncEnumeratorIsNotPossible(IHubProtocol hubProtocol, TransportType transportType, string hubPath)
        {
            using (StartLog(out var loggerFactory))
            {
                var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + hubPath), transportType, loggerFactory);
                var connection     = new HubConnection(httpConnection, hubProtocol, loggerFactory);
                try
                {
                    await connection.StartAsync().OrTimeout();

                    var channel = await connection.StreamAsync <int>("StreamBroken").OrTimeout();

                    var ex = await Assert.ThrowsAsync <HubException>(() => channel.ReadAllAsync()).OrTimeout();

                    Assert.Equal("The value returned by the streaming method 'StreamBroken' is null, does not implement the IObservable<> interface or is not a ReadableChannel<>.", ex.Message);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test");
                    throw;
                }
                finally
                {
                    await connection.DisposeAsync().OrTimeout();
                }
            }
        }
Ejemplo n.º 30
0
 public WrappedHubProtocol(string name, IHubProtocol innerProtocol)
 {
     _name          = name;
     _innerProtocol = innerProtocol;
 }