Пример #1
0
        public void ReceiveMessage(IChannelMessage response)
        {
            IResponse           _response       = (IResponse)response;
            RequestResponsePair reqResponsePair = _requests[_response.RequestId] as RequestResponsePair;
            bool unregister = false;

            if (reqResponsePair != null)
            {
                lock (reqResponsePair)
                {
                    if (reqResponsePair != null)
                    {
                        reqResponsePair.Response = _response;
                        System.Threading.Monitor.Pulse(reqResponsePair);

                        if (reqResponsePair.Listener != null)
                        {
                            reqResponsePair.Listener.OnResponseReceived(response);
                            unregister = true;
                        }
                    }
                }

                if (unregister)
                {
                    lock (_lock)
                    {
                        _requests.Remove(_response.RequestId);
                    }
                }
            }
        }
Пример #2
0
 public void ReceiveMessage(IChannelMessage response)
 {
     if (response is IRequest)
     {
         _threadPool.ExecuteTask(new RequestDeliverTask(response, requestListener));
     }
 }
        /// <summary>
        /// Post a notification to the registered <see cref="IChannel{T}"/>s in parallel.
        /// </summary>
        /// <typeparam name="T">The type of the notification topic.</typeparam>
        /// <param name="channelMessage">The message to send via the channels.</param>
        /// <returns>Returns a task which is completed when all channel notifications have been completed.</returns>
        public Task PostMessageToChannelsAsync <T>(IChannelMessage <T> channelMessage)
        {
            if (channelMessage == null)
            {
                throw new ArgumentNullException(nameof(channelMessage));
            }

            var channels = this.Settings.ResolveAll <IChannel <T> >();

            if (!channels.Any())
            {
                return(Task.CompletedTask);
            }

            var channelsTasks = new List <Task>(channels.Count());

            foreach (var channel in channels)
            {
                var channelTask = Task.Run(async() =>
                {
                    await SendMessageToChannelAsync(channel, channelMessage);
                });

                channelsTasks.Add(channelTask);
            }

            return(Task.WhenAll(channelsTasks));
        }
Пример #4
0
        public object Deserialize(byte[] buffer)
        {
            IChannelMessage response = null;

            if (buffer != null)
            {
                response = (IChannelMessage)CompactBinaryFormatter.FromByteBuffer(buffer, null);
            }
            return(response);
        }
Пример #5
0
 public void Send(IChannelMessage message)
 {
     //new OscMessage("/midi", )
     sender.Send(new OscMessage("/midi",
                                (int)message.Command,
                                (int)message.MessageType,
                                message.MidiChannel,
                                message.Data1,
                                message.Data2));
 }
        /// <summary>
        /// Queue a message to all available channels.
        /// </summary>
        /// <typeparam name="M">The type of the model in the message.</typeparam>
        /// <typeparam name="T">The type of the topic in the messages.</typeparam>
        /// <param name="channelMessage">The message to send to the available channels.</param>
        /// <returns>Returns a task whose completion is the successful queuing of the <paramref name="channelMessage"/>.</returns>
        public async Task QueueMessageToChannelsAsync <M, T>(IChannelMessage <M, T> channelMessage)
        {
            if (channelMessage == null)
            {
                throw new ArgumentNullException(nameof(channelMessage));
            }

            var channelsDispatcher = GetChannelsDispatcher <T>();

            await channelsDispatcher.QueueMessageToChannelsAsync(channelMessage);
        }
Пример #7
0
        public byte[] Serialize(object graph)
        {
            try
            {
                IChannelMessage command = graph as IChannelMessage;
                return(CompactBinaryFormatter.ToByteBuffer(command, null));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            //byte[] buffer = null;
            //CommandBase command = null;

            //if (graph is IRequest)
            //{
            //    IRequest request = graph as IRequest;
            //    command = request.Message as CommandBase;
            //}

            //else if (graph is IResponse)
            //{
            //    ChannelResponse res = graph as ChannelResponse;
            //    command = res.ResponseMessage as CommandBase;
            //}



            //if (command != null)
            //{
            //    if (command.commandType == CommandBase.CommandType.RESPONSE)
            //    {
            //        if (command.response.ResponseMessage != null)
            //            command.response.returnVal = CompactBinaryFormatter.ToByteBuffer(command.response.ResponseMessage, null);
            //    }
            //    else
            //    {
            //        if (command.command.Parameters != null)
            //            command.command.arguments = CompactBinaryFormatter.ToByteBuffer(command.command.Parameters, null);
            //    }


            //    using (MemoryStream stream = new MemoryStream())
            //    {
            //        ProtoBuf.Serializer.Serialize<CommandBase>(stream, command);
            //        buffer = stream.ToArray();
            //    }
            //}


            //return buffer;
        }
Пример #8
0
        /// <summary>
        /// E-mail a message.
        /// </summary>
        /// <typeparam name="M">The type of the model in the message.</typeparam>
        /// <param name="channelMessage">The message to send to the channel.</param>
        public async Task SendMessageAsync <M>(IChannelMessage <M, T> channelMessage)
        {
            if (channelMessage == null)
            {
                throw new ArgumentNullException(nameof(channelMessage));
            }

            var destinationIdentities = await GetDestinationIdentitiesAsync(channelMessage.Destination, channelMessage.Topic);

            if (!destinationIdentities.Any())
            {
                return;
            }

            bool useSingleMessageForMultipleRecepients = UseSingleMessageForMultipleRecepients(channelMessage.Destination, channelMessage.Topic);

            var emailDestinationAddressesCollection = GetEmailDestinationAddressesCollection(destinationIdentities, useSingleMessageForMultipleRecepients);

            var senderIdentity = await GetSenderIdentityAsync(channelMessage.Source, channelMessage.Topic);

            var senderAddress = GetMailAddress(senderIdentity);

            var destinationIdentitiesByEmail = destinationIdentities.ToReadOnlyMultiDictionary(i => i.Email);

            foreach (var emailDestinationAddresses in emailDestinationAddressesCollection)
            {
                using (var bodyWriter = new System.IO.StringWriter())
                {
                    var messageDestinationIdentities = from address in emailDestinationAddresses
                                                       where destinationIdentitiesByEmail.ContainsKey(address.Address)
                                                       from identity in destinationIdentitiesByEmail[address.Address]
                                                       select identity;

                    renderProvider.Render(
                        GetFullTemplateKey(channelMessage.TemplateKey),
                        bodyWriter,
                        channelMessage.Model,
                        GetDynamicProperties(channelMessage, messageDestinationIdentities));

                    string messageBody = bodyWriter.ToString();

                    string messageID = GetMessageID(channelMessage, messageDestinationIdentities);

                    await SendEmailMessageAsync(
                        channelMessage.Subject,
                        senderAddress,
                        emailDestinationAddresses,
                        messageBody,
                        messageID);
                }
            }
        }
        /// <summary>
        /// Send a notification to the registered <see cref="IChannel{T}"/>s sequentially.
        /// </summary>
        /// <typeparam name="T">The type of the notification topic.</typeparam>
        /// <param name="channelMessage">The message to send via the channels.</param>
        /// <returns>Returns a task which is completed when all channel notifications have been completed.</returns>
        public async Task SendMessageToChannelsAsync <T>(IChannelMessage <T> channelMessage)
        {
            if (channelMessage == null)
            {
                throw new ArgumentNullException(nameof(channelMessage));
            }

            var channels = this.Settings.ResolveAll <IChannel <T> >();

            foreach (var channel in channels)
            {
                await SendMessageToChannelAsync(channel, channelMessage);
            }
        }
Пример #10
0
        /// <summary>
        /// Builds an e-mail message ID of the format <see cref="ChannelMessage{T}.Guid"/>/<see cref="IChannelIdentity.Guid"/>
        /// if the destination identities have a single member,
        /// else returns the <see cref="ChannelMessage{T}.Guid"/>.
        /// </summary>
        /// <param name="channelMessage">The channel message.</param>
        /// <param name="destinationIdentities">The collection of destination identities.</param>
        /// <returns>
        /// Returns message-guid/destination guid if the destination identities have a single member,
        /// else returns message-gruid.
        /// </returns>
        private string GetMessageID(IChannelMessage <T> channelMessage, IEnumerable <IChannelIdentity> destinationIdentities)
        {
            var messageIdBuilder = new StringBuilder();

            messageIdBuilder.Append(channelMessage.Guid);

            if (destinationIdentities.Count() == 1)
            {
                messageIdBuilder.Append("/");

                var singleDestinationIdentity = destinationIdentities.Single();

                messageIdBuilder.Append(singleDestinationIdentity.Guid);
            }

            return(messageIdBuilder.ToString());
        }
Пример #11
0
        private static Dictionary <string, object> GetDynamicProperties(IChannelMessage <T> channelMessage, IEnumerable <IChannelIdentity> destinationIdentities)
        {
            Dictionary <string, object> dynamicProperties;

            if (channelMessage.DynamicProperties != null)
            {
                dynamicProperties = new Dictionary <string, object>(channelMessage.DynamicProperties.ToDictionary(e => e.Key, e => e.Value));
            }
            else
            {
                dynamicProperties = new Dictionary <string, object>(2);
            }

            dynamicProperties[ChannelMessagePropertyKey]        = channelMessage;
            dynamicProperties[DestinationIdentitiesPropertyKey] = destinationIdentities.ToArray();

            return(dynamicProperties);
        }
        /// <summary>
        /// Attempt to send a notification to a channel and log any error.
        /// </summary>
        /// <typeparam name="T">The type of the topic.</typeparam>
        /// <param name="channel">The Channel to send to.</param>
        /// <param name="channelMessage">The message to send via the channel.</param>
        private async Task SendMessageToChannelAsync <T>(IChannel <T> channel, IChannelMessage <T> channelMessage)
        {
            try
            {
                await channel.SendMessageAsync(channelMessage);
            }
            catch (Exception e)
            {
                var loggersRepository = lazyLoggerRepository.Value;

                var logger = loggersRepository.GetLogger(channelPostLoggerName);

                logger.Log(
                    Logging.LogLevel.Error,
                    e,
                    $"Failed to send via channel of type {channel.GetType().FullName}, subject: '{channelMessage.Subject}'");
            }
        }
Пример #13
0
        public static void PostMessage(string channelName, IChannelMessage message)
        {
            if (string.IsNullOrEmpty(channelName))
            {
                throw new ArgumentNullException(nameof(channelName));
            }

            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (!_channels.ContainsKey(channelName.ToLower(CultureInfo.InvariantCulture)))
            {
                throw new InvalidOperationException("The channel <" + channelName.ToLower(CultureInfo.InvariantCulture) + "> does not exist.");
            }

            _channels[channelName.ToLower(CultureInfo.InvariantCulture)].Enqueue(message);
        }
        /// <summary>
        /// Queue a message to all available channels.
        /// </summary>
        /// <typeparam name="M">The type of the model in the message.</typeparam>
        /// <param name="channelMessage">The message to send to the available channels.</param>
        /// <returns>Returns a task whose completion is the successful queuing of the <paramref name="channelMessage"/>.</returns>
        public Task QueueMessageToChannelsAsync <M>(IChannelMessage <M, T> channelMessage)
        {
            if (channelMessage == null)
            {
                throw new ArgumentNullException(nameof(channelMessage));
            }

            var channels = channelsFactory.Get();

            foreach (var channel in channels)
            {
                var channelTask = taskQueuer.QueueAsyncAction(channel.GetType(), async() =>
                {
                    await channel.SendMessageAsync(channelMessage);
                });
            }

            return(Task.CompletedTask);
        }
Пример #15
0
        public void OnDataReceived(IConnection sender, byte[] buffer, object context)
        {
            ReciveContext receiveContext = (ReciveContext)context;

            switch (receiveContext)
            {
            case ReciveContext.LengthReceive:
                int rspLength = Convert.ToInt32(UTF8Encoding.UTF8.GetString(buffer, 0, buffer.Length));
                buffer = new byte[rspLength];
                sender.ReceiveAsync(buffer, buffer.Length, ReciveContext.DataReceive);
                break;

            case ReciveContext.DataReceive:
                sender.ReceiveAsync(_sizeBuffer, DATA_SIZE_BUFFER_LENGTH, ReciveContext.LengthReceive);

                IChannelMessage message = null;
                if (_formatter != null)
                {
                    message = _formatter.Deserialize(buffer) as IChannelMessage;
                }

                message.Channel = this;
                message.Source  = GetSourceAddress();


                try
                {
                    if (_eventListener != null)
                    {
                        _eventListener.ReceiveMessage(message);
                    }
                }
                catch (Exception e)
                {
                    if (_traceProvider != null)
                    {
                        _traceProvider.TraceError(Name + ".Run", e.ToString());
                    }
                }
                break;
            }
        }
Пример #16
0
        public object Deserialize(byte[] buffer)
        {
            IChannelMessage response = null;

            if (buffer != null)
            {
                response = (IChannelMessage)CompactBinaryFormatter.FromByteBuffer(buffer, null);
            }
            return(response);

            //CommandBase command = null;

            //using (MemoryStream stream = new MemoryStream(buffer))
            //{
            //    command = ProtoBuf.Serializer.Deserialize<CommandBase>(stream);
            //}

            //if (command.commandType == CommandBase.CommandType.RESPONSE)
            //{
            //    if (command.response.returnVal != null)
            //        command.response.ResponseMessage = CompactBinaryFormatter.FromByteBuffer(command.response.returnVal, null);
            //}
            //return command;
        }
Пример #17
0
            public void ReceiveMessage(IChannelMessage message)
            {
                try
                {
                    IRequest request = message as IRequest;
                    if (request != null)
                    {
                        if (_threadPool != null)
                        {
                            _threadPool.ExecuteTask(new RequestDeliverTask(message, _requestListener));
                        }
                        else
                        {
                            _requestListener.OnRequest(request);
                        }
                    }
                    else
                    {
                        IResponse response = message as IResponse;

                        if (_responseListener != null)
                        {
                            _responseListener.ReceiveMessage(message);
                        }
                        //if(response != null)
                        //    _threadPool.ExecuteTask(new ResponseDeliverTask(message, _responseListener));
                    }
                }
                catch (Exception ex)
                {
                    if (LoggerManager.Instance.ServerLogger != null && LoggerManager.Instance.ServerLogger.IsErrorEnabled)
                    {
                        LoggerManager.Instance.ServerLogger.Error("DualChannelListener.RecieveMessage", ex.Message);
                    }
                }
            }
Пример #18
0
 public void Write(IChannelMessage message, HttpListenerResponse response)
 {
     _msgService.WriteHttpResponse(message, response);
     OnPostMessageServiceInvoked?.Invoke(this, EventArgs.Empty);
 }
Пример #19
0
        public byte[] Serialize(object graph)
        {
            IChannelMessage command = graph as IChannelMessage;

            return(CompactBinaryFormatter.ToByteBuffer(command, null));
        }
Пример #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataReceivedEventArgs"/> class.
 /// </summary>
 /// <param name="message">The message.</param>
 public DataReceivedEventArgs(IChannelMessage message)
 {
     Message = message;
 }
Пример #21
0
 public RequestDeliverTask(IChannelMessage message, IRequestListener requestLisetner)
 {
     _message         = message;
     _requestListener = requestLisetner;
 }
Пример #22
0
        /// <summary>
        ///
        /// </summary>
        private void Run()
        {
            while (true)
            {
                try
                {
                    //receive data size for the response
                    if (_connection != null)
                    {
                        _connection.Receive(_sizeBuffer, DATA_SIZE_BUFFER_LENGTH);

                        int rspLength = Convert.ToInt32(UTF8Encoding.UTF8.GetString(_sizeBuffer, 0, _sizeBuffer.Length));

                        if (rspLength > 0)
                        {
                            byte[] dataBuffer = new byte[rspLength];
                            _connection.Receive(dataBuffer, rspLength);

                            //deserialize the message
                            IChannelMessage message = null;
                            if (_formatter != null)
                            {
                                message = _formatter.Deserialize(dataBuffer) as IChannelMessage;
                            }

                            message.Channel = this;
                            message.Source  = GetSourceAddress();
                            if (_eventListener != null)
                            {
                                _eventListener.ReceiveMessage(message);
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                catch (ThreadAbortException) { break; }
                catch (ThreadInterruptedException) { break; }
                catch (ConnectionException ce)
                {
                    if (_traceProvider != null && _forcedDisconnected)
                    {
                        _traceProvider.TraceError(Name + ".Run", ce.ToString());
                    }
                    if (_eventListener != null & !_forcedDisconnected)
                    {
                        _eventListener.ChannelDisconnected(ce.Message);
                    }
                    break;
                }
                catch (Exception e)
                {
                    if (_traceProvider != null)
                    {
                        _traceProvider.TraceError(Name + ".Run", e.ToString());
                    }
                    break;
                    //new ChannelException();
                }
            }
        }