/// <summary>
        ///     Using the specified parameters and arguments, a formatted string shall be returned.
        ///     The <see cref="IMessageFormatter" /> is being provided as well, to enable
        ///     nested formatting. This is only called if <see cref="CanFormat" /> returns true.
        ///     The <see cref="args" /> will always contain the <see cref="FormatterRequest.Variable" />.
        /// </summary>
        /// <param name="locale">
        ///     The locale being used. It is up to the formatter what they do with this information.
        /// </param>
        /// <param name="request">
        ///     The parameters.
        /// </param>
        /// <param name="args">
        ///     The arguments.
        /// </param>
        /// <param name="messageFormatter">
        ///     The message formatter.
        /// </param>
        /// <returns>
        ///     The <see cref="string" />.
        /// </returns>
        public string Format(
            string locale, 
            FormatterRequest request, 
            Dictionary<string, object> args, 
            IMessageFormatter messageFormatter)
        {
            var arguments = this.ParseArguments(request);
            double offset = 0;
            var offsetExtension = arguments.Extensions.FirstOrDefault(x => x.Extension == "offset");
            if (offsetExtension != null)
            {
                offset = Convert.ToDouble(offsetExtension.Value);
            }

            double n = 0;
            object varResult = null;
            if (args.TryGetValue(request.Variable, out varResult))
            {
                n = Convert.ToDouble(varResult);
            }

            var pluralized = new StringBuilder(this.Pluralize(locale, arguments, n, offset));
            var result = this.ReplaceNumberLiterals(pluralized, n - offset);
            var formatted = messageFormatter.FormatMessage(result, args);
            return formatted;
        }
 public void Initialize()
 {
     _competitionEntryService = Substitute.For <ICompetitionEntryService>();
     _emailService            = Substitute.For <IEmailService>();
     _messageFormatter        = Substitute.For <IMessageFormatter>();
     _controller = new WatermelonController(_competitionEntryService, _emailService, _messageFormatter);
 }
Esempio n. 3
0
        /// <summary>
        /// Instantiate a new instance of MSMQMessageFetcher class.
        /// </summary>
        /// <param name="messageQueue">target MSMQ queue</param>
        /// <param name="messageCount">number of messages in queue</param>
        /// <param name="messageFormatter">message formatter for deserializing MSMQ message</param>
        /// <param name="prefetchCacheCapacity">prefetch cache capacity</param>
        /// <param name="maxOutstandingFetchCount">maximun number of outstanding BeginPeek operations</param>
        public MSMQMessageFetcher(MessageQueue messageQueue, long messageCount, IMessageFormatter messageFormatter, int prefetchCacheCapacity, int maxOutstandingFetchCount)
        {
            this.msmqQueueField           = messageQueue;
            this.msmqMessageCount         = messageCount;
            this.messageFormatter         = messageFormatter;
            this.prefetchCacheCapacity    = prefetchCacheCapacity;
            this.maxOutstandingFetchCount = maxOutstandingFetchCount;
            this.prefetchCredit           = this.prefetchCacheCapacity;

            this.messagePeekCursorField   = new RefCountedCursor(this.msmqQueueField.CreateCursor());
            this.messagePeekActionField   = PeekAction.Current;
            this.msmqQueueField.Disposed += this.OnQueueDisposed;

            this.prefetchTimer.AutoReset = false;
            this.prefetchTimer.Interval  = 500;
            this.prefetchTimer.Elapsed  += (sender, args) =>
            {
                Debug.WriteLine("[MSMQMessageFetcher] .prefetchTimer raised.");
                this.PeekMessage();
                if (!this.isDisposedField)
                {
                    this.prefetchTimer.Enabled = true;
                }
            };
            this.prefetchTimer.Enabled = true;

            BrokerTracing.TraceVerbose("[MSMQMessageFetcher] .Create new instance: prefetchCacheCapacity={0}, maxOutstandingFetchCount={1}", this.prefetchCacheCapacity, this.maxOutstandingFetchCount);
        }
Esempio n. 4
0
 public virtual T Receive <T>(IMessageFormatter formatter) where T : new()
 {
     try
     {
         _queue.Formatter = formatter;
         using (Message msg = _queue.Receive(_timeSpan))
         {
             if (null != msg)
             {
                 return((T)msg.Body);
             }
             return(new T());
         }
     }
     catch (MessageQueueException ex)
     {
         //var logger = log4net.LogManager.GetLogger(typeof(MsmqProvider));
         //logger.Error(ex.Message);
         return(new T());
     }
     catch (InvalidOperationException ex)
     {
         var logger = log4net.LogManager.GetLogger(typeof(MsmqProvider));
         logger.Error(ex.Message);
         throw new InvalidOperationException(ex.Message);
     }
 }
Esempio n. 5
0
        /// <summary>
        /// This is simple Implementation That will Holds Implementation that will instantiate publisher and subscriber for sending
        /// messages
        /// </summary>
        /// <param name="errorHandler">Error Log Action Handler Expect to be log</param>
        /// <param name="messageFormatter">An Implementation That Hold Massage Data Implementation</param>
        public void SendMessage(Action <String> errorHandler,
                                IMessageFormatter messageFormatter)
        {
            // Instantiate A Publisher
            if (MessagingPublisher == null)
            {
                MessagingPublisher = new MessagingPublisher();
            }

            // Instantiate A Subscriber
            if (MessagingSubscriber == null)
            {
                MessagingSubscriber = new MessagingSubscriber(MessagingPublisher);
            }

            if (MessagingSubscriber.Publisher == null)
            {
                errorHandler(ExceptionCode.SimpleMessaging_NullExceptionThrownForPublisherOverSubscriber);
            }
            else
            {
                MessagingSubscriber.Publisher.DataPublisher += PublisherOnDataPublisher;
                MessagingPublisher.TransformAndPublishData(errorHandler, messageFormatter.MassageData());
            }
        }
        /// <summary>
        /// Write message to Message Queue.
        /// </summary>
        /// <param name="pathName">Path name</param>
        /// <param name="message">Message to write</param>
        /// <param name="isLocal">Indicates whether is local</param>
        /// <param name="isTransactional">Indicates whether is transactional</param>
        /// <param name="messageFormatter">Message Formatter</param>
        /// <returns>return id of the message</returns>
        public string WriteMessage(
            string pathName,
            object message,
            bool isLocal,
            bool isTransactional,
            IMessageFormatter messageFormatter)
        {
            MessageQueue messageQueue = new MessageQueue(pathName, QueueAccessMode.Send);

            if (isLocal)
            {
                messageQueue.Label = DateTime.Now.ToString("yyyy.MM.dd hh:mm:ss");
            }

            messageQueue.Formatter = messageFormatter;

            if (isTransactional)
            {
                this.WriteTransactionalQueue(messageQueue, message);
            }
            else
            {
                messageQueue.Send(message);
            }

            string id = messageQueue.Id.ToString();

            messageQueue.Close();

            return(id);
        }
Esempio n. 7
0
 public void SendMessage(object obj, IMessageFormatter messageFormatter)
 {
     using (var msg = new Message(obj, messageFormatter))
     {
         _messageQueue.Send(msg);
     }
 }
 public MsmqMessageDeliveryQueue(string path, MessageQueueTransactionType transactionType, IMessageFormatter formatter)
 {
     _queue = new MessageQueue(path);
     _formatter = new MessageDeliveryFormatter();
     _transactionType = transactionType;
     _formatter = formatter;
 }
Esempio n. 9
0
        public override bool Send(IMessage message, FormatterType format, params Type[] targetTypes)
        {
            if (!_messageQueue.CanWrite)
            {
                return(false);
            }
            IMessageFormatter formatter = this._messageQueue.Formatter;

            // 如果Option中没有配置目标类型,则说明每次的Formatter需要单独配置
            if (null == Option.TargetTypes || 0 == Option.TargetTypes.Length)
            {
                targetTypes = Option.TargetTypes;
                switch (format)
                {
                case FormatterType.Xml:
                    formatter = new XmlMessageFormatter(targetTypes);
                    break;

                case FormatterType.Bin:
                    formatter = new BinaryMessageFormatter();
                    break;

                default:
                    break;
                }
            }
            Message packagedMessage = new Message(message, formatter);

            _messageQueue.Send(packagedMessage);
            return(true);
        }
 public MsmqMessageDeliveryQueue(string path, MessageQueueTransactionType transactionType, IMessageFormatter formatter)
 {
     _queue           = new MessageQueue(path);
     _formatter       = new MessageDeliveryFormatter();
     _transactionType = transactionType;
     _formatter       = formatter;
 }
Esempio n. 11
0
        /// <summary>
        /// Sets the body.
        /// </summary>
        /// <param name="serializedMessage">The serialized message.</param>
        /// <param name="body">The body.</param>
        /// <returns>The <see cref="SerializableMessage"/></returns>
        public static SerializableMessage SetBody(this SerializableMessage serializedMessage, object body)
        {
            if (serializedMessage == null)
            {
                throw new ArgumentNullException("serializedMessage");
            }

            lock (serializedMessage)
            {
                // create an instance of the message formatter supplied in the serialized message.
                IMessageFormatter messageFormatter = serializedMessage.GetFormatter();

                // in order to ensure that the message is written to the MessageData property correctly,
                // use the message formatter to write to a new Message object, then extract the serialized
                // data from the Message.BodyStream.
                using (Message message = new Message())
                {
                    // setup the message object...
                    message.Formatter = messageFormatter;
                    message.Body      = body;

                    // use the formatter to write the object to the message
                    // this populates the message.BodyStream property.
                    messageFormatter.Write(message, body);

                    // reset the stream position to zero just in case the message formatter neglects to do so...
                    message.BodyStream.Position = 0;

                    serializedMessage.MessageData = StreamUtility.ReadFully(message.BodyStream);

                    return(serializedMessage);
                }
            }
        }
 /// <summary>
 /// Инициализирует экземпляр класса <see cref="MSMQAsyncCommandQueue"/>,
 /// используя имя очереди MSMQ <paramref name="queueName"/> и 
 /// специализированного механизма сериализации <see cref="formatter"/>.
 /// </summary>
 /// <param name="queueName">Имя очереди MSMQ.</param>
 /// <param name="formatter">Сериализатор.</param>
 public MSMQAsyncCommandQueue(string queueName, IMessageFormatter formatter)
 {
     _formatter = formatter;
     _innerQueue = MessageQueue.Exists(queueName) 
         ? new MessageQueue(queueName) 
         : MessageQueue.Create(queueName);
 }
        public void Send(object obj, string label, MessageQueueTransaction transaction)
        {
            if (typeof(Message) == obj.GetType())
            {
                Message m = (Message)obj;
                m.Label = label;

                if (m.BodyStream == null)
                {
                    IMessageFormatter f = (m.Formatter == null) ? Formatter : m.Formatter;
                    f.Write(m, m.Body);
                }

                try
                {
                    delegateQueue.Send(m.DelegateMessage, transaction.DelegateTx);
                }
                catch (ConnectionException e)
                {
                    throw new MessageQueueException(MessageQueueErrorCode.QueueNotAvailable, e.Message);
                }
                catch (MonoMessagingException e)
                {
                    throw new MessageQueueException(MessageQueueErrorCode.Generic, e.Message);
                }
            }
            else
            {
                Message m = new Message(obj);
                Send(m, label, transaction);
            }
        }
        public string Format(
            string locale, 
            FormatterRequest request, 
            Dictionary<string, object> args, 
            object value,
            IMessageFormatter messageFormatter)
        {
            var parsed = this.ParseArguments(request);
            KeyedBlock other = null;
            foreach (var keyedBlock in parsed.KeyedBlocks)
            {
                var str = Convert.ToString(value);
                if (str == keyedBlock.Key)
                {
                    return messageFormatter.FormatMessage(keyedBlock.BlockText, args);
                }
                
                if (keyedBlock.Key == OtherKey)
                {
                    other = keyedBlock;
                }
            }

            if (other == null)
            {
                throw new MessageFormatterException(
                    "'other' option not found in pattern, and variable was not present in collection.");
            }

            return messageFormatter.FormatMessage(other.BlockText, args);
        }
        public MessageQueue Get(
            string queuePath,
            IMessageFormatter messageFormatter)
        {
            MessageQueue messageQueue;

            try
            {
                if (!MessageQueue.Exists(queuePath))
                {
                    throw new QueueNotExistException($"Queue with path {queuePath} does not exist");
                }

                messageQueue = new MessageQueue(queuePath)
                {
                    Formatter = messageFormatter
                };

                if (!messageQueue.Transactional)
                {
                    throw new QueueNotTransactionalException($"Queue {queuePath} is non transactional.");
                }
            }
            catch (Exception ex)
            {
                throw new QueueException($"Unable to connect to queue {queuePath}.", ex);
            }

            return(messageQueue);
        }
Esempio n. 16
0
        public override void InitializeMessageQueue()
        {
            if (MessageQueue.Exists(Option.Path))
            {
                // TODO 暂时无法解决如果两个Queue在不同的AppDomain时也会报错的问题,所以暂时屏蔽该异常
//                I18N i18N = I18N.GetInstance(Constants.MessengerName);
//                throw new TestflowRuntimeException(TestflowErrorCode.MessengerRuntimeError,
//                    i18N.GetFStr("MessageQueueExist", Option.Path));
                this._messageQueue = new MessageQueue(Option.Path);
            }
            else
            {
                this._messageQueue = MessageQueue.Create(Option.Path);
            }
            switch (Option.Formatter)
            {
            case FormatterType.Xml:
                _formatter = new XmlMessageFormatter(Option.TargetTypes);
                break;

            case FormatterType.Bin:
                _formatter = new BinaryMessageFormatter();
                break;

            case FormatterType.Json:
                _formatter = new JsonMessageFormatter(Option, Encoding.UTF8);
                break;

            default:
                break;
            }
            this._messageQueue.Formatter = _formatter;
//            this._messageQueue.Purge();
        }
Esempio n. 17
0
        public string Format(
            string locale,
            FormatterRequest request,
            IDictionary <string, object> args,
            object value,
            IMessageFormatter messageFormatter)
        {
            var        parsed = this.ParseArguments(request);
            KeyedBlock other  = null;

            foreach (var keyedBlock in parsed.KeyedBlocks)
            {
                var str = Convert.ToString(value);
                if (str == keyedBlock.Key)
                {
                    return(messageFormatter.FormatMessage(keyedBlock.BlockText, args));
                }

                if (keyedBlock.Key == OtherKey)
                {
                    other = keyedBlock;
                }
            }

            if (other == null)
            {
                throw new MessageFormatterException(
                          "'other' option not found in pattern, and variable was not present in collection.");
            }

            return(messageFormatter.FormatMessage(other.BlockText, args));
        }
Esempio n. 18
0
 public void SetFormatter(IMessageFormatter fmt)
 {
     if (fmt != null)
     {
         Formatter = fmt;
     }
 }
            private void GetResults(IMessageFormatter formatter, string pipeline, string messageType)
            {
                var start = GetDate("Start date");
                var end   = GetDate("End date");

                if (start == null || end == null)
                {
                    return;
                }

                var filePathAlgorithm = new DateFolderStructure(newFileOption: NewFileNameOptions.Every5Minutes);

                IFolderStructure _filePathAlgorithm = new DateFolderStructure(newFileOption: NewFileNameOptions.Every5Minutes);

                Console.Write("Root directory: ");

                var path = Console.ReadLine();

                var f = new FileResultsReader(formatter, _filePathAlgorithm, path, pipeline, messageType);

                foreach (var msg in f.Get(start.Value, end.Value))
                {
                    Console.WriteLine(msg.ToString());
                }
            }
Esempio n. 20
0
        public MessageQueueInfo(string servicePath, bool isTransactional,
                                IMessageFormatter formatter, int queueTimeout,
                                KeyValuePair <string, IMessageFormatter>[] messageFormatters)
        {
            ModuleProc PROC = new ModuleProc(this.DYN_MODULE_NAME, ".ctor");

            try
            {
                this.ServicePath     = servicePath;
                this.IsTransactional = isTransactional;
                this.Formatter       = formatter;
                this.QueueTimeout    = queueTimeout;
                if (messageFormatters != null)
                {
                    this.MessageFormatters = new SortedDictionary <string, IMessageFormatter>(StringComparer.InvariantCultureIgnoreCase);
                    foreach (KeyValuePair <string, IMessageFormatter> messageFormatter in messageFormatters)
                    {
                        this.MessageFormatters.Add(messageFormatter);
                    }
                }

                Log.InfoV(PROC, "Service Path : {0}, Is Transactional : {1}", servicePath, isTransactional);
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
            }
        }
        public MessageQueueInfo(string servicePath, bool isTransactional,
            IMessageFormatter formatter, int queueTimeout,
            KeyValuePair<string, IMessageFormatter>[] messageFormatters)
        {
            ModuleProc PROC = new ModuleProc(this.DYN_MODULE_NAME, ".ctor");

            try
            {
                this.ServicePath = servicePath;
                this.IsTransactional = isTransactional;
                this.Formatter = formatter;
                this.QueueTimeout = queueTimeout;
                if (messageFormatters != null)
                {
                    this.MessageFormatters = new SortedDictionary<string, IMessageFormatter>(StringComparer.InvariantCultureIgnoreCase);
                    foreach (KeyValuePair<string, IMessageFormatter> messageFormatter in messageFormatters)
                    {
                        this.MessageFormatters.Add(messageFormatter);
                    }
                }

                Log.InfoV(PROC, "Service Path : {0}, Is Transactional : {1}", servicePath, isTransactional);
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
            }
        }
        public void SetUp()
        {
            _view = MockRepository.GenerateMock<IChuckView>();
            _messageFormatter = MockRepository.GenerateMock<IMessageFormatter>();

            _presenter = new ChuckPresenter(_view,_messageFormatter);
        }
 public MessagePublisher(IModel channel, IMessageFormatter messageFormatter, IResponseAwaiter responseAwaiter, Logger logger)
     : base(logger)
 {
     _channel = channel;
     _messageFormatter = messageFormatter;
     _responseAwaiter = responseAwaiter;
 }
Esempio n. 24
0
        public string Format(
            string locale,
            FormatterRequest request,
            IDictionary <string, object> args,
            object value,
            IMessageFormatter messageFormatter)
        {
            var d = CastDate(value);
            var c = new CultureInfo(locale).DateTimeFormat;

            if (request.FormatterArguments == "short")
            {
                return(d.ToString("d", c));
            }

            if (request.FormatterArguments == "long")
            {
                return(d.ToString("D", c));
            }

            if (request.FormatterArguments == "full")
            {
                return(d.ToString("D", c));
            }

            if (request.FormatterArguments == "" || request.FormatterArguments == "default")
            {
                return(d.ToString("D", c));
            }

            throw new FormatException("Invalid date format: " + request.FormatterArguments);
        }
Esempio n. 25
0
        /// <summary>
        /// Gets the body.
        /// </summary>
        /// <param name="serializedMessage">The serialized message.</param>
        /// <returns>The message body as an <see cref="Object"/></returns>
        public static object GetBody(this SerializableMessage serializedMessage)
        {
            if (serializedMessage == null)
            {
                throw new ArgumentNullException("serializedMessage");
            }

            lock (serializedMessage)
            {
                // create an instance of the message formatter supplied in the serialized message.
                IMessageFormatter messageFormatter = (IMessageFormatter)Activator.CreateInstance(serializedMessage.FormatterType);

                // now use that formatter to read the message.
                using (MemoryStream memoryStream = new MemoryStream(serializedMessage.MessageData))
                {
                    using (Message message = new Message())
                    {
                        message.BodyStream = memoryStream;

                        if (messageFormatter.CanRead(message))
                        {
                            return(messageFormatter.Read(message));
                        }
                    }
                }

                return(null);
            }
        }
 internal Message(IMessage delegateMessage, object body,
                  IMessageFormatter formatter)
 {
     this.delegateMessage = delegateMessage;
     this.body            = body;
     this.formatter       = formatter;
 }
Esempio n. 27
0
 public Message CreateMessage(dynamic messageBody, IMessageFormatter formatter)
 {
     return(new Message(messageBody, formatter ?? new JsonMessageFormatter())
     {
         Recoverable = true
     });
 }
        public string MessageProcessor(UserModel userRequestInput, MessageType messageType)
        {
            string message = string.Empty;

            IMessageFormatter result = null;

            switch (userRequestInput.ChannelRequestType)
            {
            case Channel.JSON:
                JSONMessageFormatter jFormat = new JSONMessageFormatter();
                result = jFormat;
                break;

            case Channel.XML:
                XMLMessageFormatter xmlFormat = new XMLMessageFormatter();
                result = xmlFormat;
                break;

            default:
                break;
            }

            message = result?.MessageTypeFormatter(userRequestInput);

            return(message);
        }
Esempio n. 29
0
 public GameEngine(IInputProcessor inputProcessor, IConsoleDisplayService consoleDisplayService,
                   IMessageFormatter messageFormatter)
 {
     _inputProcessor        = inputProcessor;
     _consoleDisplayService = consoleDisplayService;
     _messageFormatter      = messageFormatter;
 }
Esempio n. 30
0
 public XRoadMessageReader(Stream stream, IMessageFormatter messageFormatter, string contentTypeHeader, string storagePath, IEnumerable <IServiceManager> serviceManagers)
 {
     this.contentTypeHeader = contentTypeHeader;
     this.storagePath       = storagePath;
     this.stream            = stream;
     this.serviceManagers   = serviceManagers.ToList();
     this.messageFormatter  = messageFormatter;
 }
 /// <summary>
 ///     Using the specified parameters and arguments, a formatted string shall be returned.
 ///     The <see cref="IMessageFormatter" /> is being provided as well, to enable
 ///     nested formatting. This is only called if <see cref="CanFormat" /> returns true.
 ///     The <see cref="args" /> will always contain the <see cref="FormatterRequest.Variable" />.
 /// </summary>
 /// <param name="locale">
 ///     The locale being used. It is up to the formatter what they do with this information.
 /// </param>
 /// <param name="request">
 ///     The parameters.
 /// </param>
 /// <param name="args">
 ///     The arguments.
 /// </param>
 /// <param name="messageFormatter">
 ///     The message formatter.
 /// </param>
 /// <returns>
 ///     The <see cref="string" />.
 /// </returns>
 public string Format(
     string locale, 
     FormatterRequest request, 
     Dictionary<string, object> args, 
     IMessageFormatter messageFormatter)
 {
     return args[request.Variable].ToString();
 }
Esempio n. 32
0
 /// <summary>
 /// Creates the queue.
 /// </summary>
 /// <param name="uri">The URI.</param>
 /// <param name="messageFormatter">The message formatter.</param>
 /// <returns></returns>
 public static IMessageQueue CreateQueue(Uri uri, IMessageFormatter messageFormatter)
 {
     var messageQueueDecorator = new MessageQueueDecorator(FindQueue(uri.LocalPath))
                                     {
                                         Formatter = messageFormatter
                                     };
     return messageQueueDecorator;
 }
        public EmailEventHandler(IMessageFormatter messageFormatter, IMessageDelivery messageDelivery)
        {
            if (messageFormatter == null) throw new ArgumentNullException("messageFormatter");
            if (messageDelivery == null) throw new ArgumentNullException("messageDelivery");

            this.messageFormatter = messageFormatter;
            this.messageDelivery = messageDelivery;
        }
Esempio n. 34
0
 public CMMessagingService(IMessageFormatter formatter, IConfiguration appSettings)
 {
     this.Formatter = formatter;
     this.Formatter.AddMetadata(ConfigKeys.ProductToken, appSettings.GetValue(ConfigKeys.ProductToken));
     this.GatewayBaseAddress = new Uri(appSettings.GetValue(ConfigKeys.BaseAddress));
     this.PostUri            = appSettings.GetValue(ConfigKeys.PostUri);
     this.MediaType          = "application/xml";
 }
 public RabbitMqMessenger(string uri, IExchangeNameFactory exchangeNameFactory, IRoutingKeyFactory routingKeyFactory, IMessageFormatter messageFormatter, ExchangeConfiguration configuration)
 {
     _uri = uri;
     _exchangeNameFactory = exchangeNameFactory;
     _routingKeyFactory   = routingKeyFactory;
     _messageFormatter    = messageFormatter;
     _configuration       = configuration;
 }
Esempio n. 36
0
        /// <summary>
        /// 静态消息发送方法
        /// </summary>
        /// <param name="mqServer">消息服务器</param>
        /// <param name="o">发送对象</param>
        /// <param name="label">标签</param>
        /// <param name="formater">格式化对象</param>
        public static void SendMessage(MessageQueue mqServer, object o, string label, IMessageFormatter formater)
        {
            Message msg = new Message(o, formater);
            msg.Recoverable = true;
            msg.Label = label;

            mqServer.Send(msg);
        }
Esempio n. 37
0
        ///<summary>
        ///</summary>
        public AsyncTcpListenerMessageSink(IMessageSink messageSink, IMessageFormatter messageFormatter, int?port)
        {
            this.messageSink      = messageSink;
            this.messageFormatter = messageFormatter;

            socket   = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            endPoint = new IPEndPoint(IPAddress.Loopback, port ?? defaultPort);
            socket.BeginConnect(endPoint, Connected, socket);
        }
        private static IMessage GetMessage(IMessageFormatter messageFormatter, byte[] messageBytes)
        {
            var message = messageFormatter.Deformat(messageBytes) as IMessage;

            if (message == null)
                throw new Exception("Message must implement IMessage");

            return message;
        }
Esempio n. 39
0
 public FileResultsReader(IMessageFormatter serializer, IFolderStructure filePathAlgorithm,
                          string rootPath, string pipeline, string messageType)
 {
     _serializer        = serializer;
     _filePathAlgorithm = filePathAlgorithm;
     _rootPath          = rootPath;
     _pipeline          = pipeline;
     _messageType       = messageType;
 }
Esempio n. 40
0
        /// <summary>
        /// Creates the queue.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="messageFormatter">The message formatter.</param>
        /// <returns></returns>
        public static IMessageQueue CreateQueue(Uri uri, IMessageFormatter messageFormatter)
        {
            var messageQueueDecorator = new MessageQueueDecorator(FindQueue(uri.LocalPath))
            {
                Formatter = messageFormatter
            };

            return(messageQueueDecorator);
        }
        ///<summary>
        ///</summary>
        public AsyncTcpListenerMessageSink(IMessageSink messageSink, IMessageFormatter messageFormatter, int? port)
        {
            this.messageSink = messageSink;
            this.messageFormatter = messageFormatter;

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            endPoint = new IPEndPoint(IPAddress.Loopback, port ?? defaultPort);
            socket.BeginConnect(endPoint, Connected, socket);
        }
Esempio n. 42
0
 protected Subscriber(IMessageHandlerProvider messageHandlerProvider, IRabbitConnection connection, IMessageFormatter messageFormatter, Logger logger)
     : base(logger)
 {
     MessageHandlerProvider = messageHandlerProvider;
     Connection = connection;
     Connection.ConnectionMade += ConnectionConnectionMade;
     Connection.ConnectionLost += ConnectionConnectionLost;
     MessageFormatter = messageFormatter;
 }
Esempio n. 43
0
 /// <summary>
 /// Initializes a new instance of <c>MSMQBusOptions</c> class.
 /// </summary>
 /// <param name="path">The location of the queue referenced by this System.Messaging.MessageQueue,
 /// which can be "." for the local computer.</param>
 /// <param name="sharedModeDenyReceive">The <see cref="System.Boolean"/> value which indicates whether
 /// the exclusive read access should be granted to the first application
 /// that accesses the queue.</param>
 /// <param name="enableCache">The <see cref="System.Boolean"/> value which indicates whether
 /// a connection cache should be created and used.</param>
 /// <param name="queueAccessMode">The value that indicates the access mode for the queue.</param>
 /// <param name="useInternalTransaction">The <see cref="System.Boolean"/> value which indicates whether the internal
 /// transaction should be used when sending or receiving messages.</param>
 /// <param name="messageFormatter">The formatter used to serialize an object into or deserialize
 /// an object from the body of a message read from or written to the queue.</param>
 public MSMQBusOptions(string path, bool sharedModeDenyReceive, bool enableCache, QueueAccessMode queueAccessMode, bool useInternalTransaction, IMessageFormatter messageFormatter)
 {
     this.SharedModeDenyReceive = sharedModeDenyReceive;
     this.EnableCache           = enableCache;
     this.QueueAccessMode       = queueAccessMode;
     this.Path = path;
     this.UseInternalTransaction = useInternalTransaction;
     this.MessageFormatter       = messageFormatter;
 }
 /// <summary>
 /// Using the specified parameters and arguments, a formatted string shall be returned.
 /// The <see cref="IMessageFormatter" /> is being provided as well, to enable
 /// nested formatting. This is only called if <see cref="CanFormat" /> returns true.
 /// The <see cref="args" /> will always contain the <see cref="FormatterRequest.Variable" />.
 /// </summary>
 /// <param name="locale">The locale being used. It is up to the formatter what they do with this information.</param>
 /// <param name="request">The parameters.</param>
 /// <param name="args">The arguments.</param>
 /// <param name="value">The value of <see cref="FormatterRequest.Variable" /> from the given <see cref="args" /> dictionary. Can be null.</param>
 /// <param name="messageFormatter">The message formatter.</param>
 /// <returns>
 /// The <see cref="string" />.
 /// </returns>
 public string Format(
     string locale, 
     FormatterRequest request, 
     Dictionary<string, object> args, 
     object value,
     IMessageFormatter messageFormatter)
 {
     return value != null ? value.ToString() : string.Empty;
 }
Esempio n. 45
0
        /// <summary>
        /// Constructor to create logger and tasks and queue parametrization
        /// </summary>
        public ExecutionDataflowQueueProcessing()
        {
            BagTMLog.LogDebug("BagTM Queue Processing Constructor", this);

            //Get the application configuration file.
            config =
                ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            this.hub = this.GetAppSetting(config, "hub");

            String timeSpanParameter = this.GetAppSetting(config, "timeSpan");
            int    timeSpanNumber    = 0;

            if (!int.TryParse(timeSpanParameter, out timeSpanNumber))
            {
                throw new QueueProcessingException("Parameter TimeSpan incorrectly configured");
            }

            this.timeSpan = new TimeSpan((Int64)(timeSpanNumber * TimeSpan.TicksPerSecond));

            BagTMLog.LogDebug("BagTM Queue Processing Timespan " + timeSpanParameter, timeSpan);

            String parallelismCounterParameter = this.GetAppSetting(config, "parallelismCounter");

            if (!int.TryParse(parallelismCounterParameter, out this.parallelismCounter))
            {
                throw new QueueProcessingException("Parameter ParallelismCounter incorrectly configured");
            }

            BagTMLog.LogDebug("BagTM Queue Processing ParallelismCounter " + parallelismCounter, parallelismCounter);

            TTYMessagesSection ttyMsg = ConfigurationManager.GetSection("TTYMessagesSection") as TTYMessagesSection;

            BagTMLog.LogDebug(String.Format("BagTM Queue Processing TTY Parser Collection {0} {1}",
                                            ttyMsg.ttyCollection.GetNumberOfItems(),
                                            ttyMsg.ttyCollection.Describe())
                              , this);

            try
            {
                this.messageFormater = new TTYMessageFormatter(ttyMsg.ttyCollection, new BaggageEntities(), hub);

                BagTMLog.LogDebug("BagTM Queue Processing MessageFormater", messageFormater);

                queueIn       = this.CreateMessageQueue(QUEUEIN);
                queueInSucess = this.CreateMessageQueue(QUEUESUCESS);
                queueInError  = this.CreateMessageQueue(QUEUEERROR);
                queueEngine   = this.CreateMessageQueue(QUEUEENGINE);
                BagTMLog.LogDebug("BagTM Queue Processing QueueEngine", queueEngine);
                BagTMLog.LogDebug("BagTM Queue Processing Constructor Ending", this);
            }
            catch (Exception e)
            {
                BagTMLog.LogError("BagTM Queue Processing Constructor Error ", this, e);
            }
        }
Esempio n. 46
0
 /// <summary>
 /// Initializes a new instance of <c>MSMQBusOptions</c> class.
 /// </summary>
 /// <param name="path">The location of the queue referenced by this System.Messaging.MessageQueue,
 /// which can be "." for the local computer.</param>
 /// <param name="sharedModeDenyReceive">The <see cref="System.Boolean"/> value which indicates whether
 /// the exclusive read access should be granted to the first application 
 /// that accesses the queue.</param>
 /// <param name="enableCache">The <see cref="System.Boolean"/> value which indicates whether
 /// a connection cache should be created and used.</param>
 /// <param name="queueAccessMode">The value that indicates the access mode for the queue.</param>
 /// <param name="useInternalTransaction">The <see cref="System.Boolean"/> value which indicates whether the internal
 /// transaction should be used when sending or receiving messages.</param>
 /// <param name="messageFormatter">The formatter used to serialize an object into or deserialize
 /// an object from the body of a message read from or written to the queue.</param>
 public MSMQBusOptions(string path, bool sharedModeDenyReceive, bool enableCache, QueueAccessMode queueAccessMode, bool useInternalTransaction, IMessageFormatter messageFormatter)
 {
     this.SharedModeDenyReceive = sharedModeDenyReceive;
     this.EnableCache = enableCache;
     this.QueueAccessMode = queueAccessMode;
     this.Path = path;
     this.UseInternalTransaction = useInternalTransaction;
     this.MessageFormatter = messageFormatter;
 }
        ///<summary>
        /// Async TCP based message sink.
        ///</summary>
        ///<param name="messageFormatter">The formatter to use.</param>
        ///<param name="port">The port to use.</param>
        public AsyncTcpServerMessageSink(IMessageFormatter messageFormatter, int? port)
        {
            this.messageFormatter = messageFormatter;

            var serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var endPoint = new IPEndPoint(IPAddress.Loopback, port ?? defaultPort);
            serverSocket.Bind(endPoint);
            serverSocket.Listen((int)SocketOptionName.MaxConnections);
            socket = serverSocket.Accept();
        }
Esempio n. 48
0
		public static MessageQueue GetQueue (string path, bool isTransactional, 
		                                     IMessageFormatter formatter)
		{
			MessageQueue q;
			if (MessageQueue.Exists (path)) {
				q = new MessageQueue (path);
			} else {
				q = MessageQueue.Create (path, isTransactional);
			}
			q.Formatter = formatter;
			return q;
		}		
Esempio n. 49
0
 public MsmqMailPackageQueue(string path, IMessageFormatter formatter, IDataStreamRepository streamRepository)
 {
     if (MessageQueue.Exists(path))
     {
         _MQ = new MessageQueue(path);
     }
     else
     {
         _MQ = MessageQueue.Create(path);
     }
     _Formatter = formatter;
 }
 public MsmqMessageDeliveryQueue(string path, bool createIfNotExists, IMessageFormatter formatter)
 {
     if (createIfNotExists)
     {
         if (!MessageQueue.Exists(path))
         {
             MessageQueue.Create(path, true);
         }
     }
     _queue = new MessageQueue(path);
     _formatter = formatter;
 }
Esempio n. 51
0
        public void Start(IPEndPoint endPoint, IMessageFormatter<byte[]> messageFormatter, Action<IConnection> onNewConnection)
        {
            _onNewConnection = onNewConnection;
            _factory = new ConnectionFactory<SocketConnection, byte[]>(messageFormatter);

            _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listener.Bind(endPoint);
            _listener.Listen(100);
            _listener.BeginAccept(OnAcceptCompleted, _listener);

            Log.Info("Socket Listener started on {0}", endPoint);
        }
 public UnifiedMessagingController(
     IUnifiedMessagingService messagingService,
     MessageRepository messageRepository,
     IMessageFormatter formattingMessenger,
     IFiber fiber)
 {
     _MessagingService = messagingService;
     _MessageRepository = messageRepository;
     _FormattingMessenger = formattingMessenger;
     _Fiber = fiber;
     _MessagingService.MessagesReceived += _MessagingService_MessagesReceived;
 }
Esempio n. 53
0
		public OpenedQueue Open(QueueAccessMode access, IMessageFormatter formatter)
		{
			var messageQueue = new MessageQueue(QueuePath, access);
			if (formatter != null)
				messageQueue.Formatter = formatter;
			var openedQueue = new OpenedQueue(this, messageQueue, QueueUri.ToString(),Transactional)
			{
				Formatter = formatter
			};
			if (SubQueue != null)
				return openedQueue.OpenSubQueue(SubQueue.Value, access);
			return openedQueue;
		}
 public MessageQueue CreateQueue(string queueName, QueueAccessMode accessMode, IMessageFormatter formatter)
 {
     var queue = new MessageQueue(queueName, accessMode)
     {
         Formatter = formatter ?? new JsonMessageFormatter(),
         MessageReadPropertyFilter = new MessagePropertyFilter
         {
             ArrivedTime = true,
             Body = true
         }
     };
     return (queue);
 }
Esempio n. 55
0
        /// <summary>
        /// 静态消息发送方法
        /// </summary>
        /// <param name="MessageQueuePath">消息服务器地址</param>
        /// <param name="o">发送对象</param>
        /// <param name="label">标签</param>
        /// <param name="formater">格式化对象</param>
        public static void SendMessage(string MessageQueuePath, object o, string label, IMessageFormatter formater)
        {
            using (MessageQueue mq = new MessageQueue(MessageQueuePath))
            {
                mq.Formatter = formater;

                Message msg = new Message(o, formater);
                msg.Recoverable = true;
                msg.Label = label;

                mq.Send(msg);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MonitoringChannel" /> class.
        /// </summary>
        /// <param name="keyBuilder">Builds up the final metric key.</param>
        /// <param name="formatter">The message formatter.</param>
        /// <param name="pipe">The pipe.</param>
        public MonitoringChannel(Func<string, string> keyBuilder, IMessageFormatter formatter, IPipe pipe)
        {
            if (pipe == null)
                throw new ArgumentNullException("pipe");

            if (formatter == null)
                throw new ArgumentNullException("formatter");

            this.pipe = pipe;
            this.formatter = formatter;

            this.keyBuilder = keyBuilder ?? (Func<string, string>)((string k) => k);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MessageQueueProcessor"/> class.
 /// </summary>
 /// <param name="executorService">The executor service.</param>
 /// <param name="servicePath">The service path.</param>
 /// <param name="isTransactional">if set to <c>true</c> [is transactional].</param>
 /// <param name="formatter">The formatter.</param>
 protected MessageQueueProcessor(IExecutorService executorService, string servicePath,
     bool isTransactional, IMessageFormatter formatter,
     int queueTimeout,
     IDictionary<string, IMessageFormatter> messageFormatters)
     : base(executorService)
 {
     _servicePath = servicePath;
     _isTransactional = isTransactional;
     _formatter = formatter;
     _messageFormatters = messageFormatters;
     _queueTimeout = (queueTimeout < 10 ? 10 : queueTimeout);
     this.Initialize();
 }
Esempio n. 58
0
 public override void Init()
 {
     base.Init();
     _consumers = new Hashtable();
     _msmqSettings = DestinationDefinition.Properties.Msmq;
     if (_msmqSettings != null)
     {
         MessageQueue.EnableConnectionCache = false;
         log.Debug(__Res.GetString(__Res.Msmq_StartQueue, _msmqSettings.Name));
         _messageQueue = new MessageQueue(_msmqSettings.Name);
         string messageFormatterName = MsmqProperties.BinaryMessageFormatter;
         if (!string.IsNullOrEmpty(_msmqSettings.Formatter))
             messageFormatterName = _msmqSettings.Formatter;
         log.Debug(__Res.GetString(__Res.Msmq_InitFormatter, messageFormatterName));
         if (messageFormatterName == MsmqProperties.BinaryMessageFormatter)
         {
             _messageFormatter = new BinaryMessageFormatter();
             _messageQueue.Formatter = _messageFormatter;
         }
         else if (messageFormatterName.StartsWith(MsmqProperties.XmlMessageFormatter))
         {
             string[] formatterParts = messageFormatterName.Split(new char[]{';'});
             Type[] types;
             if (formatterParts.Length == 1)
                 types = new Type[] { typeof(string) };
             else
             {
                 types = new Type[formatterParts.Length-1];
                 for (int i = 1; i < formatterParts.Length; i++)
                 {
                     Type type = ObjectFactory.Locate(formatterParts[i]);
                     if (type != null)
                         types[i-1] = type;
                     else
                         log.Error(__Res.GetString(__Res.Type_InitError, formatterParts[i]));
                 }
             }
             _messageFormatter = new XmlMessageFormatter(types);
             _messageQueue.Formatter = _messageFormatter;
         }
         else
         {
             log.Error(__Res.GetString(__Res.Type_InitError, messageFormatterName));
             _messageQueue.Close();
             _messageQueue = null;
         }
     }
     else
         log.Error(__Res.GetString(__Res.ServiceAdapter_MissingSettings));
 }
Esempio n. 59
0
        public GitShoutTrayApp(IMessageFormatter messageFormatter)
        {
            InitializeComponent();

            this.messageFormatter = messageFormatter;

            txtServer.Text = GetLastServer();
            txtPortNumber.Text = DEFAULT_PORT.ToString();
            chkUseDefaultPort.Checked = true;

            trayMenu = new ContextMenu();
            trayMenu.MenuItems.Add("Exit", OnExit);
            trayIcon.ContextMenu = trayMenu;
            trayIcon.Text = APP_NAME;
            trayIcon.BalloonTipClicked += OpenCommitsInBrowser;                  
        }       
Esempio n. 60
0
 public int  Send(IMessageFormatter Formatter)
 {
     if (_IsConnected)
     {
         NetworkStream oStream = oClient.GetStream();
         oClient.Client.Send(Formatter.GetBytes());
         byte[] buffer = new Byte[100];
         oClient.Client.Receive(buffer);
         AckMessage msg;
         String strResponse = System.Text.Encoding.ASCII.GetString(buffer);
         Logger.Info("Event Response "  + strResponse);
         msg = AckMessage.GetMessage(buffer);
         if (msg.Ack == 6)// to be checked && msg.SequenceNo == bSequenceNo)// ACK
         {
             return 0;
         }
         return -1;
     }
     else
     {
         throw new Exception("Sender Not Initialized");
     }
 }