示例#1
0
        public HubFacade(IConfigurationRoot configuration, ILogger logger)
        {
            this.logger = logger;
            var builder = new HubConnectionBuilder();

            builder.AddJsonProtocol(options =>
            {
                //set serialization options to be able to deserialize interfaces
                options.PayloadSerializerSettings.TypeNameHandling = TypeNameHandling.Objects;
            });
            var url = configuration.GetValue <string>("HubUrl");

            builder.WithUrl(url);
            logger.LogTrace($"Creating hub for {url}");
            if (bool.Parse(configuration["HubDebugLogging"]))
            {
                builder.ConfigureLogging(b =>
                {
                    b.AddProvider(new RpiConsoleLoggerProvider());
                });
            }

            Client         = builder.Build();
            Client.Closed += TryReconnect;
            Client.On <RpiOperationContract>("ServerToClient", ReceiveMessage);
        }
示例#2
0
        public async Task <bool> ConnectAsync(Uri uri, bool prerendered)
        {
            var builder = new HubConnectionBuilder();

            builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IHubProtocol, IgnitorMessagePackHubProtocol>());
            builder.WithUrl(GetHubUrl(uri));
            builder.ConfigureLogging(l => l.AddConsole().SetMinimumLevel(LogLevel.Trace));

            HubConnection = builder.Build();
            await HubConnection.StartAsync(CancellationToken);

            HubConnection.On <int, string, string>("JS.BeginInvokeJS", OnBeginInvokeJS);
            HubConnection.On <int, int, byte[]>("JS.RenderBatch", OnRenderBatch);
            HubConnection.On <Error>("JS.OnError", OnError);
            HubConnection.Closed += OnClosedAsync;

            // Now everything is registered so we can start the circuit.
            if (prerendered)
            {
                CircuitId = await GetPrerenderedCircuitIdAsync(uri);

                var result = false;
                await ExpectRenderBatch(async() => result = await HubConnection.InvokeAsync <bool>("ConnectCircuit", CircuitId));

                return(result);
            }
            else
            {
                await ExpectRenderBatch(
                    async() => CircuitId = await HubConnection.InvokeAsync <string>("StartCircuit", new Uri(uri.GetLeftPart(UriPartial.Authority)), uri),
                    TimeSpan.FromSeconds(10));

                return(CircuitId != null);
            }
        }
示例#3
0
文件: Program.cs 项目: y8x/AspNetCore
        public async Task ExecuteAsync(Uri uri)
        {
            string circuitId = await GetPrerenderedCircuitId(uri);

            var builder = new HubConnectionBuilder();

            builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IHubProtocol, IgnitorMessagePackHubProtocol>());
            builder.WithUrl(new Uri(uri, "_blazor/"));
            builder.ConfigureLogging(l => l.AddConsole().SetMinimumLevel(LogLevel.Trace));
            var hive = new ElementHive();

            await using var connection = builder.Build();
            await connection.StartAsync(CancellationToken);

            Console.WriteLine("Connected");

            connection.On <int, string, string>("JS.BeginInvokeJS", OnBeginInvokeJS);
            connection.On <int, int, byte[]>("JS.RenderBatch", OnRenderBatch);
            connection.On <Error>("JS.OnError", OnError);
            connection.Closed += OnClosedAsync;

            // Now everything is registered so we can start the circuit.
            var success = await connection.InvokeAsync <bool>("ConnectCircuit", circuitId);

            await TaskCompletionSource.Task;

            void OnBeginInvokeJS(int asyncHandle, string identifier, string argsJson)
            {
                Console.WriteLine("JS Invoke: " + identifier + " (" + argsJson + ")");
            }

            void OnRenderBatch(int browserRendererId, int batchId, byte[] batchData)
            {
                var batch = RenderBatchReader.Read(batchData);

                hive.Update(batch);

                // This will click the Counter component repeatedly resulting in infinite requests.
                _ = ClickAsync("thecounter", hive, connection);
            }

            void OnError(Error error)
            {
                Console.WriteLine("ERROR: " + error.Stack);
            }

            Task OnClosedAsync(Exception ex)
            {
                if (ex == null)
                {
                    TaskCompletionSource.TrySetResult(null);
                }
                else
                {
                    TaskCompletionSource.TrySetException(ex);
                }

                return(Task.CompletedTask);
            }
        }
 /// <summary>
 /// Configures all the services of the application on the given <see cref="IServiceCollection"/>.
 /// </summary>
 /// <param name="services">This <see cref="IServiceCollection"/> will obtain the various service registrations of the application</param>
 /// <param name="environment">Depending on this <see cref="IHostEnvironment"/> the SignalR standard logging will be configured accordingly.</param>
 /// <param name="configuration">This <see cref="IConfiguration"/> will be used as the source for the <see cref="AppSettings"/>.</param>
 /// <returns>Returns the given <paramref name="services"/> again.</returns>
 private static IServiceCollection ConfigureServices(this IServiceCollection services, IHostEnvironment environment, IConfiguration configuration)
 {
     return(services
            .Configure <AppSettings>(configuration)
            .AddAutoMapper(typeof(HubConnectionStateProfile))
            .AddTransient <IAsyncCommand, AsyncCommand>()
            .AddSingleton(provider =>
     {
         var hubConnectionBuilder = new HubConnectionBuilder()
                                    .ConfigureLogging(builder => builder.AddConfiguration(configuration.GetSection(LoggingSectionName)));
         if (environment.IsDevelopment())
         {
             hubConnectionBuilder = hubConnectionBuilder.ConfigureLogging(builder => builder.AddDebug());
         }
         return hubConnectionBuilder;
     })
            .AddSingleton <ChatClient>()
            .AddSingleton <IHostedService>(provider => provider.GetRequiredService <ChatClient>())
            .AddSingleton <IChatClient>(provider => provider.GetRequiredService <ChatClient>())
            .AddSingleton <IDispatcher, DispatcherAdapter>()
            .AddSingleton <IUserSession, UserSession>()
            .AddSingleton <MainViewModel>()
            .AddSingleton <MainWindow>()
            // The following types need to be scoped. Like this they will dispose correctly during view changes.
            .AddScoped <LoginViewModel>()
            .AddScoped <LoginControl>()
            .AddScoped <ChatViewModel>()
            .AddScoped <ChatControl>());
 }
示例#5
0
    public async Task <bool> ConnectAsync(Uri uri, bool connectAutomatically = true, Action <HubConnectionBuilder, Uri>?configure = null)
    {
        var builder = new HubConnectionBuilder();

        builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IHubProtocol, IgnitorMessagePackHubProtocol>());
        var hubUrl = GetHubUrl(uri);

        builder.WithUrl(hubUrl);
        builder.ConfigureLogging(l =>
        {
            l.SetMinimumLevel(LogLevel.Trace);
            if (LoggerProvider != null)
            {
                l.AddProvider(LoggerProvider);
            }
        });

        configure?.Invoke(builder, hubUrl);

        _hubConnection = builder.Build();

        HubConnection.On <int, string>("JS.AttachComponent", OnAttachComponent);
        HubConnection.On <int, string, string, int, long>("JS.BeginInvokeJS", OnBeginInvokeJS);
        HubConnection.On <string>("JS.EndInvokeDotNet", OnEndInvokeDotNet);
        HubConnection.On <int, byte[]>("JS.RenderBatch", OnRenderBatch);
        HubConnection.On <string>("JS.Error", OnError);
        HubConnection.Closed += OnClosedAsync;

        for (var i = 0; i < 10; i++)
        {
            try
            {
                await HubConnection.StartAsync(CancellationToken);

                break;
            }
            catch
            {
                await Task.Delay(500);

                // Retry 10 times
            }
        }

        if (!connectAutomatically)
        {
            return(true);
        }

        var descriptors = await GetPrerenderDescriptors(uri);

        await ExpectRenderBatch(
            async() => CircuitId = await HubConnection.InvokeAsync <string>("StartCircuit", uri, uri, descriptors, null, CancellationToken),
            DefaultConnectionTimeout);

        return(CircuitId != null);
    }
示例#6
0
        protected void CreateConnections(HttpTransportType transportType = HttpTransportType.WebSockets)
        {
            _pkg.Connections = new List <HubConnection>(_pkg.Job.Connections);
            _pkg.SentMassage = new List <int>(_pkg.Job.Connections);

            for (var i = 0; i < _pkg.Job.Connections; i++)
            {
                var hubConnectionBuilder = new HubConnectionBuilder()
                                           .WithUrl(_pkg.Job.ServerBenchmarkUri, transportType, httpConnectionOptions =>
                {
                    httpConnectionOptions.HttpMessageHandlerFactory = _ => _httpClientHandler;
                    httpConnectionOptions.Transports   = transportType;
                    httpConnectionOptions.CloseTimeout = TimeSpan.FromMinutes(100);
                    //httpConnectionOptions.SkipNegotiation = true;
                    //httpConnectionOptions.Url = new Uri(_pkg.Job.ServerBenchmarkUri);
                });

                //hubConnectionBuilder = hubConnectionBuilder.ConfigureLogging(builder => builder.SetMinimumLevel(LogLevel.Trace));

                HubConnection connection = null;
                switch (_pkg.Job.HubProtocol)
                {
                case "json":
                    // json hub protocol is set by default
                    connection = hubConnectionBuilder.ConfigureLogging(builder => builder.SetMinimumLevel(LogLevel.Debug)).Build();
                    break;

                case "messagepack":
                    connection = hubConnectionBuilder.AddMessagePackProtocol().ConfigureLogging(builder => builder.SetMinimumLevel(LogLevel.Trace)).Build();
                    break;

                default:
                    throw new Exception($"{_pkg.Job.HubProtocol} is an invalid hub protocol name.");
                }


                _pkg.Connections.Add(connection);
                _pkg.SentMassage.Add(0);
                // Capture the connection ID
                var ind = i;

                connection.Closed += e =>
                {
                    if (!_stopped)
                    {
                        var error = $"{ind}th Connection closed early: {e}";
                        _pkg.Job.Error += Environment.NewLine + $"[{DateTime.Now.ToString("hh:mm:ss.fff")}] " + error;
                        Util.Log(error);
                    }

                    return(Task.CompletedTask);
                };
            }
        }
示例#7
0
        protected HubConnection Connect()
        {
            var uri = new Uri(_sockets.BaseUrl.UriCombine(SignalRHubUrls.ChatUrl));
            var hubConnectionBuilder = new HubConnectionBuilder().WithUrl(uri);

            if (_sockets.OverrideLogging != null)
            {
                hubConnectionBuilder = hubConnectionBuilder.ConfigureLogging(_sockets.OverrideLogging);
            }
            var hubConnection = hubConnectionBuilder.Build();

            return(hubConnection);
        }
示例#8
0
        public async Task <bool> ConnectAsync(Uri uri, bool prerendered, bool connectAutomatically = true)
        {
            var builder = new HubConnectionBuilder();

            builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IHubProtocol, IgnitorMessagePackHubProtocol>());
            builder.WithUrl(GetHubUrl(uri));
            builder.ConfigureLogging(l =>
            {
                l.SetMinimumLevel(LogLevel.Trace);
                if (LoggerProvider != null)
                {
                    l.AddProvider(LoggerProvider);
                }
            });

            HubConnection = builder.Build();
            await HubConnection.StartAsync(CancellationToken);

            HubConnection.On <int, string, string>("JS.BeginInvokeJS", OnBeginInvokeJS);
            HubConnection.On <string>("JS.EndInvokeDotNet", OnEndInvokeDotNet);
            HubConnection.On <int, byte[]>("JS.RenderBatch", OnRenderBatch);
            HubConnection.On <string>("JS.Error", OnError);
            HubConnection.Closed += OnClosedAsync;

            if (!connectAutomatically)
            {
                return(true);
            }

            // Now everything is registered so we can start the circuit.
            if (prerendered)
            {
                CircuitId = await GetPrerenderedCircuitIdAsync(uri);

                var result = false;
                await ExpectRenderBatch(async() => result = await HubConnection.InvokeAsync <bool>("ConnectCircuit", CircuitId));

                return(result);
            }
            else
            {
                await ExpectRenderBatch(
                    async() => CircuitId = await HubConnection.InvokeAsync <string>("StartCircuit", uri, uri),
                    TimeSpan.FromSeconds(10));

                return(CircuitId != null);
            }
        }
示例#9
0
        public async Task <bool> ConnectAsync(Uri uri, bool connectAutomatically = true)
        {
            var builder = new HubConnectionBuilder();

            builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IHubProtocol, IgnitorMessagePackHubProtocol>());
            builder.WithUrl(GetHubUrl(uri));
            builder.ConfigureLogging(l =>
            {
                l.SetMinimumLevel(LogLevel.Trace);
                if (LoggerProvider != null)
                {
                    l.AddProvider(LoggerProvider);
                }
            });

            HubConnection = builder.Build();
            await HubConnection.StartAsync(CancellationToken);

            HubConnection.On <int, string>("JS.AttachComponent", OnAttachComponent);
            HubConnection.On <int, string, string>("JS.BeginInvokeJS", OnBeginInvokeJS);
            HubConnection.On <string>("JS.EndInvokeDotNet", OnEndInvokeDotNet);
            HubConnection.On <int, byte[]>("JS.RenderBatch", OnRenderBatch);
            HubConnection.On <string>("JS.Error", OnError);
            HubConnection.Closed += OnClosedAsync;

            if (CaptureOperations)
            {
                Operations = new Operations();
            }

            if (!connectAutomatically)
            {
                return(true);
            }

            var descriptors = await GetPrerenderDescriptors(uri);

            await ExpectRenderBatch(
                async() => CircuitId = await HubConnection.InvokeAsync <string>("StartCircuit", uri, uri, descriptors),
                DefaultConnectionTimeout);

            return(CircuitId != null);
        }
        public async Task Build(string host)
        {
            var builder = new HubConnectionBuilder()
                          .WithUrl(host)
                          .WithAutomaticReconnect();

            if (this.VerboseMode)
            {
                builder.ConfigureLogging(logging => logging.AddConsole());
            }

            this.connection               = builder.Build();
            this.connection.Closed       += this.HandleClosed;
            this.connection.Reconnected  += this.HandleReconnected;
            this.connection.Reconnecting += this.HandleReconnecting;
            await this.connection.StartAsync();

            if (!this.QuiteMode)
            {
                Console.Error.WriteLine(this.connection.State);
            }
        }
示例#11
0
        public async Task ExecuteAsync(Uri uri)
        {
            var httpClient = new HttpClient();
            var response   = await httpClient.GetAsync(uri);

            var content = await response.Content.ReadAsStringAsync();

            // <!-- M.A.C.Component:{"circuitId":"CfDJ8KZCIaqnXmdF...PVd6VVzfnmc1","rendererId":"0","componentId":"0"} -->
            var match     = Regex.Match(content, $"{Regex.Escape("<!-- M.A.C.Component:")}(.+?){Regex.Escape(" -->")}");
            var json      = JsonDocument.Parse(match.Groups[1].Value);
            var circuitId = json.RootElement.GetProperty("circuitId").GetString();

            var builder = new HubConnectionBuilder();

            builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IHubProtocol, IgnitorMessagePackHubProtocol>());
            builder.WithUrl(new Uri(uri, "_blazor/"));
            builder.ConfigureLogging(l => l.AddConsole().SetMinimumLevel(LogLevel.Trace));
            var hive = new ElementHive();

            await using var connection = builder.Build();
            await connection.StartAsync(CancellationToken);

            Console.WriteLine("Connected");

            connection.On <int, string, string>("JS.BeginInvokeJS", OnBeginInvokeJS);
            connection.On <int, int, byte[]>("JS.RenderBatch", OnRenderBatch);
            connection.On <Error>("JS.OnError", OnError);
            connection.Closed += OnClosedAsync;

            // Now everything is registered so we can start the circuit.
            var success = await connection.InvokeAsync <bool>("ConnectCircuit", circuitId);

            await TaskCompletionSource.Task;

            void OnBeginInvokeJS(int asyncHandle, string identifier, string argsJson)
            {
                Console.WriteLine("JS Invoke: " + identifier + " (" + argsJson + ")");
            }

            void OnRenderBatch(int browserRendererId, int batchId, byte[] batchData)
            {
                var batch = RenderBatchReader.Read(batchData);

                hive.Update(batch);

                // This will click the Counter component repeatedly resulting in infinite requests.
                _ = ClickAsync("thecounter", hive, connection);
            }

            void OnError(Error error)
            {
                Console.WriteLine("ERROR: " + error.Stack);
            }

            Task OnClosedAsync(Exception ex)
            {
                if (ex == null)
                {
                    TaskCompletionSource.TrySetResult(null);
                }
                else
                {
                    TaskCompletionSource.TrySetException(ex);
                }

                return(Task.CompletedTask);
            }
        }
示例#12
0
        public async Task <bool> ConnectAsync(Uri uri, bool prerendered)
        {
            var builder = new HubConnectionBuilder();

            builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IHubProtocol, IgnitorMessagePackHubProtocol>());
            builder.WithUrl(new Uri(uri, "_blazor/"));
            builder.ConfigureLogging(l => l.AddConsole().SetMinimumLevel(LogLevel.Trace));
            var hive = new ElementHive();

            HubConnection = builder.Build();
            await HubConnection.StartAsync(CancellationToken);

            Console.WriteLine("Connected");

            HubConnection.On <int, string, string>("JS.BeginInvokeJS", OnBeginInvokeJS);
            HubConnection.On <int, int, byte[]>("JS.RenderBatch", OnRenderBatch);
            HubConnection.On <Error>("JS.OnError", OnError);
            HubConnection.Closed += OnClosedAsync;

            // Now everything is registered so we can start the circuit.
            if (prerendered)
            {
                CircuitId = await GetPrerenderedCircuitIdAsync(uri);

                return(await HubConnection.InvokeAsync <bool>("ConnectCircuit", CircuitId));
            }
            else
            {
                CircuitId = await HubConnection.InvokeAsync <string>("StartCircuit", uri, uri);

                return(CircuitId != null);
            }

            void OnBeginInvokeJS(int asyncHandle, string identifier, string argsJson)
            {
                JSInterop?.Invoke(asyncHandle, identifier, argsJson);
            }

            void OnRenderBatch(int browserRendererId, int batchId, byte[] batchData)
            {
                var batch = RenderBatchReader.Read(batchData);

                hive.Update(batch);

                if (ConfirmRenderBatch)
                {
                    HubConnection.InvokeAsync("OnRenderCompleted", batchId, /* error */ null);
                }

                RenderBatchReceived?.Invoke(browserRendererId, batchId, batchData);
            }

            void OnError(Error error)
            {
                Console.WriteLine("ERROR: " + error.Stack);
            }

            Task OnClosedAsync(Exception ex)
            {
                if (ex == null)
                {
                    TaskCompletionSource.TrySetResult(null);
                }
                else
                {
                    TaskCompletionSource.TrySetException(ex);
                }

                return(Task.CompletedTask);
            }
        }