public TResponse SendRequestMessage <TResponse, TRequest>(TRequest message)
        {
            using (EneterTrace.Entering())
            {
                try
                {
                    ISerializer aSerializer = mySerializer.ForResponseReceiver(AttachedDuplexOutputChannel.ResponseReceiverId);

                    MultiTypedMessage aRequest = new MultiTypedMessage();
                    aRequest.TypeName    = typeof(TRequest).Name;
                    aRequest.MessageData = aSerializer.Serialize <TRequest>(message);

                    MultiTypedMessage aResponse = mySender.SendRequestMessage(aRequest);

                    TResponse aResult = aSerializer.Deserialize <TResponse>(aResponse.MessageData);
                    return(aResult);
                }
                catch (Exception err)
                {
                    string anErrorMessage = TracedObject + ErrorHandler.FailedToSendMessage;
                    EneterTrace.Error(anErrorMessage, err);
                    throw;
                }
            }
        }
        public void OpenConnection()
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myConnectionManipulatorLock))
                {
                    if (IsConnected)
                    {
                        string aMessage = TracedObject + ErrorHandler.IsAlreadyConnected;
                        EneterTrace.Error(aMessage);
                        throw new InvalidOperationException(aMessage);
                    }

                    myOutputChannel.ConnectionOpened        += OnConnectionOpened;
                    myOutputChannel.ConnectionClosed        += OnConnectionClosed;
                    myOutputChannel.ResponseMessageReceived += OnResponseMessageReceived;

                    myConnectionOpeningRequestedToStopFlag = false;
                    myConnectionOpeningEndedEvent.Reset();

                    // Try open connection in a different thread.
                    myConnectionOpeningActiveFlag = true;
                    EneterThreadPool.QueueUserWorkItem(DoOpenConnection);

                    // Indicate the ConnectionOpened event shall be raised when the connection is really open.
                    myIsConnectionOpenEventPendingFlag = true;

                    // Indicate the connection is open.
                    myConnectionIsOpenFlag = true;
                }

                DuplexChannelEventArgs anEvent = new DuplexChannelEventArgs(ChannelId, ResponseReceiverId, "");
                Dispatcher.Invoke(() => Notify(ConnectionOffline, anEvent, false));
            }
        }
示例#3
0
        /// <summary>
        /// Deserializes data into the specified type.
        /// </summary>
        /// <remarks>
        /// It internally BinaryFormatter provided by .Net.
        /// </remarks>
        /// <typeparam name="_T">Type of serialized data.</typeparam>
        /// <param name="serializedData">the sequence of bytes (byte[]), to be deserialized.</param>
        /// <returns>Deserialized object.</returns>
        public _T Deserialize <_T>(object serializedData)
        {
            using (EneterTrace.Entering())
            {
                byte[] aData = (byte[])serializedData;

                if (aData.Length == 0)
                {
                    // It will return null.
                    return(default(_T));
                }

                try
                {
                    using (MemoryStream aMemoryStream = new MemoryStream(aData))
                    {
                        BinaryFormatter aBinaryFormatter = new BinaryFormatter();
                        if (myEnforceTypeBinding)
                        {
                            aBinaryFormatter.Binder = new Binder <_T>();
                        }
                        _T aDeserializedData = (_T)aBinaryFormatter.Deserialize(aMemoryStream);

                        return(aDeserializedData);
                    }
                }
                catch (Exception err)
                {
                    EneterTrace.Error("The deserialization from binary format failed.", err);
                    throw;
                }
            }
        }
        public void SendBroadcast(object message)
        {
            using (EneterTrace.Entering())
            {
                List <string> aDisconnectedClients = new List <string>();

                using (ThreadLock.Lock(myConnectedClients))
                {
                    foreach (string aClientId in myConnectedClients.Keys)
                    {
                        try
                        {
                            MessageBusMessage aMessage           = new MessageBusMessage(EMessageBusRequest.SendResponseMessage, aClientId, message);
                            object            aSerializedMessage = mySerializer.Serialize <MessageBusMessage>(aMessage);
                            myMessageBusOutputChannel.SendMessage(aSerializedMessage);
                        }
                        catch (Exception err)
                        {
                            EneterTrace.Error(TracedObject + ErrorHandler.FailedToSendResponseMessage, err);
                            aDisconnectedClients.Add(aClientId);

                            // Note: Exception is not rethrown because if sending to one client fails it should not
                            //       affect sending to other clients.
                        }
                    }
                }

                // Disconnect failed clients.
                foreach (String anOutputConnectorAddress in aDisconnectedClients)
                {
                    CloseConnection(anOutputConnectorAddress, true);
                }
            }
        }
示例#5
0
        /// <summary>
        /// Serializes data to the xml string.
        /// </summary>
        /// <remarks>
        /// It internally XmlSerializer provided by .Net.
        /// </remarks>
        /// <typeparam name="_T">Type of serialized data.</typeparam>
        /// <param name="dataToSerialize">Data to be serialized.</param>
        /// <returns>xml string</returns>
        public object Serialize <_T>(_T dataToSerialize)
        {
            using (EneterTrace.Entering())
            {
                string aSerializedObjectStr = "";

                try
                {
                    using (StringWriter aStringWriter = new StringWriter())
                    {
                        XmlWriterSettings anXmlSettings = new XmlWriterSettings();
                        anXmlSettings.OmitXmlDeclaration = true;
                        using (XmlWriter anXmlWriter = XmlWriter.Create(aStringWriter, anXmlSettings))
                        {
                            XmlSerializer xmlSerializer = myXmlSerializerFactoryMethod(typeof(_T));
                            xmlSerializer.Serialize(anXmlWriter, dataToSerialize);
                        }

                        aSerializedObjectStr = aStringWriter.ToString();
                    }
                }
                catch (Exception err)
                {
                    EneterTrace.Error("The serialization to XML failed.", err);
                    throw;
                }

                return(aSerializedObjectStr);
            }
        }
        private void SendFrame(Func <byte[], byte[]> formatter)
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myConnectionManipulatorLock))
                {
                    if (!IsConnected)
                    {
                        string aMessage = TracedObject + ErrorHandler.FailedToSendMessageBecauseNotConnected;
                        EneterTrace.Error(aMessage);
                        throw new InvalidOperationException(aMessage);
                    }

                    try
                    {
                        // Encode the message frame.
                        // Note: According to the protocol, server shall not mask sent data.
                        byte[] aFrame = formatter(null);

                        // Send the message.
                        myClientStream.Write(aFrame, 0, aFrame.Length);
                        //myClientStream.Flush();
                    }
                    catch (Exception err)
                    {
                        EneterTrace.Error(TracedObject + ErrorHandler.FailedToSendMessage, err);
                        throw;
                    }
                }
            }
        }
        private void OnResponseMessageReceived(object sender, DuplexChannelMessageEventArgs e)
        {
            using (EneterTrace.Entering())
            {
                try
                {
                    // Deserialize the message.
                    MonitorChannelMessage aMessage = mySerializer.Deserialize <MonitorChannelMessage>(e.Message);

                    // Note: timer setting is after deserialization.
                    //       reason: if deserialization fails the timer is not updated and the client will be disconnected.
                    using (ThreadLock.Lock(myConnectionManipulatorLock))
                    {
                        // Cancel the current response timeout and set the new one.
                        myReceiveTimer.Change(myReceiveTimeout);
                    }

                    // If it is a message.
                    if (aMessage.MessageType == MonitorChannelMessageType.Message)
                    {
                        Dispatcher.Invoke(() => Notify <DuplexChannelMessageEventArgs>(ResponseMessageReceived, new DuplexChannelMessageEventArgs(e.ChannelId, aMessage.MessageContent, e.ResponseReceiverId, e.SenderAddress), true));
                    }
                }
                catch (Exception err)
                {
                    EneterTrace.Error(TracedObject + ErrorHandler.FailedToReceiveMessage, err);
                }
            }
        }
        protected override void OnRequestMessageReceived(object sender, DuplexChannelMessageEventArgs e)
        {
            using (EneterTrace.Entering())
            {
                if (RequestReceived == null)
                {
                    EneterTrace.Warning(TracedObject + ErrorHandler.NobodySubscribedForMessage);
                    return;
                }

                if (e.Message is string == false)
                {
                    string anErrorMessage = TracedObject + "failed to receive the request message because the message is not string.";
                    EneterTrace.Error(anErrorMessage);
                    return;
                }

                try
                {
                    RequestReceived(this, new StringRequestReceivedEventArgs((string)e.Message, e.ResponseReceiverId, e.SenderAddress));
                }
                catch (Exception err)
                {
                    EneterTrace.Warning(TracedObject + ErrorHandler.DetectedException, err);
                }
            }
        }
        public void StartListening()
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myListeningManipulatorLock))
                {
                    myInputChannel.ResponseReceiverConnected    += OnResponseReceiverConnected;
                    myInputChannel.ResponseReceiverDisconnected += OnResponseReceiverDisconnected;
                    myInputChannel.MessageReceived += OnMessageReceived;

                    try
                    {
                        myInputChannel.StartListening();
                    }
                    catch (Exception err)
                    {
                        EneterTrace.Error(TracedObject + ErrorHandler.FailedToStartListening, err);
                        StopListening();
                        throw;
                    }

                    myMaxOfflineCheckerRequestedToStop = false;
                }
            }
        }
示例#10
0
        private void Attach(IDuplexInputChannel duplexInputChannel)
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myDuplexInputChannels))
                {
                    if (duplexInputChannel == null)
                    {
                        string aMessage = TracedObject + "failed to attach duplex input channel because the input parameter 'duplexInputChannel' is null.";
                        EneterTrace.Error(aMessage);
                        throw new ArgumentNullException(aMessage);
                    }

                    if (string.IsNullOrEmpty(duplexInputChannel.ChannelId))
                    {
                        string aMessage = TracedObject + "failed to attach duplex input channel because the input parameter 'duplexInputChannel' has empty or null channel id.";
                        EneterTrace.Error(aMessage);
                        throw new ArgumentException(aMessage);
                    }

                    if (myDuplexInputChannels.ContainsKey(duplexInputChannel.ChannelId))
                    {
                        string anErrorMessage = TracedObject + "failed to attach duplex input channel because the channel with id '" + duplexInputChannel.ChannelId + "' is already attached.";
                        EneterTrace.Error(anErrorMessage);
                        throw new InvalidOperationException(anErrorMessage);
                    }

                    myDuplexInputChannels[duplexInputChannel.ChannelId] = new TDuplexInputChannel(duplexInputChannel);

                    duplexInputChannel.MessageReceived += OnMessageReceived;
                }
            }
        }
示例#11
0
        public void AttachDuplexInputChannel(IDuplexInputChannel duplexInputChannel)
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myDuplexInputChannels))
                {
                    Attach(duplexInputChannel);

                    try
                    {
                        duplexInputChannel.StartListening();
                    }
                    catch (Exception err)
                    {
                        // Try to clean after the failure
                        try
                        {
                            DetachDuplexInputChannel(duplexInputChannel.ChannelId);
                        }
                        catch
                        {
                        }

                        string aMessage = TracedObject + "failed to start listening for '" + duplexInputChannel.ChannelId + "'.";
                        EneterTrace.Error(aMessage, err);
                        throw;
                    }
                }
            }
        }
示例#12
0
        /// <summary>
        /// The method is called when a message from the attached duplex input channel is received.
        /// The received message is wrapped and sent to the duplex output channel.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnMessageReceived(object sender, DuplexChannelMessageEventArgs e)
        {
            using (EneterTrace.Entering())
            {
                if (!IsDuplexOutputChannelAttached)
                {
                    EneterTrace.Error(TracedObject + "is not attached to the duplex output channel.");
                    return;
                }

                try
                {
                    using (ThreadLock.Lock(myDuplexInputChannels))
                    {
                        myDuplexInputChannels[e.ChannelId].ResponseReceiverId = e.ResponseReceiverId;
                    }

                    ISerializer aSerializer = mySerializer.ForResponseReceiver(e.ResponseReceiverId);
                    object      aMessage    = DataWrapper.Wrap(e.ChannelId, e.Message, aSerializer);
                    AttachedDuplexOutputChannel.SendMessage(aMessage);
                }
                catch (Exception err)
                {
                    EneterTrace.Error(TracedObject + "failed to send the message to the duplex output channel '" + e.ChannelId + "'.", err);
                }
            }
        }
示例#13
0
        // A message from the client was received.
        private void OnMessageFromClientReceived(object sender, DuplexChannelMessageEventArgs e)
        {
            using (EneterTrace.Entering())
            {
                MessageBusMessage aMessageBusMessage;
                try
                {
                    aMessageBusMessage = mySerializer.Deserialize <MessageBusMessage>(e.Message);
                }
                catch (Exception err)
                {
                    EneterTrace.Error(TracedObject + "failed to deserialize message from service. The service will be disconnected.", err);
                    UnregisterClient(e.ResponseReceiverId, true, true);
                    return;
                }

                if (aMessageBusMessage.Request == EMessageBusRequest.ConnectClient)
                {
                    EneterTrace.Debug("CLIENT OPENS CONNECTION TO '" + aMessageBusMessage.Id + "'.");
                    RegisterClient(e.ResponseReceiverId, aMessageBusMessage.Id);
                }
                else if (aMessageBusMessage.Request == EMessageBusRequest.SendRequestMessage)
                {
                    ForwardMessageToService(e.ResponseReceiverId, aMessageBusMessage);
                }
            }
        }
示例#14
0
        private IEnumerable <string> Send(string responseReceiverId, object serializedMessage)
        {
            using (EneterTrace.Entering())
            {
                if (AttachedDuplexInputChannel == null)
                {
                    string anErrorMessage = TracedObject + "failed to send the message because the it is not attached to duplex input channel.";
                    EneterTrace.Error(anErrorMessage);
                    throw new InvalidOperationException(anErrorMessage);
                }

                try
                {
                    AttachedDuplexInputChannel.SendResponseMessage(responseReceiverId, serializedMessage);
                }
                catch (Exception err)
                {
                    EneterTrace.Error(TracedObject + "failed to send the message. The client will be disconnected and unsubscribed from all messages.", err);

                    try
                    {
                        // Try to disconnect the client.
                        AttachedDuplexInputChannel.DisconnectResponseReceiver(responseReceiverId);
                    }
                    catch
                    {
                    }

                    // Unsubscribe the failed client.
                    return(Unsubscribe(responseReceiverId, null));
                }

                return(new string[0]);
            }
        }
示例#15
0
        private void OnMessageReceived(object sender, DuplexChannelMessageEventArgs e)
        {
            using (EneterTrace.Entering())
            {
                try
                {
                    using (ThreadLock.Lock(myResponseReceiverContexts))
                    {
                        TResponseReceiverContext aResponseReceiver = GetResponseReceiver(e.ResponseReceiverId);
                        if (aResponseReceiver == null)
                        {
                            // Note: the response receiver was just disconnected.
                            return;
                        }

                        aResponseReceiver.LastReceiveTime = DateTime.Now;
                    }

                    // Deserialize the incoming message.
                    MonitorChannelMessage aMessage = mySerializer.Deserialize <MonitorChannelMessage>(e.Message);

                    // if the message is ping, then response.
                    if (aMessage.MessageType == MonitorChannelMessageType.Message)
                    {
                        // Notify the incoming message.
                        DuplexChannelMessageEventArgs aMsg = new DuplexChannelMessageEventArgs(e.ChannelId, aMessage.MessageContent, e.ResponseReceiverId, e.SenderAddress);
                        Dispatcher.Invoke(() => NotifyGeneric(MessageReceived, aMsg, true));
                    }
                }
                catch (Exception err)
                {
                    EneterTrace.Error(TracedObject + ErrorHandler.FailedToReceiveMessage, err);
                }
            }
        }
        private void Attach(IDuplexInputChannel duplexInputChannel)
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myDuplexInputChannelManipulatorLock))
                {
                    if (duplexInputChannel == null)
                    {
                        string aMessage = TracedObject + "failed to attach duplex input channel because the input parameter 'duplexInputChannel' is null.";
                        EneterTrace.Error(aMessage);
                        throw new ArgumentNullException(aMessage);
                    }

                    if (string.IsNullOrEmpty(duplexInputChannel.ChannelId))
                    {
                        string aMessage = TracedObject + "failed to attach duplex input channel because the input parameter 'duplexInputChannel' has empty or null channel id.";
                        EneterTrace.Error(aMessage);
                        throw new ArgumentException(aMessage);
                    }

                    if (IsDuplexInputChannelAttached)
                    {
                        string aMessage = TracedObject + "failed to attach duplex input channel '" + duplexInputChannel.ChannelId + "' because the channel is already attached.";
                        EneterTrace.Error(aMessage);
                        throw new InvalidOperationException(aMessage);
                    }

                    AttachedDuplexInputChannel = duplexInputChannel;

                    AttachedDuplexInputChannel.MessageReceived              += OnRequestMessageReceived;
                    AttachedDuplexInputChannel.ResponseReceiverConnected    += OnResponseReceiverConnected;
                    AttachedDuplexInputChannel.ResponseReceiverDisconnected += OnResponseReceiverDisconnected;
                }
            }
        }
示例#17
0
        public void StartListening()
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myListeningManipulatorLock))
                {
                    if (IsListening)
                    {
                        string aMessage = TracedObject + ErrorHandler.IsAlreadyListening;
                        EneterTrace.Error(aMessage);
                        throw new InvalidOperationException(aMessage);
                    }

                    myUnderlyingInputChannel.ResponseReceiverConnected    += OnResponseReceiverConnected;
                    myUnderlyingInputChannel.ResponseReceiverDisconnected += OnResponseReceiverDisconnected;
                    myUnderlyingInputChannel.MessageReceived += OnMessageReceived;

                    try
                    {
                        myUnderlyingInputChannel.StartListening();
                    }
                    catch (Exception err)
                    {
                        EneterTrace.Error(TracedObject + ErrorHandler.FailedToStartListening, err);
                        StopListening();
                    }
                }
            }
        }
        public virtual void AttachDuplexInputChannel(IDuplexInputChannel duplexInputChannel)
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myDuplexInputChannelManipulatorLock))
                {
                    Attach(duplexInputChannel);

                    try
                    {
                        AttachedDuplexInputChannel.StartListening();
                    }
                    catch (Exception err)
                    {
                        try
                        {
                            DetachDuplexInputChannel();
                        }
                        catch
                        {
                            // Ignore exception in exception.
                        }

                        EneterTrace.Error(TracedObject + ErrorHandler.FailedToStartListening, err);
                        throw;
                    }
                }
            }
        }
示例#19
0
        public NamedPipeSender(string uriPipeName, int connectionTimeout)
        {
            using (EneterTrace.Entering())
            {
                try
                {
                    // Extract server name and pipe name from Uri.
                    Uri aUri = null;
                    try
                    {
                        aUri = new Uri(uriPipeName, UriKind.Absolute);
                    }
                    catch (Exception err)
                    {
                        EneterTrace.Error(uriPipeName + ErrorHandler.InvalidUriAddress, err);
                        throw;
                    }
                    string aServerName = aUri.Host;
                    string aPipeName   = "";
                    for (int i = 1; i < aUri.Segments.Length; ++i)
                    {
                        aPipeName += aUri.Segments[i].TrimEnd('/');
                    }

                    myClientStream = new NamedPipeClientStream(aServerName, aPipeName, PipeDirection.Out, PipeOptions.Asynchronous);
                    myClientStream.Connect(connectionTimeout);
                }
                catch (Exception err)
                {
                    EneterTrace.Error(TracedObject + "failed in constructor.", err);
                    Dispose();
                    throw;
                }
            }
        }
示例#20
0
        /// <summary>
        /// Constructs the factory.
        /// </summary>
        /// <param name="certificate">Server certificate.</param>
        /// <param name="isClientCertificateRequired">true - if the client identity is verified too.</param>
        /// <param name="userCertificateValidationCallback">User provided delegate for validating the certificate supplied by the remote party.</param>
        /// <param name="userCertificateSelectionCallback">User provided delegate for selecting the certificate used for authentication.</param>
        public ServerSslFactory(X509Certificate certificate,
                                bool isClientCertificateRequired,
                                RemoteCertificateValidationCallback userCertificateValidationCallback,
                                LocalCertificateSelectionCallback userCertificateSelectionCallback)
        {
            using (EneterTrace.Entering())
            {
                if (certificate == null)
                {
                    string anError = TracedObject + "failed in constructor because the input parameter 'certificate' was null.";
                    EneterTrace.Error(anError);
                    throw new ArgumentNullException(anError);
                }

                AcceptedProtocols = SslProtocols.Ssl3 | SslProtocols.Tls;

#if NETSTANDARD || NET472
                AcceptedProtocols |= SslProtocols.Tls11 | SslProtocols.Tls12;
#endif
#if MONOANDROID || XAMARIN_IOS
                AcceptedProtocols |= SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13;
#endif

                myCertificate = certificate;
                myIsClientCertificateRequired       = isClientCertificateRequired;
                myUserCertificateValidationCallback = userCertificateValidationCallback;
                myUserCertificateSelectionCallback  = userCertificateSelectionCallback;
            }
        }
        public void OpenConnection()
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myConnectionManipulatorLock))
                {
                    if (IsConnected)
                    {
                        string aMessage = TracedObject + ErrorHandler.IsAlreadyConnected;
                        EneterTrace.Error(aMessage);
                        throw new InvalidOperationException(aMessage);
                    }

                    try
                    {
                        // Start timers.
                        myPingingTimer.Change(myPingFrequency);
                        myReceiveTimer.Change(myReceiveTimeout);

                        // Open connection in the underlying channel.
                        myUnderlyingOutputChannel.OpenConnection();
                    }
                    catch (Exception err)
                    {
                        EneterTrace.Error(TracedObject + ErrorHandler.FailedToOpenConnection, err);
                        CloseConnection();
                        throw;
                    }
                }
            }
        }
示例#22
0
        public static TServiceInterface CreateInstance <TServiceInterface>(Func <string, object[], object> call,
                                                                           Action <string, Delegate, Action <object, EventArgs> > subscribe,
                                                                           Action <string, Delegate> unsubscribe)
        {
            using (EneterTrace.Entering())
            {
                Type anInterfaceType = typeof(TServiceInterface);
                if (!anInterfaceType.IsInterface)
                {
                    string anErrorMessage = "Provided service interface '" + anInterfaceType.Name + "' is not interface.";
                    EneterTrace.Error(anErrorMessage);
                    throw new ArgumentException(anErrorMessage);
                }


                Type anImplementedClass = null;
                using (ThreadLock.Lock(myImplementedInterfaces))
                {
                    myImplementedInterfaces.TryGetValue(anInterfaceType, out anImplementedClass);
                    if (anImplementedClass == null)
                    {
                        // Dynamically implement proxy for the given interface.
                        SoftwareEngineer anEngineer = new SoftwareEngineer();
                        anImplementedClass = anEngineer.ImplementProxy(anInterfaceType);

                        myImplementedInterfaces[anInterfaceType] = anImplementedClass;
                    }

                    // Instantiate the proxy.
                    TServiceInterface aProxyInstance = (TServiceInterface)Activator.CreateInstance(anImplementedClass, call, subscribe, unsubscribe);
                    return(aProxyInstance);
                }
            }
        }
        /// <summary>
        /// Method is called when a response is received from the duplex output channel.
        /// It wrapps the response and sends the wrapped response to the correct response receiver as the response.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnResponseMessageReceived(object sender, DuplexChannelMessageEventArgs e)
        {
            using (EneterTrace.Entering())
            {
                try
                {
                    // try to find the response receiver id where the wrapped message should be responded.
                    TDuplexConnection aConnction = null;
                    using (ThreadLock.Lock(myConnections))
                    {
                        aConnction = myConnections.FirstOrDefault(x => x.DuplexOutputChannel == (IDuplexOutputChannel)sender);
                    }

                    if (aConnction != null)
                    {
                        ISerializer aSerializer = mySerializer.ForResponseReceiver(aConnction.ResponseReceiverId);

                        object aMessage = DataWrapper.Wrap(e.ChannelId, e.Message, aSerializer);
                        AttachedDuplexInputChannel.SendResponseMessage(aConnction.ResponseReceiverId, aMessage);
                    }
                    else
                    {
                        EneterTrace.Warning(TracedObject + "failed to send the response message because the response receiver id does not exist. It is possible the response receiver has already been disconnected.");
                    }
                }
                catch (Exception err)
                {
                    EneterTrace.Error(TracedObject + ErrorHandler.FailedToSendResponseMessage, err);
                }
            }
        }
示例#24
0
        private void SendFrame(Func <byte[], byte[]> formatter)
        {
            using (EneterTrace.Entering())
            {
                using (ThreadLock.Lock(myConnectionManipulatorLock))
                {
                    if (!IsConnected)
                    {
                        string aMessage = TracedObject + ErrorHandler.FailedToSendMessageBecauseNotConnected;
                        EneterTrace.Error(aMessage);
                        throw new InvalidOperationException(aMessage);
                    }

                    try
                    {
                        // Encode the message frame.
                        byte[] aMaskingKey = GetMaskingKey();
                        byte[] aFrame      = formatter(aMaskingKey);

                        // Send the message.
                        myClientStream.Write(aFrame, 0, aFrame.Length);
                    }
                    catch (Exception err)
                    {
                        EneterTrace.Error(TracedObject + ErrorHandler.FailedToSendMessage, err);
                        throw;
                    }
                }
            }
        }
示例#25
0
        public void SendMessage(string receiverId, object message)
        {
            using (EneterTrace.Entering())
            {
                // Get the message handler
                Action <object> aMessageHandler = null;

                using (ThreadLock.Lock(myRegisteredMessageHandlers))
                {
                    myRegisteredMessageHandlers.TryGetValue(receiverId, out aMessageHandler);
                }

                // If the message handler was found then send the message
                if (aMessageHandler != null)
                {
                    Action aHelperCallback = () =>
                    {
                        aMessageHandler(message);
                    };

                    EneterThreadPool.QueueUserWorkItem(aHelperCallback.Invoke);
                }
                else
                {
                    string anError = "The receiver '" + receiverId + "' does not exist.";
                    EneterTrace.Error(anError);
                    throw new InvalidOperationException(anError);
                }
            }
        }
        public HttpInputConnector(string httpAddress, IProtocolFormatter protocolFormatter, int responseReceiverInactivityTimeout)
        {
            using (EneterTrace.Entering())
            {
                Uri aUri;
                try
                {
                    // just check if the channel id is a valid Uri
                    aUri = new Uri(httpAddress);
                }
                catch (Exception err)
                {
                    EneterTrace.Error(httpAddress + ErrorHandler.InvalidUriAddress, err);
                    throw;
                }
                myHttpListenerProvider = new HttpWebServer(aUri.AbsoluteUri);

                myProtocolFormatter = protocolFormatter;
                myResponseReceiverInactivityTimeout = responseReceiverInactivityTimeout;


                // Initialize the timer to regularly check the timeout for connections with duplex output channels.
                // If the duplex output channel did not poll within the timeout then the connection
                // is closed and removed from the list.
                // Note: The timer is set here but not executed.
                myResponseReceiverInactivityTimer = new Timer(OnConnectionCheckTimer, null, -1, -1);
            }
        }
        public TcpOutputConnector(string ipAddressAndPort, string outputConnectorAddress, IProtocolFormatter protocolFormatter, ISecurityFactory clientSecurityFactory,
                                  int connectTimeout, int sendTimeout, int receiveTimeout, int sendBuffer, int receiveBuffer,
                                  bool reuseAddressFlag,
                                  int responseReceivingPort)
        {
            using (EneterTrace.Entering())
            {
                try
                {
                    myUri = new Uri(ipAddressAndPort, UriKind.Absolute);
                }
                catch (Exception err)
                {
                    EneterTrace.Error(ipAddressAndPort + ErrorHandler.InvalidUriAddress, err);
                    throw;
                }

                myOutputConnectorAddress = outputConnectorAddress;
                myClientSecurityFactory  = clientSecurityFactory;
                myProtocolFormatter      = protocolFormatter;
                myConnectTimeout         = (connectTimeout != 0) ? connectTimeout : -1;
                mySendTimeout            = sendTimeout;
                myReceiveTimeout         = receiveTimeout;
                mySendBuffer             = sendBuffer;
                myReceiveBuffer          = receiveBuffer;
                myReuseAddressFlag       = reuseAddressFlag;
                myResponseReceivingPort  = responseReceivingPort;
            }
        }
 public void SendBroadcast(object message)
 {
     using (EneterTrace.Entering())
     {
         using (ThreadLock.Lock(myConnectedClients))
         {
             // Send the response message to all connected clients.
             foreach (HttpResponseSender aClientContext in myConnectedClients)
             {
                 if (!aClientContext.IsDisposed)
                 {
                     try
                     {
                         object anEncodedMessage = myProtocolFormatter.EncodeMessage(aClientContext.ResponseReceiverId, message);
                         aClientContext.SendResponseMessage(anEncodedMessage);
                     }
                     catch (Exception err)
                     {
                         // This should never happen because it is not called when disposed.
                         EneterTrace.Error(TracedObject + "failed to send the broadcast message.", err);
                     }
                 }
             }
         }
     }
 }
示例#29
0
        /// <summary>
        /// Serializes data to the sequnce of bytes, byte[].
        /// </summary>
        /// <remarks>
        /// It internally BinaryFormatter provided by .Net.
        /// </remarks>
        /// <typeparam name="_T">Type of serialized data.</typeparam>
        /// <param name="dataToSerialize">Data to be serialized.</param>
        /// <returns>Data serialized in byte[].</returns>
        public object Serialize <_T>(_T dataToSerialize)
        {
            using (EneterTrace.Entering())
            {
                try
                {
                    using (MemoryStream aMemoryStream = new MemoryStream())
                    {
                        // Note: BinaryFormatter is not able to serialize null.
                        if (dataToSerialize == null)
                        {
                            return(myNull);
                        }

                        BinaryFormatter aBinaryFormatter = new BinaryFormatter();
                        aBinaryFormatter.Serialize(aMemoryStream, dataToSerialize);
                        byte[] aSerializedData = aMemoryStream.ToArray();

                        return(aSerializedData);
                    }
                }
                catch (Exception err)
                {
                    EneterTrace.Error("The serialization to binary format failed.", err);
                    throw;
                }
            }
        }
示例#30
0
        /// <summary>
        /// Creates security stream and authenticates as client.
        /// </summary>
        /// <param name="source">The stream wrapped by the security stream.</param>
        /// <returns>Security stream of type NegotiateStream.</returns>
        public Stream CreateSecurityStreamAndAuthenticate(Stream source)
        {
            using (EneterTrace.Entering())
            {
                NegotiateStream aNegotiateStream = new NegotiateStream(source, false);

                try
                {
                    if (myNetworkCredential != null && !string.IsNullOrEmpty(myServicePrincipalName))
                    {
                        aNegotiateStream.AuthenticateAsClient(myNetworkCredential, myServicePrincipalName);
                    }
                    else
                    {
                        aNegotiateStream.AuthenticateAsClient();
                    }
                }
                catch (Exception err)
                {
                    EneterTrace.Error(TracedObject + "failed to authenticate the client.", err);
                    throw;
                }

                return(aNegotiateStream);
            }
        }