public void Enqueue_Transactions_Abort_Properly() { recreateQueue(); BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement(); MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder; MessageDeliveryFormatter formatter = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IContract)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(IContract))); MsmqMessageDeliveryQueue queue = new MsmqMessageDeliveryQueue(Config.TestQueuePath, formatter); SubscriptionEndpoint endpoint = new SubscriptionEndpoint(Guid.NewGuid(), "SubscriptionName", "http://localhost/test", "SubscriptionConfigName", typeof(IContract), new WcfProxyDispatcher(), new PassThroughMessageFilter()); MessageDelivery enqueued = new MessageDelivery(endpoint.Id, typeof(IContract), "PublishThis", "randomMessageData", 3, new MessageDeliveryContext()); Assert.IsNull(queue.Peek(TimeSpan.FromSeconds(1))); // make sure queue is null before starting // Enqueue, but abort transaction using (TransactionScope ts = new TransactionScope()) { queue.Enqueue(enqueued); } using (TransactionScope ts = new TransactionScope()) { MessageDelivery dequeued = queue.Dequeue(TimeSpan.FromSeconds(5)); Assert.IsNull(dequeued); } }
public void FileSystemDispatcher_Picks_Up_Existing_Messages() { BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement(); MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder; ServiceBusRuntime dispatchRuntime = new ServiceBusRuntime(new DirectDeliveryCore()); var subscription = new SubscriptionEndpoint(Guid.NewGuid(), "File System Dispatcher", null, null, typeof(IContract), new FileSystemDispatcher(new ConverterMessageDeliveryWriterFactory(encoder,typeof(IContract)),Config.IncomingFilePath), new PassThroughMessageFilter()); dispatchRuntime.Subscribe(subscription); ServiceBusRuntime listenerRuntime = new ServiceBusRuntime(new DirectDeliveryCore()); var listener = new ListenerEndpoint(Guid.NewGuid(), "File System Listener", null, null, typeof(IContract), new FileSystemListener(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IContract)),Config.IncomingFilePath, Config.ProcessedFilePath)); listenerRuntime.AddListener(listener); listenerRuntime.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "Pass through", null, null, typeof(IContract), new ActionDispatcher((se, md) => { }), new PassThroughMessageFilter())); var dispatchTester = new ServiceBusTest(dispatchRuntime); var listenerTester = new ServiceBusTest(listenerRuntime); string message = "test this thing"; dispatchTester.StartAndStop(() => { dispatchRuntime.PublishOneWay(typeof(IContract), "PublishThis", message); listenerTester.WaitForDeliveries(1, TimeSpan.FromSeconds(10), () => { }); }); dispatchRuntime.RemoveSubscription(subscription); }
public void FileSystemDispatcher_Picks_Up_Existing_Messages() { BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement(); MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder; ServiceBusRuntime dispatchRuntime = new ServiceBusRuntime(new DirectDeliveryCore()); var subscription = new SubscriptionEndpoint(Guid.NewGuid(), "File System Dispatcher", null, null, typeof(IContract), new FileSystemDispatcher(new ConverterMessageDeliveryWriterFactory(encoder, typeof(IContract)), Config.IncomingFilePath), new PassThroughMessageFilter()); dispatchRuntime.Subscribe(subscription); ServiceBusRuntime listenerRuntime = new ServiceBusRuntime(new DirectDeliveryCore()); var listener = new ListenerEndpoint(Guid.NewGuid(), "File System Listener", null, null, typeof(IContract), new FileSystemListener(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IContract)), Config.IncomingFilePath, Config.ProcessedFilePath)); listenerRuntime.AddListener(listener); listenerRuntime.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "Pass through", null, null, typeof(IContract), new ActionDispatcher((se, md) => { }), new PassThroughMessageFilter())); var dispatchTester = new ServiceBusTest(dispatchRuntime); var listenerTester = new ServiceBusTest(listenerRuntime); string message = "test this thing"; dispatchTester.StartAndStop(() => { dispatchRuntime.PublishOneWay(typeof(IContract), "PublishThis", message); listenerTester.WaitForDeliveries(1, TimeSpan.FromSeconds(10), () => { }); }); dispatchRuntime.RemoveSubscription(subscription); }
public static ServiceBusRuntime MsmqRuntime <T>() { // Drop test queues if they already exist if (MsmqMessageDeliveryQueue.Exists(_testQueuePath)) { MsmqMessageDeliveryQueue.Delete(_testQueuePath); } if (MsmqMessageDeliveryQueue.Exists(_retryQueuePath)) { MsmqMessageDeliveryQueue.Delete(_retryQueuePath); } if (MsmqMessageDeliveryQueue.Exists(_failQueuePath)) { MsmqMessageDeliveryQueue.Delete(_failQueuePath); } // Create test queues MsmqMessageDeliveryQueue.Create(_testQueuePath); MsmqMessageDeliveryQueue.Create(_retryQueuePath); MsmqMessageDeliveryQueue.Create(_failQueuePath); BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement(); MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder; MessageDeliveryFormatter formatter = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(T)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(T))); MsmqMessageDeliveryQueue testQueue = new MsmqMessageDeliveryQueue(_testQueuePath, formatter); MsmqMessageDeliveryQueue retryQueue = new MsmqMessageDeliveryQueue(_retryQueuePath, formatter); MsmqMessageDeliveryQueue failQueue = new MsmqMessageDeliveryQueue(_failQueuePath, formatter); return(new ServiceBusRuntime(new QueuedDeliveryCore(testQueue, retryQueue, failQueue))); }
private static Message DeserialzieMessageFromStream(MemoryStream ms, MessageVersion messageVersion) { var bmebe = new BinaryMessageEncodingBindingElement(); bmebe.MessageVersion = messageVersion; bmebe.ReaderQuotas = XmlDictionaryReaderQuotas.Max; var bmef = bmebe.CreateMessageEncoderFactory(); return(bmef.Encoder.ReadMessage(ms, int.MaxValue)); }
private static Task <Message> DeserialzieMessageFromStreamAsync(MemoryStream ms, MessageVersion messageVersion) { var bmebe = new BinaryMessageEncodingBindingElement { MessageVersion = messageVersion, ReaderQuotas = XmlDictionaryReaderQuotas.Max }; MessageEncoderFactory bmef = bmebe.CreateMessageEncoderFactory(); return(bmef.Encoder.ReadMessageAsync(ms, int.MaxValue)); }
static void Main(string[] args) { // <Snippet0> // <Snippet1> var be = new BinaryMessageEncodingBindingElement(); // </Snippet1> // <Snippet2> be.MaxReadPoolSize = 16; // </Snippet2> // <Snippet3> be.MaxSessionSize = 2048; // </Snippet3> // <Snippet4> be.MaxWritePoolSize = 16; // </Snippet4> // <Snippet5> be.MessageVersion = MessageVersion.Default; // </Snippet5> // <Snippet6> XmlDictionaryReaderQuotas quotas = be.ReaderQuotas; // </Snippet6> // <Snippet7> var binding = new CustomBinding(); var bpCol = new BindingParameterCollection(); var context = new BindingContext(binding, bpCol); be.BuildChannelFactory <IDuplexChannel>(context); // </Snippet7> // <Snippet8> var binding2 = new CustomBinding(); var bpCol2 = new BindingParameterCollection(); var context2 = new BindingContext(binding2, bpCol2); be.BuildChannelListener <IDuplexChannel>(context2); // </Snippet8> // <Snippet9> be.CanBuildChannelListener <IDuplexChannel>(context2); // </Snippet9> // <Snippet10> BindingElement bindingElement = be.Clone(); // </Snippet10> // <Snippet11> MessageEncoderFactory mef = be.CreateMessageEncoderFactory(); // </Snippet11> // <Snippet12> MessageVersion mv = be.GetProperty <MessageVersion>(context); // </Snippet12> // </Snippet0> }
public RelayedOnewayAmqpListenerClient(BindingContext context, RelayedOnewayTransportBindingElement transportBindingElement, System.Uri uri, RelayedOnewayListener listener, EventTraceActivity activity) : base(context, transportBindingElement, uri, true, activity) { this.listener = listener; BinaryMessageEncodingBindingElement binaryMessageEncodingBindingElement = ClientMessageUtility.CreateInnerEncodingBindingElement(context); this.encoder = binaryMessageEncodingBindingElement.CreateMessageEncoderFactory().Encoder; this.messageWrapper = new MessageWrapper(this.encoder); this.bufferManager = BufferManager.CreateBufferManager(transportBindingElement.MaxBufferPoolSize, transportBindingElement.MaxBufferSize); base.IsListener = true; this.connectivitySettings = context.BindingParameters.Find <ConnectivitySettings>(); this.httpConnectivitySettings = context.BindingParameters.Find <HttpConnectivitySettings>(); }
private void CreateAndWriteMessage(byte[] bytes) { using (var stream = new MemoryStream(bytes, false)) { var mebe = new BinaryMessageEncodingBindingElement(); mebe.MessageVersion = MessageVersion.Soap12; mebe.ReaderQuotas.MaxArrayLength = XmlDictionaryReaderQuotas.Max.MaxArrayLength; mebe.ReaderQuotas.MaxDepth = XmlDictionaryReaderQuotas.Max.MaxDepth; mebe.ReaderQuotas.MaxStringContentLength = XmlDictionaryReaderQuotas.Max.MaxStringContentLength; var factory = mebe.CreateMessageEncoderFactory(); var msg = factory.Encoder.ReadMessage(stream, 1024 * 16); // I have no idea what header size to give it ... WriteMessage(msg); } }
private static MemoryStream SerializeMessageToStream(Message requestMessage) { var bmebe = new BinaryMessageEncodingBindingElement(); bmebe.MessageVersion = requestMessage.Version; bmebe.ReaderQuotas = XmlDictionaryReaderQuotas.Max; var bmef = bmebe.CreateMessageEncoderFactory(); var ms = new MemoryStream(64 * 1024); // 64K to keep out of LOH bmef.Encoder.WriteMessage(requestMessage, ms); ms.Position = 0; return(ms); }
public ChatServer() { BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement(); MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder; MessageDeliveryFormatter formatter = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IChatService)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(IChatService))); _serviceBus = new ServiceBusRuntime(new DirectDeliveryCore() , new WcfManagementService()); _serviceBus.AddListener(new ListenerEndpoint(Guid.NewGuid(), "Chat Service", "ChatServer", "http://localhost/chatServer", typeof(IChatService), new WcfServiceHostListener())); _serviceBus.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "No subscribers", "ChatClient", "", typeof(IChatService), new MethodDispatcher(new UnhandledReplyHandler(_serviceBus)), new UnhandledMessageFilter(typeof(SendMessageRequest)), true)); _serviceBus.UnhandledException+= (o, ex) => { Console.WriteLine("Unhandled Exception: "+ex.ExceptionObject); }; }
public ChatServer() { BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement(); MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder; MessageDeliveryFormatter formatter = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IChatService)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(IChatService))); _serviceBus = new ServiceBusRuntime(new DirectDeliveryCore(), new WcfManagementService()); _serviceBus.AddListener(new ListenerEndpoint(Guid.NewGuid(), "Chat Service", "ChatServer", "http://localhost/chatServer", typeof(IChatService), new WcfServiceHostListener())); _serviceBus.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "No subscribers", "ChatClient", "", typeof(IChatService), new MethodDispatcher(new UnhandledReplyHandler(_serviceBus)), new UnhandledMessageFilter(typeof(SendMessageRequest)), true)); _serviceBus.UnhandledException += (o, ex) => { Console.WriteLine("Unhandled Exception: " + ex.ExceptionObject); }; }
public void MessageContractFormatter_Can_Roundtrip_FaultContract() { recreateQueue(); BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement(); MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder; MessageDeliveryFormatter formatter = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(ISendDataContract)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(ISendDataContract))); MsmqMessageDeliveryQueue queue = new MsmqMessageDeliveryQueue(Config.TestQueuePath, formatter); string action = "sendFault"; FaultException <SendFault> outgoing = new FaultException <SendFault>(new SendFault() { Data = "This is a test" }); Dictionary <MessageDeliveryContextKey, object> context = new Dictionary <MessageDeliveryContextKey, object>(); context.Add(new MessageDeliveryContextKey("test"), "value"); MessageDelivery outgoingDelivery = new MessageDelivery(Guid.NewGuid(), typeof(ISendDataContract), action, outgoing, 5, new MessageDeliveryContext(context)); using (TransactionScope ts = new TransactionScope()) { queue.Enqueue(outgoingDelivery); ts.Complete(); } using (TransactionScope ts = new TransactionScope()) { MessageDelivery delivery = queue.Dequeue(TimeSpan.FromMinutes(1)); Assert.AreEqual(typeof(FaultException <SendFault>), delivery.Message.GetType()); FaultException <SendFault> incoming = (FaultException <SendFault>)delivery.Message; Assert.AreEqual(incoming.Data, outgoing.Data); Assert.AreEqual(context[new MessageDeliveryContextKey("test")], delivery.Context[new MessageDeliveryContextKey("test")]); Assert.AreEqual(outgoingDelivery.Action, delivery.Action); Assert.AreEqual(outgoingDelivery.ContractType, delivery.ContractType); Assert.AreEqual(outgoingDelivery.MaxRetries, delivery.MaxRetries); Assert.AreEqual(outgoingDelivery.MessageDeliveryId, delivery.MessageDeliveryId); Assert.AreEqual(outgoingDelivery.RetryCount, delivery.RetryCount); Assert.AreEqual(outgoingDelivery.TimeToProcess, delivery.TimeToProcess); Assert.AreEqual(outgoingDelivery.SubscriptionEndpointId, delivery.SubscriptionEndpointId); ts.Complete(); } }
void testMessageDelivery <T>(string messageAction, object messageData) { Type interfaceType = typeof(T); BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement(); MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder; MessageDeliveryFormatter formatter = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(T)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(T))); MsmqMessageDeliveryQueue queue = new MsmqMessageDeliveryQueue(Config.TestQueuePath, formatter); SubscriptionEndpoint endpoint = new SubscriptionEndpoint(Guid.NewGuid(), "SubscriptionName", "http://localhost/test", "SubscriptionConfigName", interfaceType, new WcfProxyDispatcher(), new PassThroughMessageFilter()); MessageDelivery enqueued = new MessageDelivery(endpoint.Id, interfaceType, messageAction, messageData, 3, new MessageDeliveryContext()); using (TransactionScope ts = new TransactionScope()) { queue.Enqueue(enqueued); ts.Complete(); } // Peek MessageDelivery dequeued = queue.Peek(TimeSpan.FromSeconds(30)); Assert.IsNotNull(dequeued); Assert.AreEqual(enqueued.Action, dequeued.Action); Assert.AreEqual(enqueued.SubscriptionEndpointId, dequeued.SubscriptionEndpointId); using (TransactionScope ts = new TransactionScope()) { // Pull for real dequeued = queue.Dequeue(TimeSpan.FromSeconds(30)); ts.Complete(); } Assert.IsNotNull(dequeued); Assert.AreEqual(enqueued.Action, dequeued.Action); Assert.AreEqual(enqueued.SubscriptionEndpointId, dequeued.SubscriptionEndpointId); // Should now be empty dequeued = queue.Peek(TimeSpan.FromSeconds(1)); Assert.IsNull(dequeued); }
static void TestWithUntypedMessage() { string baseAddress = SizedTcpDuplexTransportBindingElement.SizedTcpScheme + "://localhost:8000"; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); MessageEncodingBindingElement encodingBE = new BinaryMessageEncodingBindingElement(); Binding binding = new CustomBinding(encodingBE, new SizedTcpDuplexTransportBindingElement()); host.AddServiceEndpoint(typeof(IUntypedTest), binding, ""); host.Open(); Console.WriteLine("Host opened"); Socket socket = GetConnectedSocket(8000); Message input = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, "myAction", "Hello world"); input.Headers.To = new Uri(baseAddress); input.Headers.ReplyTo = new EndpointAddress("http://www.w3.org/2005/08/addressing/anonymous"); MessageEncoder encoder = encodingBE.CreateMessageEncoderFactory().Encoder; BufferManager bufferManager = BufferManager.CreateBufferManager(int.MaxValue, int.MaxValue); ArraySegment <byte> encoded = encoder.WriteMessage(input, int.MaxValue, bufferManager, 4); Formatting.SizeToBytes(encoded.Count, encoded.Array, 0); Console.WriteLine("Sending those bytes:"); Debugging.PrintBytes(encoded.Array, encoded.Count + encoded.Offset); socket.Send(encoded.Array, 0, encoded.Offset + encoded.Count, SocketFlags.None); byte[] recvBuffer = new byte[10000]; int bytesRecvd = socket.Receive(recvBuffer); Console.WriteLine("Received {0} bytes", bytesRecvd); Debugging.PrintBytes(recvBuffer, bytesRecvd); socket.Close(); Console.WriteLine("Press ENTER to close"); Console.ReadLine(); host.Close(); }
static void TestWithUntypedMessage() { string baseAddress = SizedTcpDuplexTransportBindingElement.SizedTcpScheme + "://localhost:8000"; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); MessageEncodingBindingElement encodingBE = new BinaryMessageEncodingBindingElement(); Binding binding = new CustomBinding(encodingBE, new SizedTcpDuplexTransportBindingElement()); host.AddServiceEndpoint(typeof(IUntypedTest), binding, ""); host.Open(); Console.WriteLine("Host opened"); Socket socket = GetConnectedSocket(8000); Message input = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, "myAction", "Hello world"); input.Headers.To = new Uri(baseAddress); input.Headers.ReplyTo = new EndpointAddress("http://www.w3.org/2005/08/addressing/anonymous"); MessageEncoder encoder = encodingBE.CreateMessageEncoderFactory().Encoder; BufferManager bufferManager = BufferManager.CreateBufferManager(int.MaxValue, int.MaxValue); ArraySegment<byte> encoded = encoder.WriteMessage(input, int.MaxValue, bufferManager, 4); Formatting.SizeToBytes(encoded.Count, encoded.Array, 0); Console.WriteLine("Sending those bytes:"); Debugging.PrintBytes(encoded.Array, encoded.Count + encoded.Offset); socket.Send(encoded.Array, 0, encoded.Offset + encoded.Count, SocketFlags.None); byte[] recvBuffer = new byte[10000]; int bytesRecvd = socket.Receive(recvBuffer); Console.WriteLine("Received {0} bytes", bytesRecvd); Debugging.PrintBytes(recvBuffer, bytesRecvd); socket.Close(); Console.WriteLine("Press ENTER to close"); Console.ReadLine(); host.Close(); }
public bool TryReceive(TimeSpan timeout, out Message message) { this.ThrowIfDisposed(); message = null; if (this.State == CommunicationState.Closed || this.State == CommunicationState.Closing) return true; var serviceOperationMessage = ((Queue)this.queue).Receive<ServiceOperationMessage>(); if (serviceOperationMessage == null) return false; var binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement(); var messageEncoderFactory = binaryMessageEncodingBindingElement.CreateMessageEncoderFactory(); var messageEncoder = messageEncoderFactory.Encoder; using (var memoryStream = new MemoryStream(serviceOperationMessage.OperationData)) { var streamedMessage = messageEncoder.ReadMessage(memoryStream, int.MaxValue); var bufferedCopy = streamedMessage.CreateBufferedCopy(int.MaxValue); message = bufferedCopy.CreateMessage(); } if (!message.Headers.Any(x => x.Name == "To" && x.Namespace == "http://www.w3.org/2005/08/addressing")) message.Headers.Add(MessageHeader.CreateHeader("To", "http://www.w3.org/2005/08/addressing", this.LocalAddress.Uri)); return true; }
public ListenerControl(WriteToLogDelegate writeToLog, Func<Task> stopLog, Action startLog, ServiceBusHelper serviceBusHelper, EntityDescription entityDescription) { this.logStopped = false; Task.Factory.StartNew(AsyncTrackMessage).ContinueWith(t => { if (t.IsFaulted && t.Exception != null) { writeToLog(t.Exception.Message); } }); this.writeToLog = writeToLog; this.stopLog = stopLog; this.startLog = startLog; this.serviceBusHelper = serviceBusHelper; this.entityDescription = entityDescription; var element = new BinaryMessageEncodingBindingElement(); var encoderFactory = element.CreateMessageEncoderFactory(); encoder = encoderFactory.Encoder; InitializeComponent(); InitializeControls(); Disposed += ListenerControl_Disposed; if (entityDescription is SubscriptionDescription) { grouperEntityInformation.GroupTitle = "Subscription Information"; } }
public void Send(Message message) { var bufferedCopy = message.CreateBufferedCopy(int.MaxValue); var messageToStream = bufferedCopy.CreateMessage(); var binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement(); var messageEncoderFactory = binaryMessageEncodingBindingElement.CreateMessageEncoderFactory(); var messageEncoder = messageEncoderFactory.Encoder; byte[] messageData; using (var memoryStream = new MemoryStream()) { messageEncoder.WriteMessage(messageToStream, memoryStream); messageData = memoryStream.ToArray(); } this.queue.Send(new ServiceOperationMessage {OperationData = messageData}); }
/// <summary> /// Reads the content of the EventData passed as argument. /// </summary> /// <param name="eventDataToRead">The EventData to read.</param> /// <param name="bodyType">BodyType</param> /// <returns>The content of the EventData.</returns> public string GetMessageText(EventData eventDataToRead, out BodyType bodyType) { string eventDataText = null; Stream stream = null; bodyType = BodyType.Stream; if (eventDataToRead == null) { return null; } var inboundMessage = eventDataToRead.Clone(); try { stream = inboundMessage.GetBody<Stream>(); if (stream != null) { var element = new BinaryMessageEncodingBindingElement { ReaderQuotas = new XmlDictionaryReaderQuotas { MaxArrayLength = int.MaxValue, MaxBytesPerRead = int.MaxValue, MaxDepth = int.MaxValue, MaxNameTableCharCount = int.MaxValue, MaxStringContentLength = int.MaxValue } }; var encoderFactory = element.CreateMessageEncoderFactory(); var encoder = encoderFactory.Encoder; var stringBuilder = new StringBuilder(); var eventData = encoder.ReadMessage(stream, MaxBufferSize); using (var reader = eventData.GetReaderAtBodyContents()) { // The XmlWriter is used just to indent the XML eventData var settings = new XmlWriterSettings { Indent = true }; using (var writer = XmlWriter.Create(stringBuilder, settings)) { writer.WriteNode(reader, true); } } eventDataText = stringBuilder.ToString(); bodyType = BodyType.Wcf; } } catch (Exception) { inboundMessage = eventDataToRead.Clone(); try { stream = inboundMessage.GetBody<Stream>(); if (stream != null) { var element = new BinaryMessageEncodingBindingElement { ReaderQuotas = new XmlDictionaryReaderQuotas { MaxArrayLength = int.MaxValue, MaxBytesPerRead = int.MaxValue, MaxDepth = int.MaxValue, MaxNameTableCharCount = int.MaxValue, MaxStringContentLength = int.MaxValue } }; var encoderFactory = element.CreateMessageEncoderFactory(); var encoder = encoderFactory.Encoder; var eventData = encoder.ReadMessage(stream, MaxBufferSize); using (var reader = eventData.GetReaderAtBodyContents()) { eventDataText = reader.ReadString(); } bodyType = BodyType.Wcf; } } catch (Exception) { try { if (stream != null) { try { stream.Seek(0, SeekOrigin.Begin); var serializer = new CustomDataContractBinarySerializer(typeof(string)); eventDataText = serializer.ReadObject(stream) as string; bodyType = BodyType.String; } catch (Exception) { try { stream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(stream)) { eventDataText = reader.ReadToEnd(); if (eventDataText.ToCharArray().GroupBy(c => c). Where(g => char.IsControl(g.Key) && g.Key != '\t' && g.Key != '\n' && g.Key != '\r'). Select(g => g.First()).Any()) { stream.Seek(0, SeekOrigin.Begin); using (var binaryReader = new BinaryReader(stream)) { var bytes = binaryReader.ReadBytes((int)stream.Length); eventDataText = BitConverter.ToString(bytes).Replace('-', ' '); } } } } catch (Exception) { eventDataText = UnableToReadMessageBody; } } } else { eventDataText = UnableToReadMessageBody; } } catch (Exception) { eventDataText = UnableToReadMessageBody; } } } return eventDataText; }
/// <summary> /// Reads the message contained in a stream. /// </summary> /// <param name="stream">The stream containing the message.</param> /// <param name="isBinary">Indicates if the body is binary or not.</param> /// <returns>The message.</returns> private static string GetMessageText(Stream stream, bool isBinary = false) { string messageText; if (stream == null) { return null; } try { var element = new BinaryMessageEncodingBindingElement { ReaderQuotas = new XmlDictionaryReaderQuotas { MaxArrayLength = int.MaxValue, MaxBytesPerRead = int.MaxValue, MaxDepth = int.MaxValue, MaxNameTableCharCount = int.MaxValue, MaxStringContentLength = int.MaxValue } }; var encoderFactory = element.CreateMessageEncoderFactory(); var encoder = encoderFactory.Encoder; var stringBuilder = new StringBuilder(); var message = encoder.ReadMessage(stream, MaxBufferSize); using (var reader = message.GetReaderAtBodyContents()) { // The XmlWriter is used just to indent the XML message var settings = new XmlWriterSettings { Indent = true }; using (var writer = XmlWriter.Create(stringBuilder, settings)) { writer.WriteNode(reader, true); } } messageText = stringBuilder.ToString(); } catch (Exception) { try { stream.Seek(0, SeekOrigin.Begin); var element = new BinaryMessageEncodingBindingElement { ReaderQuotas = new XmlDictionaryReaderQuotas { MaxArrayLength = int.MaxValue, MaxBytesPerRead = int.MaxValue, MaxDepth = int.MaxValue, MaxNameTableCharCount = int.MaxValue, MaxStringContentLength = int.MaxValue } }; var encoderFactory = element.CreateMessageEncoderFactory(); var encoder = encoderFactory.Encoder; var message = encoder.ReadMessage(stream, MaxBufferSize); using (var reader = message.GetReaderAtBodyContents()) { messageText = reader.ReadString(); } } catch (Exception) { try { stream.Seek(0, SeekOrigin.Begin); var serializer = new CustomDataContractBinarySerializer(typeof(string)); messageText = serializer.ReadObject(stream) as string; } catch (Exception) { try { stream.Seek(0, SeekOrigin.Begin); if (isBinary) { using (var binaryReader = new BinaryReader(stream)) { var bytes = binaryReader.ReadBytes((int)stream.Length); messageText = BitConverter.ToString(bytes).Replace('-', ' '); } } else { using (var reader = new StreamReader(stream)) { messageText = reader.ReadToEnd(); if (messageText.ToCharArray().GroupBy(c => c). Where(g => char.IsControl(g.Key) && g.Key != '\t' && g.Key != '\n' && g.Key != '\r'). Select(g => g.First()).Any()) { stream.Seek(0, SeekOrigin.Begin); using (var binaryReader = new BinaryReader(stream)) { var bytes = binaryReader.ReadBytes((int)stream.Length); messageText = BitConverter.ToString(bytes).Replace('-', ' '); } } } } } catch (Exception) { messageText = UnableToReadMessageBody; } } } } return messageText; }
/// <summary> /// Reads the content of the BrokeredMessage passed as argument. /// </summary> /// <param name="messageToRead">The BrokeredMessage to read.</param> /// <returns>The content of the BrokeredMessage.</returns> private static string GetMessageText(BrokeredMessage messageToRead) { string messageText = null; Stream stream = null; if (messageToRead == null) { return(null); } var inboundMessage = messageToRead.Clone(); try { stream = inboundMessage.GetBody <Stream>(); if (stream != null) { var element = new BinaryMessageEncodingBindingElement { ReaderQuotas = new XmlDictionaryReaderQuotas { MaxArrayLength = int.MaxValue, MaxBytesPerRead = int.MaxValue, MaxDepth = int.MaxValue, MaxNameTableCharCount = int.MaxValue, MaxStringContentLength = int.MaxValue } }; var encoderFactory = element.CreateMessageEncoderFactory(); var encoder = encoderFactory.Encoder; var stringBuilder = new StringBuilder(); var message = encoder.ReadMessage(stream, MaxBufferSize); using (var reader = message.GetReaderAtBodyContents()) { // The XmlWriter is used just to indent the XML message var settings = new XmlWriterSettings { Indent = true }; using (var xmlWriter = XmlWriter.Create(stringBuilder, settings)) { xmlWriter.WriteNode(reader, true); } } messageText = stringBuilder.ToString(); } } catch (Exception) { inboundMessage = messageToRead.Clone(); try { stream = inboundMessage.GetBody <Stream>(); if (stream != null) { var element = new BinaryMessageEncodingBindingElement { ReaderQuotas = new XmlDictionaryReaderQuotas { MaxArrayLength = int.MaxValue, MaxBytesPerRead = int.MaxValue, MaxDepth = int.MaxValue, MaxNameTableCharCount = int.MaxValue, MaxStringContentLength = int.MaxValue } }; var encoderFactory = element.CreateMessageEncoderFactory(); var encoder = encoderFactory.Encoder; var message = encoder.ReadMessage(stream, MaxBufferSize); using (var reader = message.GetReaderAtBodyContents()) { messageText = reader.ReadString(); } } } catch (Exception) { try { if (stream != null) { try { stream.Seek(0, SeekOrigin.Begin); var serializer = new CustomDataContractBinarySerializer(typeof(string)); messageText = serializer.ReadObject(stream) as string; } catch (Exception) { try { stream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(stream)) { messageText = reader.ReadToEnd(); if (messageText.ToCharArray().GroupBy(c => c). Where(g => char.IsControl(g.Key) && g.Key != '\t' && g.Key != '\n' && g.Key != '\r'). Select(g => g.First()).Any()) { stream.Seek(0, SeekOrigin.Begin); using (var binaryReader = new BinaryReader(stream)) { var bytes = binaryReader.ReadBytes((int)stream.Length); messageText = BitConverter.ToString(bytes).Replace('-', ' '); } } } } catch (Exception) { messageText = UnableToReadMessageBody; } } } else { messageText = UnableToReadMessageBody; } } catch (Exception) { messageText = UnableToReadMessageBody; } } } return(messageText); }