public void FixtureSetup() { _cx = ConnectionTests.CreateConnection(); if (_cx.ListDatabases().Contains("relax-reference-tests")) { _cx.DeleteDatabase("relax-reference-tests"); } _cx.CreateDatabase("relax-reference-tests"); _sx = _cx.CreateSession("relax-reference-tests"); _sx2 = _cx.CreateSession("relax-reference-tests"); _sx.Save(new Widget { Id = "w1", Name = "Widget", Cost = 30 }); _sx.Save(new Widget { Id = "w2", Name = "Gadget", Cost = 30 }); _sx.Save(new Widget { Id = "w3", Name = "Foo", Cost = 35 }); _sx.Save(new Widget { Id = "w4", Name = "Bar", Cost = 35 }); _sx.Save(new Widget { Id = "w5", Name = "Biz", Cost = 45 }); _sx.Save(new Widget { Id = "w6", Name = "Bang", Cost = 55 }); _sx.SaveRaw(JObject.Parse( @"{ _id: 'g1', Name: 'Gadget #1', Primary: 'w1' }")); _sx.SaveRaw(JObject.Parse( @"{ _id: 'g2', Name: 'Gadget #1', Secondary: ['w1', 'w2', 'w3'] }")); }
public void FixtureSetup() { _cx = ConnectionTests.CreateConnection(); if (_cx.ListDatabases().Contains("relax-session-tests")) { _cx.DeleteDatabase("relax-session-tests"); } _cx.CreateDatabase("relax-session-tests"); _sx = _cx.CreateSession("relax-session-tests"); // create an initial document on a seperate session var x = _cx.CreateSession(_sx.Database); var w = new Widget {Name = "gizmo", Tags = new[] {"whizbang", "geegollie"}}; _doc = x.Save(w); }
public void FixtureSetup() { _cx = ConnectionTests.CreateConnection(); if (_cx.ListDatabases().Contains("relax-query-tests")) { _cx.DeleteDatabase("relax-query-tests"); } _cx.CreateDatabase("relax-query-tests"); _sx = _cx.CreateSession("relax-query-tests"); // populate a few widgets & a simple design doc _sx.Save(new Widget { Name = "widget", Manufacturer = "acme" }); _sx.Save(new Widget { Name = "sprocket", Manufacturer = "acme" }); _sx.Save(new Widget { Name = "doodad", Manufacturer = "widgetco" }); _sx.Save( new DesignDocument { Language = "javascript", Views = new Dictionary<string, View> { { "all-widgets", new View { Map = @"function(doc) { emit(null, null); }" }}, { "all-manufacturers", new View() { Map = @"function(doc) { emit(doc.Manufacturer, 1); }", Reduce = @"function(keys, values, rereduce) { return sum(values); }" }} } }, "_design/widgets" ); }
private void InitDb() { Connection connection = new Connection(new Uri(Config.HOST)); connection.DeleteDatabase(Config.CLOTHES_DB_NAME); //if (!connection.ListDatabases().Any(db => db == Config.CLOTHES_DB_NAME)) //{ connection.CreateDatabase(Config.CLOTHES_DB_NAME); Session session = connection.CreateSession(Config.CLOTHES_DB_NAME); string allClothesScript = File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_Data/all-clothes-map.js")); string colorsMap = File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_Data/colors-map.js")); string colorsReduce = File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_Data/colors-reduce.js")); DesignDocument designDocument = new DesignDocument(); designDocument.Language = "javascript"; designDocument.Views = new Dictionary<string, View>(); designDocument.Views.Add("all-clothes", new View { Map = allClothesScript }); designDocument.Views.Add("colors-breakdown", new View { Map = colorsMap, Reduce = colorsReduce }); session.Save(designDocument, "_design/clothes-queries"); //} }
// // Sample invocation: csharp.example.declare_queues.exe localhost:5672 my-queue // static int Main(string[] args) { string addr = "localhost:5672"; string queue = "my-queue"; if (args.Length > 0) addr = args[0]; if (args.Length > 1) queue = args[1]; Connection connection = null; try { connection = new Connection(addr); connection.Open(); Session session = connection.CreateSession(); String queueName = queue + "; {create: always}"; Sender sender = session.CreateSender(queueName); session.Close(); connection.Close(); return 0; } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (null != connection) connection.Close(); } return 1; }
static void Main(string[] args) { String broker = args.Length > 0 ? args[0] : "localhost:5672"; String address = args.Length > 1 ? args[1] : "amq.topic"; Connection connection = null; try { connection = new Connection(broker); connection.Open(); Session session = connection.CreateSession(); Receiver receiver = session.CreateReceiver(address); Sender sender = session.CreateSender(address); sender.Send(new Message("Hello world!")); Message message = new Message(); message = receiver.Fetch(DurationConstants.SECOND * 1); Console.WriteLine("{0}", message.GetContent()); session.Acknowledge(); connection.Close(); } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (null != connection) connection.Close(); } }
protected void Page_Load( object sender, EventArgs e ) { var url = ConfigurationManager.AppSettings.Get( "CLOUDANT_URL" ); var connection = new Connection( new Uri( url ) ); if ( !connection.ListDatabases().Contains( "gmkreports" ) ) { connection.CreateDatabase( "gmkreports" ); } var repository = new Repository<Report>( connection.CreateSession( "gmkreports" ) ); var report = new Report { ID = Guid.NewGuid(), Type = 1, AccessionNumber = "123", Contents = "abcd" }; System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Reset(); watch.Start(); var id = repository.Save( report ).Id; var retrievedReport = repository.Get( id ); watch.Stop(); if ( retrievedReport.ID == report.ID && retrievedReport.Type == report.Type && retrievedReport.AccessionNumber == report.AccessionNumber && retrievedReport.Contents == report.Contents ) { _label.Text = watch.ElapsedMilliseconds.ToString(); } else { _label.Text = "Error"; } }
public CloudantDataService() { var url = ConfigurationManager.AppSettings.Get( "CLOUDANT_URL" ); var connection = new Connection( new Uri( url ) ); if ( !connection.ListDatabases().Contains( "reports" ) ) { connection.CreateDatabase( "reports" ); } _repository = new Repository<Report>( connection.CreateSession( "reports" ) ); }
public void FixtureSetup() { _cx = ConnectionTests.CreateConnection(); if (_cx.ListDatabases().Contains("relax-session-tests")) { _cx.DeleteDatabase("relax-session-tests"); } _cx.CreateDatabase("relax-session-tests"); _sx = _cx.CreateSession("relax-session-tests"); }
public void TestCreateBrowserFailsWithZeroPrefetch() { using (Connection connection = CreateConnection() as Connection) using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { connection.PrefetchPolicy.QueueBrowserPrefetch = 0; IQueue queue = session.CreateTemporaryQueue(); IQueueBrowser browser = session.CreateBrowser(queue); browser.Close(); } }
// // Sample invocation: csharp.example.drain.exe --broker localhost:5672 --timeout 30 my-queue // static int Main(string[] args) { Options options = new Options(args); Connection connection = null; try { connection = new Connection(options.Url, options.ConnectionOptions); connection.Open(); Session session = connection.CreateSession(); Receiver receiver = session.CreateReceiver(options.Address); Duration timeout = options.Forever ? DurationConstants.FORVER : DurationConstants.SECOND * options.Timeout; Message message = new Message(); while (receiver.Fetch(ref message, timeout)) { Dictionary<string, object> properties = new Dictionary<string, object>(); properties = message.Properties; Console.Write("Message(properties={0}, content='", message.MapAsString(properties)); if ("amqp/map" == message.ContentType) { Dictionary<string, object> content = new Dictionary<string, object>(); message.GetContent(content); Console.Write(message.MapAsString(content)); } else if ("amqp/list" == message.ContentType) { Collection<object> content = new Collection<object>(); message.GetContent(content); Console.Write(message.ListAsString(content)); } else { Console.Write(message.GetContent()); } Console.WriteLine("')"); session.Acknowledge(); } receiver.Close(); session.Close(); connection.Close(); return 0; } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (null != connection) connection.Close(); } return 1; }
private void DoRollbackSentMessagesThenConsumeTestImpl(bool topic) { Connection = CreateAmqpConnection(); Connection.Start(); ISession session = Connection.CreateSession(AcknowledgementMode.Transactional); IDestination destination = null; if (topic) { destination = new NmsTopic(nameof(DoRollbackSentMessagesThenConsumeTestImpl)); } else { destination = new NmsQueue(nameof(DoRollbackSentMessagesThenConsumeTestImpl)); } IMessageProducer producer = session.CreateProducer(destination); IMessageConsumer consumer = session.CreateConsumer(destination); ITextMessage message = null; int messageCount = 3; for (int i = 1; i <= messageCount; i++) { message = session.CreateTextMessage("Message " + i); producer.Send(message); } session.Rollback(); // Should not consume any messages since rollback() was called message = consumer.Receive(TimeSpan.FromMilliseconds(300)) as ITextMessage; Assert.IsNull(message, "Received unexpected message"); // Send messages and call commit for (int i = 1; i <= messageCount; i++) { message = session.CreateTextMessage("Message " + i); producer.Send(message); } session.Commit(); // consume all messages for (int i = 1; i <= messageCount; i++) { message = consumer.Receive(TimeSpan.FromSeconds(3)) as ITextMessage; Assert.IsTrue(message.Text.EndsWith(i.ToString())); Assert.IsNotNull(message, "Receive() returned null, message " + i + " was not received"); } session.Commit(); }
public void TestBytesMessageCompression() { using (Connection connection = CreateConnection(TEST_CLIENT_ID) as Connection) { connection.UseCompression = true; connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { IDestination destination = session.CreateTemporaryQueue(); using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { IBytesMessage message = session.CreateBytesMessage(); message.WriteBoolean(a); message.WriteByte(b); message.WriteChar(c); message.WriteInt16(d); message.WriteInt32(e); message.WriteInt64(f); message.WriteString(g); message.WriteBoolean(h); message.WriteByte(i); message.WriteInt16(j); message.WriteInt32(k); message.WriteInt64(l); message.WriteSingle(m); message.WriteDouble(n); producer.Send(message); message = consumer.Receive(receiveTimeout) as IBytesMessage; Assert.IsNotNull(message); Assert.IsTrue(((ActiveMQMessage)message).Compressed); Assert.AreEqual(a, message.ReadBoolean(), "Stream Boolean Value: a"); Assert.AreEqual(b, message.ReadByte(), "Stream Byte Value: b"); Assert.AreEqual(c, message.ReadChar(), "Stream Char Value: c"); Assert.AreEqual(d, message.ReadInt16(), "Stream Int16 Value: d"); Assert.AreEqual(e, message.ReadInt32(), "Stream Int32 Value: e"); Assert.AreEqual(f, message.ReadInt64(), "Stream Int64 Value: f"); Assert.AreEqual(g, message.ReadString(), "Stream String Value: g"); Assert.AreEqual(h, message.ReadBoolean(), "Stream Boolean Value: h"); Assert.AreEqual(i, message.ReadByte(), "Stream Byte Value: i"); Assert.AreEqual(j, message.ReadInt16(), "Stream Int16 Value: j"); Assert.AreEqual(k, message.ReadInt32(), "Stream Int32 Value: k"); Assert.AreEqual(l, message.ReadInt64(), "Stream Int64 Value: l"); Assert.AreEqual(m, message.ReadSingle(), "Stream Single Value: m"); Assert.AreEqual(n, message.ReadDouble(), "Stream Double Value: n"); } } } }
public void TestCreateMultipleSessionsFromDifferentThreadsWhenConnectionNotStarted() { Connection = CreateAmqpConnection(); Assert.NotNull(Connection); Parallel.For(0, 10, i => { ISession session = Connection.CreateSession(); Assert.NotNull(session); }); }
private void Run() { Console.WriteLine("Publishing to queue '" + queueName + "'\n"); int tasks = 1000; // Generate random numbers, more interesting than just i being incremented Random rnd = new Random(); try { for (int i = 0; i < tasks; i++) { TextMessage msg; ConnectionFactory factory = new TIBCO.EMS.ConnectionFactory("localhost"); connection = factory.CreateConnection("", ""); // create the session session = connection.CreateSession(false, Session.AUTO_ACKNOWLEDGE); queue = session.CreateQueue(queueName); //create the producer msgProducer = session.CreateProducer(null); msg = session.CreateTextMessage(); var number = rnd.Next(1000, 1000000); // update console Console.WriteLine("Number : " + number); // load the txt - which is a number we want to now the primes // note: receiver uses Convert.ToInt32 so we need to only pass in valid number. msg.Text = number.ToString(); //Another options is to use a property msg.SetIntProperty("number", number); //compress //msg.SetBooleanProperty("JMS_TIBCO_COMPRESS", true); //publish the message msgProducer.Send(queue, msg); Thread.Sleep(100); } Console.WriteLine("Tasks Sent : " + tasks.ToString()); } catch (EMSException e) { Console.Error.WriteLine("Exception in Tasks : " + e.Message); Console.Error.WriteLine(e.StackTrace); Environment.Exit(-1); } }
static int Main(string[] args) { Options options = new Options(args); Connection connection = null; try { connection = new Connection(options.Url, options.ConnectionOptions); connection.Open(); Session session = connection.CreateSession(); Sender sender = session.CreateSender(options.Address); Message message; if (options.Entries.Count > 0) { Dictionary<string, object> content = new Dictionary<string, object>(); SetEntries(options.Entries, content); message = new Message(content); } else { message = new Message(options.Content); message.ContentType = "text/plain"; } Address replyToAddr = new Address(options.ReplyTo); Stopwatch stopwatch = new Stopwatch(); TimeSpan timespan = new TimeSpan(0,0,options.Timeout); stopwatch.Start(); for (int count = 0; (0 == options.Count || count < options.Count) && (0 == options.Timeout || stopwatch.Elapsed <= timespan); count++) { if ("" != options.ReplyTo) message.ReplyTo = replyToAddr; string id = options.Id ; if ("" == id) { Guid g = Guid.NewGuid(); id = g.ToString(); } string spoutid = id + ":" + count; message.SetProperty("spout-id", spoutid); sender.Send(message); } session.Sync(); connection.Close(); return 0; } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (null != connection) connection.Close(); } return 1; }
public void TestExponentialRedeliveryPolicyDelaysDeliveryOnRollback() { using (Connection connection = (Connection)CreateConnection()) { IRedeliveryPolicy policy = connection.RedeliveryPolicy; policy.InitialRedeliveryDelay = 500; policy.BackOffMultiplier = 2; policy.UseExponentialBackOff = true; policy.UseCollisionAvoidance = false; connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.Transactional); IDestination destination = session.CreateTemporaryQueue(); IMessageProducer producer = session.CreateProducer(destination); IMessageConsumer consumer = session.CreateConsumer(destination); // Send the messages producer.Send(session.CreateTextMessage("1st")); producer.Send(session.CreateTextMessage("2nd")); session.Commit(); ITextMessage m; m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(m); Assert.AreEqual("1st", m.Text); session.Rollback(); // No delay on first Rollback.. m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(100)); Assert.IsNotNull(m); session.Rollback(); // Show subsequent re-delivery delay is incrementing. m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(100)); Assert.IsNull(m); m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(700)); Assert.IsNotNull(m); Assert.AreEqual("1st", m.Text); session.Rollback(); // Show re-delivery delay is incrementing exponentially m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(100)); Assert.IsNull(m); m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(500)); Assert.IsNull(m); m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(700)); Assert.IsNotNull(m); Assert.AreEqual("1st", m.Text); } }
private void DurableExample(string[] args) { try { ConnectionFactory factory = new TIBCO.EMS.ConnectionFactory(serverUrl); Connection connection = factory.CreateConnection(userName, password); // if clientID is specified we must set it right here if (clientID != null) { connection.ClientID = clientID; } Session session = connection.CreateSession(false, Session.AUTO_ACKNOWLEDGE); bool unsubscribe = false; if (unsubscribe) { Console.WriteLine("Unsubscribing durable subscriber " + durableName); session.Unsubscribe(durableName); Console.WriteLine("Successfully unsubscribed " + durableName); connection.Close(); return; } Console.WriteLine("Subscribing to topic: " + topicName); // Use createTopic() to enable subscriptions to dynamic topics. Topic topic = session.CreateTopic(topicName); TopicSubscriber subscriber = session.CreateDurableSubscriber(topic, durableName); connection.Start(); // read topic messages while (true) { Message message = subscriber.Receive(); if (message == null) { break; } Console.WriteLine("\nReceived message: " + message); } connection.Close(); } catch (EMSException e) { Console.Error.WriteLine("Exception in 1_ReceiveDurable: " + e.Message); Console.Error.WriteLine(e.StackTrace); Environment.Exit(0); } }
public void TestCreateTxSession() { Connection = CreateAmqpConnection(); Assert.NotNull(Connection); Connection.Start(); ISession session = Connection.CreateSession(AcknowledgementMode.Transactional); Assert.NotNull(session); Assert.True(session.Transacted); session.Close(); }
public void CreateConsumer(string queue, MessageListener message) { Connection connection = ConnectionActiveMq(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination dest = session.GetQueue(queue); IMessageConsumer consumer = session.CreateConsumer(dest); connection.Start(); consumer.Listener += new MessageListener(message); }
public void TestRollbackOnSessionWithNoWork() { Connection = CreateAmqpConnection(); Assert.NotNull(Connection); Connection.Start(); ISession session = Connection.CreateSession(AcknowledgementMode.Transactional); Assert.NotNull(session); Assert.True(session.Transacted); session.Rollback(); }
public BusDepotAsyncMsgConsumer(String[] args) { ParseArgs(args); #if _NET_20 try { tibemsUtilities.initSSLParams(serverUrl, args); } catch (Exception e) { System.Console.WriteLine("Exception: " + e.Message); System.Console.WriteLine(e.StackTrace); System.Environment.Exit(-1); } #endif Console.WriteLine("------------------------------------------------------------------------"); Console.WriteLine("csAsyncMsgConsumer SAMPLE"); Console.WriteLine("------------------------------------------------------------------------"); Console.WriteLine("Server....................... " + ((serverUrl != null)?serverUrl:"localhost")); Console.WriteLine("User......................... " + ((userName != null)?userName:"******")); Console.WriteLine("Destination.................. " + name); Console.WriteLine("------------------------------------------------------------------------\n"); try { ConnectionFactory factory = new TIBCO.EMS.ConnectionFactory(serverUrl); connection = factory.CreateConnection(userName, password); session = connection.CreateSession(false, Session.AUTO_ACKNOWLEDGE); connection.ExceptionListener = this; if (useTopic) { destination = session.CreateTopic(name); } else { destination = session.CreateQueue(name); } Console.WriteLine("Subscribing to destination: " + name); // create the consumer msgConsumer = session.CreateConsumer(destination); msgConsumer.MessageListener = this; connection.Start(); } catch (Exception e) { Console.Error.WriteLine("Exception in AsyncMsgConsumer: " + e.Message); Console.Error.WriteLine(e.StackTrace); } }
public Publisher TopicPublisher(string topic) { lock (_publisherCache) { if (!_publisherCache.ContainsKey(topic)) { var session = Connection.CreateSession(AcknowledgementMode.AutoAcknowledge); var producer = session.CreateProducer(session.GetTopic(topic)); var publisher = new Publisher(producer); _publisherCache.Add(topic, publisher); } return(_publisherCache[topic]); } }
private void init(string host, int port) { ReceivedNumber = 0; isFinished = false; ReceivedMessages = new List <string>(); ListionTopics = new List <string>(); Uri uriSample = new Uri("activemq:tcp://" + host + ":" + port); ConnectionFactory confSample = new ConnectionFactory(uriSample); connection = (Connection)confSample.CreateConnection(); connection.Start(); session = (Session)connection.CreateSession(); }
// csharp.map.receiver example // // Send an amqp/map message to amqp:tcp:localhost:5672 amq.direct/map_example // The map message // static int Main(string[] args) { string url = "amqp:tcp:localhost:5672"; string address = "message_queue; {create: always}"; string connectionOptions = ""; if (args.Length > 0) url = args[0]; if (args.Length > 1) address = args[1]; if (args.Length > 2) connectionOptions = args[2]; // // Create and open an AMQP connection to the broker URL // Connection connection = new Connection(url); connection.Open(); // // Create a session and a receiver fir the direct exchange using the // routing key "map_example". // Session session = connection.CreateSession(); Receiver receiver = session.CreateReceiver(address); // // Fetch the message from the broker // Message message = receiver.Fetch(DurationConstants.MINUTE); // // Extract the structured content from the message. // Dictionary<string, object> content = new Dictionary<string, object>(); message.GetContent(content); Console.WriteLine("{0}", message.AsString(content)); // // Acknowledge the receipt of all received messages. // session.Acknowledge(); // // Close the receiver and the connection. // receiver.Close(); connection.Close(); return 0; }
// Settings for Power RT updates //private const string Url = "tcp://tsclient01.spikesco.com:10560,tcp://tsclient02.spikesco.com:10560"; //private const string UserName = "******"; //private const string Password = "******"; //private const string Selector = "Pole='NA'"; //private const string Topic = "int.t.to.pwr.publish"; // Settings for FE updates //private const string Url = "tcp://dvfemsg01.spikesco.com:10590, tcp://dvfemsg02.spikesco.com:10590"; //private const string UserName = "******"; //private const string Password = "******"; //private const string Selector = "";//measurementType = 'fe_measurement'"; //private const string Topic = "int.t.fe.txt"; public void Init() { var factory = new ConnectionFactory(Url); Listener = new MyMessageListener(); _connection = factory.CreateConnection(UserName, Password); _session = _connection.CreateSession(false, Session.AUTO_ACKNOWLEDGE); _consumer = _session.CreateConsumer(_session.CreateTopic(Topic), Selector); _consumer.MessageListener = Listener; //_consumer.MessageHandler += _consumer_MessageHandler; }
public void TestQueueRollbackConsumerListener() { connection.Start(); this.session = connection.CreateSession(AcknowledgementMode.Transactional); ITemporaryQueue queue = session.CreateTemporaryQueue(); IMessageProducer producer = session.CreateProducer(queue); IMessage message = session.CreateTextMessage("Test Message"); producer.Send(message); session.Commit(); IMessageConsumer consumer = session.CreateConsumer(queue); consumer.Listener += new MessageListener(OnMessageListener); Thread.Sleep(500); // first try.. should get 2 since there is no delay on the // first redeliver.. Assert.AreEqual(2, counter); Thread.Sleep(1000); // 2nd redeliver (redelivery after 1 sec) Assert.AreEqual(3, counter); Thread.Sleep(2000); // 3rd redeliver (redelivery after 2 seconds) - it should give up after // that Assert.AreEqual(4, counter); // create new message producer.Send(session.CreateTextMessage("Test Message Again")); session.Commit(); Thread.Sleep(500); // it should be committed, so no redelivery Assert.AreEqual(5, counter); Thread.Sleep(1500); // no redelivery, counter should still be 5 Assert.AreEqual(5, counter); session.Close(); }
public void TestConsumeAfterPublishFailsForDestroyedTempDestination() { const string msgQueueName = "Test.RequestReply.MsgQueue"; Connection consumerConnection = GetNewConnection(); ISession consumerSession = consumerConnection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination consumerDestination = consumerSession.GetQueue(msgQueueName); IMessageConsumer consumer = consumerSession.CreateConsumer(consumerDestination); consumerConnection.Start(); // The real test is whether sending a message to a deleted temp queue messes up // the consumers on the same connection. for (int index = 0; index < 25; index++) { Connection producerConnection = GetNewConnection(); ISession producerSession = producerConnection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination producerDestination = producerSession.GetQueue(msgQueueName); IMessageProducer producer = producerSession.CreateProducer(producerDestination); IDestination replyDestination = producerSession.CreateTemporaryQueue(); IMessageConsumer replyConsumer = producerSession.CreateConsumer(replyDestination); producerConnection.Start(); IMessage sendMsg = producer.CreateTextMessage("Consumer check."); sendMsg.NMSReplyTo = replyDestination; producer.Send(sendMsg); // Will the following Receive() call fail on the second or subsequent calls? IMessage receiveMsg = consumer.Receive(); IMessageProducer replyProducer = consumerSession.CreateProducer(receiveMsg.NMSReplyTo); connections.Remove(producerConnection); producerConnection.Close(); //Thread.Sleep(2000); // Wait a little bit to let the delete take effect. // This message delivery NOT should work since the temp destination was removed by closing the connection. try { IMessage replyMsg = replyProducer.CreateTextMessage("Reply check."); replyProducer.Send(replyMsg); Assert.Fail("Send should fail since temp destination should not exist anymore."); } catch (NMSException e) { Tracer.Debug("Test threw expected exception: " + e.Message); } } }
public void TestCreateConsumerFromTxSession() { Connection = CreateAmqpConnection(); Connection.Start(); ISession session = Connection.CreateSession(AcknowledgementMode.Transactional); Assert.NotNull(session); Assert.True(session.Transacted); IQueue queue = session.GetQueue(TestName); IMessageConsumer consumer = session.CreateConsumer(queue); Assert.NotNull(consumer); }
public Subscriber TopicSubscriber(string topicText, MessageListener onMessageHandler) { lock (_subscriberCache) { if (!_subscriberCache.ContainsKey(topicText)) { var session = Connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination topic = session.GetTopic(topicText + Retroactive); var consumer = session.CreateConsumer(topic); var subscriber = new Subscriber(Url, consumer, onMessageHandler); _subscriberCache.Add(topicText, subscriber); } return(_subscriberCache[topicText]); } }
protected virtual void Drain() { using (ISession session = Connection.CreateSession()) { // Tries to consume any messages on the Destination IMessageConsumer consumer = session.CreateConsumer(Destination); // Should only need to wait for first message to arrive due to the way // prefetching works. IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(receiveTimeout)); while (msg != null) { msg = consumer.ReceiveNoWait(); } } }
protected void CrearConexion(string uri, AcknowledgementMode ackMode) { if (_connectionFactory == null) { _connectionFactory = new ConnectionFactory(uri); if (Connection == null) { Connection _connection = (Connection)_connectionFactory.CreateConnection(UserName, Password); _connection.PrefetchPolicy.All = 10; Connection = _connection; Connection.Start(); Session = Connection.CreateSession(ackMode); } } }
public virtual void SendAndSyncReceive() { using (ISession session = Connection.CreateSession()) { IMessageConsumer consumer = session.CreateConsumer(Destination); IMessageProducer producer = session.CreateProducer(Destination); producer.Persistent = persistent; IMessage request = CreateMessage(); producer.Send(request); IMessage message = consumer.Receive(TimeSpan.FromMilliseconds(receiveTimeout)); Assert.IsNotNull(message, "No message returned!"); AssertValidMessage(message); } }
private void Run() { try { TextMessage msg; Console.WriteLine("Publishing to destination queue '" + queueName + "'\n"); ConnectionFactory factory = new TIBCO.EMS.ConnectionFactory("localhost"); connection = factory.CreateConnection("", ""); // create the session session = connection.CreateSession(false, Session.AUTO_ACKNOWLEDGE); queue = session.CreateQueue(queueName); //create the producer msgProducer = session.CreateProducer(null); string xml = @"<Event Id='15040' Code='C1219_DEMAND_RESET' Severity='EVENT_SEVERITY_INFORMATION' Name='C1219 Demand Reset' Class='DemandResetOccurred'> <Description> C1219 Demand Reset occurred </ Description > < Message > Demand Reset occurred for meter { 0}.</ Message> <Parameter Index = '0' Name = 'sourceEmitter' Type = 'Device'/> <MetaInfo> <MeterSource> Std table 76.table proc number 20 </MeterSource> </MetaInfo> </Event> "; msg = session.CreateTextMessage(); //Add special properties msg.SetStringProperty("NUMBER_OF_EVENTS", 1.ToString()); // load the txt or xml in our use case msg.Text = xml; //compress msg.SetBooleanProperty("JMS_TIBCO_COMPRESS", true); //publish the message msgProducer.Send(queue, msg); Console.WriteLine("Published message: " + msg.ToString()); } catch (EMSException e) { Console.Error.WriteLine("Exception in 3_SendTextMessage: " + e.Message); Console.Error.WriteLine(e.StackTrace); Environment.Exit(-1); } }
static int Main(string[] args) { // Usage: csharp.example.server [url [connectionOptions]] string url = "amqp:tcp:127.0.0.1:5672"; string connectionOptions = ""; if (args.Length > 0) { url = args[0]; } if (args.Length > 1) { connectionOptions = args[1]; } try { Connection connection = new Connection(url, connectionOptions); connection.Open(); Session session = connection.CreateSession(); Receiver receiver = session.CreateReceiver("service_queue; {create: always}"); while (true) { Message request = receiver.Fetch(); Address address = request.ReplyTo; if (null != address) { Sender sender = session.CreateSender(address); String s = request.GetContent(); Message response = new Message(s.ToUpper()); sender.Send(response); Console.WriteLine("Processed request: {0} -> {1}", request.GetContent(), response.GetContent()); session.Acknowledge(); } else { Console.WriteLine("Error: no reply address specified for request: {0}", request.GetContent()); session.Reject(request); } } // connection.Close(); // unreachable in this example } catch (Exception e) { Console.WriteLine("Exception {0}.", e); } return(1); }
public void TestNornalRedeliveryPolicyOnRollbackUntilTimeToLive() { using (Connection connection = (Connection)CreateConnection()) { IRedeliveryPolicy policy = connection.RedeliveryPolicy; policy.MaximumRedeliveries = -1; policy.InitialRedeliveryDelay = 500; policy.UseExponentialBackOff = false; connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.Transactional); IDestination destination = session.CreateTemporaryQueue(); IMessageProducer producer = session.CreateProducer(destination); IMessageConsumer consumer = session.CreateConsumer(destination); // Send the messages ITextMessage textMessage = session.CreateTextMessage("1st"); textMessage.NMSTimeToLive = TimeSpan.FromMilliseconds(800.0); producer.Send(textMessage); session.Commit(); ITextMessage m; m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(m); Assert.AreEqual("1st", m.Text); session.Rollback(); // No delay on first Rollback.. m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(100)); Assert.IsNotNull(m); session.Rollback(); // Show subsequent re-delivery delay is incrementing. m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(100)); Assert.IsNull(m); m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(700)); Assert.IsNotNull(m); Assert.AreEqual("1st", m.Text); session.Rollback(); // The message gets redelivered after 500 ms every time since // we are not using exponential backoff. m = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(700)); Assert.IsNull(m); } }
public void TestReceiveSomeThenRollback() { Connection = CreateAmqpConnection(); Connection.Start(); int totalCount = 5; int consumeBeforeRollback = 2; SendToAmqQueue(totalCount); AssertQueueSize(totalCount, TimeSpan.FromMilliseconds(1000)); ISession session = Connection.CreateSession(AcknowledgementMode.Transactional); IQueue queue = session.GetQueue(TestName); IMessageConsumer consumer = session.CreateConsumer(queue); for (int i = 1; i <= consumeBeforeRollback; i++) { IMessage message = consumer.Receive(TimeSpan.FromMilliseconds(3000)); Assert.NotNull(message); Assert.AreEqual(i, message.Properties.GetInt(MESSAGE_NUMBER), "Unexpected message number"); } session.Rollback(); // Consume again.. the previously consumed messages should get delivered // again after the rollback and then the remainder should follow List <int> messageNumbers = new List <int>(); for (int i = 1; i <= totalCount; i++) { IMessage message = consumer.Receive(TimeSpan.FromMilliseconds(3000)); Assert.NotNull(message, $"Failed to receive message: {i}"); messageNumbers.Add(message.Properties.GetInt(MESSAGE_NUMBER)); } session.Commit(); Assert.AreEqual(totalCount, messageNumbers.Count, "Unexpected size of list"); for (int i = 0; i < messageNumbers.Count; i++) { Assert.AreEqual(i + 1, messageNumbers[i], "Unexpected order of messages: "); } AssertQueueEmpty(TimeSpan.FromMilliseconds(1000)); }
static int Main(string[] args) { String url = "amqp:tcp:127.0.0.1:5672"; String connectionOptions = ""; if (args.Length > 0) url = args[0]; if (args.Length > 1) connectionOptions = args[1]; Connection connection = new Connection(url, connectionOptions); try { connection.Open(); Session session = connection.CreateSession(); Sender sender = session.CreateSender("service_queue"); Address responseQueue = new Address("#response-queue; {create:always, delete:always}"); Receiver receiver = session.CreateReceiver(responseQueue); String[] s = new String[] { "Twas brillig, and the slithy toves", "Did gire and gymble in the wabe.", "All mimsy were the borogroves,", "And the mome raths outgrabe." }; Message request = new Message(""); request.ReplyTo = responseQueue; for (int i = 0; i < s.Length; i++) { request.SetContent(s[i]); sender.Send(request); Message response = receiver.Fetch(); Console.WriteLine("{0} -> {1}", request.GetContent(), response.GetContent()); } connection.Close(); return 0; } catch (Exception e) { Console.WriteLine("Exception {0}.", e); connection.Close(); } return 1; }
public void TestConsumerReceivePrefetchZeroRedeliveryZero() { const string QUEUE_NAME = "TEST.TestConsumerReceivePrefetchZeroRedeliveryZero"; using (Connection connection = CreateConnection() as Connection) using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) using (IQueue queue = session.GetQueue(QUEUE_NAME)) { session.DeleteDestination(queue); using (IMessageProducer producer = session.CreateProducer(queue)) { ITextMessage textMessage = session.CreateTextMessage("test Message"); producer.Send(textMessage); } } // consume and rollback - increase redelivery counter on message using (Connection connection = CreateConnection() as Connection) using (ISession session = connection.CreateSession(AcknowledgementMode.Transactional)) using (IQueue queue = session.GetQueue(QUEUE_NAME)) using (IMessageConsumer consumer = session.CreateConsumer(queue)) { connection.Start(); IMessage message = consumer.Receive(TimeSpan.FromMilliseconds(3000)); Assert.IsNotNull(message); session.Rollback(); } // try consume with timeout - expect it to timeout and return NULL message using (Connection connection = CreateConnection() as Connection) { connection.PrefetchPolicy.All = 0; connection.RedeliveryPolicy.MaximumRedeliveries = 0; connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.Transactional); IQueue queue = session.GetQueue(QUEUE_NAME); using (IMessageConsumer consumer = session.CreateConsumer(queue)) { IMessage message = consumer.Receive(TimeSpan.FromMilliseconds(3000)); Assert.IsNull(message); } } }
public void TestDeliveryDelay() { PurgeQueue(TimeSpan.FromMilliseconds(500)); var deliveryDelay = TimeSpan.FromSeconds(7); Connection = CreateAmqpConnection(); Connection.Start(); ISession session = Connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IQueue queue = session.GetQueue(TestName); IMessageProducer producer = session.CreateProducer(queue); producer.DeliveryDelay = deliveryDelay; DateTime? receivingTime = null; IMessageConsumer consumer = session.CreateConsumer(queue); var receivingTask = Task.Run(() => { while (true) { var message = consumer.Receive(TimeSpan.FromMilliseconds(100)); if (message != null && message.Body <string>() == "Hello") { receivingTime = DateTime.Now; return; } } }); DateTime sendTime = DateTime.Now; ITextMessage messageToSend = session.CreateTextMessage("Hello"); producer.Send(messageToSend, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.Zero); // Wait that delivery delay Thread.Sleep(deliveryDelay); receivingTask.Wait(TimeSpan.FromSeconds(20)); // make sure its done var measuredDelay = (receivingTime.Value - sendTime); Assert.Greater(measuredDelay.TotalMilliseconds, deliveryDelay.TotalMilliseconds * 0.5); Assert.Less(measuredDelay.TotalMilliseconds, deliveryDelay.TotalMilliseconds * 1.5); }
public void CreateProducer(string queue, object obj) { Connection connection = ConnectionActiveMq(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination dest = session.GetQueue(queue); using (IMessageProducer producer = session.CreateProducer(dest)) { connection.Start(); producer.DeliveryMode = MsgDeliveryMode.Persistent; IObjectMessage request = session.CreateObjectMessage(obj); producer.Send(request); } }
public void TestSelectNoLocal() { PurgeTopic(TimeSpan.FromMilliseconds(500)); Connection = CreateAmqpConnection(); Connection.Start(); ISession session = Connection.CreateSession(AcknowledgementMode.AutoAcknowledge); ITopic topic = session.GetTopic(TestName); IMessageProducer producer = session.CreateProducer(topic); ITextMessage message = session.CreateTextMessage("text"); producer.Send(message, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.Zero); IMessageConsumer messageConsumer = session.CreateConsumer(topic, null, noLocal: true); Assert.IsNull(messageConsumer.Receive(TimeSpan.FromMilliseconds(500))); }
// Direct sender example // // Send 10 messages from localhost:5672, amq.direct/key // Messages are assumed to be printable strings. // static int Main(string[] args) { String host = "localhost:5672"; String addr = "amq.direct/key"; Int32 nMsg = 10; if (args.Length > 0) host = args[0]; if (args.Length > 1) addr = args[1]; if (args.Length > 2) nMsg = Convert.ToInt32(args[2]); Console.WriteLine("csharp.direct.sender"); Console.WriteLine("host : {0}", host); Console.WriteLine("addr : {0}", addr); Console.WriteLine("nMsg : {0}", nMsg); Console.WriteLine(); Connection connection = null; try { connection = new Connection(host); connection.Open(); if (!connection.IsOpen) { Console.WriteLine("Failed to open connection to host : {0}", host); } else { Session session = connection.CreateSession(); Sender sender = session.CreateSender(addr); for (int i = 0; i < nMsg; i++) { Message message = new Message(String.Format("Test Message {0}", i)); sender.Send(message); } session.Sync(); connection.Close(); return 0; } } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (null != connection) connection.Close(); } return 1; }
public async Task SendMessage <T>(T message, string queueTopic) where T : class { _logger.Information($"Sending message of type {typeof(T)} to '{queueTopic}' queue: {JsonConvert.SerializeObject(message)}"); await ActivateAsync(); using (var session = Connection.CreateSession()) { using (var dest = session.GetQueue(queueTopic)) { using (var producer = session.CreateProducer(dest)) { var msg = session.CreateTextMessage(JsonConvert.SerializeObject(message)); msg.Properties[Sender] = CostSender; producer.Send(msg); } } } }
// Direct receiver example // // Receive 10 messages from localhost:5672, amq.direct/key // Messages are assumed to be printable strings. // static int Main(string[] args) { String host = "localhost:5672"; String addr = "amq.direct/key"; Int32 nMsg = 10; if (args.Length > 0) host = args[0]; if (args.Length > 1) addr = args[1]; if (args.Length > 2) nMsg = Convert.ToInt32(args[2]); Console.WriteLine("csharp.direct.receiver"); Console.WriteLine("host : {0}", host); Console.WriteLine("addr : {0}", addr); Console.WriteLine("nMsg : {0}", nMsg); Console.WriteLine(); Connection connection = null; try { connection = new Connection(host); connection.Open(); if (!connection.IsOpen) { Console.WriteLine("Failed to open connection to host : {0}", host); } else { Session session = connection.CreateSession(); Receiver receiver = session.CreateReceiver(addr); Message message = new Message(""); for (int i = 0; i < nMsg; i++) { Message msg2 = receiver.Fetch(DurationConstants.FORVER); Console.WriteLine("Rcvd msg {0} : {1}", i, msg2.GetContent()); } connection.Close(); return 0; } } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (null != connection) connection.Close(); } return 1; }
public void ConnectAndReceive() { try { _sessionReceiver = new TradeConfirmationReceiver(); /* * Step 1: Preparing the connection and session */ _connection = new Connection(_brokerAddress); _connection.SetOption("reconnect", true); _connection.SetOption("reconnect_limit", 2); _connection.SetOption("reconnect_urls", _failBrokerAddress); //must set the username, a little different with Eurex's Demo code //the username is case sensitive //be carful, the .cert's frendly is empty in LCMLO_LIQSPALBB.crt _connection.SetOption("username", _memberName); _connection.SetOption("transport", "ssl"); _connection.SetOption("sasl_mechanisms", "EXTERNAL"); _connection.SetOption("heartbeat", 60);//unit:seconds _connection.Open(); _session = _connection.CreateSession(); /* * Step 2: Create callback server and implicitly start it */ // The callback server is running and executing callbacks on a separate thread. _callbackServer = new CallbackServer(_session, _sessionReceiver); /* * Step 3: Creating message consumer */ _receiver = _session.CreateReceiver(_broadcastAddress); _receiver.Capacity = 100; } catch (QpidException ex) { _Log.Error("Make connection to AMQP broker failed!", ex); throw; } }
static int Main(string[] args) { string url = "amqp:tcp:127.0.0.1:5672"; string connectionOptions = ""; if (args.Length > 0) url = args[0]; // address args[1] is not used in this example if (args.Length > 2) connectionOptions = args[2]; try { Connection connection = new Connection(url, connectionOptions); connection.Open(); Session session = connection.CreateSession(); Receiver receiver = session.CreateReceiver("service_queue; {create: always}"); while (true) { Message request = receiver.Fetch(); Address address = request.ReplyTo; if (null != address) { Sender sender = session.CreateSender(address); String s = request.GetContent(); Message response = new Message(s.ToUpper()); sender.Send(response); Console.WriteLine("Processed request: {0} -> {1}", request.GetContent(), response.GetContent()); session.Acknowledge(); } else { Console.WriteLine("Error: no reply address specified for request: {0}", request.GetContent()); session.Reject(request); } } // connection.Close(); // unreachable in this example } catch (Exception e) { Console.WriteLine("Exception {0}.", e); } return 1; }
private static void Send() { string brokerAddr = "amqp:ssl:chengdudev6:11234"; string failBrokerAddr = "amqp:ssl:chengdudev6:11234"; string memberName = "ABCFR_ABCFRALMMACC1"; string requestAddress = "request." + memberName + "; { node: { type: topic }, create: never }"; string replyAddress = "response/response." + memberName + ".response_queue_1; { create: receiver, node: { type: topic } }"; Connection connection = null; Session session; try { /* * Step 1: Preparing the connection and session */ connection = new Connection(brokerAddr); connection.SetOption("reconnect", true); connection.SetOption("reconnect_limit", 1); connection.SetOption("reconnect_urls", failBrokerAddr); connection.SetOption("username", "ABCFR_ABCFRALMMACC1"); connection.SetOption("transport", "ssl"); connection.SetOption("sasl_mechanisms", "EXTERNAL"); connection.Open(); session = connection.CreateSession(); /* * Step 2: Creating message producer */ Sender sender = session.CreateSender(requestAddress); /* * Step 3: Sending a message */ Message requestMsg = new Message("<FIXML>...</FIXML>"); Address ra = new Address(replyAddress); requestMsg.ReplyTo = ra; sender.Send(requestMsg); Console.WriteLine("Request sent: {0}", requestMsg.GetContent()); session.Sync(); connection.Close(); } catch (QpidException ex) { Console.WriteLine("QpidException caught: {0}", ex.Message); } finally { if (connection != null && connection.IsOpen) { Console.WriteLine("Closing the connection."); connection.Close(); } } }
private static void SendHelloWord_BR() { //or start simpe qpid on windows : //cmd: qpidd --port=60302 --no-data-dir --auth=no String broker = "chengdudev6:21234"; string memberName = "ABCFR_ABCFRALMMACC1"; string broadcastAddress = "broadcast." + memberName + ".TradeConfirmation; { node: { type: queue }, create: never, mode: consume, assert: always }"; //string broadcastAddress = "request.ABCFR_ABCFRALMMACC1";//"bxu.testBinding";//"amq.direct";//"broadcast"; Connection connection = null; try { connection = new Connection(broker); connection.SetOption("username", "admin"); connection.SetOption("password", "admin"); connection.Open(); Session session = connection.CreateSession(); Sender sender = session.CreateSender(broadcastAddress); sender.Send(new Message("<FIXML>........</FIXML>")); session.Sync(); connection.Close(); } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (connection != null) connection.Close(); } }
// // TestProgram // public int TestProgram(string[] args) { string url = "amqp:tcp:localhost:5672"; string addr = "amq.direct/map_example"; UInt32 count = 1; string connectionOptions = ""; if (1 == args.Length) { if (args[0].Equals("-h") || args[0].Equals("-H") || args[0].Equals("/?")) { usage(url, addr, count, connectionOptions); return 1; } } if (args.Length > 0) url = args[0]; if (args.Length > 1) addr = args[1]; if (args.Length > 2) count = System.Convert.ToUInt32(args[2]); if (args.Length > 3) connectionOptions = args[3]; // // Create and open an AMQP connection to the broker URL // Connection connection = new Connection(url, connectionOptions); connection.Open(); // // Create a session and a sender to the direct exchange using the // routing key "map_example". // Session session = connection.CreateSession(); Sender sender = session.CreateSender(addr); // // Create structured content for the message. This example builds a // map of items including a nested map and a list of values. // Dictionary<string, object> content = new Dictionary<string, object>(); Dictionary<string, object> subMap = new Dictionary<string, object>(); Collection<object> colors = new Collection<object>(); // add simple types content["id"] = 987654321; content["name"] = "Widget"; content["percent"] = 0.99; // add nested amqp/map subMap["name"] = "Smith"; subMap["number"] = 354; content["nestedMap"] = subMap; // add an amqp/list colors.Add("red"); colors.Add("green"); colors.Add("white"); content["colorsList"] = colors; // add one of each supported amqp data type bool mybool = true; content["mybool"] = mybool; byte mybyte = 4; content["mybyte"] = mybyte; UInt16 myUInt16 = 5; content["myUInt16"] = myUInt16; UInt32 myUInt32 = 6; content["myUInt32"] = myUInt32; UInt64 myUInt64 = 7; content["myUInt64"] = myUInt64; char mychar = 'h'; content["mychar"] = mychar; Int16 myInt16 = 9; content["myInt16"] = myInt16; Int32 myInt32 = 10; content["myInt32"] = myInt32; Int64 myInt64 = 11; content["myInt64"] = myInt64; Single mySingle = (Single)12.12; content["mySingle"] = mySingle; Double myDouble = 13.13; content["myDouble"] = myDouble; Guid myGuid = new Guid("000102030405060708090a0b0c0d0e0f"); content["myGuid"] = myGuid; // // Construct a message with the map content and send it synchronously // via the sender. // Message message = new Message(content); for (UInt32 i = 0; i<count; i++) sender.Send(message, true); // // Wait until broker receives all messages. // session.Sync(); // // Close the connection. // connection.Close(); return 0; }
public CouchDbEventStore(string database) { var c = new Connection(new Uri("http://localhost:5984")); _session = c.CreateSession(database); }
public static void Main(string[] args) { string broker_ip = "192.168.0.78:5672"; string data_queue = "fila_dados_ext"; string command_queue = "mxt_command_qpid"; byte[] bMessage = null; Connection connection = null; bool response_received = true; try { /*Cria a conexão com o Qpid e abre a sessão sem autenticar*/ connection = new Connection(broker_ip); connection.Open(); Session session = connection.CreateSession(); Receiver receiver = session.CreateReceiver(data_queue + "; {create: always}"); Sender sender = session.CreateSender(command_queue + "; {create: always}"); /*Cria uma nova mensagem e recebe a proxima mensagem da fila se o Fetch() * não tiver argumentos ele irá esperar a proxima mensagem sem tempo * definido use (DurationConstants.SECOND * 1) para aguardar 1 segundo*/ while (true) { Message message = new Message(); bool message_receive = receiver.Fetch(ref message); String data_gateway = message.ContentType; while (message_receive) { /*Classe para verificar o tipo da mensagem*/ ConsoleApplication4.Class1 c1 = new ConsoleApplication4.Class1(); ConsoleApplication4.Class1.qpid_subject_type type = c1.get_subject_type(message.Subject); switch (type) { case ConsoleApplication4.Class1.qpid_subject_type.qpid_st_none: Console.WriteLine("Unknow Message"); break; case ConsoleApplication4.Class1.qpid_subject_type.qpid_st_pb_mxt1xx_pos: /*Cria um novo byte array com o tamanho da mensagem*/ bMessage = new byte[message.ContentSize]; /*Escreve o conteudo da mensagem no byte array*/ message.GetContent(bMessage); /*Constroi o objeto pos_mxt1xx usando o byte array para preenche-lo*/ maxtrack.pb.mxt1xx.mxt1xx_u_position pos_mxt1xx = maxtrack.pb.mxt1xx.mxt1xx_u_position.CreateBuilder().MergeFrom(bMessage).BuildPartial(); Console.Write("Serial: " + pos_mxt1xx.Firmware.Serial + "\n" + "Memory Index: " + pos_mxt1xx.Firmware.MemoryIndex + "\n" + "Latitude: " + pos_mxt1xx.GpsModem.Latitude + "\n" + "Longitude: " + pos_mxt1xx.GpsModem.Longitude + "\n" + "DATE: " + pos_mxt1xx.GpsModem.Date + "\n" + "CSQ: " + pos_mxt1xx.GpsModem.Csq + "\n" + "CellId: " + pos_mxt1xx.CellInfo.CellId + "\n" + "LocalAreaCode: " + pos_mxt1xx.CellInfo.LocalAreaCode + "\n" + "NetworkCode: " + pos_mxt1xx.CellInfo.NetworkCode + "\n" + "CountryCode: " + pos_mxt1xx.CellInfo.CountryCode + "\n" + "-----------------------------------------" + "\n" ); /*Campos Optional*/ if (pos_mxt1xx.Firmware.HasLifeTime) { Console.WriteLine("Life Time: " + pos_mxt1xx.Firmware.LifeTime + "\n" + "-----------------------------------------" + "\n"); } if (response_received) response_received = mxt1xx_output_control(!pos_mxt1xx.HardwareMonitor.Outputs.Output1, pos_mxt1xx, sender); break; case ConsoleApplication4.Class1.qpid_subject_type.qpid_st_pb_command_response: bMessage = new byte[message.ContentSize]; message.GetContent(bMessage); maxtrack.pb.commands.u_command_response response = maxtrack.pb.commands.u_command_response.CreateBuilder().MergeFrom(bMessage).BuildPartial(); if (response.Status == 5) { Console.WriteLine("Command response: Success"); response_received = true; } else Console.WriteLine("Command response: " + response.Status.ToString()); break; default: break; } /*Diz ao servidor que a mensagem foi recebida, o servidor apagará a mensagem*/ session.Acknowledge(); message_receive = false; /*Fecha a conexão*/ //connection.Close(); //System.Threading.Thread.Sleep(1000); } } } catch (Exception e) { Console.WriteLine("Exception {0}.", e); System.Threading.Thread.Sleep(10000); } }
private static void SendHelloWorld() { String broker = "chengdudev6:21234"; String address = "amq.topic"; Connection connection = null; try { connection = new Connection(broker); connection.SetOption("username", "admin"); connection.SetOption("password", "admin"); connection.Open(); Session session = connection.CreateSession(); Sender sender = session.CreateSender(address); var msg = new Message("<FIXML>........</FIXML>"); msg.Subject = "bxu.testBinding"; sender.Send(msg); //When sending the messages asynchronously, the session should be synchronized after every //few messages in order to make sure that the requests which were sent asynchronously were //delivered to the broker. session.Sync(); connection.Close(); } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (connection != null) connection.Close(); } }
/// <summary> /// A function to illustrate how to open a Session callback and /// receive messages. /// </summary> /// <param name="args">Main program arguments</param> public int TestProgram(string[] args) { string url = "amqp:tcp:localhost:5672"; string addr = "amq.direct/map_example"; int nSec = 30; string connectionOptions = ""; if (1 == args.Length) { if (args[0].Equals("-h") || args[0].Equals("-H") || args[0].Equals("/?")) { usage(url, addr, nSec); return 1; } } if (args.Length > 0) url = args[0]; if (args.Length > 1) addr = args[1]; if (args.Length > 2) nSec = System.Convert.ToInt32(args[2]); if (args.Length > 3) connectionOptions = args[3]; // // Create and open an AMQP connection to the broker URL // Connection connection = new Connection(url, connectionOptions); connection.Open(); // // Create a session. // Session session = connection.CreateSession(); // // Receive through callback // // Create callback server and implicitly start it // SessionReceiver.CallbackServer cbServer = new SessionReceiver.CallbackServer(session, this); // // The callback server is running and executing callbacks on a // separate thread. // // // Create a receiver for the direct exchange using the // routing key "map_example". // Receiver receiver = session.CreateReceiver(addr); // // Establish a capacity // receiver.Capacity = 100; // // Wait so many seconds for messages to arrive. // System.Threading.Thread.Sleep(nSec * 1000); // in mS // // Stop the callback server. // cbServer.Close(); // // Close the receiver and the connection. // try { receiver.Close(); connection.Close(); } catch (Exception exception) { // receiver or connection may throw if they closed in error. // A typical application will take more action here. Console.WriteLine("{0} Closing exception caught.", exception.ToString()); } return 0; }
private static void SendReceiveBindingHelloWord() { //or start simpe qpid on windows : //cmd: qpidd --port=60302 --no-data-dir --auth=no String broker = "chengdudev6:21234"; String senderAddress = "amq.topic"; // queue "bxu.testBinding" was binded to this exchange string reseiverAddress = "bxu.testBinding"; Connection connection = null; try { connection = new Connection(broker); connection.SetOption("username", "admin"); connection.SetOption("password", "admin"); connection.Open(); Session session = connection.CreateSession(); Receiver receiver = session.CreateReceiver(reseiverAddress); Sender sender = session.CreateSender(senderAddress); sender.Send(new Message("<FIXML>........</FIXML>")); Message message = new Message(); message = receiver.Fetch(DurationConstants.SECOND * 1); Console.WriteLine("{0}", message.GetContent()); session.Acknowledge(); connection.Close(); } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (connection != null) connection.Close(); } }
public HomeController() { Connection connection = new Connection(new Uri(Config.HOST)); _session = connection.CreateSession(Config.CLOTHES_DB_NAME); }
private static void ReceiveHelloWorld() { String broker = "chengdudev6:21234"; string reseiverAddress = "bxu.testBinding"; //bxu.testBinging was binded to exchange "amq.topic" Connection connection = null; try { connection = new Connection(broker); connection.SetOption("username", "admin"); connection.SetOption("password", "admin"); connection.Open(); Session session = connection.CreateSession(); Receiver receiver = session.CreateReceiver(reseiverAddress); Message message = new Message(); message = receiver.Fetch(DurationConstants.SECOND * 1); Console.WriteLine("{0}", message.GetContent()); //The message should be acknowledged after its processing is finished. session.Acknowledge(); connection.Close(); } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (connection != null) connection.Close(); } }
private static void SendHelloWord_SSL_BR() { //or start simpe qpid on windows : //cmd: qpidd --port=60302 --no-data-dir --auth=no String broker = "amqp:ssl:chengdudev6:11234"; string memberName = "ABCFR_ABCFRALMMACC1"; string broadcastAddress = "broadcast." + memberName + ".TradeConfirmation; { node: { type: queue }, create: never, mode: consume, assert: always }"; Connection connection = null; try { connection = new Connection(broker); connection.SetOption("username", "ABCFR_ABCFRALMMACC1"); connection.SetOption("transport", "ssl"); connection.SetOption("sasl_mechanisms", "EXTERNAL"); connection.Open(); Session session = connection.CreateSession(); Sender sender = session.CreateSender(broadcastAddress); sender.Send(new Message("<FIXML>........</FIXML>")); session.Sync(); connection.Close(); } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (connection != null) connection.Close(); } }
static void Main(string[] args) { //RequestResponse(); //return; //[[ The following two types of EnviromentVariable must set by manual, not here. //1) //System.Environment.SetEnvironmentVariable("QPID_SSL_CERT_STORE", "Personal", EnvironmentVariableTarget.Process); //System.Environment.SetEnvironmentVariable("QPID_SSL_CERT_NAME", "abcfr_abcfralmmacc1", EnvironmentVariableTarget.Process); //2) //System.Environment.SetEnvironmentVariable("QPID_LOG_ENABLE", "trace+", EnvironmentVariableTarget.Process); //System.Environment.SetEnvironmentVariable("QPID_SSL_CERT_FILENAME", @".\ABCFR_ABCFRALMMACC1.p12", EnvironmentVariableTarget.Process); //System.Environment.SetEnvironmentVariable("QPID_SSL_CERT_PASSWORD_FILE", @".\ABCFR_ABCFRALMMACC1.pwd", EnvironmentVariableTarget.Process); //System.Environment.SetEnvironmentVariable("QPID_SSL_CERT_NAME", "abcfr_abcfralmmacc1", EnvironmentVariableTarget.Process); //]] //string brokerAddr = args.Length > 0 ? args[0] : "amqp:ssl:192.168.34.11:11234"; //shit, seems must use the host name string brokerAddr = args.Length > 0 ? args[0] : "amqp:ssl:chengdudev6:11234"; string failBrokerAddr = args.Length > 1 ? args[1] : "amqp:ssl:chengdudev6:11234"; string memberName = "ABCFR_ABCFRALMMACC1"; string broadcastAddress = "broadcast." + memberName + ".TradeConfirmation; { node: { type: queue }, create: never, mode: consume, assert: always }"; Connection connection = null; Session session; try { /* * Step 1: Preparing the connection and session */ connection = new Connection(brokerAddr); connection.SetOption("reconnect", true); connection.SetOption("reconnect_limit", 2); connection.SetOption("reconnect_urls", failBrokerAddr); //shit, must set the username, a little different with Eurex's Demo code //shit, the username is case sensitive connection.SetOption("username", "ABCFR_ABCFRALMMACC1"); connection.SetOption("transport", "ssl"); connection.SetOption("sasl_mechanisms", "EXTERNAL"); //connection.SetOption("heartbeat", 120); connection.Open(); session = connection.CreateSession(); /* * Step 2: Create callback server and implicitly start it */ CallbackServer cbServer = new CallbackServer(session, new Listener()); // The callback server is running and executing callbacks on a separate thread. /* * Step 3: Creating message consumer */ Receiver receiver = session.CreateReceiver(broadcastAddress); receiver.Capacity = 100; Console.ReadLine(); //System.Threading.Thread.Sleep(20 * 1000); // in mS ///* // * Step 4: Stop the callback server and close receiver // */ //cbServer.Close(); //receiver.Close(); //session.Sync(); } catch (QpidException ex) { Console.WriteLine("QpidException caught: {0}", ex.Message); Console.WriteLine(); Console.WriteLine("Press any key to continue!"); Console.ReadLine(); } finally { if (connection != null && connection.IsOpen) { Console.WriteLine("Closing the connection."); connection.Close(); } } }
private static void RequestResponse() { string brokerAddr = "amqp:ssl:chengdudev6:11234"; string failBrokerAddr = "amqp:ssl:chengdudev6:11234"; string memberName = "ABCFR_ABCFRALMMACC1"; string requestAddress = "request." + memberName + "; { node: { type: topic }, create: never }"; string replyAddress = "response/response." + memberName + ".response_queue_1; { create: receiver, node: { type: topic } }"; string responseAddress = "response." + memberName + ".response_queue_1; {create: receiver, assert: never," + "node: { type: queue, x-declare: { auto-delete: true, exclusive: false, arguments: {'qpid.policy_type': ring," + "'qpid.max_count': 1000, 'qpid.max_size': 1000000}}, x-bindings: [{exchange: 'response', queue: 'response." + memberName + ".response_queue_1', key: 'response." + memberName + ".response_queue_1'}]}}"; Connection connection = null; Session session; try { /* * Step 1: Preparing the connection and session */ connection = new Connection(brokerAddr); connection.SetOption("reconnect", true); connection.SetOption("reconnect_limit", 1); connection.SetOption("reconnect_urls", failBrokerAddr); connection.SetOption("username", "ABCFR_ABCFRALMMACC1"); connection.SetOption("transport", "ssl"); connection.SetOption("sasl_mechanisms", "EXTERNAL"); connection.Open(); session = connection.CreateSession(); /* * Step 2: Creating message consumer */ Receiver receiver = session.CreateReceiver(responseAddress); /* * Step 2: Creating message producer */ Sender sender = session.CreateSender(requestAddress); /* * Step 3: Sending a message */ Message requestMsg = new Message("<FIXML>...</FIXML>"); Address ra = new Address(replyAddress); requestMsg.ReplyTo = ra; sender.Send(requestMsg); Console.WriteLine("Request sent: {0}", requestMsg.GetContent()); session.Sync(); /* * Step 3: Receiving a message */ Message msg = receiver.Fetch(DurationConstants.SECOND * 10); Console.WriteLine("RECEIVED MESSAGE:"); Console.WriteLine("#################"); Console.WriteLine(msg.GetContent()); session.Acknowledge(); connection.Close(); } catch (QpidException ex) { Console.WriteLine("QpidException caught: {0}", ex.Message); } finally { if (connection != null && connection.IsOpen) { Console.WriteLine("Closing the connection."); connection.Close(); } } }