private static string MessageContentAsString(Message msg, AmqpProperties props) { // AmqpBinaryBinding provides message content as a single XML "Binary" element XmlDictionaryReader reader = msg.GetReaderAtBodyContents(); while (!reader.HasValue) { reader.Read(); if (reader.EOF) { throw new InvalidDataException("empty reader for message"); } } byte[] rawdata = reader.ReadContentAsBase64(); string ct = props.ContentType; if (ct != null) { if (ct.Equals("amqp/map")) { return("mapdata (coming soon)"); } } return(Encoding.UTF8.GetString(rawdata)); }
private static string MessagePropertiesAsString(AmqpProperties props) { StringBuilder sb = new StringBuilder(); if (props.PropertyMap != null) { foreach (KeyValuePair <string, AmqpType> kvp in props.PropertyMap) { string propval; if (kvp.Value is AmqpString) { AmqpString amqps = (AmqpString)kvp.Value; propval = amqps.Value; } else { propval = kvp.Value.ToString(); } Append(sb, kvp.Key + ":" + propval); } } return(sb.ToString()); }
public void NonDefaultAmqpProperties() { const string TestString = "Test Message"; AmqpProperties messageProperties = this.CreateMessageProperties(); this.SendMessage(TestString, messageProperties); this.ReceiveMessage <string>(TestString, messageProperties); }
public void CanCopyBasicProperites() { const string ContentType = "text/plain"; const string ContentEncoding = "utf-8"; const string CorrelationId = "336dadf34"; const string MessageId = "6de45affdc"; const bool Persistent = true; const string ReplyTo = "test"; Dictionary <string, string> Headers = new Dictionary <string, string> { { "key1", "value1" }, { "key2", "value2" } }; var sut = new AmqpProperties { ContentType = ContentType, ContentEncoding = ContentEncoding, CorrelationId = CorrelationId, MessageId = MessageId, Persistent = Persistent, ReplyTo = ReplyTo, Headers = Headers }; IBasicProperties basicProperties = A.Fake <IBasicProperties>(); sut.CopyTo(basicProperties); basicProperties .ContentType .Should() .Be(ContentType, because: "Property should be copied."); basicProperties .ContentEncoding .Should() .Be(ContentEncoding, because: "Property should be copied."); basicProperties .CorrelationId .Should() .Be(CorrelationId, because: "Property should be copied."); basicProperties .MessageId .Should() .Be(MessageId, because: "Property should be copied."); basicProperties .Persistent .Should() .Be(Persistent, because: "Property should be copied."); basicProperties .ReplyTo .Should() .Be(ReplyTo, because: "Property should be copied."); basicProperties .Headers.Should().HaveCount(Headers.Count, because: "Property should be copied."); }
internal AmqpChannelProperties() { this.brokerHost = AmqpDefaults.BrokerHost; this.brokerPort = AmqpDefaults.BrokerPort; this.transferMode = AmqpDefaults.TransferMode; this.defaultMessageProperties = null; this.amqpSecurityMode = AmqpSecurityMode.None; this.amqpTransportSecurity = null; this.amqpCredential = null; this.maxBufferPoolSize = AmqpDefaults.MaxBufferPoolSize; this.maxReceivedMessageSize = AmqpDefaults.MaxReceivedMessageSize; }
private AmqpProperties CreateMessageProperties() { Dictionary <string, string> messageProperties = Util.GetProperties("..\\..\\MessageProperties.txt"); AmqpProperties amqpProperties = new AmqpProperties(); amqpProperties.ContentType = (string)messageProperties["ContentType"]; amqpProperties.Durable = Convert.ToBoolean((string)messageProperties["Durable"]); amqpProperties.RoutingKey = (string)messageProperties["RoutingKey"]; amqpProperties.TimeToLive = TimeSpan.Parse((string)messageProperties["TimeToLive"]); return(amqpProperties); }
static void Main(string[] args) { try { Options options = new Options(args); AmqpBinaryBinding binding = new AmqpBinaryBinding(); binding.BrokerHost = options.Broker; binding.BrokerPort = options.Port; binding.TransferMode = TransferMode.Streamed; IChannelFactory <IOutputChannel> factory = binding.BuildChannelFactory <IOutputChannel>(); factory.Open(); try { System.ServiceModel.EndpointAddress addr = options.Address; IOutputChannel sender = factory.CreateChannel(addr); sender.Open(); MyRawBodyWriter.Initialize(options.Content); DateTime end = DateTime.Now.Add(options.Timeout); System.ServiceModel.Channels.Message message; for (int count = 0; ((count < options.Count) || (options.Count == 0)) && ((options.Timeout == TimeSpan.Zero) || (end.CompareTo(DateTime.Now) > 0)); count++) { message = Message.CreateMessage(MessageVersion.None, "", new MyRawBodyWriter()); AmqpProperties props = new AmqpProperties(); props.ContentType = "text/plain"; string id = Guid.NewGuid().ToString() + ":" + count; props.PropertyMap.Add("spout-id", new AmqpString(id)); message.Properties["AmqpProperties"] = props; sender.Send(message); } } finally { factory.Close(); } } catch (Exception e) { Console.WriteLine("Spout: " + e); } }
private void ReceiveMessage <TObjectType>(TObjectType objectToMatch, AmqpProperties expectedProperties) { Uri receiveFromUri = new Uri("amqp:message_queue"); IChannelListener <IInputChannel> listener = Util.GetBinding().BuildChannelListener <IInputChannel>(receiveFromUri, new BindingParameterCollection()); listener.Open(); IInputChannel service = listener.AcceptChannel(TimeSpan.FromSeconds(10)); service.Open(); Message receivedMessage = service.Receive(TimeSpan.FromSeconds(10)); try { TObjectType receivedObject = receivedMessage.GetBody <TObjectType>(); Assert.True(receivedObject.Equals(objectToMatch), "Original and deserialized objects do not match"); AmqpProperties receivedProperties = (AmqpProperties)receivedMessage.Properties["AmqpProperties"]; PropertyInfo[] propInfo = typeof(AmqpProperties).GetProperties(); for (int i = 0; i < propInfo.Length; i++) { string propertyName = propInfo[i].Name; if (propertyName.Equals("RoutingKey", StringComparison.InvariantCultureIgnoreCase)) { Assert.AreEqual(RoutingKey, Convert.ToString(propInfo[i].GetValue(receivedProperties, null))); } else { Assert.AreEqual(Convert.ToString(propInfo[i].GetValue(expectedProperties, null)), Convert.ToString(propInfo[i].GetValue(receivedProperties, null))); } } } catch (NullReferenceException) { Assert.Fail("Message not received"); } catch (SerializationException) { Assert.Fail("Deserialized object not of correct type"); } finally { receivedMessage.Close(); service.Close(); listener.Close(); } }
private void SendMessage(object objectToSend, AmqpProperties propertiesToSend) { ChannelFactory <IOutputChannel> channelFactory = new ChannelFactory <IOutputChannel>(Util.GetBinding(), SendToUri); IOutputChannel proxy = channelFactory.CreateChannel(); proxy.Open(); Message toSend = Message.CreateMessage(MessageVersion.Default, string.Empty, objectToSend); toSend.Properties["AmqpProperties"] = propertiesToSend; proxy.Send(toSend); toSend.Close(); proxy.Close(); channelFactory.Close(); }
protected override void InitializeFrom(Binding binding) { base.InitializeFrom(binding); AmqpBinding amqpBinding = (AmqpBinding)binding; this.BrokerHost = amqpBinding.BrokerHost; this.BrokerPort = amqpBinding.BrokerPort; this.TransferMode = amqpBinding.TransferMode; this.Shared = amqpBinding.Shared; this.PrefetchLimit = amqpBinding.PrefetchLimit; if (!amqpBinding.SecurityEnabled) { this.Security = null; } else { if (this.Security == null) { this.Security = new AmqpSecurityElement(); } AmqpTransportSecurity sec = amqpBinding.Security.Transport; this.Security.Mode = AmqpSecurityMode.Transport; if (this.Security.Transport == null) { this.Security.Transport = new AmqpTransportSecurityElement(); } this.Security.Transport.CredentialType = sec.CredentialType; this.Security.Transport.IgnoreEndpointCredentials = sec.IgnoreEndpointClientCredentials; this.Security.Transport.UseSSL = sec.UseSSL; if (sec.DefaultCredential == null) { this.Security.Transport.DefaultCredential = null; } else { this.Security.Transport.DefaultCredential = new AmqpCredentialElement(); this.Security.Transport.DefaultCredential.UserName = sec.DefaultCredential.UserName; this.Security.Transport.DefaultCredential.Password = sec.DefaultCredential.Password; } } AmqpProperties props = amqpBinding.DefaultMessageProperties; }
static void Main(string[] args) { try { Options options = new Options(args); AmqpBinaryBinding binding = new AmqpBinaryBinding(); binding.BrokerHost = options.Broker; binding.BrokerPort = options.Port; binding.TransferMode = TransferMode.Streamed; IChannelFactory <IInputChannel> factory = binding.BuildChannelFactory <IInputChannel>(); factory.Open(); try { System.ServiceModel.EndpointAddress addr = options.Address; IInputChannel receiver = factory.CreateChannel(addr); receiver.Open(); TimeSpan timeout = options.Timeout; System.ServiceModel.Channels.Message message; while (receiver.TryReceive(timeout, out message)) { AmqpProperties props = (AmqpProperties)message.Properties["AmqpProperties"]; Console.WriteLine("Message(properties=" + MessagePropertiesAsString(props) + ", content='" + MessageContentAsString(message, props) + "')"); } } finally { factory.Close(); } } catch (Exception e) { Console.WriteLine("Drain: " + e); } }
public void Run() { IRawBodyUtility bodyUtil = new RawEncoderUtility(); IInputChannel startQueue = null; IOutputChannel doneQueue = null; UInt64 batchSize = (UInt64)opts.pubTxSize; bool txPending = false; AmqpProperties amqpProperties = null; if (opts.durable) { amqpProperties = new AmqpProperties(); amqpProperties.Durable = true; } try { publishQueue = QueueChannelFactory.CreateWriterChannel(this.destination, this.routingKey); doneQueue = QueueChannelFactory.CreateWriterChannel("", this.Fqn("pub_done")); startQueue = QueueChannelFactory.CreateReaderChannel(this.Fqn("pub_start")); // wait for our start signal Message msg; msg = startQueue.Receive(TimeSpan.MaxValue); Expect(bodyUtil.GetText(msg), "start"); msg.Close(); Stopwatch stopwatch = new Stopwatch(); AsyncCallback sendCallback = new AsyncCallback(this.AsyncSendCB); byte[] data = new byte[this.msgSize]; IAsyncResult sendResult = null; Console.WriteLine("sending {0}", this.msgCount); stopwatch.Start(); if (batchSize > 0) { Transaction.Current = new CommittableTransaction(); } for (UInt64 i = 0; i < this.msgCount; i++) { StampSequenceNo(data, i); msg = bodyUtil.CreateMessage(data); if (amqpProperties != null) { msg.Properties.Add("AmqpProperties", amqpProperties); } sendResult = publishQueue.BeginSend(msg, TimeSpan.MaxValue, sendCallback, msg); if (batchSize > 0) { txPending = true; if (((i + 1) % batchSize) == 0) { ((CommittableTransaction)Transaction.Current).Commit(); txPending = false; Transaction.Current = new CommittableTransaction(); } } } if (txPending) { ((CommittableTransaction)Transaction.Current).Commit(); } Transaction.Current = null; sendResult.AsyncWaitHandle.WaitOne(); stopwatch.Stop(); double mps = (msgCount / stopwatch.Elapsed.TotalSeconds); msg = bodyUtil.CreateMessage(String.Format("{0:0.##}", mps)); doneQueue.Send(msg, TimeSpan.MaxValue); msg.Close(); } finally { Close((IChannel)doneQueue); Close((IChannel)publishQueue); Close(startQueue); } }
private AmqpMessage WcfToQpid(Message wcfMessage) { object obj; AmqpProperties applicationProperties = null; bool success = false; AmqpMessage amqpMessage = null; if (wcfMessage.Properties.TryGetValue("AmqpProperties", out obj)) { applicationProperties = obj as AmqpProperties; } try { AmqpProperties outgoingProperties = new AmqpProperties(); // Start with AMQP properties from the binding and the URI if (this.factoryChannelProperties.DefaultMessageProperties != null) { outgoingProperties.MergeFrom(this.factoryChannelProperties.DefaultMessageProperties); } if (this.subject != null) { outgoingProperties.RoutingKey = this.subject; } if (this.qpidSubject != null) { outgoingProperties.PropertyMap["qpid.subject"] = new AmqpString(this.qpidSubject); } // Add the Properties set by the application on this particular message. // Application properties trump channel properties if (applicationProperties != null) { outgoingProperties.MergeFrom(applicationProperties); } amqpMessage = this.outputLink.CreateMessage(); amqpMessage.Properties = outgoingProperties; // copy the WCF message body to the AMQP message body if (this.streamed) { this.encoder.WriteMessage(wcfMessage, amqpMessage.BodyStream); } else { ArraySegment <byte> encodedBody = this.encoder.WriteMessage(wcfMessage, int.MaxValue, this.bufferManager); try { amqpMessage.BodyStream.Write(encodedBody.Array, encodedBody.Offset, encodedBody.Count); } finally { this.bufferManager.ReturnBuffer(encodedBody.Array); } } success = true; } finally { if (!success && (amqpMessage != null)) { amqpMessage.Dispose(); } } return(amqpMessage); }