Beispiel #1
0
        private void RegisterMessageHandler(Type handlerType, string filteredMessageHandlerCategory)
        {
            if (handlerType.IsInterface || handlerType.IsAbstract || handlerType.IsGenericType)
            {
                return;
            }
            var currentHandlerInterfaceTypes = handlerType.GetInterfaces()
                                               .Where(m => m.IsGenericType && !m.IsGenericTypeDefinition && m.GetGenericTypeDefinition() == typeof(IMessageHandler <>))
                                               .ToArray();
            var messageHandlerCategory = MessageHandlerTypeAttribute.GetCategory(handlerType);

            if (string.IsNullOrEmpty(filteredMessageHandlerCategory) || messageHandlerCategory == filteredMessageHandlerCategory)
            {
                foreach (var currentHandlerInterfaceType in currentHandlerInterfaceTypes)
                {
                    var messageType     = currentHandlerInterfaceType.GenericTypeArguments[0];
                    var messageTypeName = MessageTypeAttribute.GetTypeName(messageType);
                    if (!_messageTypes.ContainsKey(messageTypeName))
                    {
                        _messageTypes.Add(messageTypeName, messageType);
                    }
                    if (!_messageHandlers.ContainsKey(messageTypeName))
                    {
                        _messageHandlers.Add(messageTypeName, (IMessageHandler)Activator.CreateInstance(handlerType));
                    }
                    else
                    {
                        var ex = new MessageHandlerDuplicateRegistrationException(messageTypeName, handlerType, this);
                        _logger.Error(ex.Message);
                        throw ex;
                    }
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Get the <see cref="MessageTypeAttribute"/> associated with <paramref name="reply"/>
        /// </summary>
        /// <param name="reply">The <see cref="Reply"/> whose attributes are returned</param>
        /// <returns><see cref="MessageTypeAttribute"/></returns>
        public static MessageTypeAttribute GetReplyAttributes(Reply reply)
        {
            MessageTypeAttribute retval = new MessageTypeAttribute(MessageType.ServerMessage);
            var type = typeof(Reply);
            var info = type.GetMember(reply.ToString());

            retval.Source = string.Format("[{0}]", Strings_Connection.Unknown);
            if (info.Length > 0)
            {
                var attributes = info[0].GetCustomAttributes(typeof(MessageTypeAttribute), false);
                if (attributes.Length > 0)
                {
                    retval = (MessageTypeAttribute)attributes[0];
                    if (retval.MessageType == MessageType.ErrorMessage)
                    {
                        retval.Source = string.Format("[{0}]", Strings_Connection.Error);
                    }
                    else
                    {
                        retval.Source = Strings_General.ReplySource;
                    }
                }
            }

            return retval;
        }
Beispiel #3
0
        private void Register(Type type, MessageTypeAttribute msgType)
        {
            Serializer serializer = new Serializer(type, msgType);

            mTypeSerializersMap[type] = serializer;
            mIDSerializersMap[serializer.MessageType.ID] = serializer;
        }
Beispiel #4
0
        public EDIParser()
        {
            Groups             = new List <Group>();
            Segments           = new List <SegmentBase>();
            SegmentDefinitions = new Dictionary <string, Type>();
            MessageDefinitions = new Dictionary <string, Type>();
            var type = typeof(SegmentBase);

            foreach (Type segBase in AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(p => type.IsAssignableFrom(p)))
            {
                SegmentIdAttribute idAtt = Attribute.GetCustomAttribute(segBase, typeof(SegmentIdAttribute)) as SegmentIdAttribute;

                if (idAtt != null)
                {
                    SegmentDefinitions.Add(idAtt.Id, segBase);
                }
            }

            type = typeof(MessageBase);
            foreach (Type segBase in AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(p => type.IsAssignableFrom(p)))
            {
                MessageTypeAttribute idAtt = Attribute.GetCustomAttribute(segBase, typeof(MessageTypeAttribute)) as MessageTypeAttribute;

                if (idAtt != null)
                {
                    MessageDefinitions.Add(idAtt.MessageType, segBase);
                }
            }
        }
        public static IMessagePathId BuildCmdPath <TCmd>(Action <TCmd> path, Type location, LogEnum logType = LogEnum.DevConsole)
            where TCmd : ICmd
        {
            MessageTypeAttribute messageTypeDescription = MessageTypeAttribute.GetMessageTypeAttribute(typeof(TCmd));

            return(BuildMessagePath($"处理{messageTypeDescription.Description}命令", logType, path, location));
        }
Beispiel #6
0
        public static IMessagePathId BuildCmdPath <TCmd>(Type location, LogEnum logType, Action <TCmd> path)
            where TCmd : ICmd
        {
            MessageTypeAttribute messageTypeDescription = MessageTypeAttribute.GetMessageTypeAttribute(typeof(TCmd));

            return(BuildMessagePath($"处理{messageTypeDescription.Description}命令", logType, location, PathPriority.Normal, path));
        }
Beispiel #7
0
        public static void AddCmdPath <TCmd>(this Window window, LogEnum logType, Action <TCmd> action, Type location)
            where TCmd : ICmd
        {
            if (WpfUtil.IsInDesignMode)
            {
                return;
            }
            if (window.Resources == null)
            {
                window.Resources = new ResourceDictionary();
            }
            List <IMessagePathId> messagePathIds = (List <IMessagePathId>)window.Resources[messagePathIdsResourceKey];

            if (messagePathIds == null)
            {
                messagePathIds = new List <IMessagePathId>();
                window.Resources.Add(messagePathIdsResourceKey, messagePathIds);
                window.Closed += UiElement_Closed;
            }
            MessageTypeAttribute messageTypeDescription = MessageTypeAttribute.GetMessageTypeAttribute(typeof(TCmd));
            string description   = "处理" + messageTypeDescription.Description;
            var    messagePathId = VirtualRoot.AddMessagePath(description, logType, action, location);

            messagePathIds.Add(messagePathId);
        }
Beispiel #8
0
        public static void BuildCmdPath <TCmd>(Action <TCmd> path, Type location, LogEnum logType = LogEnum.DevConsole)
            where TCmd : ICmd
        {
            MessageTypeAttribute messageTypeDescription = MessageTypeAttribute.GetMessageTypeAttribute(typeof(TCmd));
            string description = "处理" + messageTypeDescription.Description;

            BuildMessagePath(description, logType, path, location);
        }
Beispiel #9
0
        /// <summary>
        /// 事件响应
        /// </summary>
        public static DelegateHandler <TEvent> On <TEvent>(LogEnum logType, Action <TEvent> action)
            where TEvent : IEvent
        {
            MessageTypeAttribute messageTypeDescription = MessageTypeAttribute.GetMessageTypeDescription(typeof(TEvent));
            string description = "处理" + messageTypeDescription.Description;

            return(Path(description, logType, action));
        }
Beispiel #10
0
        /// <summary>
        /// 命令窗口。使用该方法的代码行应将前两个参数放在第一行以方便vs查找引用时展示出参数信息
        /// </summary>
        public static DelegateHandler <TCmd> Window <TCmd>(LogEnum logType, Action <TCmd> action)
            where TCmd : ICmd
        {
            MessageTypeAttribute messageTypeDescription = MessageTypeAttribute.GetMessageTypeDescription(typeof(TCmd));
            string description = "处理" + messageTypeDescription.Description;

            return(Path(description, logType, action));
        }
Beispiel #11
0
        public static IMessagePathId BuildCmdPath <TCmd>(Action <TCmd> action, LogEnum logType = LogEnum.DevConsole)
            where TCmd : ICmd
        {
            MessageTypeAttribute messageTypeDescription = MessageTypeAttribute.GetMessageTypeDescription(typeof(TCmd));
            string description = "处理" + messageTypeDescription.Description;

            return(BuildPath(description, logType, action));
        }
Beispiel #12
0
        /// <summary>
        ///     Returns the MessageTypeAttribute for the MessageType enum
        /// </summary>
        /// <param name="messageType">MessageType</param>
        /// <returns>MessageTypeAttribute</returns>
        private static MessageTypeAttribute GetMessageTypeAttribute(MessageType messageType)
        {
            MemberInfo[]         memberInfo = messageType.GetType().GetMember(messageType.ToString());
            MessageTypeAttribute attributes =
                (MessageTypeAttribute)memberInfo[0].GetCustomAttribute(typeof(MessageTypeAttribute), false);

            return(attributes);
        }
Beispiel #13
0
        /// <summary>
        ///     Builds the correct Tag for the given messageType
        /// </summary>
        /// <param name="messageType">The messageType</param>
        /// <returns>MessageType formated string</returns>
        private static string BuildMessageTag(MessageType messageType)
        {
            // No Tag -> return empty string
            if (messageType == MessageType.None)
            {
                return("");
            }

            MessageTypeAttribute typeAttribute = GetMessageTypeAttribute(messageType);

            //TODO: Translate TagDisplayName
            //TODO: Replace later with: │ (Cef based chat)
            return($"~w~| {typeAttribute.TagColorCode}{typeAttribute.TagDisplayName.PadRight(10)}~w~| ~;~");
        }
        protected bool TryAddScopesAndName(ref RouteData data, Type type)
        {
            if (type == null)
            {
                return(false);
            }

            MessageTypeAttribute mt_attr = type.GetCustomAttributes(typeof(MessageTypeAttribute), true).FirstOrDefault() as MessageTypeAttribute;

            if (mt_attr != null)
            {
                if (!string.IsNullOrEmpty(data.Name))
                {
                    throw new InvalidOperationException("Message nesting hierarchy cannot have multiple MessageTypeAttribute");
                }

                data.Scopes = mt_attr.Scopes;
                data.Name   = mt_attr.Name;

                return(false);
            }
            else
            {
                MessageTypePrefixAttribute mp_attr = type.GetCustomAttributes(typeof(MessageTypePrefixAttribute), true).FirstOrDefault() as MessageTypePrefixAttribute;
                if (mp_attr != null)
                {
                    if (string.IsNullOrEmpty(data.Name))
                    {
                        throw new ArgumentException("The MessageTypePrefixAttribute cannot be used on a terminal Message type");
                    }

                    data.Scopes = mp_attr.Scopes.Concat(data.Scopes ?? new string[0]).ToArray();

                    return(false);
                }
                else
                {
                    if (string.IsNullOrEmpty(data.Name))
                    {
                        data.Name = Regex.Replace(Regex.Replace(type.Name, "[\\-_]?Message$", ""), "[\\-_]?MessageScope$", "").Replace('_', '-').ToLower();
                    }
                    else
                    {
                        data.Scopes = new string[] { Regex.Replace(Regex.Replace(type.Name, "[\\-_]?Message$", ""), "[\\-_]?MessageScope$", "").Replace('_', '-').ToLower() }
                    }.Concat(data.Scopes ?? new string[0]).ToArray();
Beispiel #15
0
        /// <summary>
        /// Do any channel level processing required for the reply.
        /// </summary>
        /// <param name="message">The reply message to process.</param>
        public void HandleReply(Message message)
        {
            Reply reply = (Reply)int.Parse(message.Command);
            MessageTypeAttribute attributes  = IRCMarshal.GetReplyAttributes(reply);
            MessageType          messageType = attributes.MessageType;
            GlobalSettings       settings    = GlobalSettings.Instance;
            string source = attributes.Source;

            string content;

            if (attributes.OutputAction == null)
            {
                content = message.ToString(attributes.OutputFormat, attributes.ParameterDelimiter, attributes.RemoveFirstParameter);
            }
            else
            {
                content = attributes.OutputAction.Invoke(message);
            }

            if (this.expectingNamesMessage && reply == Reply.RPL_NAMREPLY)
            {
                this.PopulateChannelNamesFromMessage(message);
            }
            else if (this.expectingNamesMessage && reply == Reply.RPL_ENDOFNAMES)
            {
                this.expectingNamesMessage = false;
                if (this.namesPopulated != null)
                {
                    this.namesPopulated.Invoke(this, this.users);
                }
            }
            else
            {
                if (settings.DebugMode == GlobalSettings.Boolean.Yes)
                {
                    this.tabPage.AppendMessage(reply.ToString(), "[RAW]", message.ToString(), MessageType.WarningMessage);
                }

                this.tabPage.AppendMessage(reply.ToString(), source, content, messageType);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Process a message that is categorised as being a numeric reply in the RFC documents.
        /// </summary>
        /// <param name="message">The message to process.</param>
        private void ProcessNumericReply(Message message)
        {
            Reply reply = (Reply)int.Parse(message.Command);
            Action<IRCTabPage> appendMessage = (IRCTabPage tabPage) =>
            {
                MessageTypeAttribute attributes = IRCMarshal.GetReplyAttributes(reply);
                MessageType messageType = attributes.MessageType;
                GlobalSettings settings = GlobalSettings.Instance;
                string source = attributes.Source;

                string content;
                if (attributes.OutputAction == null)
                {
                    content = message.ToString(attributes.OutputFormat, attributes.ParameterDelimiter, attributes.RemoveFirstParameter);
                }
                else
                {
                    content = attributes.OutputAction.Invoke(message);
                }

                if (settings.DebugMode == GlobalSettings.Boolean.Yes)
                {
                    tabPage.AppendMessage(reply.ToString(), "[RAW]", message.ToString(), MessageType.WarningMessage);
                }

                tabPage.AppendMessage(reply.ToString(), source, content, messageType);
            };

            // If we are retrieving list replies we need to populate the channel browser
            if (reply == Reply.RPL_LISTSTART)
            {
                this.parent.InvokeAction(() => this.ChannelBrowser.BeginRefresh(true));
                return;
            }
            else if (reply == Reply.RPL_LIST)
            {
                this.ChannelBrowser.AddChannel(message);
                return;
            }
            else if (reply == Reply.RPL_LISTEND)
            {
                this.parent.InvokeAction(() => this.ChannelBrowser.FlushChannels());
                return;
            }

            // If we are still awaiting the UserHost reply (i.e. we are awaiting confirmation of the full userhost 
            // prefix that we will use to determine the max PRIVMSG lengths) then cache it in the marshal for future
            // reference.
            if (this.AwaitingUserHostMessage && reply == Reply.RPL_USERHOST)
            {
                this.fullUserHost = message.TrailingParameter;
                this.AwaitingUserHostMessage = false;

                // Execute any auto commands.
                if (!this.hasExecutedAutoCommands && this.AutoCommands.Count > 0)
                {
                    for (int i = 0; i < this.AutoCommands.Count; i++)
                    {
                        MessageParseResult parseResult = MessageFactory.CreateFromUserInput(this.AutoCommands[i], null);
                        if (parseResult.Success)
                        {
                            this.Send(this.ServerTab, parseResult.IRCMessage);
                        }
                    }

                    this.hasExecutedAutoCommands = true;
                }

                if (this.reconnecting)
                {
                    // Pause the thread for a second to give time for any authentication to 
                    // take place and then rejoin the channels.
                    System.Threading.Thread.Sleep(1000);
                    this.Channels.ForEach(i =>
                    {
                        if (i.TabPage.TabType == IRCTabType.Channel)
                        {
                            this.Send(this.ServerTab, new JoinMessage(i.Name));
                        }
                    });

                    this.reconnecting = false;
                }

                return;
            }

            // If the user has received a new hidden host then we need to re-evaluate
            // their full user host mask that will be seen by other clients.
            if (reply == Reply.RPL_HOSTHIDDEN)
            {
                this.AwaitingUserHostMessage = true;
                this.Send(this.ServerTab, new UserHostMessage(new string[] { this.connection.Nickname }));
            }

            // If we have a names reply or an end of names reply, then we need to check the channel 
            // it is in regards to exists in our channel list, and if it does check to see if it 
            // is awaiting a reply from a names request (i.e. it is wanting to refresh the user list).
            //
            // If this is indeed the case, we need to force it through to that channel rather than
            // following the default procedure of going to the selected tab.
            if ((reply == Reply.RPL_NAMREPLY) || (reply == Reply.RPL_ENDOFNAMES))
            {
                string target = string.Empty;
                if (reply == Reply.RPL_NAMREPLY)
                {
                    target = message.Parameters[2];
                }
                else
                {
                    target = message.Parameters[1];
                }

                IRCChannel channel = this.channels.Find(i => i.Name.Equals(target, StringComparison.OrdinalIgnoreCase));
                if (channel != null && channel.ExpectingNamesMessage)
                {
                    channel.HandleReply(message);
                    return;
                }
            }

            // If the currently selected tab belongs to the channel list for this connection
            // AND we aren't awaiting a mode message (i.e. connecting to the server)
            // then marshal the message to the owning channel, otherwise default to the server tab
            this.TabHost.InvokeAction(() =>
                {
                    IRCChannel selectedChannel = this.Channels.Find(i => this.TabHost.SelectedTab.Equals(i.TabPage));
                    if ((selectedChannel != null) && (!this.AwaitingModeMessage))
                    {
                        selectedChannel.HandleReply(message);
                    }
                    else
                    {
                        appendMessage.Invoke(this.ServerTab);
                    }
                });

            // If a nick in use message comes through, we need to revert the nick against the connection
            // back to the previously assigned nick (if there is one).
            // If there wasn't one, then we'll append an underscore to the current one and resend the nick message
            // we couldn't possibly get stuck in a loop, right?
            if (reply == Reply.ERR_NICKNAMEINUSE)
            {
                if (this.previousNickName.Equals(this.Connection.Nickname, StringComparison.OrdinalIgnoreCase))
                {
                    this.previousNickName = string.Format("{0}_", this.previousNickName);
                    this.connection.Nickname = this.previousNickName;
                    this.Send(this.ServerTab, new NickMessage(this.previousNickName));
                }
                else
                {
                    if (!this.AwaitingModeMessage)
                    {
                        this.Connection.Nickname = this.previousNickName;
                    }
                    else
                    {
                        this.previousNickName = string.Format("{0}_", this.connection.Nickname);
                        this.connection.Nickname = this.previousNickName;
                        this.Send(this.ServerTab, new NickMessage(this.previousNickName));
                    }
                }
            }
        }
Beispiel #17
0
        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="message">消息</param>
        /// <param name="methodName">方法名</param>
        /// <param name="correlationId">关联ID</param>
        public void SendRequest <T>(Envelope <T> message, string methodName, string correlationId) where T : class
        {
            if (message == null || message.Body == null)
            {
                throw new ArgumentNullException("message");
            }
            var queueName         = _disableQueuePrefix ? methodName : $"rpc.{methodName}";
            var callbackQueueName = $"{queueName}.callback";
            var body             = Serializer.Serialize(message.Body);
            var messageTypeName  = MessageTypeAttribute.GetTypeName(message.Body.GetType());
            var routingKey       = string.IsNullOrEmpty(ExchangeName) ? queueName : methodName;
            var envelopedMessage = new EnvelopedMessage(message.MessageId,
                                                        messageTypeName,
                                                        message.Timestamp,
                                                        Serializer.GetString(body),
                                                        routingKey,
                                                        correlationId,
                                                        callbackQueueName);

            var context = new MessageSendingTransportationContext(ExchangeName, new Dictionary <string, object> {
                { MessagePropertyConstants.MESSAGE_ID, string.IsNullOrEmpty(message.MessageId) ? Guid.NewGuid().ToString() : message.MessageId },
                { MessagePropertyConstants.MESSAGE_TYPE, messageTypeName },
                { MessagePropertyConstants.TIMESTAMP, message.Timestamp },
                { MessagePropertyConstants.CONTENT_TYPE, Serializer.ContentType },
                { MessagePropertyConstants.PAYLOAD, Serializer.GetString(body) },
                { MessagePropertyConstants.ROUTING_KEY, routingKey },
                { MessagePropertyConstants.REPLY_TO, callbackQueueName },
                { MessagePropertyConstants.CORRELATION_ID, correlationId }
            });

            TriggerOnMessageSent(new MessageSentEventArgs(this.GetSenderType(), context));
            try
            {
                if (!IsRunning())
                {
                    throw new ObjectDisposedException(nameof(RpcClient));
                }
                IncreaseRetryingMessageCount();

                RetryPolicy.Retry(() =>
                {
                    using (var channel = _conn.CreateChannel())
                    {
                        var properties           = channel.CreateBasicProperties();
                        properties.Persistent    = true;
                        properties.DeliveryMode  = 2;
                        properties.ContentType   = Serializer.ContentType;
                        properties.MessageId     = message.MessageId;
                        properties.Type          = messageTypeName;
                        properties.Timestamp     = new AmqpTimestamp(DateTime2UnixTime.ToUnixTime(message.Timestamp));
                        properties.ReplyTo       = callbackQueueName;
                        properties.CorrelationId = correlationId;
                        if (_confirmEnabled)
                        {
                            channel.ConfirmSelect();
                        }
                        channel.BasicPublish(exchange: ExchangeName,
                                             routingKey: routingKey,
                                             mandatory: true,
                                             basicProperties: properties,
                                             body: body);
                        if (_confirmEnabled && !channel.WaitForConfirms())
                        {
                            throw new Exception("Wait for confirm after sending message failed");
                        }
                    }
                },
                                  cancelOnFailed: (retryCount, retryException) =>
                {
                    return(false);
                },
                                  retryCondition: ex => IOHelper.IsIOError(ex) || RabbitMQExceptionHelper.IsChannelError(ex),
                                  retryTimeInterval: 1000,
                                  maxRetryCount: _maxRetryCount);
                TriggerOnMessageSendingSucceeded(new MessageSendingSucceededEventArgs(this.GetSenderType(), context));
            }
            catch (Exception ex)
            {
                var realEx = ex is TargetInvocationException ? ex.InnerException : ex;
                context.LastException = realEx;
                TriggerOnMessageSendingFailed(new MessageSendingFailedEventArgs(this.GetSenderType(), context));
                throw new MessageSendFailedException(envelopedMessage, ExchangeName, realEx);
            }
            finally
            {
                DecreaseRetryingMessageCount();
            }
        }
Beispiel #18
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message">消息</param>
        public void SendMessage <T>(Envelope <T> message) where T : class
        {
            if (message == null || message.Body == null)
            {
                throw new ArgumentNullException("message");
            }
            var body            = Serializer.Serialize(message.Body);
            var messageTypeName = MessageTypeAttribute.GetTypeName(message.Body.GetType());
            var routingKey      = string.Empty;

            if (_publishToExchange)
            {
                uint routingKeyHashCode = 0;
                if (!uint.TryParse(message.RoutingKey, out routingKeyHashCode))
                {
                    routingKeyHashCode = (uint)message.RoutingKey.GetHashCode();
                }
                routingKey = (routingKeyHashCode % _publishToExchangeQueueCount).ToString();
            }
            else
            {
                routingKey = message.RoutingKey == null ? string.Empty : message.RoutingKey;
            }
            var envelopedMessage = new EnvelopedMessage(message.MessageId,
                                                        messageTypeName,
                                                        message.Timestamp,
                                                        Serializer.GetString(body),
                                                        routingKey,
                                                        string.Empty,
                                                        string.Empty);

            var context = new MessageSendingTransportationContext(ExchangeName, new Dictionary <string, object> {
                { MessagePropertyConstants.MESSAGE_ID, string.IsNullOrEmpty(message.MessageId) ? Guid.NewGuid().ToString() : message.MessageId },
                { MessagePropertyConstants.MESSAGE_TYPE, messageTypeName },
                { MessagePropertyConstants.TIMESTAMP, message.Timestamp },
                { MessagePropertyConstants.CONTENT_TYPE, Serializer.ContentType },
                { MessagePropertyConstants.PAYLOAD, Serializer.GetString(body) },
                { MessagePropertyConstants.ROUTING_KEY, routingKey }
            });

            try
            {
                TriggerOnMessageSent(new MessageSentEventArgs(this.GetSenderType(), context));
                if (!IsRunning())
                {
                    throw new ObjectDisposedException(nameof(PubsubSender));
                }
                IncreaseRetryingMessageCount();

                RetryPolicy.Retry(() =>
                {
                    using (var channel = _conn.CreateChannel())
                    {
                        var properties          = channel.CreateBasicProperties();
                        properties.Persistent   = true;
                        properties.DeliveryMode = 2;
                        properties.ContentType  = Serializer.ContentType;
                        properties.MessageId    = message.MessageId;
                        properties.Type         = messageTypeName;
                        properties.Timestamp    = new AmqpTimestamp(DateTime2UnixTime.ToUnixTime(message.Timestamp));
                        if (_confirmEnabled)
                        {
                            channel.ConfirmSelect();
                        }
                        channel.BasicPublish(exchange: ExchangeName,
                                             routingKey: routingKey,
                                             mandatory: _atLeastMatchOneQueue,
                                             basicProperties: properties,
                                             body: body);
                        if (_confirmEnabled && !channel.WaitForConfirms())
                        {
                            throw new Exception("Wait for confirm after sending message failed");
                        }
                    }
                },
                                  cancelOnFailed: (retryCount, retryException) =>
                {
                    return(false);
                },
                                  retryCondition: ex => IOHelper.IsIOError(ex) || RabbitMQExceptionHelper.IsChannelError(ex),
                                  retryTimeInterval: 1000,
                                  maxRetryCount: _maxRetryCount);
                TriggerOnMessageSendingSucceeded(new MessageSendingSucceededEventArgs(this.GetSenderType(), context));
            }
            catch (Exception ex)
            {
                var realEx = ex is TargetInvocationException ? ex.InnerException : ex;
                context.LastException = realEx;
                TriggerOnMessageSendingFailed(new MessageSendingFailedEventArgs(this.GetSenderType(), context));
                throw new MessageSendFailedException(envelopedMessage, ExchangeName, realEx);
            }
            finally
            {
                DecreaseRetryingMessageCount();
            }
        }
Beispiel #19
0
 public Serializer(Type bodyType, MessageTypeAttribute msgType)
 {
     mBodyType   = bodyType;
     MessageType = msgType;
     Init();
 }