ToWireFormattedString() public static method

Converts the DateTime to a string suitable for transport over the wire.
public static ToWireFormattedString ( System.DateTime dateTime ) : string
dateTime System.DateTime
return string
        public async Task <int> Retry(IncomingMessage message, TimeSpan delay, TransportTransaction transportTransaction)
        {
            var outgoingMessage = new OutgoingMessage(message.MessageId, new Dictionary <string, string>(message.Headers), message.Body);

            var currentDelayedRetriesAttempt = message.GetDelayedDeliveriesPerformed() + 1;

            outgoingMessage.SetCurrentDelayedDeliveries(currentDelayedRetriesAttempt);
            outgoingMessage.SetDelayedDeliveryTimestamp(DateTime.UtcNow);

            UnicastAddressTag         messageDestination;
            List <DeliveryConstraint> deliveryConstraints = null;

            if (timeoutManagerAddress == null)
            {
                // transport supports native deferred messages, directly send to input queue with delay constraint:
                deliveryConstraints = new List <DeliveryConstraint>(1)
                {
                    new DelayDeliveryWith(delay)
                };
                messageDestination = new UnicastAddressTag(endpointInputQueue);
            }
            else
            {
                // transport doesn't support native deferred messages, reroute to timeout manager:
                outgoingMessage.Headers[TimeoutManagerHeaders.RouteExpiredTimeoutTo] = endpointInputQueue;
                outgoingMessage.Headers[TimeoutManagerHeaders.Expire] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow + delay);
                messageDestination = new UnicastAddressTag(timeoutManagerAddress);
            }

            var transportOperations = new TransportOperations(new TransportOperation(outgoingMessage, messageDestination, deliveryConstraints: deliveryConstraints));

            await dispatcher.Dispatch(transportOperations, transportTransaction, new ContextBag()).ConfigureAwait(false);

            return(currentDelayedRetriesAttempt);
        }
Example #2
0
        internal static void SetExceptionHeaders(Dictionary <string, string> headers, Exception e, Address failedQueue, string reason, bool legacyStackTrace)
        {
            if (!string.IsNullOrWhiteSpace(reason))
            {
                headers["NServiceBus.ExceptionInfo.Reason"] = reason;
            }
            headers["NServiceBus.ExceptionInfo.ExceptionType"] = e.GetType().FullName;

            if (e.InnerException != null)
            {
                headers["NServiceBus.ExceptionInfo.InnerExceptionType"] = e.InnerException.GetType().FullName;
            }

            headers["NServiceBus.ExceptionInfo.HelpLink"] = e.HelpLink;
            headers["NServiceBus.ExceptionInfo.Message"]  = e.GetMessage();
            headers["NServiceBus.ExceptionInfo.Source"]   = e.Source;
            if (legacyStackTrace)
            {
                headers["NServiceBus.ExceptionInfo.StackTrace"] = e.StackTrace;
            }
            else
            {
                headers["NServiceBus.ExceptionInfo.StackTrace"] = e.ToString();
            }
            headers[FaultsHeaderKeys.FailedQ]    = failedQueue.ToString();
            headers["NServiceBus.TimeOfFailure"] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
        }
        public async Task Invoke(MessageContext context)
        {
            var timeoutId = context.Headers["Timeout.Id"];

            var timeoutData = await persister.Peek(timeoutId, context.Extensions).ConfigureAwait(false);

            if (timeoutData == null)
            {
                return;
            }

            timeoutData.Headers[Headers.TimeSent] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
            timeoutData.Headers["NServiceBus.RelatedToTimeoutId"] = timeoutData.Id;

            var outgoingMessage    = new OutgoingMessage(context.MessageId, timeoutData.Headers, timeoutData.State);
            var transportOperation = new TransportOperation(outgoingMessage, new UnicastAddressTag(timeoutData.Destination), dispatchConsistency);
            await dispatcher.Dispatch(new TransportOperations(transportOperation), context.TransportTransaction, context.Extensions).ConfigureAwait(false);

            var timeoutRemoved = await persister.TryRemove(timeoutId, context.Extensions).ConfigureAwait(false);

            if (!timeoutRemoved)
            {
                // timeout was concurrently removed between Peek and TryRemove. Throw an exception to rollback the dispatched message if possible.
                throw new Exception($"timeout '{timeoutId}' was concurrently processed.");
            }
        }
Example #4
0
        public static void SetExceptionHeaders(Dictionary <string, string> headers, Exception e)
        {
            headers["NServiceBus.ExceptionInfo.ExceptionType"] = e.GetType().FullName;

            if (e.InnerException != null)
            {
                headers["NServiceBus.ExceptionInfo.InnerExceptionType"] = e.InnerException.GetType().FullName;
            }

            headers["NServiceBus.ExceptionInfo.HelpLink"]   = e.HelpLink;
            headers["NServiceBus.ExceptionInfo.Message"]    = e.GetMessage().Truncate(16384);
            headers["NServiceBus.ExceptionInfo.Source"]     = e.Source;
            headers["NServiceBus.ExceptionInfo.StackTrace"] = e.ToString();
            headers["NServiceBus.TimeOfFailure"]            = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);

            // ReSharper disable once ConditionIsAlwaysTrueOrFalse
            if (e.Data == null)
            // ReSharper disable HeuristicUnreachableCode
            {
                return;
            }
            // ReSharper restore HeuristicUnreachableCode
#pragma warning disable DE0006
            foreach (DictionaryEntry entry in e.Data)
#pragma warning restore DE0006
            {
                if (entry.Value == null)
                {
                    continue;
                }
                headers["NServiceBus.ExceptionInfo.Data." + entry.Key] = entry.Value.ToString();
            }
        }
        static void SerializeDeliveryConstraint(DeliveryConstraint constraint, Dictionary <string, string> options)
        {
            if (constraint is NonDurableDelivery)
            {
                options["NonDurable"] = true.ToString();
                return;
            }
            if (constraint is DoNotDeliverBefore doNotDeliverBefore)
            {
                options["DeliverAt"] = DateTimeExtensions.ToWireFormattedString(doNotDeliverBefore.At);
                return;
            }

            if (constraint is DelayDeliveryWith delayDeliveryWith)
            {
                options["DelayDeliveryFor"] = delayDeliveryWith.Delay.ToString();
                return;
            }

            if (constraint is DiscardIfNotReceivedBefore discard)
            {
                options["TimeToBeReceived"] = discard.MaxTime.ToString();
                return;
            }

            throw new Exception($"Unknown delivery constraint {constraint.GetType().FullName}");
        }
Example #6
0
        public override AddressTag Apply(Dictionary <string, string> headers)
        {
            headers[TimeoutManagerHeaders.RouteExpiredTimeoutTo] = ultimateDestination;
            headers[TimeoutManagerHeaders.Expire] = DateTimeExtensions.ToWireFormattedString(deliverAt);

            return(new UnicastAddressTag(timeoutManagerAddress));
        }
        protected override Task Terminate(IUnsubscribeContext context)
        {
            var eventType = context.EventType;

            var publisherAddresses = subscriptionRouter.GetAddressesForEventType(eventType);

            if (publisherAddresses.Count == 0)
            {
                throw new Exception($"No publisher address could be found for message type {eventType}. Ensure the configured publisher endpoint has at least one known instance.");
            }

            var unsubscribeTasks = new List <Task>(publisherAddresses.Count);

            foreach (var publisherAddress in publisherAddresses)
            {
                Logger.Debug("Unsubscribing to " + eventType.AssemblyQualifiedName + " at publisher queue " + publisherAddress);

                var unsubscribeMessage = ControlMessageFactory.Create(MessageIntentEnum.Unsubscribe);

                unsubscribeMessage.Headers[Headers.SubscriptionMessageType]    = eventType.AssemblyQualifiedName;
                unsubscribeMessage.Headers[Headers.ReplyToAddress]             = replyToAddress;
                unsubscribeMessage.Headers[Headers.SubscriberTransportAddress] = replyToAddress;
                unsubscribeMessage.Headers[Headers.SubscriberEndpoint]         = endpoint;
                unsubscribeMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
                unsubscribeMessage.Headers[Headers.NServiceBusVersion] = GitFlowVersion.MajorMinorPatch;

                unsubscribeTasks.Add(SendUnsubscribeMessageWithRetries(publisherAddress, unsubscribeMessage, eventType.AssemblyQualifiedName, context.Extensions));
            }
            return(Task.WhenAll(unsubscribeTasks));
        }
        protected override async Task Terminate(IIncomingPhysicalMessageContext context)
        {
            var message   = context.Message;
            var timeoutId = message.Headers["Timeout.Id"];

            var timeoutData = await persister.Peek(timeoutId, context.Extensions).ConfigureAwait(false);

            if (timeoutData == null)
            {
                return;
            }

            var sendOptions = new DispatchOptions(new UnicastAddressTag(timeoutData.Destination), dispatchConsistency);

            timeoutData.Headers[Headers.TimeSent] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
            timeoutData.Headers["NServiceBus.RelatedToTimeoutId"] = timeoutData.Id;

            await dispatcher.Dispatch(new[] { new TransportOperation(new OutgoingMessage(message.MessageId, timeoutData.Headers, timeoutData.State), sendOptions) }, context.Extensions).ConfigureAwait(false);

            var timeoutRemoved = await persister.TryRemove(timeoutId, context.Extensions).ConfigureAwait(false);

            if (!timeoutRemoved)
            {
                // timeout was concurrently removed between Peek and TryRemove. Throw an exception to rollback the dispatched message if possible.
                throw new Exception($"timeout '{timeoutId}' was concurrently processed.");
            }
        }
Example #9
0
        protected override async Task Terminate(IUnsubscribeContext context)
        {
            var eventType = context.EventType;

            await subscriptionManager.Unsubscribe(eventType, context.Extensions).ConfigureAwait(false);


            var publisherAddresses = subscriptionRouter.GetAddressesForEventType(eventType);

            if (publisherAddresses.Count == 0)
            {
                return;
            }

            var unsubscribeTasks = new List <Task>(publisherAddresses.Count);

            foreach (var publisherAddress in publisherAddresses)
            {
                Logger.Debug("Unsubscribing to " + eventType.AssemblyQualifiedName + " at publisher queue " + publisherAddress);

                var unsubscribeMessage = ControlMessageFactory.Create(MessageIntentEnum.Unsubscribe);

                unsubscribeMessage.Headers[Headers.SubscriptionMessageType]    = eventType.AssemblyQualifiedName;
                unsubscribeMessage.Headers[Headers.ReplyToAddress]             = replyToAddress;
                unsubscribeMessage.Headers[Headers.SubscriberTransportAddress] = replyToAddress;
                unsubscribeMessage.Headers[Headers.SubscriberEndpoint]         = endpoint;
                unsubscribeMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
                unsubscribeMessage.Headers[Headers.NServiceBusVersion] = GitVersionInformation.MajorMinorPatch;

                unsubscribeTasks.Add(SendUnsubscribeMessageWithRetries(publisherAddress, unsubscribeMessage, eventType.AssemblyQualifiedName, context.Extensions));
            }

            await Task.WhenAll(unsubscribeTasks).ConfigureAwait(false);
        }
Example #10
0
        protected override async Task Terminate(ISubscribeContext context)
        {
            var eventType = context.EventType;

            var publisherAddresses = subscriptionRouter.GetAddressesForEventType(eventType)
                                     .EnsureNonEmpty(() => $"No publisher address could be found for message type {eventType}. Ensure the configured publisher endpoint has at least one known instance.");

            var subscribeTasks = new List <Task>();

            foreach (var publisherAddress in publisherAddresses)
            {
                Logger.Debug($"Subscribing to {eventType.AssemblyQualifiedName} at publisher queue {publisherAddress}");

                var subscriptionMessage = ControlMessageFactory.Create(MessageIntentEnum.Subscribe);

                subscriptionMessage.Headers[Headers.SubscriptionMessageType]    = eventType.AssemblyQualifiedName;
                subscriptionMessage.Headers[Headers.ReplyToAddress]             = subscriberAddress;
                subscriptionMessage.Headers[Headers.SubscriberTransportAddress] = subscriberAddress;
                subscriptionMessage.Headers[Headers.SubscriberEndpoint]         = subscriberEndpoint;
                subscriptionMessage.Headers[Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
                subscriptionMessage.Headers[Headers.NServiceBusVersion] = GitFlowVersion.MajorMinorPatch;

                subscribeTasks.Add(SendSubscribeMessageWithRetries(publisherAddress, subscriptionMessage, eventType.AssemblyQualifiedName, context.Extensions));
            }
            await Task.WhenAll(subscribeTasks.ToArray()).ConfigureAwait(false);
        }
        protected override async Task Terminate(IInvokeHandlerContext context)
        {
            if (context.Extensions.TryGet(out ActiveSagaInstance saga) && saga.NotFound && saga.Metadata.SagaType == context.MessageHandler.Instance.GetType())
            {
                return;
            }

            var messageHandler = context.MessageHandler;

            var startTime = DateTime.UtcNow;

            try
            {
                await messageHandler
                .Invoke(context.MessageBeingHandled, context)
                .ThrowIfNull()
                .ConfigureAwait(false);
            }
            catch (Exception e)
            {
                e.Data["Message type"]         = context.MessageMetadata.MessageType.FullName;
                e.Data["Handler type"]         = context.MessageHandler.HandlerType.FullName;
                e.Data["Handler start time"]   = DateTimeExtensions.ToWireFormattedString(startTime);
                e.Data["Handler failure time"] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
                throw;
            }
        }
Example #12
0
 /// <summary>
 ///     Initializes the transport message with a CombGuid as identifier
 /// </summary>
 public TransportMessage()
 {
     id = CombGuid.Generate().ToString();
     Headers[NServiceBus.Headers.MessageId] = id;
     CorrelationId = id;
     MessageIntent = MessageIntentEnum.Send;
     Headers[NServiceBus.Headers.NServiceBusVersion] = GitFlowVersion.MajorMinorPatch;
     Headers[NServiceBus.Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
 }
Example #13
0
        public Task Invoke(IAuditContext context, Func <IAuditContext, Task> next)
        {
            if (context.Extensions.TryGet(out ProcessingStatisticsBehavior.State state))
            {
                context.AddAuditData(Headers.ProcessingStarted, DateTimeExtensions.ToWireFormattedString(state.ProcessingStarted));
                // We can't take the processing time from the state since we don't know it yet.
                context.AddAuditData(Headers.ProcessingEnded, DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow));
            }

            return(next(context));
        }
Example #14
0
        /// <summary>
        ///     Initializes the transport message with a CombGuid as identifier
        /// </summary>
        public TransportMessage()
        {
            id = CombGuid.Generate().ToString();
            Headers[NServiceBus.Headers.MessageId] = id;
            CorrelationId = id;
            Headers.Add(NServiceBus.Headers.OriginatingEndpoint, Configure.EndpointName);
            Headers.Add(NServiceBus.Headers.OriginatingHostId, UnicastBus.HostIdForTransportMessageBecauseEverythingIsStaticsInTheConstructor.ToString("N"));
            MessageIntent = MessageIntentEnum.Send;
            Headers[NServiceBus.Headers.NServiceBusVersion] = GitFlowVersion.MajorMinorPatch;
            Headers[NServiceBus.Headers.TimeSent]           = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);

            AddBackwardsCompatibilityHeaders();
        }
Example #15
0
        public void Invoke(IncomingContext context, Action next)
        {
            next();

            var sendOptions = new SendOptions(AuditQueue)
            {
                TimeToBeReceived = TimeToBeReceivedOnForwardedMessages
            };

            //set audit related headers
            context.PhysicalMessage.Headers[Headers.ProcessingStarted] = DateTimeExtensions.ToWireFormattedString(context.Get <DateTime>("IncomingMessage.ProcessingStarted"));
            context.PhysicalMessage.Headers[Headers.ProcessingEnded]   = DateTimeExtensions.ToWireFormattedString(context.Get <DateTime>("IncomingMessage.ProcessingEnded"));

            MessageAuditer.Audit(sendOptions, context.PhysicalMessage);
        }
Example #16
0
        public Task Invoke(IRoutingContext context, Func <IRoutingContext, Task> next)
        {
            var message = context.Message;

            if (!message.Headers.ContainsKey(Headers.NServiceBusVersion))
            {
                message.Headers[Headers.NServiceBusVersion] = GitVersionInformation.MajorMinorPatch;
            }

            if (!message.Headers.ContainsKey(Headers.TimeSent))
            {
                message.Headers[Headers.TimeSent] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
            }
            return(next(context));
        }
        internal static void SetExceptionHeaders(Dictionary <string, string> headers, Exception e, Address failedQueue, string reason, bool legacyStackTrace)
        {
            if (!string.IsNullOrWhiteSpace(reason))
            {
                headers["NServiceBus.ExceptionInfo.Reason"] = reason;
            }
            headers["NServiceBus.ExceptionInfo.ExceptionType"] = e.GetType().FullName;

            if (e.InnerException != null)
            {
                headers["NServiceBus.ExceptionInfo.InnerExceptionType"] = e.InnerException.GetType().FullName;
            }

            headers["NServiceBus.ExceptionInfo.HelpLink"] = e.HelpLink;
            headers["NServiceBus.ExceptionInfo.Message"]  = e.GetMessage();
            headers["NServiceBus.ExceptionInfo.Source"]   = e.Source;
            if (legacyStackTrace)
            {
                headers["NServiceBus.ExceptionInfo.StackTrace"] = e.StackTrace;
            }
            else
            {
                headers["NServiceBus.ExceptionInfo.StackTrace"] = e.ToString();
            }
            headers[FaultsHeaderKeys.FailedQ]    = failedQueue.ToString();
            headers["NServiceBus.TimeOfFailure"] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);

// ReSharper disable once ConditionIsAlwaysTrueOrFalse
            if (e.Data == null)
            {
// ReSharper disable once HeuristicUnreachableCode
                return;
            }

            foreach (DictionaryEntry entry in e.Data)
            {
                if (entry.Value == null)
                {
                    continue;
                }
                headers["NServiceBus.ExceptionInfo.Data." + entry.Key] = entry.Value.ToString();
            }
        }
Example #18
0
        public static void SetExceptionHeaders(this TransportMessage message, Exception e, Address failedQueue, string reason = null)
        {
            if (!string.IsNullOrWhiteSpace(reason))
            {
                message.Headers["NServiceBus.ExceptionInfo.Reason"] = reason;
            }
            message.Headers["NServiceBus.ExceptionInfo.ExceptionType"] = e.GetType().FullName;

            if (e.InnerException != null)
            {
                message.Headers["NServiceBus.ExceptionInfo.InnerExceptionType"] = e.InnerException.GetType().FullName;
            }

            message.Headers["NServiceBus.ExceptionInfo.HelpLink"]   = e.HelpLink;
            message.Headers["NServiceBus.ExceptionInfo.Message"]    = e.GetMessage();
            message.Headers["NServiceBus.ExceptionInfo.Source"]     = e.Source;
            message.Headers["NServiceBus.ExceptionInfo.StackTrace"] = e.StackTrace;
            message.Headers[FaultsHeaderKeys.FailedQ]    = failedQueue.ToString();
            message.Headers["NServiceBus.TimeOfFailure"] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow);
        }
 public static void SetDelayedDeliveryTimestamp(this OutgoingMessage message, DateTime timestamp)
 {
     message.Headers[Headers.DelayedRetriesTimestamp] = DateTimeExtensions.ToWireFormattedString(timestamp);
 }