Example #1
0
        static async Task Run()
        {
            string address = "amqp://*****:*****@localhost:5672";

            Connection connection = await Connection.Factory.CreateAsync(new Address(address));

            Session    session = new Session(connection);
            SenderLink sender  = new SenderLink(session, "test-sender", "q1");

            Message message1 = new Message("Hello AMQP!");
            await sender.SendAsync(message1);

            ReceiverLink receiver = new ReceiverLink(session, "test-receiver", "q1");
            Message      message2 = await receiver.ReceiveAsync();

            Console.WriteLine(message2.GetBody <string>());
            receiver.Accept(message2);

            await sender.CloseAsync();

            await receiver.CloseAsync();

            await session.CloseAsync();

            await connection.CloseAsync();
        }
Example #2
0
 // 데이터베이스 연결종료(비동기)
 protected async Task DisconnectAsync()
 {
     if (IsConnected)
     {
         await Connection.CloseAsync();
     }
 }
Example #3
0
        public void CloseConnectionWithDetachTest()
        {
            this.testListener.RegisterTarget(TestPoint.Close, (stream, channel, fields) =>
            {
                // send a detach
                TestListener.FRM(stream, 0x16UL, 0, channel, 0u, true);
                return TestOutcome.Continue;
            });

            string testName = "CloseConnectionWithDetachTest";

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                Connection connection = new Connection(this.address);
                Session session = new Session(connection);
                SenderLink sender = new SenderLink(session, "sender-" + testName, "any");
                sender.Send(new Message("test") { Properties = new Properties() { MessageId = testName } });
                connection.Close();
                Assert.IsTrue(connection.Error == null, "connection has error!" + connection.Error);
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async () =>
            {
                Connection connection = await Connection.Factory.CreateAsync(this.address);
                Session session = new Session(connection);
                SenderLink sender = new SenderLink(session, "sender-" + testName, "any");
                await sender.SendAsync(new Message("test") { Properties = new Properties() { MessageId = testName } });
                await connection.CloseAsync();
                Assert.IsTrue(connection.Error == null, "connection has error!" + connection.Error);

            }).Unwrap().GetAwaiter().GetResult();
        }
Example #4
0
        public void SendWithInvalidRemoteChannelTest()
        {
            this.testListener.RegisterTarget(TestPoint.Transfer, (stream, channel, fields) =>
            {
                // send an end with invalid channel
                TestListener.FRM(stream, 0x17UL, 0, 33);
                return(TestOutcome.Stop);
            });

            string testName = "SendWithProtocolErrorTest";

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                Connection connection = new Connection(this.address);
                Session    session    = new Session(connection);
                SenderLink sender     = new SenderLink(session, "sender-" + testName, "any");
                try
                {
                    sender.Send(new Message("test")
                    {
                        Properties = new Properties()
                        {
                            MessageId = testName
                        }
                    });
                    Assert.IsTrue(false, "Send should throw exception");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual(ErrorCode.NotFound, (string)exception.Error.Condition);
                }
                connection.Close();
                Assert.AreEqual(ErrorCode.NotFound, (string)connection.Error.Condition);
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async() =>
            {
                Connection connection = await Connection.Factory.CreateAsync(this.address);
                Session session       = new Session(connection);
                SenderLink sender     = new SenderLink(session, "sender-" + testName, "any");
                try
                {
                    await sender.SendAsync(new Message("test")
                    {
                        Properties = new Properties()
                        {
                            MessageId = testName
                        }
                    });
                    Assert.IsTrue(false, "Send should throw exception");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual(ErrorCode.NotFound, (string)exception.Error.Condition);
                }
                await connection.CloseAsync();
                Assert.AreEqual(ErrorCode.NotFound, (string)connection.Error.Condition);
            }).Unwrap().GetAwaiter().GetResult();
        }
Example #5
0
        public static async Task <Message> ProcessManagementRequestAsync(Message message, ManagementRequestProcessor processor)
        {
            ContainerHost host = Open();

            try
            {
                host.RegisterRequestProcessor("$management", processor);
                Connection connection = await host.ConnectAsync();

                var session = new Session(connection);
                try
                {
                    return(await session.SendControlRequestAsync("$management", message));
                }
                finally
                {
                    await session.CloseAsync();

                    await connection.CloseAsync();
                }
            }
            finally
            {
                host.Close();
            }
        }
Example #6
0
        public async Task Connection_CloseAsync_ClosesSocket(bool usePipe, ConnectionCloseMethod method)
        {
            using var server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, IPAddress.Loopback);
            using SocketsConnectionFactory factory = new SocketsConnectionFactory(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Connection connection = await factory.ConnectAsync(server.EndPoint);

            Stream stream = null;

            if (usePipe)
            {
                _ = connection.Pipe;
            }
            else
            {
                stream = connection.Stream;
            }

            connection.ConnectionProperties.TryGet(out Socket socket);

            await connection.CloseAsync(method);

            Assert.Throws <ObjectDisposedException>(() => socket.Send(new byte[1]));

            if (!usePipe) // No way to observe the stream if we work with the pipe
            {
                Assert.Throws <ObjectDisposedException>(() => stream.Write(new byte[1]));
            }
        }
Example #7
0
        public static async Task <IDictionary <string, object> > ProcessCbsRequestAsync(string messageId, CbsRequestProcessor processor)
        {
            var           responseProperties = new Dictionary <string, object>();
            ContainerHost host = Open();

            try
            {
                host.RegisterRequestProcessor("$cbs", processor);
                Connection connection = await host.ConnectAsync();

                var session = new Session(connection);
                try
                {
                    Message response = await session.SendCbsRequestAsync(messageId);

                    responseProperties["CorrelationId"] = response.Properties.CorrelationId;
                    responseProperties["status-code"]   = response.ApplicationProperties["status-code"];
                }
                finally
                {
                    await session.CloseAsync();

                    await connection.CloseAsync();
                }
            }
            finally
            {
                host.Close();
            }
            return(responseProperties);
        }
        public void ConnectionMaxFrameSizeTest()
        {
            this.testListener.RegisterTarget(TestPoint.Open, (stream, channel, fields) =>
            {
                TestListener.FRM(stream, 0x10UL, 0, 0, "TestListener", "localhost", 512u);
                return(TestOutcome.Stop);
            });

            this.testListener.RegisterTarget(TestPoint.Begin, (stream, channel, fields) =>
            {
                TestListener.FRM(stream, 0x11UL, 0, channel, channel, 0u, 100u, 100u, 8u, null, null, null,
                                 new Fields()
                {
                    { new Symbol("big-string"), new string('a', 1024) }
                });
                return(TestOutcome.Stop);
            });

            string testName = "ConnectionMaxFrameSizeTest";

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                Open open = new Open()
                {
                    ContainerId = testName, HostName = "localhost", MaxFrameSize = 2048
                };
                Connection connection = new Connection(this.address, null, open, null);
                Session    session    = new Session(connection);
                SenderLink sender     = new SenderLink(session, "sender-" + testName, "any");
                sender.Send(new Message("test")
                {
                    Properties = new Properties()
                    {
                        MessageId = testName
                    }
                });
                connection.Close();
                Assert.IsTrue(connection.Error == null, "connection has error!" + connection.Error);
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async() =>
            {
                ConnectionFactory factory = new ConnectionFactory();
                factory.AMQP.MaxFrameSize = 2048;
                Connection connection     = await factory.CreateAsync(this.address);
                Session session           = new Session(connection);
                SenderLink sender         = new SenderLink(session, "sender-" + testName, "any");
                await sender.SendAsync(new Message("test")
                {
                    Properties = new Properties()
                    {
                        MessageId = testName
                    }
                });
                await connection.CloseAsync();
                Assert.IsTrue(connection.Error == null, "connection has error!" + connection.Error);
            }).Unwrap().GetAwaiter().GetResult();
        }
Example #9
0
        /// <summary>
        ///   Closes the consumer.
        /// </summary>
        ///
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        /// <returns>A task to be resolved on when the operation has completed.</returns>
        ///
        public virtual async Task CloseAsync(CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();
            Closed = true;

            EventHubsEventSource.Log.ClientCloseStart(typeof(EventHubConsumerClient), EventHubName, Identifier);

            // Attempt to close the active transport consumers.  In the event that an exception is encountered,
            // it should not impact the attempt to close the connection, assuming ownership.

            var transportConsumerException = default(Exception);

            try
            {
                var pendingCloses = new List <Task>();

                foreach (var consumer in ActiveConsumers.Values)
                {
                    pendingCloses.Add(consumer.CloseAsync(CancellationToken.None));
                }

                ActiveConsumers.Clear();
                await Task.WhenAll(pendingCloses).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                EventHubsEventSource.Log.ClientCloseError(typeof(EventHubConsumerClient), EventHubName, Identifier, ex.Message);
                transportConsumerException = ex;
            }

            // An exception when closing the connection supersedes one observed when closing the
            // individual transport clients.

            try
            {
                if (OwnsConnection)
                {
                    await Connection.CloseAsync().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                EventHubsEventSource.Log.ClientCloseError(typeof(EventHubConsumerClient), EventHubName, Identifier, ex.Message);
                transportConsumerException = null;
                throw;
            }
            finally
            {
                EventHubsEventSource.Log.ClientCloseComplete(typeof(EventHubConsumerClient), EventHubName, Identifier);
            }

            // If there was an active exception pending from closing the individual
            // transport consumers, surface it now.

            if (transportConsumerException != default)
            {
                throw transportConsumerException;
            }
        }
        /// <summary>
        ///   Closes the producer.
        /// </summary>
        ///
        /// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
        ///
        /// <returns>A task to be resolved on when the operation has completed.</returns>
        ///
        public virtual async Task CloseAsync(CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

            if (IsClosed)
            {
                return;
            }

            IsClosed = true;

            var identifier = GetHashCode().ToString();

            EventHubsEventSource.Log.ClientCloseStart(typeof(EventHubProducerClient), EventHubName, identifier);

            // Attempt to close the pool of producers.  In the event that an exception is encountered,
            // it should not impact the attempt to close the connection, assuming ownership.

            var transportProducerPoolException = default(Exception);

            try
            {
                await PartitionProducerPool.CloseAsync(cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                EventHubsEventSource.Log.ClientCloseError(typeof(EventHubProducerClient), EventHubName, identifier, ex.Message);
                transportProducerPoolException = ex;
            }

            // An exception when closing the connection supersedes one observed when closing the
            // individual transport clients.

            try
            {
                if (OwnsConnection)
                {
                    await Connection.CloseAsync().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                EventHubsEventSource.Log.ClientCloseError(typeof(EventHubProducerClient), EventHubName, identifier, ex.Message);
                throw;
            }
            finally
            {
                EventHubsEventSource.Log.ClientCloseComplete(typeof(EventHubProducerClient), EventHubName, identifier);
            }

            // If there was an active exception pending from closing the
            // transport producer pool, surface it now.

            if (transportProducerPoolException != default)
            {
                ExceptionDispatchInfo.Capture(transportProducerPoolException).Throw();
            }
        }
Example #11
0
        public async Task ReceiverSenderAsync()
        {
            string testName = "ReceiverSenderAsync";

            ConnectionFactory connectionFactory = new ConnectionFactory();

            // Creating first ReceiverLink
            Connection firstReceiverConnection = await connectionFactory.CreateAsync(this.testTarget.Address);

            Session      firstReceiverSession = new Session(firstReceiverConnection);
            ReceiverLink firstReceiverLink    = new ReceiverLink(firstReceiverSession, "receiver-link", testName);

            // Does not work when creating SenderLink after first ReceiverLink
            var senderConnection = await connectionFactory.CreateAsync(this.testTarget.Address);

            var senderSession = new Session(senderConnection);
            var senderLink    = new SenderLink(senderSession, "sender-link", testName);

            // Send and receive message
            await senderLink.SendAsync(new Message(testName));

            Message firstMessageReceived = await firstReceiverLink.ReceiveAsync(TimeSpan.FromMilliseconds(1000));

            // Close first reveiver link
            await firstReceiverLink.CloseAsync();

            await firstReceiverSession.CloseAsync();

            await firstReceiverConnection.CloseAsync();

            // Creating second ReceiverLink
            Connection secondReceiverConnection = await connectionFactory.CreateAsync(this.testTarget.Address);

            Session      secondReceiverSession = new Session(secondReceiverConnection);
            ReceiverLink secondReceiverLink    = new ReceiverLink(secondReceiverSession, "receiver-link", testName);

            // Send and receive message
            await senderLink.SendAsync(new Message(testName));

            Message message = await secondReceiverLink.ReceiveAsync(TimeSpan.FromMilliseconds(1000));

            Assert.IsTrue(message != null, "No message received");
            secondReceiverLink.Accept(message);

            // Close second reveiver link
            await secondReceiverLink.CloseAsync();

            await secondReceiverSession.CloseAsync();

            await secondReceiverConnection.CloseAsync();

            // Close sender link
            await senderLink.CloseAsync();

            await senderSession.CloseAsync();

            await senderConnection.CloseAsync();
        }
        /// <summary>
        ///   Closes the client.
        /// </summary>
        ///
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        public virtual async Task CloseAsync(CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();

            if (IsClosed)
            {
                return;
            }

            IsClosed = true;

            var clientHash = GetHashCode().ToString(CultureInfo.InvariantCulture);

            Logger.ClientCloseStart(typeof(PartitionReceiver), EventHubName, clientHash);

            // Attempt to close the transport consumer.  In the event that an exception is encountered,
            // it should not impact the attempt to close the connection, assuming ownership.

            var transportConsumerException = default(Exception);

            try
            {
                await InnerConsumer.CloseAsync(CancellationToken.None).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.ClientCloseError(typeof(PartitionReceiver), EventHubName, clientHash, ex.Message);
                transportConsumerException = ex;
            }

            // An exception when closing the connection supersedes one observed when closing the
            // transport consumer.

            try
            {
                if (OwnsConnection)
                {
                    await Connection.CloseAsync().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Logger.ClientCloseError(typeof(PartitionReceiver), EventHubName, clientHash, ex.Message);
                throw;
            }
            finally
            {
                Logger.ClientCloseComplete(typeof(PartitionReceiver), EventHubName, clientHash);
            }

            // If there was an active exception pending from closing the transport
            // consumer, surface it now.

            if (transportConsumerException != default)
            {
                ExceptionDispatchInfo.Capture(transportConsumerException).Throw();
            }
        }
Example #13
0
        public override async Task SetUp()
        {
            await base.SetUp();

            if (Connection != null && Connection.State == ConnectionState.Open)
            {
                await Connection.CloseAsync();
            }
        }
Example #14
0
        public virtual async Task DisconnectAsync()
        {
            // print message
            PrintMessage(ClassName, JobType.Error);

            await Connection.CloseAsync();

            IsConnected = false;
        }
Example #15
0
        static async Task <int> SslConnectionTestAsync()
        {
            try
            {
                ConnectionFactory factory = new ConnectionFactory();

                String certFile = "c:\\Users\\JAkub\\Downloads\\ABCFR_ABCFRALMMACC1.crt";
                factory.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
                factory.SSL.LocalCertificateSelectionCallback   = (a, b, c, d, e) => X509Certificate.CreateFromCertFile(certFile);
                factory.SSL.ClientCertificates.Add(X509Certificate.CreateFromCertFile(certFile));

                factory.AMQP.MaxFrameSize = 64 * 1024;
                factory.AMQP.ContainerId  = "fixml-client";

                factory.SASL.Profile = SaslProfile.External;

                Trace.TraceLevel    = TraceLevel.Frame;
                Trace.TraceListener = (f, a) => Console.WriteLine(String.Format(f, a));

                Connection.DisableServerCertValidation = false;

                Address    brokerAddress = new Address("amqps://ecag-fixml-simu1.deutsche-boerse.com:10170");
                Connection connection    = await factory.CreateAsync(brokerAddress);

                Session session = new Session(connection);

                ReceiverLink receiver = new ReceiverLink(session, "broadcast-receiver", "broadcast.ABCFR_ABCFRALMMACC1.TradeConfirmation");

                while (true)
                {
                    Message msg = receiver.Receive(60000);

                    if (msg == null)
                    {
                        break;
                    }

                    Amqp.Framing.Data payload     = (Amqp.Framing.Data)msg.BodySection;
                    String            payloadText = Encoding.UTF8.GetString(payload.Binary);

                    Console.WriteLine("Received message: {0}", payloadText);
                    receiver.Accept(msg);
                }

                Console.WriteLine("No message received for 60 seconds");

                await connection.CloseAsync();

                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0}.", e);
                return(1);
            }
        }
Example #16
0
        public async Task UnsubscribeUser(ulong discordUserId, string twitterUsername, string discordUsername)
        {
            long twitterUserId = await Program.TwitterBotInstance.GetUserId(twitterUsername);

            try {
                if (Connection.State == ConnectionState.Closed)
                {
                    await Connection.OpenAsync();
                }
                // First delete the relationship, as we know that's gone
                MySqlCommand Command = new MySqlCommand("DELETE FROM DiscordTwitterUsers WHERE DiscordId=@D_ID AND TwitterId=@T_ID;", Connection);
                Command.Prepare();
                Command.Parameters.AddWithValue("@D_ID", discordUserId);
                Command.Parameters.AddWithValue("@T_ID", twitterUserId);
                await Command.ExecuteNonQueryAsync();

                // Cleanup:
                // If that was the only relationship they had, now remove the discord/twitter users from their standalone tables
                // If statements in pure SQL weren't playing nice so I do them in the code
                Command.CommandText = "SELECT 1 FROM DiscordTwitterUsers WHERE DiscordId=@D_ID;";
                Reader = await Command.ExecuteReaderAsync();

                if (!Reader.Read()) // If empty result
                {
                    Reader.Close(); // Close off before doing more commands
                    Command.CommandText = "DELETE FROM DiscordUsers WHERE Id=@D_ID;";
                    await Command.ExecuteNonQueryAsync();
                }

                // Then do the same for out-of-use Twitter accounts
                Command.CommandText = "SELECT 1 FROM DiscordTwitterUsers WHERE TwitterId=@T_ID;";
                Reader = Command.ExecuteReader();
                if (!Reader.Read())
                {
                    Reader.Close();
                    Command.CommandText = "DELETE FROM TwitterUsers WHERE Id=@T_ID;";
                    await Command.ExecuteNonQueryAsync();

                    // If nobody is interested in this twitter account, unfollow
                    await Program.TwitterBotInstance.UnfollowUser(twitterUserId, discordUsername);
                }
            } catch (MySqlException e) {
                Utils.MainLog(
                    $"MySqlException occured while unsubscribing users: {e.ToString()}",
                    "Error", "UnsubscribeUser");
            } finally {
                if (Reader != null)
                {
                    Reader.Close();
                }
                if (Connection != null)
                {
                    await Connection.CloseAsync();
                }
            }
        }
Example #17
0
        public virtual async Task CloseAsync()
        {
            if (_connection != null)
            {
                await _connection.CloseAsync().ConfigureAwait(false);

                _connection = null;
                _session    = null;
            }
        }
        public async override Task CloseAsync()
        {
            await _faultTolerantSendingLink.CloseAsync().ConfigureAwait(false);

            await _feedbackReceiver.CloseAsync().ConfigureAwait(false);

            await _fileNotificationReceiver.CloseAsync().ConfigureAwait(false);

            await Connection.CloseAsync().ConfigureAwait(false);
        }
        public void ReceiveWithLinkDetachErrorTest()
        {
            this.testListener.RegisterTarget(TestPoint.Flow, (stream, channel, fields) =>
            {
                // detach link with error. receive calls should throw
                TestListener.FRM(stream, 0x16UL, 0, channel, fields[0], true, new Error()
                {
                    Condition = ErrorCode.InternalError
                });
                return(TestOutcome.Stop);
            });
            this.testListener.RegisterTarget(TestPoint.Detach, (stream, channel, fields) =>
            {
                return(TestOutcome.Stop);
            });

            string testName = "ReceiveWithLinkDetachErrorTest";

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                Connection   connection = new Connection(this.address);
                Session      session    = new Session(connection);
                ReceiverLink receiver   = new ReceiverLink(session, "receiver-" + testName, "any");
                try
                {
                    receiver.Receive();
                    Assert.IsTrue(false, "Receive should fail with error");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual((Symbol)ErrorCode.InternalError, exception.Error.Condition);
                }
                connection.Close();
                Assert.AreEqual((Symbol)ErrorCode.InternalError, receiver.Error.Condition);
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async() =>
            {
                Connection connection = await Connection.Factory.CreateAsync(this.address);
                Session session       = new Session(connection);
                ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "any");
                try
                {
                    await receiver.ReceiveAsync();
                    Assert.IsTrue(false, "Receive should fail with error");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual((Symbol)ErrorCode.InternalError, exception.Error.Condition);
                }
                await connection.CloseAsync();
                Assert.AreEqual((Symbol)ErrorCode.InternalError, receiver.Error.Condition);
            }).Unwrap().GetAwaiter().GetResult();
        }
        async Task SendReceiveAsync(int count)
        {
            // it is also possible to create the Address object form a Uri string as follows,
            //   wss://[sas-policy]:[sas-key]@[ns].servicebus.windows.net/$servicebus/websocket
            // note that [sas-policy] and [sas-key] should be URL encoded
            Address wsAddress = new Address(this.Namespace, 443, this.KeyName, this.KeyValue, "/$servicebus/websocket", "wss");
            WebSocketTransportFactory wsFactory = new WebSocketTransportFactory("AMQPWSB10");

            Trace.WriteLine(TraceLevel.Information, "Establishing a connection...");
            ConnectionFactory connectionFactory = new ConnectionFactory(new TransportProvider[] { wsFactory });
            Connection        connection        = await connectionFactory.CreateAsync(wsAddress);

            Trace.WriteLine(TraceLevel.Information, "Creating a session...");
            Session session = new Session(connection);

            Trace.WriteLine(TraceLevel.Information, "Creating a sender link...");
            SenderLink sender = new SenderLink(session, "websocket-sender-link", this.Entity);

            Trace.WriteLine(TraceLevel.Information, "Sending {0} messages...", count);
            for (int i = 0; i < count; i++)
            {
                Message message = new Message("testing");
                message.Properties = new Properties()
                {
                    MessageId = "websocket-test-" + i
                };
                await sender.SendAsync(message);
            }

            Trace.WriteLine(TraceLevel.Information, "Closing sender...");
            await sender.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Receiving messages...");
            ReceiverLink receiver = new ReceiverLink(session, "websocket-receiver-link", this.Entity);

            for (int i = 0; i < count; i++)
            {
                Message message = await receiver.ReceiveAsync(30000);

                if (message == null)
                {
                    break;
                }

                receiver.Accept(message);
            }

            Trace.WriteLine(TraceLevel.Information, "Closing receiver...");
            await receiver.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Shutting down...");
            await session.CloseAsync();

            await connection.CloseAsync();
        }
Example #21
0
        // Method we use to list a discord user's subscriptions
        public async Task <List <string> > GetSubscriptions(ulong discordId)
        {
            // Twitter IDs are always longs -- while they're stored as UNSIGNED BIGINTS I could get them as ulongs
            // but I'll keep them as longs for consistency's sake

            // This is a list of Ids, which aren't necessarily human-readable. We will parse to usernames later.
            List <long> IdResults = new List <long>();

            try {
                if (Connection.State == ConnectionState.Closed)
                {
                    await Connection.OpenAsync();
                }

                MySqlCommand Command = new MySqlCommand("SELECT TwitterId FROM DiscordTwitterUsers WHERE DiscordId=@D_ID", Connection);
                Command.Prepare();
                Command.Parameters.AddWithValue("@D_ID", discordId);
                Reader = await Command.ExecuteReaderAsync();

                while (await Reader.ReadAsync())
                {
                    // Read all the twitter ids that match and add them to list
                    IdResults.Add(Reader.GetInt64(0));
                }
            } catch (MySqlException e) {
                Utils.MainLog(
                    $"MySqlException occured while getting subscriptions for a Discord user: {e.ToString()}",
                    "Error",
                    "GetSubscriptions"
                    );
            } finally {
                if (Reader != null)
                {
                    Reader.Close();
                }
                if (Connection != null)
                {
                    await Connection.CloseAsync();
                }
            }

            // Internal function to convert enumerable as LINQ doesn't accept async predicates
            async Task <List <string> > IdsToUsernames(List <long> IdList)
            {
                IEnumerable <Task <string> > TaskList = IdList.Select(id => Program.TwitterBotInstance.GetUsername(id));
                var Usernames = await Task.WhenAll(TaskList);

                return(Usernames.ToList());
            }

            // Convert all entries to usernames using Twitter bot's lookup
            List <string> UsernameResults = await IdsToUsernames(IdResults);

            return(UsernameResults);
        }
Example #22
0
        public void SendTimeoutTest()
        {
            this.testListener.RegisterTarget(TestPoint.Transfer, (stream, channel, fields) =>
            {
                return(TestOutcome.Stop);
            });

            string   testName = "SendTimeoutTest";
            TimeSpan timeout  = TimeSpan.FromMilliseconds(600);

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                Connection connection = new Connection(this.address);
                Session    session    = new Session(connection);
                SenderLink sender     = new SenderLink(session, "sender-" + testName, "any");
                try
                {
                    sender.Send(new Message("test")
                    {
                        Properties = new Properties()
                        {
                            MessageId = testName
                        }
                    }, timeout);
                    Assert.IsTrue(false, "Send should throw exception");
                }
                catch (TimeoutException)
                {
                }
                connection.Close();
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async() =>
            {
                Connection connection = await Connection.Factory.CreateAsync(this.address);
                Session session       = new Session(connection);
                SenderLink sender     = new SenderLink(session, "sender-" + testName, "any");
                try
                {
                    await sender.SendAsync(new Message("test")
                    {
                        Properties = new Properties()
                        {
                            MessageId = testName
                        }
                    }, timeout);
                    Assert.IsTrue(false, "Send should throw exception");
                }
                catch (TimeoutException)
                {
                }
                await connection.CloseAsync();
            }).Unwrap().GetAwaiter().GetResult();
        }
Example #23
0
        public void SaslMismatchTest()
        {
            this.testListener.RegisterTarget(TestPoint.Header, (stream, channel, fields) =>
            {
                stream.Write(new byte[] { (byte)'A', (byte)'M', (byte)'Q', (byte)'P', 3, 1, 0, 0 }, 0, 8);
                stream.Write(new byte[] { (byte)'A', (byte)'M', (byte)'Q', (byte)'P', 0, 1, 0, 0 }, 0, 8);
                TestListener.FRM(stream, 0x10UL, 0, 0, "TestListener", "localhost", 512u);
                TestListener.FRM(stream, 0x18UL, 0, 0);
                return(TestOutcome.Stop);
            });

            string testName = "SaslMismatchTest";
            bool   failed;

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                failed = true;
                try
                {
                    Open open = new Open()
                    {
                        ContainerId = testName, HostName = "localhost", MaxFrameSize = 2048
                    };
                    Connection connection = new Connection(this.address, null, open, null);
                    connection.Close(TimeSpan.FromSeconds(5));
                    failed = connection.Error != null;
                }
                catch (Exception e)
                {
                    Trace.WriteLine(TraceLevel.Information, "Exception {0}:{1}", e.GetType().Name, e.Message);
                }
                Assert.IsTrue(failed, "should fail");
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async() =>
            {
                failed = true;
                try
                {
                    ConnectionFactory factory = new ConnectionFactory();
                    factory.AMQP.MaxFrameSize = 2048;
                    Connection connection     = await factory.CreateAsync(this.address);
                    await connection.CloseAsync(TimeSpan.FromSeconds(5));
                    Trace.WriteLine(TraceLevel.Frame, "Error {0}", connection.Error);
                    failed = connection.Error != null;
                }
                catch (Exception e)
                {
                    Trace.WriteLine(TraceLevel.Information, "Exception {0}:{1}", e.GetType().Name, e.Message);
                }
                Assert.IsTrue(failed, "should fail");
            }).Unwrap().GetAwaiter().GetResult();
        }
Example #24
0
        /// <summary>
        /// Asynchronously close the underlying Redis connection
        /// </summary>
        /// <param name="allowCommandsToComplete">whether allow Redis commands to complete</param>
        /// <returns>task represents the asynchronous close operation</returns>
        public async Task CloseAsync(bool allowCommandsToComplete = true)
        {
            if (!_disposed)
            {
                await Connection?.CloseAsync(allowCommandsToComplete);

                Connection?.Dispose();
                GC.SuppressFinalize(this);

                _disposed = true;
            }
        }
Example #25
0
        /// <summary>
        ///   Closes the consumer.
        /// </summary>
        ///
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        /// <returns>A task to be resolved on when the operation has completed.</returns>
        ///
        public virtual async Task CloseAsync(CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();
            IsClosed = true;

            var clientHash = GetHashCode().ToString();

            ServiceBusEventSource.Log.ClientCloseStart(typeof(ServiceBusReceiverClient), EntityName, clientHash);

            // Attempt to close the transport consumer.  In the event that an exception is encountered,
            // it should not impact the attempt to close the connection, assuming ownership.

            var transportConsumerException = default(Exception);

            try
            {
                await Consumer.CloseAsync(CancellationToken.None).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                ServiceBusEventSource.Log.ClientCloseError(typeof(ServiceBusReceiverClient), EntityName, clientHash, ex.Message);
                transportConsumerException = ex;
            }

            // An exception when closing the connection supersedes one observed when closing the
            // individual transport clients.

            try
            {
                if (OwnsConnection)
                {
                    await Connection.CloseAsync().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                ServiceBusEventSource.Log.ClientCloseError(typeof(ServiceBusReceiverClient), EntityName, clientHash, ex.Message);
                transportConsumerException = null;
                throw;
            }
            finally
            {
                ServiceBusEventSource.Log.ClientCloseComplete(typeof(ServiceBusReceiverClient), EntityName, clientHash);
            }

            // If there was an active exception pending from closing the individual
            // transport consumers, surface it now.

            if (transportConsumerException != default)
            {
                throw transportConsumerException;
            }
        }
Example #26
0
        public override async Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogDebug($"QueueListener stopping.");

            await _receiverLink.CloseAsync();

            await _session.CloseAsync();

            await _connection.CloseAsync();

            _logger.LogDebug($"QueueListener stopped.");
        }
Example #27
0
        async Task SendReceiveAsync(int count)
        {
            Trace.WriteLine(TraceLevel.Information, "Establishing a connection...");
            Connection connection = await Connection.Factory.CreateAsync(this.GetAddress());

            Trace.WriteLine(TraceLevel.Information, "Creating a session...");
            Session session = new Session(connection);

            Trace.WriteLine(TraceLevel.Information, "Creating a sender link...");
            SenderLink sender = new SenderLink(session, "topic-sender-link", this.Entity);

            Trace.WriteLine(TraceLevel.Information, "Sending {0} messages...", count);
            for (int i = 0; i < count; i++)
            {
                Message message = new Message();
                message.Properties = new Properties()
                {
                    MessageId = "topic-test-" + i
                };
                message.BodySection = new Data()
                {
                    Binary = Encoding.UTF8.GetBytes("message #" + i)
                };
                await sender.SendAsync(message);
            }

            Trace.WriteLine(TraceLevel.Information, "Closing sender...");
            await sender.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Receiving messages from subscription...");
            ReceiverLink receiver = new ReceiverLink(session, "receiver-link", this.Entity + "/Subscriptions/sub1");

            for (int i = 0; i < count; i++)
            {
                Message message = await receiver.ReceiveAsync(30000);

                if (message == null)
                {
                    break;
                }

                receiver.Accept(message);
            }

            Trace.WriteLine(TraceLevel.Information, "Closing receiver...");
            await receiver.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Shutting down...");
            await session.CloseAsync();

            await connection.CloseAsync();
        }
        /// <summary>
        ///     Remove the underlying transaction from the connection
        /// </summary>
        protected virtual async Task ClearTransactionAsync(CancellationToken cancellationToken = default)
        {
            Debug.Assert(Connection.CurrentTransaction == null || Connection.CurrentTransaction == this);

            await Connection.UseTransactionAsync(null, cancellationToken);

            if (!_connectionClosed)
            {
                _connectionClosed = true;

                await Connection.CloseAsync();
            }
        }
Example #29
0
        public async Task WebSocketSendReceiveAsync()
        {
            if (Environment.GetEnvironmentVariable("CoreBroker") == "1")
            {
                // No Websocket listener on .Net Core
                return;
            }

            string testName = "WebSocketSendReceiveAsync";

            // assuming it matches the broker's setup and port is not taken
            Address wsAddress = new Address(address);
            int     nMsgs     = 50;

            ConnectionFactory connectionFactory = new ConnectionFactory(
                new TransportProvider[] { new WebSocketTransportFactory() });
            Connection connection = await connectionFactory.CreateAsync(wsAddress);

            Session    session = new Session(connection);
            SenderLink sender  = new SenderLink(session, "sender-" + testName, "q1");

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message();
                message.Properties = new Properties()
                {
                    MessageId = "msg" + i, GroupId = testName
                };
                message.ApplicationProperties       = new ApplicationProperties();
                message.ApplicationProperties["sn"] = i;
                await sender.SendAsync(message);
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1");

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = await receiver.ReceiveAsync();

                Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]);
                receiver.Accept(message);
            }

            await sender.CloseAsync();

            await receiver.CloseAsync();

            await session.CloseAsync();

            await connection.CloseAsync();
        }
        static async Task <int> SslConnectionTestAsync()
        {
            try{
                ConnectionFactory factory = new ConnectionFactory();

                String certFile = "C:\\location\\certificate.cer";
                factory.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
                factory.SSL.LocalCertificateSelectionCallback   = (a, b, c, d, e) => X509Certificate.CreateFromCertFile(certFile);
                factory.SSL.ClientCertificates.Add(X509Certificate.CreateFromCertFile(certFile));

                factory.SASL.Profile = SaslProfile.External;
                Connection.DisableServerCertValidation = false;

                Address    address    = new Address("amqps://*****:*****@host:5671");
                Connection connection = await factory.CreateAsync(address);

                Session    session = new Session(connection);
                SenderLink sender  = new SenderLink(session, "sender-link", "amqp");
                Message    message = null;

                DateTime d1 = DateTime.Now;
                Console.WriteLine(d1);
                Console.WriteLine("Send Start time : {0}!", d1);

                for (int i = 0; i < 5; i++)
                {
                    string msg = "num --" + i + "-->this is a testing message for sender, to test sending proformance";
                    message = new Message(msg);
                    sender.SendAsync(message);
                    Console.WriteLine("Sent messaging {0}!", msg);
                }

                DateTime d2 = DateTime.Now;
                Console.WriteLine("Send End time : {0}!", d2);
                Console.WriteLine("Press enter key to exit...");
                Console.ReadLine();

                await sender.CloseAsync();

                await session.CloseAsync();

                await connection.CloseAsync();

                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0}.", e);
                return(1);
            }
        }
        /// <summary>
        ///     Remove the underlying transaction from the connection
        /// </summary>
        protected virtual async Task ClearTransactionAsync(CancellationToken cancellationToken = default)
        {
            Check.DebugAssert(
                Connection.CurrentTransaction == null || Connection.CurrentTransaction == this,
                "Connection.CurrentTransaction is unexpected instance");

            await Connection.UseTransactionAsync(null, cancellationToken).ConfigureAwait(false);

            if (!_connectionClosed)
            {
                _connectionClosed = true;

                await Connection.CloseAsync().ConfigureAwait(false);
            }
        }
Example #32
0
        public void SendWithInvalidRemoteChannelTest()
        {
            this.testListener.RegisterTarget(TestPoint.Transfer, (stream, channel, fields) =>
            {
                // send an end with invalid channel
                TestListener.FRM(stream, 0x17UL, 0, 33);
                return TestOutcome.Stop;
            });

            string testName = "SendWithProtocolErrorTest";

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                Connection connection = new Connection(this.address);
                Session session = new Session(connection);
                SenderLink sender = new SenderLink(session, "sender-" + testName, "any");
                try
                {
                    sender.Send(new Message("test") { Properties = new Properties() { MessageId = testName } });
                    Assert.IsTrue(false, "Send should throw exception");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual(ErrorCode.NotFound, (string)exception.Error.Condition);
                }
                connection.Close();
                Assert.AreEqual(ErrorCode.NotFound, (string)connection.Error.Condition);
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async () =>
            {
                Connection connection = await Connection.Factory.CreateAsync(this.address);
                Session session = new Session(connection);
                SenderLink sender = new SenderLink(session, "sender-" + testName, "any");
                try
                {
                    await sender.SendAsync(new Message("test") { Properties = new Properties() { MessageId = testName } });
                    Assert.IsTrue(false, "Send should throw exception");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual(ErrorCode.NotFound, (string)exception.Error.Condition);
                }
                await connection.CloseAsync();
                Assert.AreEqual(ErrorCode.NotFound, (string)connection.Error.Condition);
            }).Unwrap().GetAwaiter().GetResult();
        }
Example #33
0
        public void ReceiveWithConnectionResetTest()
        {
            this.testListener.RegisterTarget(TestPoint.Flow, (stream, channel, fields) =>
            {
                stream.Dispose();
                return TestOutcome.Continue;
            });

            string testName = "ReceiveWithConnectionResetTest";

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                Connection connection = new Connection(this.address);
                Session session = new Session(connection);
                ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "any");
                DateTime start = DateTime.UtcNow;
                Message message = receiver.Receive();
                Assert.IsTrue(message == null);
                Assert.IsTrue(DateTime.UtcNow.Subtract(start).TotalMilliseconds < 5000, "Receive call is not cancelled.");
                connection.Close();
                Assert.AreEqual(ErrorCode.ConnectionForced, (string)connection.Error.Condition);
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async () =>
            {
                Connection connection = await Connection.Factory.CreateAsync(this.address);
                Session session = new Session(connection);
                ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "any");
                DateTime start = DateTime.UtcNow;
                Message message = await receiver.ReceiveAsync();
                Assert.IsTrue(message == null);
                Assert.IsTrue(DateTime.UtcNow.Subtract(start).TotalMilliseconds < 1000, "Receive call is not cancelled.");
                await connection.CloseAsync();
                Assert.AreEqual(ErrorCode.ConnectionForced, (string)connection.Error.Condition);
            }).Unwrap().GetAwaiter().GetResult();
        }
        public async void ListenEx(Connection dataConnection)
        {
            // accept inside try so EndService could clean up.
            try
            {
                await dataConnection.AcceptAsync();
                var protocolHandler = BeginService(dataConnection);
                do
                {
                    // process requests from this connection.
                    protocolHandler.BeginRequest();
                    while (protocolHandler.KeepReading)
                    {
                        await dataConnection.ReadAsync();
                        protocolHandler.CheckRequestData();
                    }

                    // execute collected requests.
                    var stillExecuting = protocolHandler.ParseExecuteRequest();
                    while (stillExecuting > 0)
                    {
                        await dataConnection.FlushAsync(false);
                        stillExecuting = await protocolHandler.WaitForExecuting();
                    }
                    // send last piece of accumulated response to the client.
                    await dataConnection.FlushAsync(true);
                } 
                while (dataConnection.KeepAlive);
                
                // allow chance of graceful close.
                await dataConnection.CloseAsync();
            }
            finally
            {
                //todo: pre-close connection on errors ??
                EndService(dataConnection);
            }
        }