public virtual Task SendAsync(ArraySegment<byte> message, WebSocketMessageType messageType, bool endOfMessage = true)
        {
            if (WebSocket.State != WebSocketState.Open)
            {
                return TaskAsyncHelper.Empty;
            }

            var sendContext = new SendContext(this, message, messageType, endOfMessage);

            return _sendQueue.Enqueue(async state =>
            {
                var context = (SendContext)state;

                if (context.Handler.WebSocket.State != WebSocketState.Open)
                {
                    return;
                }

                try
                {
                    await context.Handler.WebSocket.SendAsync(context.Message, context.MessageType, context.EndOfMessage, CancellationToken.None);
                }
                catch (Exception ex)
                {
                    // Swallow exceptions on send
                    Trace.TraceError("Error while sending: " + ex);
                }
            },
            sendContext);
        }
        public override Task Send(PersistentResponse response)
        {
            OnSendingResponse(response);

            var context = new SendContext(this, response);

            // Ensure delegate continues to use the C# Compiler static delegate caching optimization.
            return EnqueueOperation(state => PerformSend(state), context);
        }
        /// <summary>
        /// Returns a stream with the encryption bits in place to ensure proper message encryption
        /// </summary>
        /// <param name="provider">The crypto stream provider</param>
        /// <param name="stream">The original stream to which the encrypted message content is written</param>
        /// <param name="context">The second context of the message</param>
        /// <returns>A stream for serializing the message which will be encrypted</returns>
        public static Stream GetEncryptStream(this ICryptoStreamProvider provider, Stream stream, SendContext context)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));

            object keyIdObj;
            string keyId = context.Headers.TryGetHeader(EncryptedMessageSerializer.EncryptionKeyHeader, out keyIdObj)
                ? keyIdObj.ToString()
                : default(string);

            return provider.GetEncryptStream(stream, keyId, CryptoStreamMode.Write);
        }
Exemple #4
0
        Task IFilter <SendContext <T> > .Send(SendContext <T> context, IPipe <SendContext <T> > next)
        {
            var transformContext = new SendTransformContext <T>(context);

            TransformResult <T> result = _transform.ApplyTo(transformContext);

            if (result.IsNewValue)
            {
                var transformedContext = context.CreateProxy(result.Value);

                return(next.Send(transformedContext));
            }

            return(next.Send(context));
        }
        static Header[] GetHeaders <T>(SendContext context)
        {
            var headers = new List <Header>();

            headers.Add(MessageTypeKey, new MessageUrn(typeof(T)));
            headers.Add(new Header(PolymorphicMessageTypesKey, string.Join(";", TypeMetadataCache <T> .MessageTypeNames)));

            if (context.CorrelationId.HasValue)
            {
                headers.Add(RequestIdKey, context.CorrelationId.Value.ToString());
            }
            if (context.RequestId.HasValue)
            {
                headers.Add(RequestIdKey, context.RequestId.Value.ToString());
            }
            if (context.ConversationId.HasValue)
            {
                headers.Add(ConversationIdKey, context.ConversationId.Value.ToString());
            }
            if (context.InitiatorId.HasValue)
            {
                headers.Add(InitiatorIdKey, context.InitiatorId.Value.ToString());
            }

            headers.Add(SourceAddressKey, context.SourceAddress);
            headers.Add(DestinationAddressKey, context.DestinationAddress);

            if (context.ResponseAddress != null)
            {
                headers.Add(ResponseAddressKey, context.ResponseAddress);
            }
            if (context.FaultAddress != null)
            {
                headers.Add(FaultAddressKey, context.FaultAddress);
            }

            if (context.TimeToLive.HasValue)
            {
                headers.Add(ExpirationTimeKey, DateTime.UtcNow + context.TimeToLive.Value);
            }

            headers.Add(SentTimeKey, DateTime.UtcNow);

            headers.Add(new Header(HostInfoKey, HostMetadataCache.Host));

            return(headers.ToArray());
        }
        public JsonMessageEnvelope CreateJsonMessageEnvelope <T>(SendContext <T> context) where T : class
        {
            var container = context.Message as MessageContainer;

            if (container == null)
            {
                throw new ArgumentException("Message must be MessageContainer type");
            }

            var separatorIndex = container.MessageType.LastIndexOf('.');
            var classNamespace = container.MessageType.Substring(0, separatorIndex);
            var className      = container.MessageType.Substring(separatorIndex + 1);

            var messageType = $"urn:message:{classNamespace}:{className}";

            return(new JsonMessageEnvelope(context, container.Message, new[] { messageType }));
        }
Exemple #7
0
        public static Error ProcessOnSend(
            ILayerStack layerStack, MessageType messageType, SendContext sendContext, out IBonded layerData, Logger logger)
        {
            Error error = null;
            layerData = null;

            if (layerStack != null)
            {
                error = layerStack.OnSend(messageType, sendContext, out layerData);
                if (error != null)
                {
                    logger.Site().Warning("Layer error occurred sending message of type {0} (Code: {1} Message: {2}).",
                        messageType, error.error_code, error.message);
                }
            }

            return error;
        }
        public JsonMessageEnvelope(SendContext context, object message, string[] messageTypeNames)
        {
            if (context.MessageId.HasValue)
                MessageId = context.MessageId.Value.ToString();

            if (context.RequestId.HasValue)
                RequestId = context.RequestId.Value.ToString();

            if (context.CorrelationId.HasValue)
                CorrelationId = context.CorrelationId.Value.ToString();

            if (context.ConversationId.HasValue)
                ConversationId = context.ConversationId.Value.ToString();

            if (context.InitiatorId.HasValue)
                InitiatorId = context.InitiatorId.Value.ToString();

            if (context.SourceAddress != null)
                SourceAddress = context.SourceAddress.ToString();

            if (context.DestinationAddress != null)
                DestinationAddress = context.DestinationAddress.ToString();

            if (context.ResponseAddress != null)
                ResponseAddress = context.ResponseAddress.ToString();

            if (context.FaultAddress != null)
                FaultAddress = context.FaultAddress.ToString();

            MessageType = messageTypeNames;

            Message = message;

            if (context.TimeToLive.HasValue)
                ExpirationTime = DateTime.UtcNow + context.TimeToLive;

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

            foreach (var header in context.Headers.GetAll())
                Headers[header.Key] = header.Value;

            Host = HostMetadataCache.Host;
        }
Exemple #9
0
        static void SetRawJsonMessageHeaders <T>(SendContext context)
            where T : class
        {
            if (context.MessageId.HasValue)
            {
                context.Headers.Set(MessageHeaders.MessageId, context.MessageId.Value.ToString());
            }

            if (context.CorrelationId.HasValue)
            {
                context.Headers.Set(MessageHeaders.CorrelationId, context.CorrelationId.Value.ToString());
            }

            if (context.ConversationId.HasValue)
            {
                context.Headers.Set(MessageHeaders.ConversationId, context.ConversationId.Value.ToString());
            }

            context.Headers.Set(MessageHeaders.MessageType, string.Join(";", TypeMetadataCache <T> .MessageTypeNames));

            if (context.ResponseAddress != null)
            {
                context.Headers.Set(MessageHeaders.ResponseAddress, context.ResponseAddress);
            }

            if (context.FaultAddress != null)
            {
                context.Headers.Set(MessageHeaders.FaultAddress, context.FaultAddress);
            }

            if (context.InitiatorId.HasValue)
            {
                context.Headers.Set(MessageHeaders.InitiatorId, context.InitiatorId.Value.ToString());
            }

            if (context.SourceAddress != null)
            {
                context.Headers.Set(MessageHeaders.SourceAddress, context.SourceAddress);
            }

            context.Headers.Set(MessageHeaders.ContentType, ContentTypeHeaderValue);
            context.Headers.Set(MessageHeaders.Host.Info, JsonConvert.SerializeObject(HostMetadataCache.Host, Formatting.None));
        }
		public void The_endpoint_consumer_should_be_returned()
		{
			var endpoint = MockRepository.GenerateMock<IEndpoint>();
			endpoint.Stub(x => x.Address.Uri).Return(new Uri("msmq://localhost/queue_name"));

			_pipeline.ConnectEndpoint<PingMessage>(endpoint);

			PipelineViewer.Trace(_pipeline);

			var message = new PingMessage();

			var context = new SendContext<PingMessage>(message);

			endpoint.Expect(x => x.Send(context)).IgnoreArguments();

			_pipeline.Dispatch(message);

			endpoint.VerifyAllExpectations();
		}
        internal Task SendAsync(ArraySegment<byte> message, WebSocketMessageType messageType, bool endOfMessage = true)
        {
            if (_isClosed)
            {
                return TaskAsyncHelper.Empty;
            }

            var sendContext = new SendContext(this, message, messageType, endOfMessage);

            return _sendQueue.Enqueue(state =>
            {
                var context = (SendContext)state;

                if (context.Handler._isClosed)
                {
                    return TaskAsyncHelper.Empty;
                }

                return context.Handler.WebSocket.SendAsync(context.Message, context.MessageType, context.EndOfMessage, CancellationToken.None);
            },
            sendContext);
        }
        protected override Task Send(int streamIndex, IList<Message> messages)
        {
            var context = new SendContext(_key, messages, _connection);

            // Increment the channel number
            return _connection.Strings.Increment(_db, _key)
                               .Then((id, ctx) =>
                               {
                                   byte[] data = RedisMessage.ToBytes(id, ctx.Messages);

                                   return ctx.Connection.Publish(ctx.Key, data);
                               },
                               context);
        }
        public Task Send(Func<object, Task> send, object state)
        {
            lock (_lockObj)
            {
                if (_error != null)
                {
                    throw _error;
                }

                // If the queue is closed then stop sending
                if (_state == StreamState.Closed)
                {
                    throw new InvalidOperationException(Resources.Error_StreamClosed);
                }

                var context = new SendContext(this, send, state);

                if (_initializeDrainTask != null && !_initializeDrainTask.IsCompleted)
                {
                    // Wait on the draining of the queue before proceeding with the send
                    // NOTE: Calling .Wait() here is safe because the task wasn't created on an ASP.NET request thread
                    //       and thus has no captured sync context
                    _initializeDrainTask.Wait();
                }

                if (UsingTaskQueue)
                {
                    Task task = _queue.Enqueue(Send, context);

                    if (task == null)
                    {
                        // The task is null if the queue is full
                        throw new InvalidOperationException(Resources.Error_TaskQueueFull);
                    }

                    // Always observe the task in case the user doesn't handle it
                    return task.Catch(_logger);
                }

                return Send(context);
            }
        }
Exemple #14
0
 public void Send(EndPoint endPoint, byte[] buffer, int offset, int count)
 {
     _logger.Debug("Sending " + count + " bytes to " + endPoint + ":\r\n" +
                   Encoding.ASCII.GetString(buffer, 0, count));
     var context = new SendContext(endPoint, buffer);
     _socket.BeginSendTo(buffer, 0, count, SocketFlags.None, endPoint, OnSendComplete,
                         context);
 }
        public Task Send(int streamIndex, IList<Message> messages)
        {
            var context = new SendContext(this, streamIndex, messages);

            return _streams[streamIndex].Send(state => Send(state), context);
        }
Exemple #16
0
		void Data (FormatOptions options, MimeMessage message, CancellationToken cancellationToken, ITransferProgress progress)
		{
			var response = SendCommand ("DATA", cancellationToken);

			if (response.StatusCode != SmtpStatusCode.StartMailInput)
				throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);

			if (progress != null) {
				var ctx = new SendContext (progress, null);

				using (var stream = new ProgressStream (Stream, ctx.Update)) {
					using (var filtered = new FilteredStream (stream)) {
						filtered.Add (new SmtpDataFilter ());

						message.WriteTo (options, filtered, cancellationToken);
						filtered.Flush ();
					}
				}
			} else {
				using (var filtered = new FilteredStream (Stream)) {
					filtered.Add (new SmtpDataFilter ());

					message.WriteTo (options, filtered, cancellationToken);
					filtered.Flush ();
				}
			}

			Stream.Write (EndData, 0, EndData.Length, cancellationToken);
			Stream.Flush (cancellationToken);

			response = Stream.ReadResponse (cancellationToken);

			switch (response.StatusCode) {
			default:
				throw new SmtpCommandException (SmtpErrorCode.MessageNotAccepted, response.StatusCode, response.Response);
			case SmtpStatusCode.AuthenticationRequired:
				throw new ServiceNotAuthenticatedException (response.Response);
			case SmtpStatusCode.Ok:
				OnMessageSent (new MessageSentEventArgs (message, response.Response));
				break;
			}
		}
Exemple #17
0
		void Bdat (FormatOptions options, MimeMessage message, CancellationToken cancellationToken, ITransferProgress progress)
		{
			long size;

			using (var measure = new MeasuringStream ()) {
				message.WriteTo (options, measure, cancellationToken);
				size = measure.Length;
			}

			var bytes = Encoding.UTF8.GetBytes (string.Format ("BDAT {0} LAST\r\n", size));

			Stream.Write (bytes, 0, bytes.Length, cancellationToken);

			if (progress != null) {
				var ctx = new SendContext (progress, size);

				using (var stream = new ProgressStream (Stream, ctx.Update)) {
					message.WriteTo (options, stream, cancellationToken);
					stream.Flush (cancellationToken);
				}
			} else {
				message.WriteTo (options, Stream, cancellationToken);
				Stream.Flush (cancellationToken);
			}

			var response = Stream.ReadResponse (cancellationToken);

			switch (response.StatusCode) {
			default:
				throw new SmtpCommandException (SmtpErrorCode.MessageNotAccepted, response.StatusCode, response.Response);
			case SmtpStatusCode.AuthenticationRequired:
				throw new ServiceNotAuthenticatedException (response.Response);
			case SmtpStatusCode.Ok:
				OnMessageSent (new MessageSentEventArgs (message, response.Response));
				break;
			}
		}
        public void TransportSendAndReceive()
        {
            using (var management = new RabbitMqEndpointManagement(_queue))
            {
                management.BindQueue(_queue.Name, _exchange.Name, ExchangeType.Fanout, "", null);
            }

            IOutboundTransport t = _factory.BuildOutbound(new TransportSettings(_exchange));
            var context = new SendContext<string>("dru");
            context.SetBodyWriter(stream =>
                {
                    byte[] buffer = Encoding.UTF8.GetBytes(context.Message);
                    stream.Write(buffer, 0, buffer.Length);
                });
            t.Send(context);

            IInboundTransport i = _factory.BuildInbound(new TransportSettings(_queue));

            i.Receive(s =>
                {
                    return ss =>
                        {
                            string name;
                            using (var stream = new MemoryStream())
                            {
                                ss.CopyBodyTo(stream);

                                name = Encoding.UTF8.GetString(stream.ToArray());
                            }

                            Assert.AreEqual("dru", name);
                            Console.WriteLine(name);
                        };
                }, 1.Minutes());
        }
Exemple #19
0
        public Task Send(Func<object, Task> send, object state)
        {
            lock (_lockObj)
            {
                if (_error != null)
                {
                    throw _error;
                }

                // If the queue is closed then stop sending
                if (_state == StreamState.Closed)
                {
                    throw new InvalidOperationException(Resources.Error_StreamClosed);
                }

                if (_state == StreamState.Initial)
                {
                    throw new InvalidOperationException(Resources.Error_StreamNotOpen);
                }

                var context = new SendContext(this, send, state);

                if (UsingTaskQueue)
                {
                    Task task = _queue.Enqueue(Send, context);

                    if (task == null)
                    {
                        // The task is null if the queue is full
                        throw new InvalidOperationException(Resources.Error_TaskQueueFull);
                    }

                    // Always observe the task in case the user doesn't handle it
                    return task.Catch();
                }

                _perfCounters.ScaleoutSendQueueLength.Increment();
                return Send(context).Finally(counter =>
                {
                    ((IPerformanceCounter)counter).Decrement();
                }, 
                _perfCounters.ScaleoutSendQueueLength);
            }
        }