Example #1
1
		public void TestProducerSendWithTimeout()
		{
			int timeout = 1500;
			Uri uri = new Uri(string.Format("mock://localhost:61616?connection.RequestTimeout={0}&transport.respondToMessages=false", timeout));

			ConnectionFactory factory = new ConnectionFactory(uri);
			using(IConnection connection = factory.CreateConnection())
			using(ISession session = connection.CreateSession())
			{
				IDestination destination = session.GetTopic("Test");
				using(IMessageProducer producer = session.CreateProducer(destination))
				{
					ITextMessage message = session.CreateTextMessage("Hello World");

					for(int i = 0; i < 10; ++i)
					{
						DateTime start = DateTime.Now;

						try
						{
							producer.Send(message);
							Assert.Fail("Expected a RequestTimedOutException");
						}
						catch(RequestTimedOutException)
						{
						}
						
						TimeSpan elapsed = DateTime.Now - start;
						// Make sure we timed out.
						Assert.GreaterOrEqual((int) elapsed.TotalMilliseconds, timeout - 10, "Did not reach timeout limit.");
					}
				}
			}
		}
Example #2
0
    public static void Main()
    {
        ConnectionFactory factory = new ConnectionFactory();
        factory.HostName = "127.0.0.1";
        using (IConnection connection = factory.CreateConnection())
        using (IModel channel = connection.CreateModel())
        {
            channel.QueueDeclare(QueueName, false, false, false, null);

            QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel);

            bool autoAck = true;
            channel.BasicConsume(QueueName, autoAck, consumer);

            System.Console.WriteLine(" [*] Message List\n" +
                                     "To exit press CTRL+C");
            while (true)
            {
                BasicDeliverEventArgs ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                byte[] body = ea.Body;
                string message = System.Text.Encoding.UTF8.GetString(body);
                System.Console.WriteLine(" [x] Received {0}", message);
            }
        }
    }
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using( var connection = factory.CreateConnection() )
        using( var channel = connection.CreateModel() )
        {
            channel.QueueDeclare( queue: "task_queue", durable: true, exclusive: false, autoDelete: false, arguments: null );

            channel.BasicQos( prefetchSize: 0, prefetchCount: 1, global: false );
            var consumer = new QueueingBasicConsumer( channel );
            channel.BasicConsume( queue: "task_queue", noAck: false, consumer: consumer );

            Console.WriteLine( " [*] Waiting for messages. To exit press CTRL+C" );
            while( true )
            {
                var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                var body = ea.Body;
                var message = Encoding.UTF8.GetString( body );
                Console.WriteLine( " [x] Received {0}", message );

                int dots = message.Split( '.' ).Length - 1;
                Thread.Sleep( dots * 1000 );

                Console.WriteLine( " [x] Done" );

                channel.BasicAck( deliveryTag: ea.DeliveryTag, multiple: false );
            }
        }
    }
Example #4
0
 //https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/dotnet/NewTask/NewTask.cs
 static void Enqueue(string queueName, string hostName, string msg, int cycles)
 {
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     var factory = new ConnectionFactory() { HostName = hostName };
     factory.UserName = "******";
     factory.Password = "******";
     using (var connection = factory.CreateConnection())
     {
         using (var channel = connection.CreateModel())
         {
             byte[] body;
             QueueDeclareOk res = channel.QueueDeclare(queueName, true, false, false, null);
             if (msg != null)
                 body = Encoding.UTF8.GetBytes(msg);
             else
                 body = new byte[0];
             var properties = channel.CreateBasicProperties();
             properties.SetPersistent(true);
             sw.Start();
             for (int n = 0; n < cycles; ++n)
             {
                 channel.BasicPublish("", queueName, properties, body);
             }
             sw.Stop();
         }
     }
     Console.WriteLine(" [x] Enqueue {0} with count = {1}, time = {2} ms", "", cycles, sw.ElapsedMilliseconds);
 }
 public UnitOfWork(string nameOrConnectionString)
 {
     var connectionFactory = new ConnectionFactory(nameOrConnectionString);
     _connection = connectionFactory.Create();
     _connection.Open();
     _transaction = _connection.BeginTransaction();
 }
Example #6
0
    public void Worker()
    {
        Text log = GameObject.Find("console").GetComponent<Text>();
           	  var factory = new ConnectionFactory() { HostName = "diablo", UserName = "******" ,Password = "******"};
        using(var connection = factory.CreateConnection())
        using(var channel = connection.CreateModel())
        {
            channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                //var body = ea.Body;
                //var message = Encoding.UTF8.GetString(body);
                //Console.WriteLine(" [x] Received {0}", message);

               /// int dots = message.Split('.').Length - 1;
                //
                Thread.Sleep(1000);
                log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] recebendo mensagens. \n";

                channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);

            };
            channel.BasicConsume(queue: "Work_Queue",
                                 noAck: false,
                                 consumer: consumer);
        }
    }
Example #7
0
 //https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/dotnet/Worker/Worker.cs
 static void Dequeue(string queueName, string hostName, int expected)
 {
     int count = 0;
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     var factory = new ConnectionFactory() { HostName = hostName };
     factory.UserName = "******";
     factory.Password = "******";
     using (var connection = factory.CreateConnection())
     {
         using (var channel = connection.CreateModel())
         {
             channel.QueueDeclare(queueName, true, false, false, null);
             channel.BasicQos(0, 1, false);
             var consumer = new QueueingBasicConsumer(channel);
             channel.BasicConsume(queueName, false, consumer);
             sw.Start();
             while (count < expected)
             {
                 BasicDeliverEventArgs ea = consumer.Queue.Dequeue();
                 var body = ea.Body;
                 var message = Encoding.UTF8.GetString(body);
                 channel.BasicAck(ea.DeliveryTag, false);
                 ++count;
             }
             sw.Stop();
         }
     }
     Console.WriteLine(" [x] {0} messages dequeued in time = {1} ms", count, sw.ElapsedMilliseconds);
 }
        public RabbitMqConnectionFactory(ConnectionConfiguration connectionConfiguration)
        {
            if (connectionConfiguration == null)
            {
                throw new ArgumentNullException("connectionConfiguration");
            }

            if (connectionConfiguration.HostConfiguration == null)
            {
                throw new ArgumentException(
                    "The connectionConfiguration has a null HostConfiguration.", "connectionConfiguration");
            }

            Configuration = connectionConfiguration;

            connectionFactory = new ConnectionFactory
            {
                HostName = connectionConfiguration.HostConfiguration.Host,
                Port = connectionConfiguration.HostConfiguration.Port,
                VirtualHost = Configuration.VirtualHost,
                UserName = Configuration.UserName,
                Password = Configuration.Password,
                RequestedHeartbeat = Configuration.RequestedHeartbeat,
                ClientProperties = Configuration.ClientProperties
            };
        }
        protected static ConnectionFactory GetConnectionFactory()
        {
            //var factory = new ConnectionFactory()
            //{
            //  HostName = "equinox.local",
            //  Port = 5672,
            //  VirtualHost = "/",
            //  UserName = "******",
            //  Password = "******"
            //};

            var factory = new ConnectionFactory()
            {
                Uri = "amqp://*****:*****@fox.rmq.cloudamqp.com/icxhlaxw",
                UserName = "******",
                Password = "******"
            };

            //var factory = new ConnectionFactory()
            //{
            //    HostName = "localhost",
            //    Port = 5672,
            //    //VirtualHost = "/",
            //    //UserName = "******",
            //    //Password = "******"
            //};

            return factory;
        }
Example #10
0
    public void NewTask()
    {
        string filepath = Utils.GetFullPathFileName("Chegou.png");
        byte[] body = Utils.GetFileAsBytesOrNull (filepath);
        var factory = new ConnectionFactory() { HostName = "diablo" };
        using(var connection = factory.CreateConnection())
            using(var channel = connection.CreateModel())
        {
            //channel.QueueDeclare("Work_Queue"); // version shup
            channel.QueueDeclare("Work_Queue",true,false,false,null);

            var properties = channel.CreateBasicProperties();
            properties.SetPersistent(true);

            channel.BasicPublish(exchange: "",
                                 routingKey: "Work_Queue",
                                 basicProperties: properties,
                                 body: body);
            Text text ,log;
            text =  GameObject.Find("TextPE").GetComponent<Text>();
            int count = int.Parse(text.text) + 1;
            text.text= count.ToString();
            log = GameObject.Find("console").GetComponent<Text>();
            var fileInfo = new System.IO.FileInfo("Chegou.png");
            var fileSize = (fileInfo.Length/1024f)/1024f;
            log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Mensagem Enviada Work Queue : " + fileSize.ToString("0.00") + " MB" + "\n";

            connection.Close();
            //Console.WriteLine(" [x] Sent {0}", message);
        }
    }
Example #11
0
    public void SendSimpleQueue()
    {
        string filepath = Utils.GetFullPathFileName("rabbit.ogg");
        byte[] body = Utils.GetFileAsBytesOrNull (filepath);

        var factory = new ConnectionFactory() { HostName = "diablo" ,UserName = "******" ,Password = "******" };
        using(var connection = factory.CreateConnection())
            using(var channel = connection.CreateModel())
        {
            //channel.QueueDeclare("SimpleQueue"); //version shup
            channel.QueueDeclare("SimpleQueue",true,false,false,null);

        //			string message = "Hello World!";
            //var body = Encoding.UTF8.GetBytes(message);

            channel.BasicPublish(exchange: "",
                                 routingKey: "SimpleQueue",
                                 basicProperties: null,
                                 body: body);

            Text text ,log;
            text =  GameObject.Find("TextPE").GetComponent<Text>();
            int count = int.Parse(text.text) + 1;
            text.text= count.ToString();
            log = GameObject.Find("console").GetComponent<Text>();
            var fileInfo = new System.IO.FileInfo("rabbit.ogg");
            var fileSize = (fileInfo.Length/1024f)/1024f;
            log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Mensagem Enviada SingleQueue : " + fileSize.ToString("0.00") + " MB" + "\n";

            connection.Close();
        }
    }
Example #12
0
        public static IGroupDataProvider GetProviderFromConfigName(ILog log, IConfig groupsConfig, string configName)
        {
            switch (configName)
            {
                case "XmlRpc":
                    string ServiceURL = groupsConfig.GetString("XmlRpcServiceURL");
                    bool DisableKeepAlive = groupsConfig.GetBoolean("XmlRpcDisableKeepAlive", false);

                    string ServiceReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", String.Empty);
                    string ServiceWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", String.Empty);

                    log.InfoFormat("[GROUPS]: XmlRpc Service URL set to: {0}", ServiceURL);

                    return new XmlRpcGroupDataProvider(ServiceURL, DisableKeepAlive, ServiceReadKey, ServiceWriteKey);


                case "Native":
                    string dbType = groupsConfig.GetString("NativeProviderDBType");
                    string connStr = groupsConfig.GetString("NativeProviderConnString");

                    ConnectionFactory connFactory = new ConnectionFactory(dbType, connStr);
                    return new NativeGroupDataProvider(connFactory);

            }

            return null;
        }
Example #13
0
    public static void Main()
    {
        ConnectionFactory factory = new ConnectionFactory();
        factory.HostName = "localhost";
        using (IConnection connection = factory.CreateConnection())
        using (IModel channel = connection.CreateModel()) {
            channel.ExchangeDeclare("logs", "fanout");

            string queue_name = channel.QueueDeclare();

            channel.QueueBind(queue_name, "logs", "");
            QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel);
            channel.BasicConsume(queue_name, true, consumer);

            Console.WriteLine(" [*] Waiting for logs." +
                              "To exit press CTRL+C");
            while(true) {
                BasicDeliverEventArgs ea =
                    (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                byte[] body = ea.Body;
                string message = System.Text.Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] {0}", message);
            }
        }
    }
        public void TestHundredsOfConnectionsWithRandomHeartbeatInterval()
        {
            var rnd = new Random();
            List<IConnection> xs = new List<IConnection>();
            for (var i = 0; i < 200; i++)
            {
                var n = Convert.ToUInt16(rnd.Next(2, 6));
                var cf = new ConnectionFactory() { RequestedHeartbeat = n, AutomaticRecoveryEnabled = false };
                var conn = cf.CreateConnection();
                xs.Add(conn);
                var ch = conn.CreateModel();
                bool wasShutdown = false;

                conn.ConnectionShutdown += (sender, evt) =>
                    {
                        CheckInitiator(evt);
                    };
            }

            SleepFor(60);

            foreach (var x in xs)
            {
                x.Close();
            }
        }
        public void TestThatHeartbeatWriterWithTLSEnabled()
        {
            if (!LongRunningTestsEnabled())
            {
                Console.WriteLine("RABBITMQ_LONG_RUNNING_TESTS is not set, skipping test");
                return;
            }

            var cf = new ConnectionFactory()
            {
                RequestedHeartbeat = heartbeatTimeout,
                AutomaticRecoveryEnabled = false
            };

            string sslDir = IntegrationFixture.CertificatesDirectory();
            if (null == sslDir)
            {
                Console.WriteLine("SSL_CERT_DIR is not configured, skipping test");
                return;
            }
            cf.Ssl.ServerName = System.Net.Dns.GetHostName();
            Assert.IsNotNull(sslDir);
            cf.Ssl.CertPath = sslDir + "/client/keycert.p12";
            string p12Password = Environment.GetEnvironmentVariable("PASSWORD");
            Assert.IsNotNull(p12Password, "missing PASSWORD env var");
            cf.Ssl.CertPassphrase = p12Password;
            cf.Ssl.Enabled = true;

            RunSingleConnectionTest(cf);
        }
        public void TestNoCopyOnSend()
        {
            Uri uri = new Uri("mock://localhost:61616?connection.CopyMessageOnSend=false");

            ConnectionFactory factory = new ConnectionFactory(uri);
            using(IConnection connection = factory.CreateConnection())
            using(ISession session = connection.CreateSession())
            {
                IDestination destination = session.GetTopic("Test");
                using(IMessageProducer producer = session.CreateProducer(destination))
                {
                    ITextMessage message = session.CreateTextMessage();

                    for(int i = 0; i < 10; ++i)
                    {
                        try
                        {
                            message.Properties["TribbleName"] = "Tribble" + i.ToString();
                            message.Text = "The Trouble with Tribbles - " + i.ToString();
                            producer.Send(message);
                        }
                        catch(MessageNotWriteableException)
                        {
                            Assert.Greater(i, 0);
                            Assert.Less(i, 10);
                        }
                    }
                }
            }
        }
        public void TestRedelivered()
        {
            // enqueue several messages
            PurgeDatabase();
            PurgeAndFillQueue();

            // receive just one
            INetTxConnectionFactory factory = new NetTxConnectionFactory(ReplaceEnvVar(connectionURI));
            using (INetTxConnection connection = factory.CreateNetTxConnection())
            {
                connection.Start();

                using (INetTxSession session = connection.CreateNetTxSession())
                {
                    IQueue queue = session.GetQueue(testQueueName);

                    // read message from queue and insert into db table
                    using (IMessageConsumer consumer = session.CreateConsumer(queue))
                    {
                        using (TransactionScope scoped = new TransactionScope(TransactionScopeOption.RequiresNew))
                        using (SqlConnection sqlConnection = new SqlConnection(sqlConnectionString))
                        using (SqlCommand sqlInsertCommand = new SqlCommand())
                        {
                            sqlConnection.Open();
                            sqlInsertCommand.Connection = sqlConnection;

                            ITextMessage message = consumer.Receive(TimeSpan.FromMilliseconds(10000)) as ITextMessage;
                            sqlInsertCommand.CommandText =
                                string.Format("INSERT INTO {0} VALUES ({1})", testTable, Convert.ToInt32(message.Text));
                            sqlInsertCommand.ExecuteNonQuery();

                            scoped.Complete();
                        }
                    }

                    session.Close();
                }
            }

            // check that others message have status redelivered = false
            IConnectionFactory checkFactory = new ConnectionFactory(ReplaceEnvVar(connectionURI));

            using (IConnection connection = checkFactory.CreateConnection())
            {
                connection.Start();

                using (ISession session = connection.CreateSession())
                using (IQueueBrowser browser = session.CreateBrowser(session.GetQueue(testQueueName)))
                {
                    IEnumerator enumerator = browser.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        IMessage msg = enumerator.Current as IMessage;
                        Assert.IsNotNull(msg, "message is not in the queue!");
                        Assert.IsFalse(msg.NMSRedelivered, "message is redelivered!");
                    }
                }
            }
        }
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using(var connection = factory.CreateConnection())
        using(var channel = connection.CreateModel())
        {
            channel.ExchangeDeclare(exchange: "logs", type: "fanout");

            var queueName = channel.QueueDeclare().QueueName;
            channel.QueueBind(queue: queueName, exchange: "logs", routingKey: "");

            Console.WriteLine(" [*] Waiting for logs.");
            
            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] {0}", message);
            };
            channel.BasicConsume(queue: queueName, noAck: true, consumer: consumer);

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
    }
Example #19
0
    public void SendPSMessage()
    {
        string filepath = Utils.GetFullPathFileName("Chegou.png");
        byte[] messageBytes = Utils.GetFileAsBytesOrNull (filepath);

        var factory = new ConnectionFactory() { HostName = "diablo" , UserName = "******" , Password = "******"};
        using(var connection = factory.CreateConnection())
            using(var channel = connection.CreateModel())
        {
            channel.ExchangeDeclare(exchange: "publishSubEX", type: "fanout");

            var body = messageBytes;
            //var body = Encoding.UTF8.GetBytes(message);
            channel.BasicPublish(exchange: "publishSubEX",
                                 routingKey: "",
                                 basicProperties: null,
                                 body: body);

            Text text ,log;
            text =  GameObject.Find("TextPE").GetComponent<Text>();
            int count = int.Parse(text.text) + 1;
            text.text= count.ToString();
            log = GameObject.Find("console").GetComponent<Text>();
            var fileInfo = new System.IO.FileInfo("Chegou.png");
            var fileSize = (fileInfo.Length/1024f)/1024f;
            log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Mensagem Enviada Publish / Subscribe : " + fileSize.ToString("0.00") + " MB" + "\n";

        }
    }
Example #20
0
    public void receivePSMessage()
    {
        Debug.Log("Start");
        Text log = GameObject.Find("console").GetComponent<Text>();
        log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Aguardando mensagens.\n";
        var factory = new ConnectionFactory() { HostName = "diablo", UserName = "******", Password = "******"  };
        using(var connection = factory.CreateConnection())
            using(var channel = connection.CreateModel())
        {
            if(uuid == ""){
                setUuid("amq-" + Guid.NewGuid().ToString());
            }
            channel.ExchangeDeclare(exchange: "publishSubEX", type: "fanout");
            var queueName = channel.QueueDeclare(uuid, false,false,false,null);
            channel.QueueBind(queueName,"publishSubEX","");

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                Utils.SaveFileToDisk("rabbit.png",body);
                var fileInfo = new System.IO.FileInfo("rabbit.png");
                var fileSize = (fileInfo.Length/1024f)/1024f;
                log.text = log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Mensagem Enviada Publish / Subscribe : " + fileSize.ToString("0.00") + " MB" + "\n";
            };
            channel.BasicConsume(queue: queueName,
                                 noAck: true,
                                 consumer: consumer);
        }
    }
Example #21
0
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using (var connection = factory.CreateConnection())
        {
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare("task_queue", true, false, false, null);

                channel.BasicQos(0, 1, false);
                var consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume("task_queue", false, consumer);

                Console.WriteLine(" [*] Waiting for messages. " +
                                  "To exit press CTRL+C");
                while (true)
                {
                    var ea =
                        (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(" [x] Received {0}", message);

                    int dots = message.Split('.').Length - 1;
                    Thread.Sleep(dots * 1000);

                    Console.WriteLine(" [x] Done");

                    channel.BasicAck(ea.DeliveryTag, false);
                }
            }
        }
    }
        public void TestHundredsOfConnectionsWithRandomHeartbeatInterval()
        {
            if (!LongRunningTestsEnabled())
            {
                Console.WriteLine("RABBITMQ_LONG_RUNNING_TESTS is not set, skipping test");
                return;
            }

            var rnd = new Random();
            List<IConnection> xs = new List<IConnection>();
            for (var i = 0; i < 200; i++)
            {
                var n = Convert.ToUInt16(rnd.Next(2, 6));
                var cf = new ConnectionFactory() { RequestedHeartbeat = n, AutomaticRecoveryEnabled = false };
                var conn = cf.CreateConnection();
                xs.Add(conn);
                var ch = conn.CreateModel();
                bool wasShutdown = false;

                conn.ConnectionShutdown += (sender, evt) =>
                    {
                        CheckInitiator(evt);
                    };
            }

            SleepFor(60);

            foreach (var x in xs)
            {
                x.Close();
            }
        }
Example #23
0
        public void Initialise(Scene scene, IConfigSource config)
        {
            if (!m_Enabled)
                return;

            //TODO: At some point, strip this out of the ini file, in Search Module, 
            // we're going to recycle the Profile connection string however to make 
            // life a bit easier.
            IConfig profileConfig = config.Configs["Startup"];
            string connstr = profileConfig.GetString("core_connection_string", String.Empty);


            m_log.Info("[PROFILE] Profile module is activated");

            //TODO: Bad assumption on my part that we're enabling it and the connstr is actually
            // valid, but I'm sick of dinking with this thing  :)
            m_Enabled = true;

            _connFactory = new ConnectionFactory("MySQL", connstr);

            string storageConnStr = profileConfig.GetString("storage_connection_string", String.Empty);

            _regionConnFactory = new ConnectionFactory("MySQL", storageConnStr);

            // Hook up events
            scene.EventManager.OnNewClient += OnNewClient;
        }
Example #24
0
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using (var connection = factory.CreateConnection())
        {
            using (var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare("logs", "fanout");

                var queueName = channel.QueueDeclare();

                channel.QueueBind(queueName, "logs", "");
                var consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume(queueName, true, consumer);

                Console.WriteLine(" [*] Waiting for logs." +
                                  "To exit press CTRL+C");
                while (true)
                {
                    var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(" [x] {0}", message);
                }
            }
        }
    }
Example #25
0
 private IConnection CreateConnection()
 {
     IConnectionFactory factory = new ConnectionFactory(jmsServer);
     IConnection connection = factory.CreateConnection(userId, password);
     connection.Start();
     return connection;
 }
Example #26
0
    public void ConsumeSimpleQueue()
    {
        var factory = new ConnectionFactory() { HostName = "diablo" ,UserName = "******" ,Password = "******" };
        using(var connection = factory.CreateConnection())
            using(var channel = connection.CreateModel())
        {
            //channel.QueueDeclare("SimpleQueue"); //version shup
            channel.QueueDeclare("SimpleQueue",true,false,false,null);

            BasicGetResult result = channel.BasicGet("SimpleQueue", true);
            while (result != null)
            {
                //string message = result.Body;

                Utils.SaveFileToDisk("rabbitVideo.ogg",result.Body);
                result = channel.BasicGet("SimpleQueue", true);
                var fileInfo = new System.IO.FileInfo("rabbitVideo.ogg");
                var fileSize = (fileInfo.Length/1024f)/1024f;
                Atualiza(fileSize.ToString("0.00") + " MB");

            }
            if(result == null){
                Text log;
                log = GameObject.Find("console").GetComponent<Text>();
                log.text = log.text + "[ "+ DateTime.Now.ToString("HH:mm:ss") +" ] Não Há mensagens para consumir \n";
                connection.Close();

            }

        }
    }
 public void TestHandleLeakWithEnabledHeartbeats()
 {
     var cf = new ConnectionFactory()
     {
         RequestedHeartbeat = 16
     };
     PerformLeakTest(cf);
 }
Example #28
0
 public static System.Data.SQLite.SQLiteConnection GetConnection()
 {
     if (instance == null)
     {
         instance = new ConnectionFactory();
     }
     return instance._connection;
 }
Example #29
0
    public static void Main(string[] args)
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        string m_topics = "topic_logs";
        using (var connection = factory.CreateConnection())
        {
            using (var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(m_topics, "topic");
                var queueName = channel.QueueDeclare();
                var bindingkeys = args;

                if (args.Length < 1)
                {
                    //Console.Error.WriteLine("Usage: {0} [binding_key... (use # for all) ]",
                    //                        Environment.GetCommandLineArgs()[0]);
                    //Environment.ExitCode = 1;
                    //return;
                    Console.WriteLine("Receiving all DOM data using routingkey '#'");
                    channel.QueueBind(queueName, m_topics, "#");
                }

                foreach (var bindingKey in bindingkeys)
                {
                    channel.QueueBind(queueName, m_topics, bindingKey);
                    Console.WriteLine("Receiving DOM data from to '" + bindingKey + "'");
                }

                Console.WriteLine(" [*] Waiting for DOM. " +
                                  "To exit press CTRL+C");

                var consumer = new QueueingBasicConsumer(channel);
                channel.BasicConsume(queueName, true, consumer);

                while (true)
                {
                    var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    var routingKey = ea.RoutingKey;

                    Console.WriteLine(" [x] Received DOM data from '{0}'", routingKey);
                    //Console.WriteLine(" [x] Received '{0}':'{1}'",
                    //                  routingKey, message);

                    var deserialized = JsonConvert.DeserializeObject(message);

                    Console.WriteLine(deserialized);

                    // http://james.newtonking.com/json/help/index.html?topic=html/QueryingLINQtoJSON.htm

                    //deserialized

                }
            }
        }
    }
Example #30
0
 public RPCClient()
 {
     var factory = new ConnectionFactory() { HostName = "localhost" };
     connection = factory.CreateConnection();
     channel = connection.CreateModel();
     replyQueueName = channel.QueueDeclare();
     consumer = new QueueingBasicConsumer(channel);
     channel.BasicConsume(replyQueueName, true, consumer);
 }
Example #31
0
        static void Main(string[] args)
        {
            try
            {
                #region Definindo conexão com o rabbit
                ConnectionFactory factory = new ConnectionFactory();
                factory.UserName    = "******";
                factory.Password    = "******";
                factory.VirtualHost = "development";
                factory.HostName    = "localhost";
                factory.Port        = 5672;
                #endregion

                //Criando conexão
                _connection = factory.CreateConnection();

                //Criando um canal para para envio e leitura de mensagem
                _channel = _connection.CreateModel();
                var queueName = "Minha_Queue";

                ConsumerMsg(queueName);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            finally
            {
                //Fechando canal
                _channel.Close();

                //fechando conexão
                _connection.Close();
            }
        }
        public async Task UpdateHolidayCalendar(HolidayCalendar holidayCalendar)
        {
            await _serviceProvider.DoDapperServiceAsync(DefaultDbConfig, async (unitOfWork) =>
            {
                IHolidayCalendarRepository holidayCalendarRepository = ConnectionFactory.GetConnectionProvider(DefaultDbConfig.ConnectionType).GetRepository <IHolidayCalendarRepository>(unitOfWork);
                IJobConfigRepository jobConfigRepository             = ConnectionFactory.GetConnectionProvider(DefaultDbConfig.ConnectionType).GetRepository <IJobConfigRepository>(unitOfWork);
                var dbHolidayCalendar = await holidayCalendarRepository.GetAsync(holidayCalendar.Id);
                if (dbHolidayCalendar == null)
                {
                    throw new SpriteException("未找到假期信息");
                }
                await holidayCalendarRepository.UpdateAsync(holidayCalendar);
                var activeJobConfigs = await jobConfigRepository.GetActiveJobConfigs();
                foreach (var activeJobConfig in activeJobConfigs)
                {
                    if (activeJobConfig.HolidayCalendarId.HasValue && activeJobConfig.HolidayCalendarId.Value == holidayCalendar.Id)
                    {
                        await _jobManager.UnScheduleJob(activeJobConfig);
                    }
                }

                await _jobManager.DeleteCalendar(holidayCalendar.Id);

                await _jobManager.AddCalendar(holidayCalendar);

                foreach (var activeJobConfig in activeJobConfigs)
                {
                    if (activeJobConfig.HolidayCalendarId.HasValue && activeJobConfig.HolidayCalendarId.Value == holidayCalendar.Id)
                    {
                        await _jobManager.ScheduleJob(activeJobConfig);
                    }
                }
            });

            Logger.LogInformation($"UpdateHolidayCalendar:{JsonConvert.SerializeObject(holidayCalendar)}");
        }
            public AdomdDataProviderFactory()
            {
                // parameters

                TimeSpan evictionInterval = new TimeSpan(TimeSpan.TicksPerSecond);

                TimeSpan idleInterval = new TimeSpan(TimeSpan.TicksPerMinute * 5);

                int idleCount = 10;

                TimeSpan idleCounterInterval = new TimeSpan(TimeSpan.TicksPerMinute * 2);

                IKeyedPooledItemFactory <IDbConnection, string> factory = new ConnectionFactory();

                Bounds bounds = new Bounds(0, 100);

                EvictionCriteria criteria = new EvictionCriteria(evictionInterval, idleInterval, idleCount, idleCounterInterval);

                const string name = "BoundedKeyedPool<IDataConnection,string>";

                // create the pool

                pool = new BoundedKeyedPool <IDbConnection, string>(name, factory, bounds, criteria);
            }
Example #34
0
        public static void Main()
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(exchange: "logs", type: "fanout");

                    var queueName = channel.QueueDeclare().QueueName;
                    channel.QueueBind(queue: queueName,
                                      exchange: "logs",
                                      routingKey: "");

                    Console.WriteLine(" [*] Waiting for logs.");

                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                    {
                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] {0}", message);
                    };
                    channel.BasicConsume(queue: queueName,
                                         autoAck: true,
                                         consumer: consumer);

                    Console.WriteLine(" Press [enter] to exit.");
                    Console.ReadLine();
                }
            }
        }
Example #35
0
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "csq",
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null
                                         );

                    while (true)
                    {
                        Console.Write("Enter the message (Empty to exit):");
                        var message = Console.ReadLine();
                        if (string.IsNullOrEmpty(message))
                        {
                            break;
                        }
                        var payload = Encoding.UTF8.GetBytes(message);
                        channel.BasicPublish(exchange: "",
                                             routingKey: "csq",
                                             basicProperties: null,
                                             body: payload
                                             );
                    }
                }
            }
        }
Example #36
0
        /// <summary>
        /// Return matching RabbitMQ connection if exist (match by amqp scheme)
        /// or create new connection to RabbitMQ (thread-safe)
        /// </summary>
        /// <param name="connectionFactory"></param>
        /// <returns></returns>
        public IConnection GetConnection(ConnectionFactory connectionFactory)
        {
            var connectionId = GetConnectionId(connectionFactory);

            IConnection connection;
            var         connectionFound = s_connectionPool.TryGetValue(connectionId, out connection);

            if (connectionFound != false && connection.IsOpen != false)
            {
                return(connection);
            }

            lock (s_lock)
            {
                connectionFound = s_connectionPool.TryGetValue(connectionId, out connection);

                if (connectionFound == false || connection.IsOpen == false)
                {
                    connection = CreateConnection(connectionFactory);
                }
            }

            return(connection);
        }
Example #37
0
        private void InitRabbitMQ()
        {
            var factory = new ConnectionFactory()
            {
                HostName    = _options.HostName,
                UserName    = _options.UserName,
                Password    = _options.Password,
                Port        = _options.Port,
                VirtualHost = _options.VHost,
            };

            // create connection
            _connection = factory.CreateConnection();

            // create channel
            _channel = _connection.CreateModel();

            _channel.ExchangeDeclare("amq.topic", ExchangeType.Topic, true, false);
            _channel.QueueDeclare("ERPOrderingQueue", true, false, false, null);
            _channel.QueueBind("ERPOrderingQueue", "amq.topic", "ERPOrderingQueue", null);
            _channel.BasicQos(0, 1, false);

            _connection.ConnectionShutdown += RabbitMQ_ConnectionShutdown;
        }
Example #38
0
        public RabbitMqConsumer(
            RabbitMqConfig config,
            Func <BasicDeliverEventArgs, Task> onMessage)
        {
            var factory = new ConnectionFactory
            {
                Uri = config.ConnectionString,
                DispatchConsumersAsync = true
            };

            _connection = factory.CreateConnection();
            _model      = _connection.CreateModel();

            var consumer = new AsyncEventingBasicConsumer(_model);

            consumer.Received += async(_, message) =>
            {
                await onMessage(message);

                _model.BasicAck(message.DeliveryTag, false);
            };

            _model.BasicConsume(config.Destination, false, consumer);
        }
Example #39
0
        private void SendMessage(SendMessageDto model)
        {
            try
            {
                var factory = new ConnectionFactory
                {
                    UserName = "******", //用户名
                    Password = "******", //密码
                    HostName = "t.cn"   //rabbitmq ip
                };

                var exchageName = "exchange_reptile";
                var queueName   = "queue_reptile";
                var routeKey    = "key_reptile";

                using (var connection = factory.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        channel.ExchangeDeclare(exchageName, ExchangeType.Direct, false, false);
                        channel.QueueDeclare(queueName, false, false, false, null);
                        channel.QueueBind(queueName, exchageName, routeKey, null);

                        var message   = JsonConvert.SerializeObject(model);
                        var sendBytes = Encoding.UTF8.GetBytes(message);
                        //发布消息
                        channel.BasicPublish(exchageName, routeKey, null, sendBytes);
                        Console.Write(message);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Example #40
0
        public void CadastrarUsuario(string username, string password)
        {
            try
            {
                string sql = "insert into tbl_user(user_name, user_password) values('" + username + "', '" + password + "');";

                con = ConnectionFactory.Connection();

                MySqlCommand cmd = new MySqlCommand(sql, con);

                con.Open();

                MySqlDataReader dtreader = cmd.ExecuteReader();
            }
            catch (MySqlException e)
            {
                MessageBox.Show("Algo errado aconteceu durante o cadastro. Por favor, tente novamente mais tarde.", "Erro!", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
                throw new Exception(e.Message);
            }
            finally
            {
                con.Close();
            }
        }
Example #41
0
        public void TestCloseDisconnectedHandler()
        {
            using (new NATSServer())
            {
                bool   disconnected = false;
                Object mu           = new Object();

                Options o = utils.DefaultTestOptions;
                o.AllowReconnect            = false;
                o.DisconnectedEventHandler += (sender, args) =>
                {
                    lock (mu)
                    {
                        disconnected = true;
                        Monitor.Pulse(mu);
                    }
                };

                IConnection c = new ConnectionFactory().CreateConnection(o);
                lock (mu)
                {
                    c.Close();
                    Monitor.Wait(mu, 20000);
                }
                Assert.True(disconnected);

                // now test using.
                disconnected = false;
                lock (mu)
                {
                    using (c = new ConnectionFactory().CreateConnection(o)) { };
                    Monitor.Wait(mu, 20000);
                }
                Assert.True(disconnected);
            }
        }
Example #42
0
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };
            var exchange_name    = "ClockTick";
            int minute_msg_count = 0;
            var appid            = "25894721";
            var exchange_id      = "01020304";
            var rnd_id           = "010";
            var queue_name       = appid + "X" + exchange_id + "x" + rnd_id;

            int  rec_count = 0;
            bool isExit    = false;

            Console.WriteLine("Client01 正在订阅 SecondTick 与 MinuteTick  消息,按 V 键可退出程序");

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(exchange: exchange_name, type: "topic");

                    var queueName = channel.QueueDeclare(queue_name).QueueName;
                    channel.QueueBind(queue: queueName,
                                      exchange: exchange_name,
                                      routingKey: "#.SecondTick");
                    channel.QueueBind(queue: queueName,
                                      exchange: exchange_name,
                                      routingKey: "#.MinuteTick");

                    Task.Factory.StartNew(() =>
                    {
                        while (Console.ReadKey().Key != ConsoleKey.V)
                        {
                            ;
                        }
                        isExit = true;
                    });

                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                    {
                        var    body      = ea.Body;
                        UInt32 MsgTypeID = body.GetUInt32WithEndianBit(0x0D, BitConverterEx.EndianBitType.BigEndian);

                        if (MsgTypeID == 0x0000002)
                        {
                            Console.Beep();
                            minute_msg_count++;
                        }



                        UInt16 context_len = body.GetUInt16WithEndianBit(0x19, BitConverterEx.EndianBitType.BigEndian);
                        var    message     = Encoding.UTF8.GetString(body, 32, context_len);
                        var    obj         = JsonConvert.DeserializeObject <MessageBody>(message);
                        var    rec_str     = string.Concat(Enumerable.Repeat("*", minute_msg_count % 10));;
                        //var routingKey = ea.RoutingKey;

                        rec_count++;
                        if (rec_count % 2 == 0)
                        {
                            Console.Write("\r+   " + rec_str);
                        }
                        else
                        {
                            Console.Write("\r-   " + rec_str);
                        }
                    };
                    channel.BasicConsume(queue: queueName,
                                         noAck: true,
                                         consumer: consumer);

                    while (!isExit)
                    {
                        System.Threading.Thread.Sleep(200);
                    }
                    channel.BasicCancel(consumer.ConsumerTag);
                }
            }
        }
Example #43
0
 public TransferListener(ConnectionFactory factory, ITransferCommand transferCommand, ITransferCommunicator transferCommunicator)
 {
     _transferCommand      = transferCommand;
     _transferCommunicator = transferCommunicator;
     _factory = factory;
 }
Example #44
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            RegisterAppInsights(services);

            // Add framework services.
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(HttpGlobalExceptionFilter));
            }).AddControllersAsServices();  //Injecting Controllers themselves thru DI
                                            //For further info see: http://docs.autofac.org/en/latest/integration/aspnetcore.html#controllers-as-services

            services.AddTransient <IOrderingIntegrationEventService, OrderingIntegrationEventService>();

            services.AddHealthChecks(checks =>
            {
                var minutes = 1;
                if (int.TryParse(Configuration["HealthCheck:Timeout"], out var minutesParsed))
                {
                    minutes = minutesParsed;
                }
                checks.AddSqlCheck("OrderingDb", Configuration["ConnectionString"], TimeSpan.FromMinutes(minutes));
            });

            services.AddEntityFrameworkSqlServer()
            .AddDbContext <OrderingContext>(options =>
            {
                options.UseSqlServer(Configuration["ConnectionString"],
                                     sqlServerOptionsAction: sqlOptions =>
                {
                    sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                    sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                });
            },
                                            ServiceLifetime.Scoped //Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
                                            );

            services.AddDbContext <IntegrationEventLogContext>(options =>
            {
                options.UseSqlServer(Configuration["ConnectionString"],
                                     sqlServerOptionsAction: sqlOptions =>
                {
                    sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                    //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                    sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                });
            });


            services.Configure <OrderingSettings>(Configuration);

            services.AddSwaggerGen(options =>
            {
                options.DescribeAllEnumsAsStrings();
                options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Title          = "Ordering HTTP API",
                    Version        = "v1",
                    Description    = "The Ordering Service HTTP API",
                    TermsOfService = "Terms Of Service"
                });

                options.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type             = "oauth2",
                    Flow             = "implicit",
                    AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
                    TokenUrl         = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
                    Scopes           = new Dictionary <string, string>()
                    {
                        { "orders", "Ordering API" }
                    }
                });

                options.OperationFilter <AuthorizeCheckOperationFilter>();
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            // Add application services.
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IIdentityService, IdentityService>();
            services.AddTransient <Func <DbConnection, IIntegrationEventLogService> >(
                sp => (DbConnection c) => new IntegrationEventLogService(c));

            services.AddTransient <IOrderingIntegrationEventService, OrderingIntegrationEventService>();

            if (Configuration.GetValue <bool>("AzureServiceBusEnabled"))
            {
                services.AddSingleton <IServiceBusPersisterConnection>(sp =>
                {
                    var logger = sp.GetRequiredService <ILogger <DefaultServiceBusPersisterConnection> >();

                    var serviceBusConnectionString = Configuration["EventBusConnection"];
                    var serviceBusConnection       = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);

                    return(new DefaultServiceBusPersisterConnection(serviceBusConnection, logger));
                });
            }
            else
            {
                services.AddSingleton <IRabbitMQPersistentConnection>(sp =>
                {
                    var logger = sp.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >();


                    var factory = new ConnectionFactory()
                    {
                        HostName = Configuration["EventBusConnection"]
                    };

                    if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
                    {
                        factory.UserName = Configuration["EventBusUserName"];
                    }

                    if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
                    {
                        factory.Password = Configuration["EventBusPassword"];
                    }

                    var retryCount = 5;
                    if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
                    {
                        retryCount = int.Parse(Configuration["EventBusRetryCount"]);
                    }

                    return(new DefaultRabbitMQPersistentConnection(factory, logger, retryCount));
                });
            }

            RegisterEventBus(services);
            ConfigureAuthService(services);
            services.AddOptions();

            //configure autofac

            var container = new ContainerBuilder();

            container.Populate(services);

            container.RegisterModule(new MediatorModule());
            container.RegisterModule(new ApplicationModule(Configuration["ConnectionString"]));

            return(new AutofacServiceProvider(container.Build()));
        }
Example #45
0
        public async void Demo()
        {
            if (!BluetoothConnection.IsBluetoothSupported)
            {
                Console.WriteLine("Bluetooth is not supported on this Device");
                return;
            }

            //1. Get the clients in range.
            DeviceInfo[] devicesInRange = await ConnectionFactory.GetBluetoothDevicesAsync();

            if (devicesInRange.Length <= 0)
            {
                return;                            //We need at least one bluetooth connection to deal with :)
            }
            //2. Create a new instance of the bluetoothConnection with the factory.
            Tuple <ConnectionResult, BluetoothConnection> bluetoothConnection = await ConnectionFactory.CreateBluetoothConnectionAsync(devicesInRange[0]);

            if (bluetoothConnection.Item1 != ConnectionResult.Connected)
            {
                return;                                                         //We were not able to connect to the server.
            }
            //3. Register what happens if we receive a packet of type "CalculationResponse"
            bluetoothConnection.Item2.RegisterPacketHandler <CalculationResponse>((response, con) => Console.WriteLine($"Answer received {response.Result}"), this);
            //4. Send a calculation request.
            bluetoothConnection.Item2.Send(new CalculationRequest(10, 10), this);
        }
Example #46
0
        public static int Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.Error.WriteLine("Usage: PerfTest <uri> <number of messages> <size of messages>");
                Console.Error.WriteLine("RabbitMQ .NET client version " + typeof(IModel).Assembly.GetName().Version.ToString());
                Console.Error.WriteLine("Parameters:");
                Console.Error.WriteLine("  <uri> = \"amqp://*****:*****@host:port/vhost\"");
                return(2);
            }

            string serverAddress = args[0];
            int    messageCount  = int.Parse(args[1]);
            int    messageSize   = int.Parse(args[2]);

            Message = new byte[messageSize];

            ConnectionFactory cf = new ConnectionFactory();

            cf.Uri = serverAddress;
            using (IConnection conn = cf.CreateConnection())
            {
                Stopwatch sendTimer    = new Stopwatch();
                Stopwatch receiveTimer = new Stopwatch();

                using (IModel ch = conn.CreateModel()) {
                    sendTimer.Start();

                    for (int i = 0; i < messageCount; ++i)
                    {
                        ch.BasicPublish("", "", null, Message);
                    }
                }
                sendTimer.Stop();

                using (IModel ch = conn.CreateModel()) {
                    string q = ch.QueueDeclare();

                    for (int i = 0; i < messageCount + 1; ++i)
                    {
                        ch.BasicPublish("", q, null, Message);
                    }
                    //This ensures that all messages have been enqueued
                    ch.BasicGet(q, true);

                    QueueingBasicConsumer consumer =
                        new QueueingBasicConsumer(ch);
                    receiveTimer.Start();
                    ch.BasicConsume(q, true, consumer);

                    for (int i = 0; i < messageCount; ++i)
                    {
                        consumer.Queue.Dequeue();
                    }
                    receiveTimer.Stop();
                }

                Console.WriteLine("Performance Test Completed");
                Console.WriteLine("Send:    {0}Hz", ToHertz(sendTimer.ElapsedMilliseconds, messageCount));
                Console.WriteLine("Receive: {0}Hz", ToHertz(receiveTimer.ElapsedMilliseconds, messageCount));

                return(0);
            }
        }
Example #47
0
        static void Main(string[] args)
        {
            var connectionFactory = new ConnectionFactory()
            {
                UserName = "******",
                Password = "******",
                HostName = "localhost"
            };

            var connection = connectionFactory.CreateConnection();
            var model      = connection.CreateModel();
            var properties = model.CreateBasicProperties();

            properties.Persistent = false;

            byte[] messageBuffer = Encoding.UTF8.GetBytes("Direct Messages");
            byte[] messageTopic  = Encoding.UTF8.GetBytes("Message from Topic Exchange 'Bombay'");
            byte[] messageFanout = Encoding.UTF8.GetBytes("Message is of fanout Exchange type");
            byte[] messageHeader = Encoding.UTF8.GetBytes("Message to Headers Exchange 'format=pdf' ");

            //-----------------------------publish message(direct exchange)-------------------------------------//

            //publish message (direct exchange)
            //model.ExchangeDeclare(".netDemoExchange", ExchangeType.Direct);
            //model.QueueDeclare(".netDemoQueue", true, false, false, null);
            //model.QueueBind(".netDemoQueue", ".netDemoExchange", "directExchange_key");
            //model.BasicPublish(".netDemoExchange", "directExchange_key", properties, messageBuffer);

            //-----------------------------publish message(topic exchange)-------------------------------------//

            //model.ExchangeDeclare("topic.exchange", ExchangeType.Topic);

            //model.QueueDeclare("topic.bombay.queue", true, false, false, null);
            //model.QueueDeclare("topic.delhi.queue", true, false, false, null);

            //model.QueueBind("topic.bombay.queue", "topic.exchange", "*.Bombay.*");
            //model.QueueBind("topic.delhi.queue", "topic.exchange", "Delhi.#");

            //model.BasicPublish("topic.exchange", "Message.Bombay.Email", properties, messageTopic);

            //-----------------------------publish message(fanout exchange)-------------------------------------//

            //model.ExchangeDeclare("fanout.exchange", ExchangeType.Fanout);

            //model.QueueDeclare("Mumbai", true, false, false, null);
            //model.QueueDeclare("Bangalore", true, false, false, null);
            //model.QueueDeclare("Chennai", true, false, false, null);
            //model.QueueDeclare("Hyderabad", true, false, false, null);

            //model.QueueBind("Mumbai", "fanout.exchange", String.Empty);
            //model.QueueBind("Bangalore", "fanout.exchange", String.Empty);
            //model.QueueBind("Chennai", "fanout.exchange", String.Empty);
            //model.QueueBind("Hyderabad", "fanout.exchange", String.Empty);

            //model.BasicPublish("fanout.exchange", "", properties, messageFanout);

            //-----------------------------publish message(headers exchange)-------------------------------------//
            model.ExchangeDeclare("headers.exchange", ExchangeType.Headers);

            model.QueueDeclare("ReportPDF", true, false, false, null);
            model.QueueDeclare("ReportExcel", true, false, false, null);

            Dictionary <string, object> arguments1 = new Dictionary <string, object>();

            arguments1.Add("format", "pdf");
            arguments1.Add("x-match", "all");

            properties.Headers = arguments1;

            model.QueueBind("ReportPDF", "headers.exchange", "");

            model.BasicPublish("headers.exchange", "", properties, messageHeader);
        }
        private static IConnection CreateConnectionWithTcpEndpoints(RabbitMqServiceOptions options, ConnectionFactory factory)
        {
            var clientEndpoints = new List <AmqpTcpEndpoint>();

            foreach (var endpoint in options.TcpEndpoints)
            {
                var sslOption = endpoint.SslOption;
                if (sslOption != null)
                {
                    var convertedOption = new SslOption(sslOption.ServerName, sslOption.CertificatePath, sslOption.Enabled);
                    if (!string.IsNullOrEmpty(sslOption.CertificatePassphrase))
                    {
                        convertedOption.CertPassphrase = sslOption.CertificatePassphrase;
                    }

                    if (sslOption.AcceptablePolicyErrors != null)
                    {
                        convertedOption.AcceptablePolicyErrors = sslOption.AcceptablePolicyErrors.Value;
                    }

                    clientEndpoints.Add(new AmqpTcpEndpoint(endpoint.HostName, endpoint.Port, convertedOption));
                }
                else
                {
                    clientEndpoints.Add(new AmqpTcpEndpoint(endpoint.HostName, endpoint.Port));
                }
            }
            return(TryToCreateConnection(() => factory.CreateConnection(clientEndpoints), options.InitialConnectionRetries, options.InitialConnectionRetryTimeoutMilliseconds));
        }
Example #49
0
        static void Main(string[] args)
        {
            LogManager.Configuration = new XmlLoggingConfiguration($"{AppContext.BaseDirectory}nlog.config");

            var logger = LogManager.GetLogger("openrmf_msg_controls");
            ControlsDBContext _context;

            // Create a new connection factory to create a connection.
            ConnectionFactory cf = new ConnectionFactory();


            // add the options for the server, reconnecting, and the handler events
            Options opts = ConnectionFactory.GetDefaultOptions();

            opts.MaxReconnect            = -1;
            opts.ReconnectWait           = 2000;
            opts.Name                    = "openrmf-msg-controls";
            opts.Url                     = Environment.GetEnvironmentVariable("NATSSERVERURL");
            opts.AsyncErrorEventHandler += (sender, events) =>
            {
                logger.Info("NATS client error. Server: {0}. Message: {1}. Subject: {2}", events.Conn.ConnectedUrl, events.Error, events.Subscription.Subject);
            };

            opts.ServerDiscoveredEventHandler += (sender, events) =>
            {
                logger.Info("A new server has joined the cluster: {0}", events.Conn.DiscoveredServers);
            };

            opts.ClosedEventHandler += (sender, events) =>
            {
                logger.Info("Connection Closed: {0}", events.Conn.ConnectedUrl);
            };

            opts.ReconnectedEventHandler += (sender, events) =>
            {
                logger.Info("Connection Reconnected: {0}", events.Conn.ConnectedUrl);
            };

            opts.DisconnectedEventHandler += (sender, events) =>
            {
                logger.Info("Connection Disconnected: {0}", events.Conn.ConnectedUrl);
            };

            // Creates a live connection to the NATS Server with the above options
            IConnection c = cf.CreateConnection(opts);

            var options = new DbContextOptionsBuilder <ControlsDBContext>().UseInMemoryDatabase("ControlSet").Options;

            _context = new ControlsDBContext(options);

            // setup the internal database
            ControlsLoader.LoadControlsXML(_context);

            // send back a full listing of controls based on the filter passed in
            EventHandler <MsgHandlerEventArgs> getControls = (sender, natsargs) =>
            {
                try {
                    // print the message
                    logger.Info("New NATS subject: {0}", natsargs.Message.Subject);
                    logger.Info("New NATS data: {0}", Encoding.UTF8.GetString(natsargs.Message.Data));
                    var    listing = _context.ControlSets.ToList();
                    var    result  = new List <ControlSet>(); // put all results in here
                    Filter filter  = JsonConvert.DeserializeObject <Filter>(Encoding.UTF8.GetString(natsargs.Message.Data));
                    if (listing != null)
                    {
                        // figure out the impact level filter
                        if (filter != null && !string.IsNullOrEmpty(filter.impactLevel) && filter.impactLevel.Trim().ToLower() == "low")
                        {
                            result = listing.Where(x => x.lowimpact).ToList();
                        }
                        else if (filter != null && !string.IsNullOrEmpty(filter.impactLevel) && filter.impactLevel.Trim().ToLower() == "moderate")
                        {
                            result = listing.Where(x => x.moderateimpact).ToList();
                        }
                        else if (filter != null && !string.IsNullOrEmpty(filter.impactLevel) && filter.impactLevel.Trim().ToLower() == "high")
                        {
                            result = listing.Where(x => x.highimpact).ToList();
                        }
                        else
                        {
                            result = listing; // get all the data
                        }
                        // include things that are not P0 meaning not used, and that there is no low/moderate/high designation
                        // these should always be included where the combination of all "false" and not P0 = include them
                        result.AddRange(listing.Where(x => x.priority != "P0" && x.family.ToLower() != "pii" &&
                                                      !x.lowimpact && !x.moderateimpact && !x.highimpact).ToList());

                        // see if the PII  filter is true, and if so add in the PII family by appending that to the result from above
                        if (filter.pii)
                        {
                            result.AddRange(listing.Where(x => !string.IsNullOrEmpty(x.family) && x.family.ToLower() == "pii").ToList());
                        }
                    }
                    // now publish it back out w/ the reply subject
                    string msg = JsonConvert.SerializeObject(result);
                    // publish back out on the reply line to the calling publisher
                    logger.Info("Sending back compressed Checklist Data");
                    c.Publish(natsargs.Message.Reply, Encoding.UTF8.GetBytes(Compression.CompressString(msg)));
                    c.Flush(); // flush the line
                }
                catch (Exception ex) {
                    // log it here
                    logger.Error(ex, "Error retrieving controls for the filter sent {0}", Encoding.UTF8.GetString(natsargs.Message.Data));
                }
            };

            // send back a full listing of controls based on the filter passed in
            EventHandler <MsgHandlerEventArgs> getControlsByTerm = (sender, natsargs) =>
            {
                try {
                    // print the message
                    logger.Info("New NATS subject: {0}", natsargs.Message.Subject);
                    logger.Info("New NATS data: {0}", Encoding.UTF8.GetString(natsargs.Message.Data));
                    string term       = Encoding.UTF8.GetString(natsargs.Message.Data);
                    string searchTerm = term.Replace(" ", ""); // get rid of things we do not need
                    string msg        = "";
                    // find the control from the data passed in
                    var result = _context.ControlSets.Where(x => x.subControlNumber == searchTerm || x.number == searchTerm).ToList();
                    if (result != null && result.Count > 0)
                    {
                        msg = JsonConvert.SerializeObject(result.FirstOrDefault());
                    }
                    else   // try to get the main family description and return that
                    {
                        int index = GetFirstIndex(term);
                        if (index < 0)
                        {
                            msg = "";
                        }
                        else   // see if there is a family title we can pass back
                        {
                            searchTerm = term.Substring(0, index).Trim();
                            result     = _context.ControlSets.Where(x => x.subControlNumber == searchTerm || x.number == searchTerm).ToList();
                            if (result != null && result.Count > 0)
                            {
                                msg = JsonConvert.SerializeObject(result.FirstOrDefault());
                            }
                            else
                            {
                                msg = "";
                            }
                        }
                    }

                    // publish back out on the reply line to the calling publisher
                    logger.Info("Sending back compressed Checklist Data");
                    c.Publish(natsargs.Message.Reply, Encoding.UTF8.GetBytes(Compression.CompressString(msg)));
                    c.Flush(); // flush the line
                }
                catch (Exception ex) {
                    // log it here
                    logger.Error(ex, "Error retrieving control for search term {0}", Encoding.UTF8.GetString(natsargs.Message.Data));
                }
            };

            // The simple way to create an asynchronous subscriber
            // is to simply pass the event in.  Messages will start
            // arriving immediately.
            logger.Info("setting up the OpenRMF control subscription by filter");
            IAsyncSubscription asyncControls = c.SubscribeAsync("openrmf.controls", getControls);

            logger.Info("setting up the OpenRMF control subscription by filter");
            IAsyncSubscription asyncControlByTerm = c.SubscribeAsync("openrmf.controls.search", getControlsByTerm);
        }
        public async Task InitAsync()
        {
            try
            {
                using (var con = ConnectionFactory.GetConnection())
                {
                    if (await con.QueryFirstOrDefaultAsync <int>($"select count(1) from pg_class where relname = '{Prefix}RequestInfo' ") == 0)
                    {
                        await con.ExecuteAsync($@"
                            CREATE TABLE ""{Prefix}RequestInfo"" ( 
                              ID varchar(50) Primary Key,
                              ParentId varchar(50),
                              Node varchar(50) ,
                              Route varchar(255),
                              Url varchar(255),
                              RequestType varchar(50),
                              Method varchar(10), 
                              Milliseconds Int,
                              StatusCode Int,
                              IP varchar(255),
                              Port Int, 
                              LocalIP varchar(50),
                              LocalPort Int, 
                              CreateTime timestamp(3) without time zone
                            ); 
                        ").ConfigureAwait(false);
                    }

                    if (await con.QueryFirstOrDefaultAsync <int>($"select count(1) from pg_class where relname = '{Prefix}RequestDetail' ") == 0)
                    {
                        await con.ExecuteAsync($@"
                            CREATE TABLE ""{Prefix}RequestDetail"" ( 
                                ID varchar(50) Primary Key,
                                RequestId varchar(50),
                                Scheme varchar(10),
                                QueryString text,
                                Header text,
                                Cookie text,
                                RequestBody text,
                                ResponseBody text,
                                ErrorMessage text,
                                ErrorStack text,
                                CreateTime timestamp(3) without time zone 
                            ); 
                        ");
                    }

                    if (await con.QueryFirstOrDefaultAsync <int>($"select count(1) from pg_class where relname = '{Prefix}Performance' ") == 0)
                    {
                        await con.ExecuteAsync($@" 

                            CREATE TABLE ""{Prefix}Performance"" ( 
                                ID varchar(50) Primary Key,
                                Service varchar(200),
                                Instance varchar(200),
                                GCGen0 Int,
                                GCGen1 Int,
                                GCGen2 Int,
                                HeapMemory Numeric,
                                ProcessCPU Numeric,
                                ProcessMemory Numeric, 
                                ThreadCount Int,
                                PendingThreadCount Int, 
                                CreateTime timestamp(3) without time zone 

                            ); 
                        ");
                    }



                    if (await con.QueryFirstOrDefaultAsync <int>($"select count(1) from information_schema.columns where table_catalog = '{ConnectionFactory.DataBase}' and table_name = '{Prefix}MonitorJob' and column_name = 'nodes' ") > 0)
                    {
                        await con.ExecuteAsync($@"DROP TABLE ""{Prefix}MonitorJob"" ");
                    }


                    if (await con.QueryFirstOrDefaultAsync <int>($"select count(1) from pg_class where relname = '{Prefix}MonitorJob' ") == 0)
                    {
                        await con.ExecuteAsync($@"
                            CREATE TABLE ""{Prefix}MonitorJob"" ( 
                              ID varchar(50) Primary Key,
                              Title varchar(255) ,
                              Description varchar(255),
                              CronLike varchar(255),
                              Emails varchar(1000),
                              WebHook varchar(1000),
                              Mobiles varchar(1000),
                              Status Int,
                              Service varchar(255),
                              Instance varchar(255),
                              PayLoad varchar(3000),  
                              CreateTime timestamp(3) without time zone
                            ); 
                        ");
                    }

                    if (await con.QueryFirstOrDefaultAsync <int>($"select count(1) from pg_class where relname = '{Prefix}SysUser' ") == 0)
                    {
                        await con.ExecuteAsync($@"
                            CREATE TABLE ""{Prefix}SysUser"" ( 
                              ID varchar(50) Primary Key,
                              UserName varchar(255) ,
                              Password varchar(255) 
                            ); 
                        ");
                    }

                    if (await con.QueryFirstOrDefaultAsync <int>($"select count(1) from pg_class where relname = '{Prefix}SysConfig' ") == 0)
                    {
                        await con.ExecuteAsync($@"
                            CREATE TABLE ""{Prefix}SysConfig"" ( 
                              ID varchar(50) Primary Key,
                              Key varchar(255) ,
                              Value varchar(255) 
                            ); 
                        ");
                    }

                    if (await con.QueryFirstOrDefaultAsync <int>($@"Select count(1) from ""{Prefix}SysUser"" ") == 0)
                    {
                        await con.ExecuteAsync($@" Insert Into ""{Prefix}SysUser"" (Id,UserName,Password) Values ('{MD5_16(Guid.NewGuid().ToString())}', '{Core.Config.BasicConfig.DefaultUserName}','{Core.Config.BasicConfig.DefaultPassword}') ");
                    }



                    var lang = await con.QueryFirstOrDefaultAsync <string>($@"Select * from ""{Prefix}SysConfig"" Where Key =  '{BasicConfig.Language}' ");

                    if (!lang.IsEmpty())
                    {
                        if (lang.ToLowerInvariant() == "chinese" || lang.ToLowerInvariant() == "english")
                        {
                            await con.ExecuteAsync($@" Delete From ""{Prefix}SysConfig"" Where Key =  '{BasicConfig.Language}'  ");

                            await con.ExecuteAsync($@" Insert Into ""{Prefix}SysConfig"" (Id,Key,Value) Values ('{MD5_16(Guid.NewGuid().ToString())}','{BasicConfig.Language}','en-us') ");
                        }
                    }
                    else
                    {
                        await con.ExecuteAsync($@" Insert Into ""{Prefix}SysConfig"" (Id,Key,Value) Values ('{MD5_16(Guid.NewGuid().ToString())}','{BasicConfig.Language}','en-us') ");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("数据库初始化失败:" + ex.Message, ex);
            }
        }
        static void ReceiveMsg()
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.RollingFile(@"log-{Date}.txt", outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}")
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            try
            {
                Log.Information(messageTemplate: "Starting the Program");

                var factory = new ConnectionFactory()
                {
                    HostName = "localhost"
                };
                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare(queue: "qwebapp",
                                             durable: false,
                                             exclusive: false,
                                             autoDelete: false,
                                             arguments: null);

                        var consumer = new EventingBasicConsumer(channel);
                        consumer.Received += (model, ea) =>
                        {
                            try
                            {
                                Log.Information(messageTemplate: "Receiving the messages");
                                var body    = ea.Body.ToArray();
                                var message = Encoding.UTF8.GetString(body);
                                Console.WriteLine(" [x] Received {0}", message);

                                channel.BasicAck(ea.DeliveryTag, false);
                            }
                            catch (Exception ex)
                            {
                                // log ex
                                Log.Fatal(ex, messageTemplate: "Something went wrong with delivery, doing a Nack");
                                channel.BasicNack(ea.DeliveryTag, false, false);
                            }
                        };
                        channel.BasicConsume(queue: "qwebapp",
                                             autoAck: false,
                                             consumer: consumer);

                        Console.WriteLine(" Press [enter] to exit.");
                        Console.ReadLine();
                    }
            }
            catch (Exception ex)
            {
                // log ex
                Log.Fatal(messageTemplate: "Something went wrong");
                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Example #52
0
 public RabbitMQClientService(ConnectionFactory connectionFactory, ILogger <RabbitMQClientService> logger)
 {
     this._connectionFactory = connectionFactory;
     this._logger            = logger;
 }
Example #53
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            RegisterAppInsights(services);

            // Add framework services.
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(HttpGlobalExceptionFilter));
                options.Filters.Add(typeof(ValidateModelStateFilter));
            }).AddControllersAsServices();

            ConfigureAuthService(services);

            services.AddHealthChecks(checks =>
            {
                checks.AddValueTaskCheck("HTTP Endpoint",
                                         () => new ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok")),
                                         TimeSpan.Zero //No cache for this HealthCheck, better just for demos
                                         );
            });

            services.Configure <BasketSettings>(Configuration);

            //By connecting here we are making sure that our service
            //cannot start until redis is ready. This might slow down startup,
            //but given that there is a delay on resolving the ip address
            //and then creating the connection it seems reasonable to move
            //that cost to startup instead of having the first request pay the
            //penalty.
            services.AddSingleton(sp =>
            {
                var settings      = sp.GetRequiredService <IOptions <BasketSettings> >().Value;
                var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true);

                configuration.ResolveDns = true;

                return(ConnectionMultiplexer.Connect(configuration));
            });


            if (Configuration.GetValue <bool>("AzureServiceBusEnabled"))
            {
                services.AddSingleton <IServiceBusPersisterConnection>(sp =>
                {
                    var serviceBusConnectionString = Configuration["EventBusConnection"];
                    var serviceBusConnection       = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);

                    return(new DefaultServiceBusPersisterConnection(serviceBusConnection));
                });
            }
            else
            {
                services.AddSingleton <IRabbitMqPersistentConnection>(sp =>
                {
                    var logger = sp.GetRequiredService <ILogger <DefaultRabbitMqPersistentConnection> >();

                    var factory = new ConnectionFactory
                    {
                        HostName = Configuration["EventBusConnection"]
                    };

                    if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
                    {
                        factory.UserName = Configuration["EventBusUserName"];
                    }

                    if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
                    {
                        factory.Password = Configuration["EventBusPassword"];
                    }

                    var retryCount = 5;
                    if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
                    {
                        retryCount = int.Parse(Configuration["EventBusRetryCount"]);
                    }

                    return(new DefaultRabbitMqPersistentConnection(factory, logger, retryCount));
                });
            }

            RegisterEventBus(services);

            services.AddSwaggerGen(options =>
            {
                options.DescribeAllEnumsAsStrings();
                options.SwaggerDoc("v1", new Info
                {
                    Title          = "Basket HTTP API",
                    Version        = "v1",
                    Description    = "The Basket Service HTTP API",
                    TermsOfService = "Terms Of Service"
                });

                options.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type             = "oauth2",
                    Flow             = "implicit",
                    AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
                    TokenUrl         = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
                    Scopes           = new Dictionary <string, string>
                    {
                        { "basket", "Basket API" }
                    }
                });

                options.OperationFilter <AuthorizeCheckOperationFilter>();
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IBasketRepository, RedisBasketRepository>();
            services.AddTransient <IIdentityService, IdentityService>();

            services.AddOptions();

            var container = new ContainerBuilder();

            container.Populate(services);

            return(new AutofacServiceProvider(container.Build()));
        }
 public RabbitMQWorkerClientService(ConnectionFactory connectionFactory, ILogger <RabbitMQWorkerClientService> logger)
 {
     _connectionFactory = connectionFactory;
     _logger            = logger;
 }
Example #55
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
            });


            services.AddCors(options =>
            {
                options.AddPolicy("any",
                                  builder =>
                {
                    builder.AllowAnyOrigin().AllowCredentials();
                });
            });
            ///EventBus
            RegisterEventBus(services);
            services.AddSingleton <IRabbitMQPersistentConnection>(sp =>
            {
                var factory = new ConnectionFactory()
                {
                    HostName = Configuration["EventBusConnection"]
                };

                if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
                {
                    factory.UserName = Configuration["EventBusUserName"];
                }

                if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
                {
                    factory.Password = Configuration["EventBusPassword"];
                }

                var retryCount = 5;
                if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
                {
                    retryCount = int.Parse(Configuration["EventBusRetryCount"]);
                }

                return(new DefaultRabbitMQPersistentConnection(factory, retryCount));
            });
            RedisCache.redisConfigInfo = new RedisConfigInfo(this.Configuration);

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "WxChat API",
                    Description    = "微信api文档",
                    TermsOfService = "None",
                    Contact        = new Contact
                    {
                        Name  = "antu",
                        Email = string.Empty,
                        Url   = ""
                    },
                    License = new License
                    {
                        Name = "许可证名字",
                        Url  = ""
                    }
                });

                // 为 Swagger JSON and UI设置xml文档注释路径
                var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
                var xmlPath  = Path.Combine(basePath, "MessageService.xml");
                options.IncludeXmlComments(xmlPath);
            });


            services.AddSingleton <RequestEvent>();
            services.AddSingleton <Request>();
            services.AddSingleton <Token>();


            var container = new ContainerBuilder();

            container.Populate(services);
            return(new AutofacServiceProvider(container.Build()));
        }
        private static IConnection CreateNamedConnection(RabbitMqServiceOptions options, ConnectionFactory factory)
        {
            if (options.HostNames?.Any() == true)
            {
                return(TryToCreateConnection(() => factory.CreateConnection(options.HostNames.ToList(), options.ClientProvidedName), options.InitialConnectionRetries, options.InitialConnectionRetryTimeoutMilliseconds));
            }

            factory.HostName = options.HostName;
            return(TryToCreateConnection(() => factory.CreateConnection(options.ClientProvidedName), options.InitialConnectionRetries, options.InitialConnectionRetryTimeoutMilliseconds));
        }
Example #57
0
        public async Task InitAsync()
        {
            try
            {
                using (var con = ConnectionFactory.GetConnection())
                {
                    if (con.QueryFirstOrDefault <int>($" Select Count(*) from sysobjects where id = object_id('{ConnectionFactory.DataBase}.dbo.RequestInfo') ") == 0)
                    {
                        await con.ExecuteAsync(@"   
                            CREATE TABLE [dbo].[RequestInfo](
	                            [Id] [varchar](50) NOT NULL PRIMARY KEY,
                                [ParentId] [nvarchar](50) NULL,
	                            [Node] [nvarchar](50) NULL,
	                            [Route] [nvarchar](120) NULL,
	                            [Url] [nvarchar](200) NULL,
                                [RequestType] [nvarchar](50) NULL,
	                            [Method] [nvarchar](50) NULL,
	                            [Milliseconds] [int] NULL,
	                            [StatusCode] [int] NULL,
	                            [IP] [nvarchar](50) NULL,
                                [Port] [int] NULL,
                                [LocalIP] [nvarchar](50) NULL,
                                [LocalPort] [int] NULL,
	                            [CreateTime] [datetime] NULL)
                    ").ConfigureAwait(false);
                    }

                    if (con.QueryFirstOrDefault <int>($" Select Count(*) from sysobjects where id = object_id('{ConnectionFactory.DataBase}.dbo.RequestDetail') ") == 0)
                    {
                        await con.ExecuteAsync(@"   
                            CREATE TABLE [dbo].[RequestDetail](
	                            [Id] [varchar](50) NOT NULL PRIMARY KEY,
	                            [RequestId] [varchar](50) NOT NULL,
                                [Scheme] [varchar](10) NULL,
                                [QueryString] [text] NULL,
                                [Header] [text] NULL,
                                [Cookie] [text] NULL,
                                [RequestBody] [text] NULL,
                                [ResponseBody] [text] NULL,
                                [ErrorMessage] [text] NULL,
                                [ErrorStack] [text] NULL,
                                [CreateTime] [datetime] NULL )
                    ").ConfigureAwait(false);
                    }

                    if (con.QueryFirstOrDefault <int>($"Select Count(*) from sysobjects where id = object_id('{ConnectionFactory.DataBase}.dbo.MonitorJob')") == 0)
                    {
                        await con.ExecuteAsync(@"  
                            CREATE TABLE [dbo].[MonitorJob](
	                            [Id] [varchar](50) NOT NULL PRIMARY KEY,
	                            [Title] [nvarchar](255) NULL,
                                [Description] [nvarchar](255) NULL,
                                [CronLike] [nvarchar](255) NULL, 
                                [Emails] [nvarchar](1000)  NULL,
                                [WebHook] [nvarchar](1000) NULL,
                                [Mobiles] [nvarchar](1000) NULL,
                                [Status] [int] NULL,
                                [Nodes] [nvarchar](255) NULL,
                                [PayLoad] [nvarchar](2000) NULL, 
	                            [CreateTime] [datetime] NULL )
                      ").ConfigureAwait(false);
                    }

                    if (con.QueryFirstOrDefault <int>($"Select Count(*) from sysobjects where id = object_id('{ConnectionFactory.DataBase}.dbo.SysUser')") == 0)
                    {
                        await con.ExecuteAsync($@"

                           CREATE TABLE [SysUser]( 
	                            [Id] [varchar](50) NOT NULL PRIMARY KEY,
	                            [UserName] [nvarchar](100) NOT NULL, 
	                            [Password] [nvarchar](100) NOT NULL );  

                            Insert Into [SysUser] Values ('{MD5_16(Guid.NewGuid().ToString())}','{Core.Config.BasicConfig.DefaultUserName}','{Core.Config.BasicConfig.DefaultPassword}'); 

                         ").ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Database init failed:" + ex.Message, ex);
            }
        }
 public AutorecoveringConnection(ConnectionFactory factory)
 {
     m_factory = factory;
 }
Example #59
0
        public static int Main(string[] args)
        {
            bool persistMode = false;

            int optionIndex = 0;

            while (optionIndex < args.Length)
            {
                if (args[optionIndex] == "/persist")
                {
                    persistMode = true;
                }
                else
                {
                    break;
                }
                optionIndex++;
            }

            if (((args.Length - optionIndex) < 1) ||
                (((args.Length - optionIndex - 1) % 2) == 1))
            {
                Console.Error.WriteLine("Usage: SendMap [<option> ...] <exchange-uri> [[<key> <value>] ...]");
                Console.Error.WriteLine("RabbitMQ .NET client version " + typeof(IModel).Assembly.GetName().Version.ToString());
                Console.Error.WriteLine("Exchange-URI: amqp://host[:port]/exchange[/routingkey][?type=exchangetype]");
                Console.Error.WriteLine("Keys must start with '+' or with '-'. Those starting with '+' are placed in");
                Console.Error.WriteLine("the body of the message, and those starting with '-' are placed in the headers.");
                Console.Error.WriteLine("Values must start with a single character typecode and a colon.");
                Console.Error.WriteLine("Supported typecodes are:");
                Console.Error.WriteLine(" S - string/byte array");
                Console.Error.WriteLine(" x - byte array (base-64)");
                Console.Error.WriteLine(" t - boolean");
                Console.Error.WriteLine(" i - 32-bit integer");
                Console.Error.WriteLine(" d - double-precision float");
                Console.Error.WriteLine(" D - fixed-point decimal");
                Console.Error.WriteLine("Note that some types are valid only in the body of a message, and some are");
                Console.Error.WriteLine("valid only in the headers.");
                Console.Error.WriteLine("The exchange \"amq.default\" is an alias for the default (\"\") AMQP exchange,");
                Console.Error.WriteLine("introduced so that the default exchange can be addressed via URI syntax.");
                Console.Error.WriteLine("Available options:");
                Console.Error.WriteLine("  /persist     send message in 'persistent' mode");
                return(2);
            }

            Uri    uri          = new Uri(args[optionIndex++]);
            string exchange     = uri.Segments[1].TrimEnd(new char[] { '/' });
            string exchangeType = uri.Query.StartsWith("?type=") ? uri.Query.Substring(6) : null;
            string routingKey   = uri.Segments.Length > 2 ? uri.Segments[2] : "";

            if (exchange == "amq.default")
            {
                exchange = "";
            }

            ConnectionFactory cf = new ConnectionFactory();

            cf.Endpoint = new AmqpTcpEndpoint(uri);

            using (IConnection conn = cf.CreateConnection())
            {
                using (IModel ch = conn.CreateModel()) {
                    if (exchangeType != null)
                    {
                        ch.ExchangeDeclare(exchange, exchangeType);
                    }

                    IMapMessageBuilder b = new MapMessageBuilder(ch);
                    while ((optionIndex + 1) < args.Length)
                    {
                        string keyAndDiscriminator = args[optionIndex++];
                        string valueAndType        = args[optionIndex++];

                        if (keyAndDiscriminator.Length < 1)
                        {
                            Console.Error.WriteLine("Invalid key: '{0}'", keyAndDiscriminator);
                            return(2);
                        }
                        string key           = keyAndDiscriminator.Substring(1);
                        char   discriminator = keyAndDiscriminator[0];

                        IDictionary <string, object> target;
                        switch (discriminator)
                        {
                        case '-':
                            target = b.Headers;
                            break;

                        case '+':
                            target = b.Body;
                            break;

                        default:
                            Console.Error.WriteLine("Invalid key: '{0}'",
                                                    keyAndDiscriminator);
                            return(2);
                        }

                        if (valueAndType.Length < 2 || valueAndType[1] != ':')
                        {
                            Console.Error.WriteLine("Invalid value: '{0}'", valueAndType);
                            return(2);
                        }
                        string valueStr = valueAndType.Substring(2);
                        char   typeCode = valueAndType[0];

                        object value;
                        switch (typeCode)
                        {
                        case 'S':
                            value = valueStr;
                            break;

                        case 'x':
                            value = new BinaryTableValue(Convert.FromBase64String(valueStr));
                            break;

                        case 't':
                            value = (valueStr.ToLower() == "true" ||
                                     valueStr.ToLower() == "yes" ||
                                     valueStr.ToLower() == "on" ||
                                     valueStr == "1");
                            break;

                        case 'i':
                            value = int.Parse(valueStr);
                            break;

                        case 'd':
                            value = double.Parse(valueStr);
                            break;

                        case 'D':
                            value = decimal.Parse(valueStr);
                            break;

                        default:
                            Console.Error.WriteLine("Invalid type code: '{0}'", typeCode);
                            return(2);
                        }

                        target[key] = value;
                    }
                    if (persistMode)
                    {
                        ((IBasicProperties)b.GetContentHeader()).DeliveryMode = 2;
                    }
                    ch.BasicPublish(exchange,
                                    routingKey,
                                    (IBasicProperties)b.GetContentHeader(),
                                    b.GetContentBody());
                    return(0);
                }
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public virtual IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc(options =>
            {
                options.EnableDetailedErrors = true;
            });

            RegisterAppInsights(services);

            services.AddControllers(options =>
            {
                options.Filters.Add(typeof(HttpGlobalExceptionFilter));
                options.Filters.Add(typeof(ValidateModelStateFilter));
            })     // Added for functional tests
            .AddApplicationPart(typeof(BasketController).Assembly)
            .AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);

            services.AddSwaggerGen(options =>
            {
                options.DescribeAllEnumsAsStrings();
                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "eShopOnContainers - Basket HTTP API",
                    Version     = "v1",
                    Description = "The Basket Service HTTP API"
                });

                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Type  = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows()
                    {
                        Implicit = new OpenApiOAuthFlow()
                        {
                            AuthorizationUrl = new Uri($"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize"),
                            TokenUrl         = new Uri($"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token"),
                            Scopes           = new Dictionary <string, string>()
                            {
                                { "basket", "Basket API" }
                            }
                        }
                    }
                });

                options.OperationFilter <AuthorizeCheckOperationFilter>();
            });

            ConfigureAuthService(services);

            services.AddCustomHealthCheck(Configuration);

            services.Configure <BasketSettings>(Configuration);

            //By connecting here we are making sure that our service
            //cannot start until redis is ready. This might slow down startup,
            //but given that there is a delay on resolving the ip address
            //and then creating the connection it seems reasonable to move
            //that cost to startup instead of having the first request pay the
            //penalty.
            services.AddSingleton <ConnectionMultiplexer>(sp =>
            {
                var settings      = sp.GetRequiredService <IOptions <BasketSettings> >().Value;
                var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true);

                configuration.ResolveDns = true;

                return(ConnectionMultiplexer.Connect(configuration));
            });


            if (Configuration.GetValue <bool>("AzureServiceBusEnabled"))
            {
                services.AddSingleton <IServiceBusPersisterConnection>(sp =>
                {
                    var serviceBusConnectionString = Configuration["EventBusConnection"];
                    var serviceBusConnection       = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);

                    var subscriptionClientName = Configuration["SubscriptionClientName"];
                    return(new DefaultServiceBusPersisterConnection(serviceBusConnection, subscriptionClientName));
                });
            }
            else
            {
                services.AddSingleton <IRabbitMQPersistentConnection>(sp =>
                {
                    var logger = sp.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >();

                    var factory = new ConnectionFactory()
                    {
                        HostName = Configuration["EventBusConnection"],
                        DispatchConsumersAsync = true
                    };

                    if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
                    {
                        factory.UserName = Configuration["EventBusUserName"];
                    }

                    if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
                    {
                        factory.Password = Configuration["EventBusPassword"];
                    }

                    var retryCount = 5;
                    if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
                    {
                        retryCount = int.Parse(Configuration["EventBusRetryCount"]);
                    }

                    return(new DefaultRabbitMQPersistentConnection(factory, logger, retryCount));
                });
            }

            RegisterEventBus(services);


            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder
                                  .SetIsOriginAllowed((host) => true)
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IBasketRepository, RedisBasketRepository>();
            services.AddTransient <IIdentityService, IdentityService>();

            services.AddOptions();

            var container = new ContainerBuilder();

            container.Populate(services);

            return(new AutofacServiceProvider(container.Build()));
        }