Ejemplo n.º 1
0
        private TestServiceConnection MockServiceConnection(IConnectionFactory serviceConnectionFactory      = null,
                                                            IClientConnectionFactory clientConnectionFactory = null,
                                                            ILoggerFactory loggerFactory = null,
                                                            GracefulShutdownMode mode    = GracefulShutdownMode.Off)
        {
            clientConnectionFactory ??= new ClientConnectionFactory();
            serviceConnectionFactory ??= new TestConnectionFactory(conn => Task.CompletedTask);
            loggerFactory ??= NullLoggerFactory.Instance;

            var services          = new ServiceCollection();
            var connectionHandler = new EndlessConnectionHandler();

            services.AddSingleton(connectionHandler);
            var builder = new ConnectionBuilder(services.BuildServiceProvider());

            builder.UseConnectionHandler <EndlessConnectionHandler>();
            ConnectionDelegate handler = builder.Build();

            return(new TestServiceConnection(
                       serviceConnectionFactory,
                       clientConnectionFactory,
                       loggerFactory,
                       handler,
                       mode: mode
                       ));
        }
Ejemplo n.º 2
0
        private async Task GetContextAsync(int databaseId)
        {
            var connectionDetails = (await metaUow.DatabaseRepository.GetAsync(databaseId)).ConnectionDetails;
            var connection        = ConnectionBuilder.Build(connectionDetails);

            uow = new PositionUnitOfWork(connection);
        }
Ejemplo n.º 3
0
        private void GetContext(int databaseId)
        {
            var connectionDetails = (metaUow.DatabaseRepository.Get(databaseId)).ConnectionDetails;
            var connection        = ConnectionBuilder.Build(connectionDetails);

            uow = new PositionUnitOfWork(connection);
        }
Ejemplo n.º 4
0
        public async Task StartAsync <TContext>(IHttpApplication <TContext> application, CancellationToken cancellationToken)
        {
            try
            {
                // Kestrel does not support big-endian architectures. Kestrel
                // 不支持大端模式的处理器
                //https://www.cnblogs.com/little-white/p/3236548.html
                if (!BitConverter.IsLittleEndian)
                {
                    throw new PlatformNotSupportedException(CoreStrings.BigEndianNotSupported);
                }
                EndPoint endPoint;
                if (ServerOptions.Host.StartsWith("unix://", StringComparison.Ordinal))
                {
                    endPoint = new UnixDomainSocketEndPoint(ServerOptions.Host.Substring(ServerOptions.Host.IndexOf("unix://") + 1));
                }
                else if (ServerOptions.Host.Contains("localhost"))
                {
                    endPoint = new IPEndPoint(IPAddress.Loopback, ServerOptions.Port);
                }
                else if (IPAddress.TryParse(ServerOptions.Host, out var ip))
                {
                    endPoint = new IPEndPoint(ip, ServerOptions.Port);
                }
                else
                {
                    endPoint = new IPEndPoint(IPAddress.IPv6Any, ServerOptions.Port);
                }
                async Task OnBind(EndPoint _endPoint)
                {
                    // 构建委托:用于处理socket请求
                    var connectionBuilder = new ConnectionBuilder();

                    connectionBuilder.Use(next => { return(new HttpConnectionMiddleware <TContext>(application).OnConnectionAsync); });
                    var connectionDelegate = connectionBuilder.Build();

                    // Add the connection limit middleware
                    //if (Options.Limits.MaxConcurrentConnections.HasValue)
                    //{
                    //    connectionDelegate = new ConnectionLimitMiddleware(connectionDelegate, Options.Limits.MaxConcurrentConnections.Value, Trace).OnConnectionAsync;
                    //}

                    // 构建服务端Socket: 用于进行监听客户端请求
                    var g         = _transportFactory.BindAsync(_endPoint).Result;
                    var transport = await _transportFactory.BindAsync(_endPoint).ConfigureAwait(false);

                    // 通过 ThreadPool.UnsafeQueueUserWorkItem,分配任务: 服务端接收 socket请求连接,处理请求
                    var connectionDispatcher = new ConnectionDispatcher(connectionDelegate, ServiceContext);
                    var acceptLoopTask       = connectionDispatcher.StartAcceptingConnections(transport);
                }
                await OnBind(endPoint);
            }
            catch (Exception ex)
            {
                Dispose();
                throw;
            }
            throw new NotImplementedException();
        }
        public async Task TestServiceConnectionWithEndlessApplicationTaskNeverEnds()
        {
            var clientConnectionId = Guid.NewGuid().ToString();

            using (StartVerifiableLog(out var loggerFactory, LogLevel.Warning, expectedErrors: c => true,
                                      logChecker: logs =>
            {
                Assert.Single(logs);
                Assert.Equal("DetectedLongRunningApplicationTask", logs[0].Write.EventId.Name);
                Assert.Equal($"The connection {clientConnectionId} has a long running application logic that prevents the connection from complete.", logs[0].Write.Message);
                return(true);
            }))
            {
                var            ccm                 = new TestClientConnectionManager();
                var            ccf                 = new ClientConnectionFactory();
                var            protocol            = new ServiceProtocol();
                TestConnection transportConnection = null;
                var            connectionFactory   = new TestConnectionFactory(conn =>
                {
                    transportConnection = conn;
                    return(Task.CompletedTask);
                });
                var services          = new ServiceCollection();
                var connectionHandler = new EndlessConnectionHandler();
                services.AddSingleton(connectionHandler);
                var builder = new ConnectionBuilder(services.BuildServiceProvider());
                builder.UseConnectionHandler <EndlessConnectionHandler>();
                ConnectionDelegate handler = builder.Build();
                var connection             = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf,
                                                                   "serverId", Guid.NewGuid().ToString("N"),
                                                                   null, null, null, closeTimeOutMilliseconds: 1);

                var connectionTask = connection.StartAsync();

                // completed handshake
                await connection.ConnectionInitializedTask.OrTimeout();

                Assert.Equal(ServiceConnectionStatus.Connected, connection.Status);

                await transportConnection.Application.Output.WriteAsync(
                    protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { })));

                var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout();

                // complete reading to end the connection
                transportConnection.Application.Output.Complete();

                // Assert timeout
                var lifetime = clientConnection.LifetimeTask;
                var task     = await Task.WhenAny(lifetime, Task.Delay(1000));

                Assert.NotEqual(lifetime, task);

                Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status);

                // since the service connection ends, the client connection is cleaned up from the collection...
                Assert.Empty(ccm.ClientConnections);
            }
        }
Ejemplo n.º 6
0
        public async Task ClientConnectionOutgoingAbortCanEndLifeTime()
        {
            using (StartVerifiableLog(out var loggerFactory, LogLevel.Warning, expectedErrors: c => true,
                                      logChecker: logs =>
            {
                Assert.Equal(2, logs.Count);
                Assert.Equal("SendLoopStopped", logs[0].Write.EventId.Name);
                Assert.Equal("ApplicationTaskFailed", logs[1].Write.EventId.Name);
                return(true);
            }))
            {
                var            ccm                 = new TestClientConnectionManager();
                var            ccf                 = new ClientConnectionFactory();
                var            protocol            = new ServiceProtocol();
                TestConnection transportConnection = null;
                var            connectionFactory   = new TestConnectionFactory(conn =>
                {
                    transportConnection = conn;
                    return(Task.CompletedTask);
                });
                var services          = new ServiceCollection();
                var connectionHandler = new EndlessConnectionHandler();
                services.AddSingleton(connectionHandler);
                var builder = new ConnectionBuilder(services.BuildServiceProvider());
                builder.UseConnectionHandler <EndlessConnectionHandler>();
                ConnectionDelegate handler = builder.Build();
                var connection             = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf,
                                                                   "serverId", Guid.NewGuid().ToString("N"), null, null,
                                                                   closeTimeOutMilliseconds: 500);

                var connectionTask = connection.StartAsync();

                // completed handshake
                await connection.ConnectionInitializedTask.OrTimeout();

                Assert.Equal(ServiceConnectionStatus.Connected, connection.Status);
                var clientConnectionId = Guid.NewGuid().ToString();

                await transportConnection.Application.Output.WriteAsync(
                    protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { })));

                var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout();

                clientConnection.CancelOutgoing();

                await clientConnection.LifetimeTask.OrTimeout();

                // complete reading to end the connection
                transportConnection.Application.Output.Complete();

                // 1s for application task to timeout
                await connectionTask.OrTimeout(1000);

                Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status);
                Assert.Empty(ccm.ClientConnections);

                connectionHandler.CancellationToken.Cancel();
            }
        }
Ejemplo n.º 7
0
        public static ServerBuilder Listen(this ServerBuilder builder, EndPoint endPoint, IConnectionListenerFactory connectionListenerFactory, Action <IConnectionBuilder> configure)
        {
            var connectionBuilder = new ConnectionBuilder(builder.ApplicationServices);

            configure(connectionBuilder);
            builder.Bindings.Add(new EndPointBinding(endPoint, connectionBuilder.Build(), connectionListenerFactory));
            return(builder);
        }
Ejemplo n.º 8
0
        public async Task ClientConnectionWithDiagnosticClientTagTest()
        {
            using (StartVerifiableLog(out var loggerFactory))
            {
                var            ccm                 = new TestClientConnectionManager();
                var            ccf                 = new ClientConnectionFactory();
                var            protocol            = new ServiceProtocol();
                TestConnection transportConnection = null;
                var            connectionFactory   = new TestConnectionFactory(conn =>
                {
                    transportConnection = conn;
                    return(Task.CompletedTask);
                });

                var diagnosticClientConnectionId = "diagnosticClient";
                var normalClientConnectionId     = "normalClient";

                var services          = new ServiceCollection();
                var connectionHandler = new DiagnosticClientConnectionHandler(diagnosticClientConnectionId);
                services.AddSingleton(connectionHandler);
                var builder = new ConnectionBuilder(services.BuildServiceProvider());
                builder.UseConnectionHandler <DiagnosticClientConnectionHandler>();
                ConnectionDelegate handler = builder.Build();

                var connection = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf,
                                                       "serverId", Guid.NewGuid().ToString("N"), null, null, closeTimeOutMilliseconds: 500);

                var connectionTask = connection.StartAsync();

                // completed handshake
                await connection.ConnectionInitializedTask.OrTimeout();

                Assert.Equal(ServiceConnectionStatus.Connected, connection.Status);

                await transportConnection.Application.Output.WriteAsync(
                    protocol.GetMessageBytes(new OpenConnectionMessage(diagnosticClientConnectionId, null, new Dictionary <string, StringValues>
                {
                    { Constants.AsrsIsDiagnosticClient, "true" }
                }, null)));

                await transportConnection.Application.Output.WriteAsync(
                    protocol.GetMessageBytes(new OpenConnectionMessage(normalClientConnectionId, null)));

                var connections = await Task.WhenAll(ccm.WaitForClientConnectionAsync(normalClientConnectionId).OrTimeout(),
                                                     ccm.WaitForClientConnectionAsync(diagnosticClientConnectionId).OrTimeout());

                await Task.WhenAll(from c in connections select c.LifetimeTask.OrTimeout());

                // complete reading to end the connection
                transportConnection.Application.Output.Complete();

                // 1s for application task to timeout
                await connectionTask.OrTimeout(1000);

                Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status);
                Assert.Empty(ccm.ClientConnections);
            }
        }
Ejemplo n.º 9
0
        static void main2()
        {
            var m = new Prasatec.Cu2Com.Data.User();

            m.Login = "******";
            m.Email = "root@localhost";
            var b = new ConnectionBuilder <Raden.Engines.MysqlEngine>()
                    .Server("nctslaws")
                    .Database("timetrack")
                    .Username("timetrack")
                    .Password("timetrack");
            var c        = b.Build();
            var qbuilder = new QueryBuilder <Prasatec.Cu2Com.Data.User>()
                           .Where(x => x.ID, 2)

                           /*.Where(x => x.ID, 4, QueryLogicalOperators.LogicalOr, QueryComparisonOperators.IsLike, 4, "*")
                            * .Where<Prasatec.Cu2Com.Data.Role>(x => x.ID, y => y.Role, QueryLogicalOperators.LogicalOr, QueryComparisonOperators.EqualTo, 3)
                            * .Group(x => x.Role)
                            * .Having(x => x.ID, 4, QueryLogicalOperators.LogicalOr, QueryComparisonOperators.IsNotNull, 4, "*", QueryColumnActions.Count)
                            * .Sort(x => x.Name, QuerySortDirections.Descending)
                            * .SetLimit(100, 13)*/;
            var q = qbuilder.Build();
            var r = c.Retrieve <Prasatec.Cu2Com.Data.User>(q);// m);

            m = r.Records[0];
            c.Update <User>(q, m);

            /*foreach (var p in q.Parameters)
             * {
             *  Console.WriteLine(p);
             * }*/
            Console.WriteLine("AffectedRows: {0}", r.AffectedRows);
            Console.WriteLine("InsertId: {0}", r.InsertId);
            Console.WriteLine("CountPages: {0}", r.CountPages);
            Console.WriteLine("CountRecords: {0}", r.CountRecords);
            Console.WriteLine("CountTotal: {0}", r.CountTotal);
            Console.WriteLine("ErrorMessage: {0}", r.ErrorMessage);
            Console.WriteLine("ScalarValue: {0}", r.ScalarValue);
            Console.WriteLine("Successful: {0}", r.Successful);
            if (r.Records != null)
            {
                foreach (var record in r.Records)
                {
                    Console.WriteLine("--> Record ID: {0}", record.ID);
                    Console.WriteLine("--> Record Code: {0}", record.Code);
                    Console.WriteLine("--> Record CreatedAt: {0}", record.CreatedAt);
                    Console.WriteLine("--> Record CreatedBy: {0}", record.CreatedBy);
                    Console.WriteLine("--> Record Email: {0}", record.Email);
                    Console.WriteLine("--> Record Login: {0}", record.Login);
                    Console.WriteLine("--> Record ModifiedAt: {0}", record.ModifiedAt);
                    Console.WriteLine("--> Record ModifiedBy: {0}", record.ModifiedBy);
                    Console.WriteLine("--> Record Name: {0}", record.Name);
                    Console.WriteLine("--> Record Password: {0}", record.Password);
                    Console.WriteLine("--> Record Role: {0}", record.Role);
                }
            }
        }
Ejemplo n.º 10
0
        private void cetak_2()
        {
            try
            {
                string text           = System.IO.File.ReadAllText("./settings2.txt");
                var    thePrinterConn = ConnectionBuilder.Build(text);
                try
                {
                    // Open the connection - physical connection is established here.
                    thePrinterConn.Open();

                    // This example prints "This is a ZPL test." near the top of the label.
                    string zplData = "^XA" +
                                     //item id
                                     "^FO015,21^A0,34,24^FD" + txt2AsalBarang.Text + "^FS" +
                                     "^FO440,21^A0,34,24^FD" + txt2AsalBarang.Text + "^FS" +
                                     //item name 1
                                     "^FO015,55^A0,34,24^FD" + txt2NamaBarang.Text + "^FS" +
                                     "^FO440,55^A0,34,24^FD" + txt2NamaBarang.Text + "^FS" +
                                     //item name 2
                                     "^FO015,89^A0,34,24^FD" + txt2TipeMobil.Text + "^FS" +
                                     "^FO440,89^A0,34,24^FD" + txt2TipeMobil.Text + "^FS" +
                                     //item name 3
                                     "^FO015,123^A0,34,24^FD" + txt2KodeJual.Text + "^FS" +
                                     "^FO440,123^A0,34,24^FD" + txt2KodeJual.Text + "^FS" +
                                     //item chinese
                                     "^FO015,156^CI28^A@N,36,30,E:SIMSUN.FNT^FD" + txt2HurufMandarin.Text + "^FS" +
                                     "^FO440,156^CI28^A@N,36,30,E:SIMSUN.FNT^FD" + txt2HurufMandarin.Text + "^FS" +
                                     "^XZ";

                    // Send the data to printer as a byte array.
                    thePrinterConn.Write(Encoding.UTF8.GetBytes(zplData));
                }
                catch (ConnectionException ex)
                {
                    // Handle communications error here.
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    // Close the connection to release resources.
                    thePrinterConn.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Peringatan", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            txt2NamaBarang.Text    = "";
            txt2TipeMobil.Text     = "";
            txt2KodeJual.Text      = "";
            txt2KodeMandarin.Text  = "";
            txt2HurufMandarin.Text = "";
            num2Cetak.Value        = 0;
            txt2NamaBarang.Focus();
        }
Ejemplo n.º 11
0
        public async Task TestServiceConnectionWithNormalApplicationTask()
        {
            using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug))
            {
                var            ccm                 = new TestClientConnectionManager();
                var            ccf                 = new ClientConnectionFactory();
                var            protocol            = new ServiceProtocol();
                TestConnection transportConnection = null;
                var            connectionFactory   = new TestConnectionFactory(conn =>
                {
                    transportConnection = conn;
                    return(Task.CompletedTask);
                });
                var services = new ServiceCollection();
                var builder  = new ConnectionBuilder(services.BuildServiceProvider());
                builder.UseConnectionHandler <TestConnectionHandler>();
                ConnectionDelegate handler = builder.Build();
                var connection             = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf,
                                                                   "serverId", Guid.NewGuid().ToString("N"), null, null);

                var connectionTask = connection.StartAsync();

                // completed handshake
                await connection.ConnectionInitializedTask.OrTimeout();

                Assert.Equal(ServiceConnectionStatus.Connected, connection.Status);
                var clientConnectionId = Guid.NewGuid().ToString();

                await transportConnection.Application.Output.WriteAsync(
                    protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { })));

                var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout();

                await transportConnection.Application.Output.WriteAsync(
                    protocol.GetMessageBytes(new CloseConnectionMessage(clientConnectionId)));

                // Normal end with close message
                await ccm.WaitForClientConnectionRemovalAsync(clientConnectionId).OrTimeout();

                // another connection comes in
                clientConnectionId = Guid.NewGuid().ToString();

                await transportConnection.Application.Output.WriteAsync(
                    protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { })));

                clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout();

                // complete reading to end the connection
                transportConnection.Application.Output.Complete();

                await connectionTask.OrTimeout();

                Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status);
                Assert.Empty(ccm.ClientConnections);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Maps incoming requests with the specified path to the provided connection pipeline.
        /// </summary>
        /// <param name="path">The request path.</param>
        /// <param name="options">Options used to configure the connection.</param>
        /// <param name="configure">A callback to configure the connection.</param>
        public void MapConnections(PathString path, HttpConnectionDispatcherOptions options, Action <IConnectionBuilder> configure)
        {
            var connectionBuilder = new ConnectionBuilder(_routes.ServiceProvider);

            configure(connectionBuilder);
            var socket = connectionBuilder.Build();

            _routes.MapRoute(path, c => _dispatcher.ExecuteAsync(c, options, socket));
            _routes.MapRoute(path + "/negotiate", c => _dispatcher.ExecuteNegotiateAsync(c, options));
        }
Ejemplo n.º 13
0
        private void print_label()
        {
            String itemId      = txtItemId.Text;
            String itemName1   = txtItemName1.Text;
            String itemName2   = txtItemName2.Text;
            String itemName3   = txtItemName3.Text;
            String itemChinese = txtItemChinese.Text;
            //Connection thePrinterConn = new TcpConnection("127.0.0.1", TcpConnection.DEFAULT_ZPL_TCP_PORT);
            ///Connection thePrinterConn = new UsbConnection("Port_#0001.Hub_#0004");
            var thePrinterConn = ConnectionBuilder.Build("USB:ZDesigner GT800 (ZPL)");

            try
            {
                // Open the connection - physical connection is established here.
                thePrinterConn.Open();

                // This example prints "This is a ZPL test." near the top of the label.
                string zplData = "^XA" +
                                 //item id
                                 "^FO00,22^A0,38,26^FD" + itemId + "^FS" +
                                 "^FO290,22^A0,38,26^FD" + itemId + "^FS" +
                                 "^FO580,22^A0,38,26^FD" + itemId + "^FS" +
                                 //item name 1
                                 "^FO00,55^A0,30,22^FD" + itemName1 + "^FS" +
                                 "^FO290,55^A0,30,22^FD" + itemName1 + "^FS" +
                                 "^FO580,55^A0,30,22^FD" + itemName1 + "^FS" +
                                 //item name 2
                                 "^FO00,82^A0,30,22^FD" + itemName2 + "^FS" +
                                 "^FO290,82^A0,30,22^FD" + itemName2 + "^FS" +
                                 "^FO580,82^A0,30,22^FD" + itemName2 + "^FS" +
                                 //item name 3
                                 "^FO00,108^A0,30,22^FD" + itemName3 + "^FS" +
                                 "^FO290,108^A0,30,22^FD" + itemName3 + "^FS" +
                                 "^FO580,108^A0,30,22^FD" + itemName3 + "^FS" +
                                 //item chinese
                                 "^FO00,138^CI28^A@N,40,40,E:SIMSUN.FNT^FD" + itemChinese + "^FS" +
                                 "^FO290,138^CI28^A@N,40,40,E:SIMSUN.FNT^FD" + itemChinese + "^FS" +
                                 "^FO580,138^CI28^A@N,40,40,E:SIMSUN.FNT^FD" + itemChinese + "^FS" +
                                 "^XZ";

                // Send the data to printer as a byte array.
                thePrinterConn.Write(Encoding.UTF8.GetBytes(zplData));
            }
            catch (ConnectionException e)
            {
                // Handle communications error here.
                Console.WriteLine(e.ToString());
            }
            finally
            {
                // Close the connection to release resources.
                thePrinterConn.Close();
            }
        }
Ejemplo n.º 14
0
    /// <summary>
    /// Maps incoming requests with the specified path to the provided connection pipeline.
    /// </summary>
    /// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/> to add the route to.</param>
    /// <param name="pattern">The route pattern.</param>
    /// <param name="options">Options used to configure the connection.</param>
    /// <param name="configure">A callback to configure the connection.</param>
    /// <returns>An <see cref="ConnectionEndpointRouteBuilder"/> for endpoints associated with the connections.</returns>
    public static ConnectionEndpointRouteBuilder MapConnections(this IEndpointRouteBuilder endpoints, string pattern, HttpConnectionDispatcherOptions options, Action <IConnectionBuilder> configure)
    {
        var dispatcher = endpoints.ServiceProvider.GetRequiredService <HttpConnectionDispatcher>();

        var connectionBuilder = new ConnectionBuilder(endpoints.ServiceProvider);

        configure(connectionBuilder);
        var connectionDelegate = connectionBuilder.Build();

        // REVIEW: Consider expanding the internals of the dispatcher as endpoint routes instead of
        // using if statements we can let the matcher handle

        var conventionBuilders = new List <IEndpointConventionBuilder>();

        // Build the negotiate application
        var app = endpoints.CreateApplicationBuilder();

        app.UseWebSockets();
        app.Run(c => dispatcher.ExecuteNegotiateAsync(c, options));
        var negotiateHandler = app.Build();

        var negotiateBuilder = endpoints.Map(pattern + "/negotiate", negotiateHandler);

        conventionBuilders.Add(negotiateBuilder);
        // Add the negotiate metadata so this endpoint can be identified
        negotiateBuilder.WithMetadata(_negotiateMetadata);
        negotiateBuilder.WithMetadata(options);

        // build the execute handler part of the protocol
        app = endpoints.CreateApplicationBuilder();
        app.UseWebSockets();
        app.Run(c => dispatcher.ExecuteAsync(c, options, connectionDelegate));
        var executehandler = app.Build();

        var executeBuilder = endpoints.Map(pattern, executehandler);

        conventionBuilders.Add(executeBuilder);

        var compositeConventionBuilder = new CompositeEndpointConventionBuilder(conventionBuilders);

        // Add metadata to all of Endpoints
        compositeConventionBuilder.Add(e =>
        {
            // Add the authorization data as metadata
            foreach (var data in options.AuthorizationData)
            {
                e.Metadata.Add(data);
            }
        });

        return(new ConnectionEndpointRouteBuilder(compositeConventionBuilder));
    }
        public static void Print(string zpl)
        {
            //await Task.Run(() =>
            //{
            //    DiscoveredPrinter discoveredPrinter = GetUSBPrinter();

            //    ZebraPrinter printer = PrintHelper.Connect(discoveredPrinter, PrinterLanguage.ZPL);
            //    PrintHelper.SetPageLanguage(printer);
            //    if (PrintHelper.CheckStatus(printer))
            //    {
            //        PrintHelper.Print(printer, zpl);
            //        if (PrintHelper.CheckStatusAfter(printer))
            //        {
            //            Console.WriteLine($"Label Printed");
            //        }
            //    }
            //    printer = PrintHelper.Disconnect(printer);
            //    Console.WriteLine("Done Printing");
            //});

            Connection thePrinterConn = null;

            try
            {
                var db        = new IPConfigurationManager();
                var ipAddress = db.GetIP();
                // Instantiate connection for ZPL TCP port at given address
                thePrinterConn = ConnectionBuilder.Build($"TCP:{ipAddress}:9100");

                // Open the connection - physical connection is established here.
                thePrinterConn.Open();

                // This example prints "This is a ZPL test." near the top of the label.
                //string zplData = "^XA^FO20,20^A0N,25,25^FDThis is a ZPL test.^FS^XZ";

                // Send the data to printer as a byte array.
                thePrinterConn.Write(Encoding.UTF8.GetBytes(zpl));
            }
            catch (ConnectionException e)
            {
                // Handle communications error here.
                Console.WriteLine(e.ToString());
            }
            finally
            {
                // Close the connection to release resources.
                if (thePrinterConn != null)
                {
                    thePrinterConn.Close();
                }
            }
        }
Ejemplo n.º 16
0
        private void print_label2()
        {
            String asalBarang   = txt2AsalBarang.Text;
            String namaBarang   = txt2NamaBarang.Text;
            String tipeMobil    = txt2TipeMobil.Text;
            String kodeJual     = txt2KodeJual.Text;
            String kodeMandarin = txt2KodeMandarin.Text;
            //Connection thePrinterConn = new TcpConnection("127.0.0.1", TcpConnection.DEFAULT_ZPL_TCP_PORT);
            ///Connection thePrinterConn = new UsbConnection("Port_#0001.Hub_#0004");
            var thePrinterConn = ConnectionBuilder.Build("USB:ZDesigner GT800 (ZPL)");

            try
            {
                // Open the connection - physical connection is established here.
                thePrinterConn.Open();

                // This example prints "This is a ZPL test." near the top of the label.
                string zplData = "^XA" +
                                 //item id
                                 "^FO18,22^A0,38,26^FD" + asalBarang + "^FS" +
                                 "^FO435,22^A0,38,26^FD" + asalBarang + "^FS" +
                                 //item name 1
                                 "^FO18,55^A0,38,26^FD" + namaBarang + "^FS" +
                                 "^FO435,55^A0,38,26^FD" + namaBarang + "^FS" +
                                 //item name 2
                                 "^FO18,88^A0,38,26^FD" + tipeMobil + "^FS" +
                                 "^FO435,88^A0,38,26^FD" + tipeMobil + "^FS" +
                                 //item name 3
                                 "^FO18,121^A0,38,26^FD" + kodeJual + "^FS" +
                                 "^FO435,121^A0,38,26^FD" + kodeJual + "^FS" +
                                 //item chinese
                                 "^FO18,154^CI28^A@N,40,40,E:SIMSUN.FNT^FD" + kodeMandarin + "^FS" +
                                 "^FO435,154^CI28^A@N,40,40,E:SIMSUN.FNT^FD" + kodeMandarin + "^FS" +
                                 "^XZ";

                // Send the data to printer as a byte array.
                thePrinterConn.Write(Encoding.UTF8.GetBytes(zplData));
            }
            catch (ConnectionException e)
            {
                // Handle communications error here.
                Console.WriteLine(e.ToString());
            }
            finally
            {
                // Close the connection to release resources.
                thePrinterConn.Close();
            }
        }
Ejemplo n.º 17
0
        private static TestServiceConnection CreateServiceConnection(Action <ConnectionBuilder> use = null,
                                                                     TestClientConnectionManager clientConnectionManager = null,
                                                                     string serverId                                  = null,
                                                                     string connectionId                              = null,
                                                                     GracefulShutdownMode?mode                        = null,
                                                                     IServiceMessageHandler messageHandler            = null,
                                                                     IServiceEventHandler eventHandler                = null,
                                                                     IClientConnectionFactory clientConnectionFactory = null,
                                                                     ILoggerFactory loggerFactory                     = null)
        {
            clientConnectionManager ??= new TestClientConnectionManager();
            clientConnectionFactory ??= new ClientConnectionFactory();

            var container         = new TestConnectionContainer();
            var connectionFactory = new TestConnectionFactory(conn =>
            {
                container.Instance = conn;
                return(Task.CompletedTask);
            });

            var services = new ServiceCollection();
            var builder  = new ConnectionBuilder(services.BuildServiceProvider());

            if (use == null)
            {
                use = (builder) => builder.UseConnectionHandler <TestConnectionHandler>();
            }
            use(builder);

            builder.UseConnectionHandler <TestConnectionHandler>();

            ConnectionDelegate handler = builder.Build();

            return(new TestServiceConnection(
                       container,
                       new ServiceProtocol(),
                       clientConnectionManager,
                       connectionFactory,
                       loggerFactory ?? NullLoggerFactory.Instance,
                       handler,
                       clientConnectionFactory,
                       serverId ?? "serverId",
                       connectionId ?? Guid.NewGuid().ToString("N"),
                       null,
                       messageHandler ?? new TestServiceMessageHandler(),
                       eventHandler ?? new TestServiceEventHandler(),
                       mode: mode ?? GracefulShutdownMode.Off
                       ));
        }
Ejemplo n.º 18
0
        bool SendZplOverBluetooth()
        {
            var success = false;

            try
            {
                var connection = ConnectionBuilder.Build("BT:" + zebraPrinter.MACAddress);
                // Open the connection - physical connection is established here.
                connection.Open();

                /* New change, print multiple labels from those selected */
                var pos = 0;
                foreach (IGLNLocation loc in locationList)
                {
                    if (loc.ToPrint)
                    {
                        // Actual Label
                        var zplData = GetZplGLNLabel(loc, pos);
                        fileUtility.LogFile("ZPL Output Debug", zplData, "MainActivity", 440, "SendZplOverBluetooth");

                        // Send the data to printer as a byte array.
                        byte[] response = connection.SendAndWaitForResponse(GetBytes(zplData), 3000, 1000, "\"");
                        locationList[pos].Printed = true;
                        locationList[pos].ToPrint = false;
                        SaveFile(locationsFile, locationList[pos]);

                        RunOnUiThread(() => ((CheckListCustomArrayAdapter)locationsView.Adapter).NotifyDataSetChanged());
                        ((CheckListCustomArrayAdapter)locationsView.Adapter).SetPrintedIndex(pos);
                        ((CheckListCustomArrayAdapter)locationsView.Adapter).SetRowPrinted(((CheckListCustomArrayAdapter)locationsView.Adapter).GetView(pos, null, null) as CheckedTextView, pos);
                    }

                    pos++;
                }

                connection.Close();
                success = true;
            }
            catch (Zebra.Sdk.Comm.ConnectionException ex)
            {
                // call LogFile method and pass argument as Exception message, event name, control name, error line number, current form name
                fileUtility.LogFile(ex.Message, ex.ToString(), MethodBase.GetCurrentMethod().Name, ExceptionHelper.LineNumber(ex), Class.SimpleName);
            }

            return(success);
        }
        public static IServiceCollection AddServerApplication <TTransport>(this IServiceCollection services,
                                                                           EndPoint serverEndPoint,
                                                                           Action <IConnectionBuilder> serverApplication,
                                                                           params object[] args) where TTransport : IConnectionListenerFactory
        {
            services.AddOptions <ServerApplicationOptions>()
            .Configure <IServiceProvider>((options, serviceProvider) =>
            {
                var serverBuilder = new ConnectionBuilder(serviceProvider);
                serverApplication(serverBuilder);
                var binding = new ServerBinding
                {
                    ServerApplication         = serverBuilder.Build(),
                    EndPoint                  = serverEndPoint,
                    ConnectionListenerFactory = ActivatorUtilities.CreateInstance <TTransport>(serviceProvider, args)
                };
                options.Bindings.Add(binding);
            });

            services.AddHostedService <ServerApplication>();

            return(services);
        }
        public async Task NonListenerPipeConnectionsAreLoggedAndIgnored()
        {
            var libuv         = new LibuvFunctions();
            var listenOptions = new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0));
            var logger        = new TestApplicationErrorLogger();

            var serviceContextPrimary = new TestServiceContext();
            var builderPrimary        = new ConnectionBuilder();

            builderPrimary.UseHttpServer(serviceContextPrimary, new DummyApplication(c => c.Response.WriteAsync("Primary")), HttpProtocols.Http1);
            var transportContextPrimary = new TestLibuvTransportContext()
            {
                Log = new LibuvTrace(logger)
            };

            transportContextPrimary.ConnectionDispatcher = new ConnectionDispatcher(serviceContextPrimary, builderPrimary.Build());

            var serviceContextSecondary = new TestServiceContext
            {
                DateHeaderValueManager = serviceContextPrimary.DateHeaderValueManager,
                ServerOptions          = serviceContextPrimary.ServerOptions,
                Scheduler  = serviceContextPrimary.Scheduler,
                HttpParser = serviceContextPrimary.HttpParser,
            };
            var builderSecondary = new ConnectionBuilder();

            builderSecondary.UseHttpServer(serviceContextSecondary, new DummyApplication(c => c.Response.WriteAsync("Secondary")), HttpProtocols.Http1);
            var transportContextSecondary = new TestLibuvTransportContext();

            transportContextSecondary.ConnectionDispatcher = new ConnectionDispatcher(serviceContextSecondary, builderSecondary.Build());

            var libuvTransport = new LibuvTransport(libuv, transportContextPrimary, listenOptions);

            var pipeName    = (libuv.IsWindows ? @"\\.\pipe\kestrel_" : "/tmp/kestrel_") + Guid.NewGuid().ToString("n");
            var pipeMessage = Guid.NewGuid().ToByteArray();

            // Start primary listener
            var libuvThreadPrimary = new LibuvThread(libuvTransport);
            await libuvThreadPrimary.StartAsync();

            var listenerPrimary = new ListenerPrimary(transportContextPrimary);
            await listenerPrimary.StartAsync(pipeName, pipeMessage, listenOptions, libuvThreadPrimary);

            var address = GetUri(listenOptions);

            // Add secondary listener
            var libuvThreadSecondary = new LibuvThread(libuvTransport);
            await libuvThreadSecondary.StartAsync();

            var listenerSecondary = new ListenerSecondary(transportContextSecondary);
            await listenerSecondary.StartAsync(pipeName, pipeMessage, listenOptions, libuvThreadSecondary);

            // TCP Connections get round-robined
            await AssertResponseEventually(address, "Secondary", allowed : new[] { "Primary" });

            Assert.Equal("Primary", await HttpClientSlim.GetStringAsync(address));

            // Create a pipe connection and keep it open without sending any data
            var connectTcs      = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);
            var connectionTrace = new LibuvTrace(new TestApplicationErrorLogger());
            var pipe            = new UvPipeHandle(connectionTrace);

            libuvThreadPrimary.Post(_ =>
            {
                var connectReq = new UvConnectRequest(connectionTrace);

                pipe.Init(libuvThreadPrimary.Loop, libuvThreadPrimary.QueueCloseHandle);
                connectReq.Init(libuvThreadPrimary);

                connectReq.Connect(
                    pipe,
                    pipeName,
                    (req, status, ex, __) =>
                {
                    req.Dispose();

                    if (ex != null)
                    {
                        connectTcs.SetException(ex);
                    }
                    else
                    {
                        connectTcs.SetResult(null);
                    }
                },
                    null);
            }, (object)null);

            await connectTcs.Task;

            // TCP connections will still get round-robined between only the two listeners
            Assert.Equal("Secondary", await HttpClientSlim.GetStringAsync(address));
            Assert.Equal("Primary", await HttpClientSlim.GetStringAsync(address));
            Assert.Equal("Secondary", await HttpClientSlim.GetStringAsync(address));

            await libuvThreadPrimary.PostAsync(_ => pipe.Dispose(), (object)null);

            // Wait up to 10 seconds for error to be logged
            for (var i = 0; i < 10 && logger.TotalErrorsLogged == 0; i++)
            {
                await Task.Delay(100);
            }

            // Same for after the non-listener pipe connection is closed
            Assert.Equal("Primary", await HttpClientSlim.GetStringAsync(address));
            Assert.Equal("Secondary", await HttpClientSlim.GetStringAsync(address));
            Assert.Equal("Primary", await HttpClientSlim.GetStringAsync(address));

            await listenerSecondary.DisposeAsync();

            await libuvThreadSecondary.StopAsync(TimeSpan.FromSeconds(5));

            await listenerPrimary.DisposeAsync();

            await libuvThreadPrimary.StopAsync(TimeSpan.FromSeconds(5));

            Assert.Equal(1, logger.TotalErrorsLogged);
            var errorMessage = logger.Messages.First(m => m.LogLevel == LogLevel.Error);

            Assert.Equal(TestConstants.EOF, Assert.IsType <UvException>(errorMessage.Exception).StatusCode);
        }
Ejemplo n.º 21
0
        private void print_data()
        {
            String id            = txtId.Text.Replace("'", "''");
            String asalBarang    = txtAsalBarang.Text.Replace("'", "''");
            String namaBarang    = txtNamaBarang.Text.Replace("'", "''");
            String tipeMobil     = txtTipeMobil.Text.Replace("'", "''");
            String kodeJual      = txtKodeJual.Text.Replace("'", "''");
            String kodeMandarin  = txtKodeMandarin.Text.Replace("'", "''");
            String hurufMandarin = angka_cina(int.Parse(kodeMandarin));

            //String jumlahBarang = numJumlahBarang.Value.ToString();
            try
            {
                //string settings = System.IO.File.ReadAllText("./settings.txt");
                var thePrinterConn = ConnectionBuilder.Build("ZDesigner GT800 (ZPL) (Inventory)");
                try
                {
                    // Open the connection - physical connection is established here.
                    thePrinterConn.Open();

                    // This example prints "This is a ZPL test." near the top of the label.
                    string zplData = "^XA" +
                                     //item id
                                     "^FO150,25^A0,55,40^FD" + asalBarang + "^FS" +
                                     //"^FO290,22^A0,38,26^FD" + kodeJual + "^FS" +
                                     //"^FO580,22^A0,38,26^FD" + kodeJual + "^FS" +
                                     //item name 1
                                     "^FO150,75^A0,55,40^FD" + namaBarang + "^FS" +
                                     //"^FO290,55^A0,30,22^FD" + asalBarang + "^FS" +
                                     //"^FO580,55^A0,30,22^FD" + asalBarang + "^FS" +
                                     //item name 2
                                     "^FO150,125^A0,55,40^FD" + tipeMobil + "^FS" +
                                     //"^FO290,82^A0,30,22^FD" + namaBarang + "^FS" +
                                     //"^FO580,82^A0,30,22^FD" + namaBarang + "^FS" +
                                     //item name 3
                                     "^FO150,175^A0,55,40^FD" + kodeJual + "^FS" +
                                     //"^FO290,108^A0,30,22^FD" + tipeMobil + "^FS" +
                                     //"^FO580,108^A0,30,22^FD" + tipeMobil + "^FS" +
                                     //item chinese
                                     "^FO150,225^CI28^A@N,36,36,E:SIMSUN.FNT^FD" + hurufMandarin + "^FS" +
                                     //"^FO290,138^CI28^A@N,40,40,E:SIMSUN.FNT^FD" + hurufMandarin + "^FS" +
                                     //"^FO580,138^CI28^A@N,40,40,E:SIMSUN.FNT^FD" + hurufMandarin + "^FS" +
                                     "^FO10,295^B3N,N,50,Y,N^FD" + kodeJual + "^FS" +
                                     "^XZ";

                    // Send the data to printer as a byte array.
                    thePrinterConn.Write(Encoding.UTF8.GetBytes(zplData));
                }
                catch (ConnectionException e)
                {
                    // Handle communications error here.
                    Console.WriteLine(e.ToString());
                    MessageBox.Show(e.ToString(), "Gagal", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                finally
                {
                    // Close the connection to release resources.
                    thePrinterConn.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Gagal", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Ejemplo n.º 22
0
        static async Task Main(string[] args)
        {
            var configurationBuilder =
                new ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(new[]
            {
                new KeyValuePair <string, string>("tests:repeats", "10"),
                new KeyValuePair <string, string>("tests:rows", "10")
            });
            configurationBuilder.AddEnvironmentVariables("saprfc");
            configurationBuilder.AddCommandLine(args);
            configurationBuilder.AddUserSecrets <Program>();

            var config = configurationBuilder.Build();

            var settings = new Dictionary <string, string>
            {
                { "ashost", config["saprfc:ashost"] },
                { "sysnr", config["saprfc:sysnr"] },
                { "client", config["saprfc:client"] },
                { "user", config["saprfc:username"] },
                { "passwd", config["saprfc:password"] },
                { "lang", "EN" }
            };

            var rows    = Convert.ToInt32(config["tests:rows"]);
            var repeats = Convert.ToInt32(config["tests:repeats"]);

            Console.WriteLine($"Test rows: {rows}");
            Console.WriteLine($"Test repeats: {repeats}");


            StartProgramDelegate callback = command =>
            {
                var programParts = command.Split(' ');
                var arguments    = command.Replace(programParts[0], "");
                var p            = Process.Start(AppDomain.CurrentDomain.BaseDirectory + @"\" + programParts[0] + ".exe",
                                                 arguments.TrimStart());

                return(RfcErrorInfo.Ok());
            };

            var connectionBuilder = new ConnectionBuilder(settings)
                                    .WithStartProgramCallback(callback)
                                    .ConfigureRuntime(c =>
                                                      c.WithLogger(new SimpleConsoleLogger()));

            using (var context = new RfcContext(connectionBuilder.Build()))
            {
                await context.PingAsync();

                await RunIntegrationTests(context);

                long totalTest1 = 0;
                long totalTest2 = 0;

                for (var run = 0; run < repeats; run++)
                {
                    Console.WriteLine($"starting Test Run {run + 1} of {repeats}\tTest 01");
                    totalTest1 += await RunPerformanceTest01(context, rows);

                    Console.WriteLine($"starting Test Run {run + 1} of {repeats}\tTest 02");
                    totalTest2 += await RunPerformanceTest02(context, rows);

                    GC.Collect();
                }

                Console.WriteLine("Total runtime Test 01: " + totalTest1);
                Console.WriteLine("Total runtime Test 02: " + totalTest2);
                Console.WriteLine("Average runtime Test 01: " + totalTest1 / repeats);
                Console.WriteLine("Average runtime Test 02: " + totalTest2 / repeats);
            }
        }
Ejemplo n.º 23
0
        public async Task ClientConnectionContextAbortCanSendOutCloseMessage()
        {
            using (StartVerifiableLog(out var loggerFactory, LogLevel.Trace, expectedErrors: c => true,
                                      logChecker: logs =>
            {
                return(true);
            }))
            {
                var            ccm                 = new TestClientConnectionManager();
                var            ccf                 = new ClientConnectionFactory();
                var            protocol            = new ServiceProtocol();
                TestConnection transportConnection = null;
                var            connectionFactory   = new TestConnectionFactory(conn =>
                {
                    transportConnection = conn;
                    return(Task.CompletedTask);
                });

                var services          = new ServiceCollection();
                var lastWill          = "This is the last will";
                var connectionHandler = new LastWillConnectionHandler(lastWill);
                services.AddSingleton(connectionHandler);
                var builder = new ConnectionBuilder(services.BuildServiceProvider());
                builder.UseConnectionHandler <LastWillConnectionHandler>();
                ConnectionDelegate handler = builder.Build();

                var connection = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf,
                                                       "serverId", Guid.NewGuid().ToString("N"), null, null, closeTimeOutMilliseconds: 500);

                var connectionTask = connection.StartAsync();

                // completed handshake
                await connection.ConnectionInitializedTask.OrTimeout();

                Assert.Equal(ServiceConnectionStatus.Connected, connection.Status);
                var clientConnectionId = Guid.NewGuid().ToString();

                await transportConnection.Application.Output.WriteAsync(
                    protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { })));

                var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout();

                await clientConnection.LifetimeTask.OrTimeout();

                transportConnection.Transport.Output.Complete();
                var input = await transportConnection.Application.Input.ReadAsync();

                var buffer   = input.Buffer;
                var canParse = protocol.TryParseMessage(ref buffer, out var msg);
                Assert.True(canParse);
                var message = msg as ConnectionDataMessage;
                Assert.NotNull(message);

                Assert.Equal(clientConnectionId, message.ConnectionId);
                Assert.Equal(lastWill, Encoding.UTF8.GetString(message.Payload.First.ToArray()));

                // complete reading to end the connection
                transportConnection.Application.Output.Complete();

                // 1s for application task to timeout
                await connectionTask.OrTimeout(1000);

                Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status);
                Assert.Empty(ccm.ClientConnections);
            }
        }
        public async Task PipeConnectionsWithWrongMessageAreLoggedAndIgnored()
        {
            var libuv         = new LibuvFunctions();
            var listenOptions = new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0));

            var logger = new TestApplicationErrorLogger();

            var serviceContextPrimary = new TestServiceContext();
            var builderPrimary        = new ConnectionBuilder();

            builderPrimary.UseHttpServer(serviceContextPrimary, new DummyApplication(c => c.Response.WriteAsync("Primary")), HttpProtocols.Http1);
            var transportContextPrimary = new TestLibuvTransportContext()
            {
                Log = new LibuvTrace(logger)
            };

            transportContextPrimary.ConnectionDispatcher = new ConnectionDispatcher(serviceContextPrimary, builderPrimary.Build());

            var serviceContextSecondary = new TestServiceContext
            {
                DateHeaderValueManager = serviceContextPrimary.DateHeaderValueManager,
                ServerOptions          = serviceContextPrimary.ServerOptions,
                Scheduler  = serviceContextPrimary.Scheduler,
                HttpParser = serviceContextPrimary.HttpParser,
            };
            var builderSecondary = new ConnectionBuilder();

            builderSecondary.UseHttpServer(serviceContextSecondary, new DummyApplication(c => c.Response.WriteAsync("Secondary")), HttpProtocols.Http1);
            var transportContextSecondary = new TestLibuvTransportContext();

            transportContextSecondary.ConnectionDispatcher = new ConnectionDispatcher(serviceContextSecondary, builderSecondary.Build());

            var libuvTransport = new LibuvTransport(libuv, transportContextPrimary, listenOptions);

            var pipeName    = (libuv.IsWindows ? @"\\.\pipe\kestrel_" : "/tmp/kestrel_") + Guid.NewGuid().ToString("n");
            var pipeMessage = Guid.NewGuid().ToByteArray();

            // Start primary listener
            var libuvThreadPrimary = new LibuvThread(libuvTransport);
            await libuvThreadPrimary.StartAsync();

            var listenerPrimary = new ListenerPrimary(transportContextPrimary);
            await listenerPrimary.StartAsync(pipeName, pipeMessage, listenOptions, libuvThreadPrimary);

            var address = GetUri(listenOptions);

            // Add secondary listener with wrong pipe message
            var libuvThreadSecondary = new LibuvThread(libuvTransport);
            await libuvThreadSecondary.StartAsync();

            var listenerSecondary = new ListenerSecondary(transportContextSecondary);
            await listenerSecondary.StartAsync(pipeName, Guid.NewGuid().ToByteArray(), listenOptions, libuvThreadSecondary);

            // Wait up to 10 seconds for error to be logged
            for (var i = 0; i < 10 && logger.TotalErrorsLogged == 0; i++)
            {
                await Task.Delay(100);
            }

            // TCP Connections don't get round-robined
            Assert.Equal("Primary", await HttpClientSlim.GetStringAsync(address));
            Assert.Equal("Primary", await HttpClientSlim.GetStringAsync(address));
            Assert.Equal("Primary", await HttpClientSlim.GetStringAsync(address));

            await listenerSecondary.DisposeAsync();

            await libuvThreadSecondary.StopAsync(TimeSpan.FromSeconds(5));

            await listenerPrimary.DisposeAsync();

            await libuvThreadPrimary.StopAsync(TimeSpan.FromSeconds(5));

            Assert.Equal(1, logger.TotalErrorsLogged);
            var errorMessage = logger.Messages.First(m => m.LogLevel == LogLevel.Error);

            Assert.IsType <IOException>(errorMessage.Exception);
            Assert.Contains("Bad data", errorMessage.Exception.ToString());
        }
Ejemplo n.º 25
0
        public async Task TestServiceConnectionWithErrorApplicationTask()
        {
            using (StartVerifiableLog(out var loggerFactory, LogLevel.Warning, expectedErrors: c => true,
                                      logChecker: logs =>
            {
                Assert.Equal(2, logs.Count);
                Assert.Equal("SendLoopStopped", logs[0].Write.EventId.Name);
                Assert.Equal("ApplicationTaskFailed", logs[1].Write.EventId.Name);
                return(true);
            }))
            {
                var            ccm                 = new TestClientConnectionManager();
                var            ccf                 = new ClientConnectionFactory();
                var            protocol            = new ServiceProtocol();
                TestConnection transportConnection = null;
                var            connectionFactory   = new TestConnectionFactory(conn =>
                {
                    transportConnection = conn;
                    return(Task.CompletedTask);
                });
                var services          = new ServiceCollection();
                var errorTcs          = new TaskCompletionSource <Exception>();
                var connectionHandler = new ErrorConnectionHandler(errorTcs);
                services.AddSingleton(connectionHandler);
                var builder = new ConnectionBuilder(services.BuildServiceProvider());

                builder.UseConnectionHandler <ErrorConnectionHandler>();
                ConnectionDelegate handler = builder.Build();

                var connection = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf,
                                                       "serverId", Guid.NewGuid().ToString("N"), null, null);

                var connectionTask = connection.StartAsync();

                // completed handshake
                await connection.ConnectionInitializedTask.OrTimeout();

                Assert.Equal(ServiceConnectionStatus.Connected, connection.Status);
                var clientConnectionId = Guid.NewGuid().ToString();

                await transportConnection.Application.Output.WriteAsync(
                    protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { })));

                var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout();

                errorTcs.SetException(new InvalidOperationException("error operation"));

                await clientConnection.LifetimeTask.OrTimeout();

                // Should complete the connection when application throws
                await ccm.WaitForClientConnectionRemovalAsync(clientConnectionId).OrTimeout();

                // Application task should not affect the underlying service connection
                Assert.Equal(ServiceConnectionStatus.Connected, connection.Status);

                // complete reading to end the connection
                transportConnection.Application.Output.Complete();

                await connectionTask.OrTimeout();

                Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status);
                Assert.Empty(ccm.ClientConnections);
            }
        }
        public async Task ConnectionsGetRoundRobinedToSecondaryListeners()
        {
            var libuv = new LibuvFunctions();

            var listenOptions = new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0));

            var serviceContextPrimary   = new TestServiceContext();
            var transportContextPrimary = new TestLibuvTransportContext();
            var builderPrimary          = new ConnectionBuilder();

            builderPrimary.UseHttpServer(serviceContextPrimary, new DummyApplication(c => c.Response.WriteAsync("Primary")), HttpProtocols.Http1);
            transportContextPrimary.ConnectionDispatcher = new ConnectionDispatcher(serviceContextPrimary, builderPrimary.Build());

            var serviceContextSecondary = new TestServiceContext();
            var builderSecondary        = new ConnectionBuilder();

            builderSecondary.UseHttpServer(serviceContextSecondary, new DummyApplication(c => c.Response.WriteAsync("Secondary")), HttpProtocols.Http1);
            var transportContextSecondary = new TestLibuvTransportContext();

            transportContextSecondary.ConnectionDispatcher = new ConnectionDispatcher(serviceContextSecondary, builderSecondary.Build());

            var libuvTransport = new LibuvTransport(libuv, transportContextPrimary, listenOptions);

            var pipeName    = (libuv.IsWindows ? @"\\.\pipe\kestrel_" : "/tmp/kestrel_") + Guid.NewGuid().ToString("n");
            var pipeMessage = Guid.NewGuid().ToByteArray();

            // Start primary listener
            var libuvThreadPrimary = new LibuvThread(libuvTransport);
            await libuvThreadPrimary.StartAsync();

            var listenerPrimary = new ListenerPrimary(transportContextPrimary);
            await listenerPrimary.StartAsync(pipeName, pipeMessage, listenOptions, libuvThreadPrimary);

            var address = GetUri(listenOptions);

            // Until a secondary listener is added, TCP connections get dispatched directly
            Assert.Equal("Primary", await HttpClientSlim.GetStringAsync(address));
            Assert.Equal("Primary", await HttpClientSlim.GetStringAsync(address));

            var listenerCount = listenerPrimary.UvPipeCount;
            // Add secondary listener
            var libuvThreadSecondary = new LibuvThread(libuvTransport);
            await libuvThreadSecondary.StartAsync();

            var listenerSecondary = new ListenerSecondary(transportContextSecondary);
            await listenerSecondary.StartAsync(pipeName, pipeMessage, listenOptions, libuvThreadSecondary);

            var maxWait = Task.Delay(TestConstants.DefaultTimeout);

            // wait for ListenerPrimary.ReadCallback to add the secondary pipe
            while (listenerPrimary.UvPipeCount == listenerCount)
            {
                var completed = await Task.WhenAny(maxWait, Task.Delay(100));

                if (ReferenceEquals(completed, maxWait))
                {
                    throw new TimeoutException("Timed out waiting for secondary listener to become available");
                }
            }

            // Once a secondary listener is added, TCP connections start getting dispatched to it
            await AssertResponseEventually(address, "Secondary", allowed : new[] { "Primary" });

            // TCP connections will still get round-robined to the primary listener
            Assert.Equal("Primary", await HttpClientSlim.GetStringAsync(address));
            Assert.Equal("Secondary", await HttpClientSlim.GetStringAsync(address));
            Assert.Equal("Primary", await HttpClientSlim.GetStringAsync(address));

            await listenerSecondary.DisposeAsync();

            await libuvThreadSecondary.StopAsync(TimeSpan.FromSeconds(5));

            await listenerPrimary.DisposeAsync();

            await libuvThreadPrimary.StopAsync(TimeSpan.FromSeconds(5));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Maps incoming requests with the specified path to the provided connection pipeline.
        /// </summary>
        /// <param name="endpoints">The <see cref="IEndpointBuilder"/> to add the route to.</param>
        /// <param name="pattern">The route pattern.</param>
        /// <param name="options">Options used to configure the connection.</param>
        /// <param name="configure">A callback to configure the connection.</param>
        /// <returns>An <see cref="ConnectionEndpointRouteBuilder"/> for endpoints associated with the connections.</returns>
        public static ConnectionEndpointRouteBuilder MapConnections(this IEndpointBuilder endpoints, string pattern, HttpConnectionDispatcherOptions options, Action <IConnectionBuilder> configure)
        {
            var dispatcher = endpoints.ServiceProvider.GetRequiredService(_httpConnectionDispatcherType);

            var ExecuteNegotiateAsync = (Func <HttpContext, HttpConnectionDispatcherOptions, Task>)
                                        _httpConnectionDispatcherType
                                        .GetMethod("ExecuteNegotiateAsync") !
                                        .CreateDelegate(typeof(Func <HttpContext, HttpConnectionDispatcherOptions, Task>), dispatcher);

            var ExecuteAsync = (Func <HttpContext, HttpConnectionDispatcherOptions, ConnectionDelegate, Task>)
                               _httpConnectionDispatcherType
                               .GetMethod("ExecuteAsync") !
                               .CreateDelegate(typeof(Func <HttpContext, HttpConnectionDispatcherOptions, ConnectionDelegate, Task>), dispatcher);

            var connectionBuilder = new ConnectionBuilder(endpoints.ServiceProvider);

            configure(connectionBuilder);
            var connectionDelegate = connectionBuilder.Build();

            // REVIEW: Consider expanding the internals of the dispatcher as endpoint routes instead of
            // using if statements we can let the matcher handle

            var conventionBuilders = new List <IEndpointConventionBuilder>();

            // Build the negotiate application
            var app = endpoints.CreateApplicationBuilder();

            app.UseWebSockets();
            app.Run(c => ExecuteNegotiateAsync(c, options));
            var negotiateHandler = app.Build();

            var negotiateBuilder = endpoints.MapRequestDelegate(pattern + "/negotiate", negotiateHandler);

            conventionBuilders.Add(negotiateBuilder);
            // Add the negotiate metadata so this endpoint can be identified
            negotiateBuilder.WithMetadata(new NegotiateMetadata());

            // build the execute handler part of the protocol
            app = endpoints.CreateApplicationBuilder();
            app.UseWebSockets();
            app.Run(c => ExecuteAsync(c, options, connectionDelegate));
            var executehandler = app.Build();

            var executeBuilder = endpoints.MapRequestDelegate(pattern, executehandler);

            conventionBuilders.Add(executeBuilder);

            var compositeConventionBuilder = new CompositeEndpointConventionBuilder(conventionBuilders);

            // Add metadata to all of Endpoints
            compositeConventionBuilder.Add(e =>
            {
                // Add the authorization data as metadata
                foreach (var data in options.AuthorizationData)
                {
                    e.Metadata.Add(data);
                }
            });

            return((ConnectionEndpointRouteBuilder)
                   typeof(ConnectionEndpointRouteBuilder)
                   .GetTypeInfo().DeclaredConstructors
                   .Single()
                   .Invoke(new object[] { compositeConventionBuilder }));
        }