/// <summary>
 /// Encodes close connection request.
 /// </summary>
 /// <param name="responseReceiverId">client id</param>
 /// <returns></returns>
 public object EncodeCloseConnectionMessage(string responseReceiverId)
 {
     using (EneterTrace.Entering())
     {
         using (MemoryStream aBuffer = new MemoryStream())
         {
             EncodeCloseConnectionMessage(responseReceiverId, aBuffer);
             return(aBuffer.ToArray());
         }
     }
 }
Пример #2
0
 // Attaches input channels for services and their channels and starts listening.
 public void AttachDuplexInputChannels(IDuplexInputChannel serviceInputChannel, IDuplexInputChannel clientInputChannel)
 {
     using (EneterTrace.Entering())
     {
         using (ThreadLock.Lock(myAttachDetachLock))
         {
             myServiceConnector.AttachDuplexInputChannel(serviceInputChannel);
             myClientConnector.AttachDuplexInputChannel(clientInputChannel);
         }
     }
 }
Пример #3
0
        private void RegisterService(string serviceId, string serviceResponseReceiverId)
        {
            using (EneterTrace.Entering())
            {
                bool            anIsNewServiceRegistered = false;
                TServiceContext aServiceContext          = null;
                using (ThreadLock.Lock(myConnectionLock))
                {
                    aServiceContext = myConnectedServices.FirstOrDefault(x => x.ServiceId == serviceId || x.ServiceResponseReceiverId == serviceResponseReceiverId);
                    if (aServiceContext == null)
                    {
                        aServiceContext = new TServiceContext(serviceId, serviceResponseReceiverId);
                        myConnectedServices.Add(aServiceContext);
                        anIsNewServiceRegistered = true;
                    }
                }

                if (anIsNewServiceRegistered)
                {
                    if (ServiceRegistered != null)
                    {
                        try
                        {
                            MessageBusServiceEventArgs anEvent = new MessageBusServiceEventArgs(serviceId, serviceResponseReceiverId);
                            ServiceRegistered(this, anEvent);
                        }
                        catch (Exception err)
                        {
                            EneterTrace.Error(TracedObject + ErrorHandler.DetectedException, err);
                        }
                    }
                }
                else
                {
                    // If this connection has registered the same service then do nothing.
                    if (aServiceContext.ServiceId == serviceId &&
                        aServiceContext.ServiceResponseReceiverId == serviceResponseReceiverId)
                    {
                    }
                    else if (aServiceContext.ServiceId != serviceId &&
                             aServiceContext.ServiceResponseReceiverId == serviceResponseReceiverId)
                    {
                        EneterTrace.Warning("The connection has already registered a different service '" + aServiceContext.ServiceId + "'. Connection will be disconnected.");
                        UnregisterService(serviceResponseReceiverId);
                    }
                    else if (aServiceContext.ServiceId == serviceId &&
                             aServiceContext.ServiceResponseReceiverId != serviceResponseReceiverId)
                    {
                        EneterTrace.Warning("Service '" + serviceId + "' is already registered. Connection will be disconnected.");
                        UnregisterService(serviceResponseReceiverId);
                    }
                }
            }
        }
Пример #4
0
 /// <summary>
 /// Puts message to the queue.
 /// </summary>
 /// <param name="message">message that shall be enqueued</param>
 public void EnqueueMessage(TMessage message)
 {
     using (EneterTrace.Entering())
     {
         lock (myMessageQueue)
         {
             myMessageQueue.Enqueue(message);
             Monitor.Pulse(myMessageQueue);
         }
     }
 }
Пример #5
0
 public IEnumerable <string> GetSubscribedResponseReceivers(string messageTypeId)
 {
     using (EneterTrace.Entering())
     {
         using (ThreadLock.Lock(mySubscribtions))
         {
             string[] aResult = mySubscribtions.Where(x => x.MessageTypeId == messageTypeId).Select(y => y.ReceiverId).ToArray();
             return(aResult);
         }
     }
 }
Пример #6
0
 public bool ExistListener(Uri address)
 {
     using (EneterTrace.Entering())
     {
         using (ThreadLock.Lock(myHandlers))
         {
             bool isAny = myHandlers.Any(x => x.Key.AbsolutePath == address.AbsolutePath);
             return(isAny);
         }
     }
 }
Пример #7
0
 /// <summary>
 /// Releases all threads waiting for messages in DequeueMessage() and sets the queue to the unblocking mode.
 /// </summary>
 /// <remarks>
 /// When the queue is in unblocking mode, the dequeue or peek will not block if data is not available but
 /// it will return null or default values.
 /// </remarks>
 public void UnblockProcessingThreads()
 {
     using (EneterTrace.Entering())
     {
         lock (myMessageQueue)
         {
             myIsBlockingMode = false;
             Monitor.PulseAll(myMessageQueue);
         }
     }
 }
 public NamedPipeInputConnector(string inputConnectorAddress, IProtocolFormatter protocolFormatter, int connectionTimeout, int numberOfListeningInstances, PipeSecurity security)
 {
     using (EneterTrace.Entering())
     {
         myInputConnectorAddress = inputConnectorAddress;
         myProtocolFormatter = protocolFormatter;
         myConnectionTimeout = connectionTimeout;
         myNumberOfListeningInstances = numberOfListeningInstances;
         mySecurity = security;
     }
 }
Пример #9
0
 public void SendResponseMessage(object message)
 {
     using (EneterTrace.Entering())
     {
         using (ThreadLock.Lock(mySenderLock))
         {
             byte[] aMessage = (byte[])message;
             myClientStream.Write(aMessage, 0, aMessage.Length);
         }
     }
 }
Пример #10
0
 public void SendRequestMessage(object message)
 {
     using (EneterTrace.Entering())
     {
         using (ThreadLock.Lock(myConnectionManipulatorLock))
         {
             object anEncodedMessage = myProtocolFormatter.EncodeMessage(myOutputConnectorAddress, message);
             myClient.SendMessage(anEncodedMessage);
         }
     }
 }
 /// <summary>
 /// Creates duplex input channel.
 /// </summary>
 /// <remarks>
 /// Channel id represents the logical address of the service inside the message bus. E.g. "Eneter.EchoService".
 /// </remarks>
 /// <param name="channelId">logical address of the service inside the message bus</param>
 /// <returns>duplex input channel</returns>
 public IDuplexInputChannel CreateDuplexInputChannel(string channelId)
 {
     using (EneterTrace.Entering())
     {
         IThreadDispatcher         aDispatcher = InputChannelThreading.GetDispatcher();
         IThreadDispatcher         aDispatcherAfterMessageDecoded = myDispatchingAfterMessageDecoded.GetDispatcher();
         IInputConnector           anInputConnector = myInputConnectorFactory.CreateInputConnector(channelId);
         DefaultDuplexInputChannel anInputChannel   = new DefaultDuplexInputChannel(channelId, aDispatcher, aDispatcherAfterMessageDecoded, anInputConnector);
         return(anInputChannel);
     }
 }
Пример #12
0
 public void SendRequestMessage(object message)
 {
     using (EneterTrace.Entering())
     {
         // Note: do not send the client id. It will be automatically assign in the message bus before forwarding the message to the service.
         //       It is done like this due to security reasons. So that some client cannot pretend other client just by sending a different id.
         MessageBusMessage aMessage           = new MessageBusMessage(EMessageBusRequest.SendRequestMessage, "", message);
         object            aSerializedMessage = mySerializer.Serialize <MessageBusMessage>(aMessage);
         myMessageBusOutputChannel.SendMessage(aSerializedMessage);
     }
 }
Пример #13
0
 public MessageBusOutputConnector(string inputConnectorAddress, ISerializer serializer, IDuplexOutputChannel messageBusOutputChannel,
                                  int openConnectionTimeout)
 {
     using (EneterTrace.Entering())
     {
         myServiceId  = inputConnectorAddress;
         mySerializer = serializer;
         myMessageBusOutputChannel = messageBusOutputChannel;
         myOpenConnectionTimeout   = (openConnectionTimeout == 0) ? -1 : openConnectionTimeout;
     }
 }
Пример #14
0
 public void RemoveDuplexOutputChannel(string channelId)
 {
     using (EneterTrace.Entering())
     {
         using (ThreadLock.Lock(myChannelManipulatorLock))
         {
             myOutputChannelIds.Remove(channelId);
             CloseOutputChannel(channelId);
         }
     }
 }
Пример #15
0
 /// <summary>
 ///  Creates the duplex input channel which can receive and send messages to the duplex output channel using shared memory.
 /// </summary>
 /// <param name="channelId">Address which shell be used for listening.
 /// It is the name of the memory-mapped file that will be used to send and receive messages.
 /// </param>
 /// <returns>duplex input channel</returns>
 public IDuplexInputChannel CreateDuplexInputChannel(string channelId)
 {
     using (EneterTrace.Entering())
     {
         IInputConnectorFactory aConnectorFactory = new SharedMemoryConnectorFactory(myProtocolFormatter, ConnectTimeout, SendTimeout, MaxMessageSize, SharedMemorySecurity);
         IThreadDispatcher      aThreadDispatcher = InputChannelThreading.GetDispatcher();
         IInputConnector        anInputConnector  = aConnectorFactory.CreateInputConnector(channelId);
         IThreadDispatcher      aDispatcherAfterMessageDecoded = myDispatchingAfterMessageDecoded.GetDispatcher();
         return(new DefaultDuplexInputChannel(channelId, aThreadDispatcher, aDispatcherAfterMessageDecoded, anInputConnector));
     }
 }
Пример #16
0
 public SharedMemoryConnectorFactory(IProtocolFormatter protocolFormatter, TimeSpan connectTimeout, TimeSpan sendTimeout, int maxMessageSize, MemoryMappedFileSecurity memoryMappedFileSecurity)
 {
     using (EneterTrace.Entering())
     {
         myProtocolFormatter = protocolFormatter;
         myConnectTimeout    = connectTimeout;
         mySendTimeout       = sendTimeout;
         myMaxMessageSize    = maxMessageSize;
         mySecurity          = memoryMappedFileSecurity;
     }
 }
 public void SendResponseMessage(string outputConnectorAddress, object message)
 {
     using (EneterTrace.Entering())
     {
         Uri        aUri             = new Uri(outputConnectorAddress);
         IPAddress  anIpAddress      = IPAddress.Parse(aUri.Host);
         IPEndPoint anEndpoint       = new IPEndPoint(anIpAddress, aUri.Port);
         byte[]     anEncodedMessage = (byte[])myProtocolFormatter.EncodeMessage(outputConnectorAddress, message);
         myReceiver.SendTo(anEncodedMessage, anEndpoint);
     }
 }
Пример #18
0
 public CallbackSerializer(GetSerializerCallback getSerializerCallback)
 {
     using (EneterTrace.Entering())
     {
         if (getSerializerCallback == null)
         {
             throw new ArgumentNullException("getSerializerCallback is null");
         }
         GetSerializerCallback = getSerializerCallback;
     }
 }
Пример #19
0
 public void SendRequestMessage(object message)
 {
     using (EneterTrace.Entering())
     {
         using (ThreadLock.Lock(myConnectionManipulatorLock))
         {
             object anEncodedMessage = myProtocolFormatter.EncodeMessage(myResponseReceiverId, message);
             SendMessage(anEncodedMessage);
         }
     }
 }
Пример #20
0
            private void Newarr <T>(ILGenerator gen, int length)
            {
                using (EneterTrace.Entering())
                {
                    // Push the size of the array to the stack.
                    Ldc_I4(gen, length);

                    // Allocate the array and store the reference on the stack.
                    gen.Emit(OpCodes.Newarr, typeof(T));
                }
            }
        public void CloseConnection()
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myConnectionManipulatorLock))
                {
                    myResponseMessageHandler = null;

                    myResponseReceiver.StopListening();
                }
            }
        }
 public void TearDown()
 {
     EneterTrace.StopProfiler();
     EneterTrace.DetailLevel = EneterTrace.EDetailLevel.Short;
     if (EneterTrace.TraceLog is StreamWriter)
     {
         Thread.Sleep(500);
         TextWriter aTrace = EneterTrace.TraceLog;
         EneterTrace.TraceLog = null;
         aTrace.Close();
     }
 }
        /// <summary>
        /// Creates the duplex input channel which can receive and send messages to the duplex output channel using UDP.
        /// </summary>
        /// <remarks>
        /// It can create duplex input channels for unicast, multicast or broadcast communication.
        /// If the property UnicastCommunication is set to true then it creates the input channel for the unicast communication.
        /// It means, like a service it can receive connections and messages from multiple output channels but
        /// send messages only to particular output channels which are connected.
        /// If the property UnicastCommunication is set to false then it creates the output channel for mulitcast or broadcast communication.
        /// It means it can send mulitcast or broadcast messages which can be received by multiple output channels.
        /// It also can receive multicast and broadcast messages.
        /// <example>
        /// Creating the duplex input channel for unicast communication.
        /// <code>
        /// IMessagingSystemFactory aMessaging = new UdpMessagingSystemFactory();
        /// IDuplexInputChannel anInputChannel = aMessaging.CreateDuplexInputChannel("udp://127.0.0.1:8765/");
        /// </code>
        /// </example>
        /// <example>
        /// Creating the duplex input channel for multicast communication.
        /// <code>
        /// IProtocolFormatter aProtocolFormatter = new EasyProtocolFormatter();
        /// IMessagingSystemFactory aMessaging = new UdpMessagingSystemFactory(aProtocolFormatter)
        /// {
        ///     // Setup the factory to create channels for mulitcast or broadcast communication.
        ///     UnicastCommunication = false,
        ///
        ///     // Specify the mulitcast group to receive messages from.
        ///     MulticastGroupToReceive = "234.4.5.6"
        /// }
        ///
        /// // Create duplex input channel which is listening to udp://127.0.0.1:8095/ and can also receive multicast messages
        /// // sent to udp://234.4.5.6:8095/.
        /// IDuplexInputChannel anInputChannel = aMessaging.CreateDuplexInputChannel("udp://127.0.0.1:8095/");
        /// </code>
        /// </example>
        /// <example>
        /// Sending mulitcast and broadcast messages from the duplex input channel.
        /// <code>
        /// IProtocolFormatter aProtocolFormatter = new EasyProtocolFormatter();
        /// IMessagingSystemFactory aMessaging = new UdpMessagingSystemFactory(aProtocolFormatter)
        /// {
        ///     // Setup the factory to create channels for mulitcast or broadcast communication.
        ///     UnicastCommunication = false,
        ///
        ///     // Setup the factory to create chennels which are allowed to send broadcast messages.
        ///     AllowSendingBroadcasts = true
        /// }
        ///
        /// // Create duplex input channel which is listening to udp://127.0.0.1:8095/.
        /// IDuplexInputChannel anInputChannel = aMessaging.CreateDuplexInputChannel("udp://127.0.0.1:8095/");
        ///
        /// // Subscribe to handle messages.
        /// anIputChannel.MessageReceived += OnMessageReceived;
        ///
        /// // Start listening.
        /// anIputChannel.StartListening();
        ///
        /// ...
        ///
        /// // Send a multicast message.
        /// // Note: it will be received by all output and input channels which have joined the multicast group 234.4.5.6
        /// // and are listening to the port 8095.
        /// anInputChannel.SendResponseMessage("udp://234.4.5.6:8095/", "Hello");
        ///
        /// ...
        ///
        /// // Send a broadcast message.
        /// // Note: it will be received by all output and input channels within the sub-network which are listening to the port 8095.
        /// anInputChannel.SendResponseMessage("udp://255.255.255.255:8095/", "Hello");
        ///
        /// ...
        ///
        /// // Stop listening.
        /// anInputChannel.StopListening();
        /// </code>
        /// </example>
        /// </remarks>
        /// <param name="channelId">Identifies this duplex input channel. The channel id must be a valid URI address (e.g. udp://127.0.0.1:8090/) the input channel will listen to.</param>
        /// <returns>duplex input channel</returns>
        public IDuplexInputChannel CreateDuplexInputChannel(string channelId)
        {
            using (EneterTrace.Entering())
            {
                IThreadDispatcher aDispatcher = InputChannelThreading.GetDispatcher();

                IInputConnectorFactory aConnectorFactory = new UdpConnectorFactory(myProtocolFormatter, ReuseAddress, -1, UnicastCommunication, AllowSendingBroadcasts, Ttl, MulticastGroupToReceive, MulticastLoopback, MaxAmountOfConnections);
                IInputConnector        anInputConnector  = aConnectorFactory.CreateInputConnector(channelId);

                return(new DefaultDuplexInputChannel(channelId, aDispatcher, myDispatcherAfterMessageDecoded, anInputConnector));
            }
        }
Пример #24
0
        public void StartListening(Action <TcpClient> connectionHandler)
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myListeningManipulatorLock))
                {
                    if (IsListening)
                    {
                        string aMessage = TracedObject + ErrorHandler.IsAlreadyListening;
                        EneterTrace.Error(aMessage);
                        throw new InvalidOperationException(aMessage);
                    }

                    if (connectionHandler == null)
                    {
                        throw new ArgumentNullException("The input parameter connectionHandler is null.");
                    }

                    try
                    {
                        myStopListeningRequested = false;
                        myAmountOfConnections    = 0;

                        myConnectionHandler = connectionHandler;

                        myListener = new TcpListener(myAddress);
                        myListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, myReuseAddressFlag);
                        myListener.Server.LingerState = new LingerOption(true, 0);
                        myListener.Start();

                        // Listen in another thread
                        myListeningThread = new Thread(DoTcpListening);
                        myListeningThread.Start();
                    }
                    catch (Exception err)
                    {
                        EneterTrace.Error(TracedObject + ErrorHandler.FailedToStartListening, err);

                        try
                        {
                            // Clear after failed start
                            StopListening();
                        }
                        catch
                        {
                            // We tried to clean after failure. The exception can be ignored.
                        }

                        throw;
                    }
                }
            }
        }
 public void StopListening()
 {
     using (EneterTrace.Entering())
     {
         using (ThreadLock.Lock(myListeningManipulatorLock))
         {
             myMessageBusOutputChannel.CloseConnection();
             myMessageBusOutputChannel.ResponseMessageReceived -= OnMessageFromMessageBusReceived;
             myMessageHandler = null;
         }
     }
 }
Пример #26
0
        /// <summary>
        /// Disables the automatic reconnecting.
        /// </summary>
        public void DisableReconnecting()
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myMonitoringManipulatorLock))
                {
                    myIsMonitoringFlag = false;

                    myDuplexOutputChannel.ConnectionClosed -= OnConnectionClosed;
                }
            }
        }
Пример #27
0
        public static byte[] ReadBytes(Stream inputStream, int length)
        {
            using (EneterTrace.Entering())
            {
                using (MemoryStream aBuf = new MemoryStream())
                {
                    ReadBytes(inputStream, length, aBuf);

                    return(aBuf.ToArray());
                }
            }
        }
Пример #28
0
 public static void ReadToEnd(Stream inputStream, Stream outputStream)
 {
     using (EneterTrace.Entering())
     {
         int    aSize   = 0;
         byte[] aBuffer = new byte[32768];
         while ((aSize = inputStream.Read(aBuffer, 0, aBuffer.Length)) != 0)
         {
             outputStream.Write(aBuffer, 0, aSize);
         }
     }
 }
Пример #29
0
        public static byte[] ReadToEnd(Stream inputStream)
        {
            using (EneterTrace.Entering())
            {
                using (MemoryStream aBuf = new MemoryStream())
                {
                    ReadToEnd(inputStream, aBuf);

                    return(aBuf.ToArray());
                }
            }
        }
        public void DisconnectResponseReceiver(string responseReceiverId)
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myResponseReceivers))
                {
                    myResponseReceivers.RemoveWhere(x => x.ResponseReceiverId == responseReceiverId);
                }

                myInputChannel.DisconnectResponseReceiver(responseReceiverId);
            }
        }