private IDbCommand CreateNew() { var conn = new TConnection { ConnectionString = _template.Connection.ConnectionString }; var newItem = conn.CreateCommand(); newItem.CommandText = _template.CommandText; foreach (IDbDataParameter parameter in _template.Parameters) { IDbDataParameter pNew = newItem.CreateParameter(); pNew.DbType = parameter.DbType; pNew.Direction = parameter.Direction; //pNew.IsNullable = parameter.IsNullable; pNew.ParameterName = parameter.ParameterName; pNew.Precision = parameter.Precision; pNew.Scale = parameter.Scale; pNew.Size = parameter.Size; pNew.SourceColumn = parameter.SourceColumn; #if !(SILVERLIGHT || WINDOWS_PHONE) pNew.SourceVersion = parameter.SourceVersion; #endif //pNew.Value = ()parameter.Value. newItem.Parameters.Add(pNew); } _maxStore++; return(newItem); }
/// <summary> /// It is called when a connection with the receiver is broken. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnOutputChannelConnectionClosed(object sender, DuplexChannelEventArgs e) { using (EneterTrace.Entering()) { TConnection aNewConnection = null; using (ThreadLock.Lock(myConnectionsLock)) { // Find the client id associated with the duplex output channel which raised this event. // Note: We need to get the response receiver id representing the client connected to this BackupRouter. TConnection aConnection = myOpenConnections.FirstOrDefault(x => x.DuplexOutputChannel.ResponseReceiverId == e.ResponseReceiverId); // If the corresponding client exists. // E.g. the client could close its connection to the backup router in parallel/very short time bofore the connection was broken. if (aConnection != null) { // Close the broken connection. CloseConnection(aConnection); myOpenConnections.Remove(aConnection); // Set the next available receiver. SetNextAvailableReceiver(); // Open the new connection. aNewConnection = OpenConnection(aConnection.ResponseReceiverId); myOpenConnections.Add(aNewConnection); } } if (aNewConnection != null) { NotifyConnectionRedirected(aNewConnection.ResponseReceiverId, e.ChannelId, aNewConnection.DuplexOutputChannel.ChannelId); } } }
/// <summary> /// It is called when a message is received from a client connected to this Backup Router. /// The message will be forwarded to the connected service. /// If the sending fails the connection is considered broken it will try to reconnect with the next /// available service and send the message again. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void OnRequestMessageReceived(object sender, DuplexChannelMessageEventArgs e) { using (EneterTrace.Entering()) { TConnection aConnection; using (ThreadLock.Lock(myConnectionsLock)) { // If the client does not have associated connection to the service behind the router create it. aConnection = myOpenConnections.FirstOrDefault(x => x.ResponseReceiverId == e.ResponseReceiverId); if (aConnection == null) { aConnection = OpenConnection(e.ResponseReceiverId); myOpenConnections.Add(aConnection); } try { aConnection.DuplexOutputChannel.SendMessage(e.Message); // The message was successfully sent. return; } catch (Exception err) { // Sending of the message failed. Therefore the connection is considered broken. EneterTrace.Warning(TracedObject + "failed to forward the message to " + aConnection.DuplexOutputChannel.ChannelId + ". The connection will be redirected.", err); } // Redirect and try to send again. try { // Close the broken connection. CloseConnection(aConnection); myOpenConnections.Remove(aConnection); // Set next available receiver. SetNextAvailableReceiver(); // Open the new connection. TConnection aNewConnection = OpenConnection(e.ResponseReceiverId); myOpenConnections.Add(aNewConnection); NotifyConnectionRedirected(aNewConnection.ResponseReceiverId, aConnection.DuplexOutputChannel.ChannelId, aNewConnection.DuplexOutputChannel.ChannelId); // Send the message via the new connection. aNewConnection.DuplexOutputChannel.SendMessage(e.Message); } catch (Exception err) { string aMessage = TracedObject + "failed to forward the message after the redirection"; EneterTrace.Error(aMessage, err); throw; } } } }
public TConnection AddConnection(TNode src, TNode dst) { TConnection C = new TConnection(__MaxArcID, src, dst); src.Connections.Add(C); Connections.Add(__MaxArcID, C); TConnections.Add(__MaxArcID, C); ++(__MaxArcID); return(C); }
/// <summary> /// It is called when the client actively closed the connection with this backup router. /// It will close the associated connection with the service. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void OnResponseReceiverDisconnected(object sender, ResponseReceiverEventArgs e) { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myConnectionsLock)) { TConnection aConnetion = myOpenConnections.FirstOrDefault(x => x.ResponseReceiverId == e.ResponseReceiverId); CloseConnection(aConnetion); myOpenConnections.Remove(aConnetion); } } }
/// <summary> /// It is called when a client opens the connection to this backup router. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void OnResponseReceiverConnected(object sender, ResponseReceiverEventArgs e) { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myConnectionsLock)) { // Open the associated connection with the service for the incoming client. TConnection aConnection = OpenConnection(e.ResponseReceiverId); myOpenConnections.Add(aConnection); } } }
private void handle_exception(TConnection aConnection, Exception e) { if (e is System.IO.IOException) { // try to close imb connection and reconnect again Debug.WriteLine(DateTime.Now + ": >> Recovering from IO exception in IMB reader thread: " + e.Message); aConnection.recover(); Debug.WriteLine(DateTime.Now + ": Recovered"); } else { Debug.WriteLine(DateTime.Now + ": ## exception in IMB reader thread: " + e.Message); } }
private IDuplexOutputChannel GetAssociatedDuplexOutputChannel(string duplexInputChannelId, string responseReceiverId, string duplexOutputChannelId) { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myDuplexInputChannelContextManipulatorLock)) { TDuplexInputChannelContext aDuplexInputChannelContext = myDuplexInputChannelContexts.FirstOrDefault(x => x.AttachedDuplexInputChannel.ChannelId == duplexInputChannelId); if (aDuplexInputChannelContext == null) { string anError = TracedObject + "failed to return the duplex output channel associated with the duplex input channel '" + duplexInputChannelId + "' because the duplex input channel was not attached."; EneterTrace.Error(anError); throw new InvalidOperationException(anError); } TConnection aConnection = aDuplexInputChannelContext.OpenConnections.FirstOrDefault(x => x.ResponseReceiverId == responseReceiverId && x.ConnectedDuplexOutputChannel.ChannelId == duplexOutputChannelId); if (aConnection == null) { IDuplexOutputChannel anAssociatedDuplexOutputChannel = MessagingSystemFactory.CreateDuplexOutputChannel(duplexOutputChannelId); try { anAssociatedDuplexOutputChannel.ResponseMessageReceived += OnResponseMessageReceived; anAssociatedDuplexOutputChannel.OpenConnection(); } catch (Exception err) { anAssociatedDuplexOutputChannel.ResponseMessageReceived -= OnResponseMessageReceived; EneterTrace.Error(TracedObject + "failed to open connection for the duplex output channel '" + duplexOutputChannelId + "'.", err); throw; } aConnection = new TConnection(responseReceiverId, anAssociatedDuplexOutputChannel); aDuplexInputChannelContext.OpenConnections.Add(aConnection); } return(aConnection.ConnectedDuplexOutputChannel); } } }
/// <summary> /// It is called when a response message from the service is received. /// The response message must be redirected to the associated client. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnOutputChannelResponseMessageReceived(object sender, DuplexChannelMessageEventArgs e) { using (EneterTrace.Entering()) { string aResponseReceiverId = null; using (ThreadLock.Lock(myConnectionsLock)) { TConnection aConnection = myOpenConnections.FirstOrDefault(x => x.DuplexOutputChannel.ResponseReceiverId == e.ResponseReceiverId); if (aConnection != null) { aResponseReceiverId = aConnection.ResponseReceiverId; } } if (aResponseReceiverId == null) { EneterTrace.Warning(TracedObject + "could not find receiver for the incoming response message."); return; } using (ThreadLock.Lock(myDuplexInputChannelManipulatorLock)) { // Send the response message via the duplex input channel to the sender. if (AttachedDuplexInputChannel != null) { try { AttachedDuplexInputChannel.SendResponseMessage(aResponseReceiverId, e.Message); } catch (Exception err) { EneterTrace.Error(TracedObject + ErrorHandler.FailedToSendResponseMessage, err); } } else { EneterTrace.Error(TracedObject + "cannot send the response message when the duplex input channel is not attached."); } } } }
public void RemoveReceiver(string channelId) { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myConnectionsLock)) { // Find all open connections with this receiver then close them and remove from the list. List <string> aClientsToBeRedirected = new List <string>(); myOpenConnections.RemoveAll(x => { if (x.DuplexOutputChannel.ChannelId == channelId) { aClientsToBeRedirected.Add(x.ResponseReceiverId); CloseConnection(x); // Indicate it can be removed from the list. return(true); } return(false); }); // Remove the receiver from the list of available receivers. myAvailableReceivers.Remove(channelId); if (myAvailableReceiverIdx >= myAvailableReceivers.Count) { myAvailableReceiverIdx = Math.Max(0, myAvailableReceivers.Count - 1); } // If there are still available receivers then try to redirect closed connections. foreach (string aClientId in aClientsToBeRedirected) { TConnection aConnection = OpenConnection(aClientId); myOpenConnections.Add(aConnection); } } } }
private TConnection StartConnection(Socket socket) { var revAsyncEvent = _argsPool.Pop(); _bufferManager.SetBuffer(revAsyncEvent); var conn = new TConnection(); conn.Params = _server.Params; conn.Init(socket, revAsyncEvent, new TCoding()); conn.State = ConnectionState.Opened; conn.ConnectionClosed += OnConnectionDisconnected; conn.FrontController = _server.FrontController; _conns.Add(conn); _server.CurrentConnectionCount++; conn.Run(); return(conn); }
internal void OnConnectionDisconnected(TConnection conn) { lock (innerLock) { if (_conns.Contains(conn)) { _server.CurrentConnectionCount--; _conns.Remove(conn); _bufferManager.FreeBuffer(conn.ReceiveAsyncEvent); _argsPool.Push(conn.ReceiveAsyncEvent); if (!_server._stopped && _pendingQueue.Count > 0) { var socket = _pendingQueue.Dequeue(); if (socket != null) { StartConnection(socket); } } } } }
public string GetAssociatedResponseReceiverId(string responseReceiverId) { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myDuplexInputChannelContextManipulatorLock)) { // Go via all attached input channel contexts. foreach (TDuplexInputChannelContext aContext in myDuplexInputChannelContexts) { // Check if some open connection for that input channel does not contain duplex output channel with // passed responseReceiverId. TConnection aConnection = aContext.OpenConnections.FirstOrDefault(x => x.ConnectedDuplexOutputChannel.ResponseReceiverId == responseReceiverId); if (aConnection != null) { return(aConnection.ResponseReceiverId); } } return(null); } } }
protected void SendResponseMessage(string duplexOutputChannelResponseReceiverId, object message) { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myDuplexInputChannelContextManipulatorLock)) { TConnection anAssociatedConnection = null; TDuplexInputChannelContext aDuplexInputChannelContext = myDuplexInputChannelContexts.FirstOrDefault(x => { anAssociatedConnection = x.OpenConnections.FirstOrDefault(xx => xx.ConnectedDuplexOutputChannel.ResponseReceiverId == duplexOutputChannelResponseReceiverId); return(anAssociatedConnection != null); }); if (aDuplexInputChannelContext == null) { string anError = TracedObject + "failed to send the response message because the duplex input channel associated with the response was not found."; EneterTrace.Error(anError); throw new InvalidOperationException(anError); } if (anAssociatedConnection == null) { string anError = TracedObject + "failed to send the response message because the duplex output channel with the given response receiver id was not found."; EneterTrace.Error(anError); throw new InvalidOperationException(anError); } try { aDuplexInputChannelContext.AttachedDuplexInputChannel.SendResponseMessage(anAssociatedConnection.ResponseReceiverId, message); } catch (Exception err) { EneterTrace.Error(TracedObject + "failed to send the response message for the response receiver '" + anAssociatedConnection.ResponseReceiverId + "' through the duplex input channel '" + aDuplexInputChannelContext.AttachedDuplexInputChannel.ChannelId + "'.", err); throw; } } } }
private void CloseConnection(TConnection connection) { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myConnectionsLock)) { if (connection != null) { try { connection.DuplexOutputChannel.CloseConnection(); } catch (Exception err) { EneterTrace.Warning(TracedObject + "failed to close connection.", err); } connection.DuplexOutputChannel.ResponseMessageReceived -= OnOutputChannelResponseMessageReceived; connection.DuplexOutputChannel.ConnectionClosed -= OnOutputChannelConnectionClosed; } } } }
private void CreateConnection(ref SqlDataReader reader, ref RoutingNetwork Network) { TConnection Connection = null; string SourceStationID = reader["stop_id"].ToString(); string DestinationStationID = reader["next_stop_id"].ToString(); if (SourceStationID != string.Empty & Stops.ContainsKey(SourceStationID)) { if (DestinationStationID != string.Empty & Stops.ContainsKey(DestinationStationID)) { TNode SourceStation = Stops[SourceStationID]; TNode DestinationStation = Stops[DestinationStationID]; // int srcArrivalTime = Globals.ConvertTimeToSeconds(reader["arrival_time"].ToString()); int srcDepartureTime = Globals.ConvertTimeToSeconds(reader["departure_time"].ToString()); int dstArrivalTime = Globals.ConvertTimeToSeconds(reader["next_arrival_time"].ToString()); int dstDepartureTime = Globals.ConvertTimeToSeconds(reader["next_departure_time"].ToString()); //----------------------------------------------------------------------------------- //Connection = Network.AreConnected(SourceStation, DestinationStation, reader["route_id"].ToString()); Connection = null; if (Connection == null) { Connection = Network.AddConnection(SourceStation, DestinationStation); } //------------------------------------------------------------------------------------ Connection.AddTimeTableEntry( new TimeTableEntry(srcArrivalTime, srcDepartureTime, dstArrivalTime, dstDepartureTime, reader["route_id"].ToString(), reader["route_long_name"].ToString(), reader["route_short_name"].ToString(), reader["route_desc"].ToString(), reader["route_type"].ToString(), reader["route_url"].ToString(), reader["trip_id"].ToString(), reader["service_id"].ToString(), GetDates(reader["service_id"].ToString()), reader["agency_id"].ToString()) ); } } }
// A response message is received from the request receiver. private void OnResponseMessageReceived(object sender, DuplexChannelMessageEventArgs e) { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myReceiverManipulatorLock)) { // Find the connection associated with the ResponseRecieverId to which this response message // was delivered. TConnection aConnection = myOpenConnections.FirstOrDefault(x => x.DuplexOutputChannel.ResponseReceiverId == e.ResponseReceiverId); if (aConnection == null) { EneterTrace.Warning(TracedObject + "could not find the receiver for the incoming response message."); return; } // Forward the response message to the client. IDuplexInputChannel anInputChannel = AttachedDuplexInputChannel; if (anInputChannel != null) { try { anInputChannel.SendResponseMessage(aConnection.ResponseReceiverId, e.Message); } catch (Exception err) { EneterTrace.Error(TracedObject + ErrorHandler.FailedToSendResponseMessage, err); try { // Forwarding the response to the client failed so disconnect the client. anInputChannel.DisconnectResponseReceiver(aConnection.ResponseReceiverId); } catch (Exception err2) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToDisconnectResponseReceiver + aConnection.ResponseReceiverId, err2); } myOpenConnections.RemoveWhere(x => { if (x.ResponseReceiverId == aConnection.ResponseReceiverId) { try { x.DuplexOutputChannel.CloseConnection(); } catch (Exception err2) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToCloseConnection, err2); } x.DuplexOutputChannel.ResponseMessageReceived -= OnResponseMessageReceived; x.DuplexOutputChannel.ConnectionClosed -= OnRequestReceiverClosedConnection; return(true); } return(false); }); EneterThreadPool.QueueUserWorkItem(() => Notify(ResponseReceiverDisconnected, new ResponseReceiverEventArgs(aConnection.ResponseReceiverId, aConnection.SenderAddress))); } } else { EneterTrace.Error(TracedObject + "cannot send the response message when the duplex input channel is not attached."); } } } }
// A message from a client is received. It must be forwarded to a request receiver from the pool. protected override void OnRequestMessageReceived(object sender, DuplexChannelMessageEventArgs e) { using (EneterTrace.Entering()) { while (true) { string aChannelId; // Get the next available receiver. using (ThreadLock.Lock(myReceiverManipulatorLock)) { if (myAvailableReceivers.Count == 0) { EneterTrace.Error(TracedObject + "failed to forward the message because there no receivers in the pool."); break; } // Move to the next receiver. ++myCurrentAvailableReceiverIdx; if (myCurrentAvailableReceiverIdx >= myAvailableReceivers.Count) { myCurrentAvailableReceiverIdx = 0; } aChannelId = myAvailableReceivers[myCurrentAvailableReceiverIdx]; // If there is not open connection for the current response receiver id, then open it. TConnection aConnection = myOpenConnections.FirstOrDefault(x => x.ResponseReceiverId == e.ResponseReceiverId && x.DuplexOutputChannel.ChannelId == aChannelId); if (aConnection == null) { IDuplexOutputChannel anOutputChannel = myOutputMessagingFactory.CreateDuplexOutputChannel(aChannelId); anOutputChannel.ResponseMessageReceived += OnResponseMessageReceived; anOutputChannel.ConnectionClosed += OnRequestReceiverClosedConnection; try { anOutputChannel.OpenConnection(); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToOpenConnection, err); anOutputChannel.ResponseMessageReceived -= OnResponseMessageReceived; anOutputChannel.ConnectionClosed -= OnRequestReceiverClosedConnection; // It was not possible to open the connection with the given receiver. // So remove the receiver from available receivers. myAvailableReceivers.Remove(aChannelId); NotifyRequestRecieverRemoved(aChannelId); // Continue with the next receiver. continue; } aConnection = new TConnection(e.ResponseReceiverId, e.SenderAddress, anOutputChannel); myOpenConnections.Add(aConnection); } // Try to forward the message via the connection. try { aConnection.DuplexOutputChannel.SendMessage(e.Message); } catch (Exception err) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToSendMessage, err); try { // Remove the connection. aConnection.DuplexOutputChannel.CloseConnection(); } catch (Exception err2) { EneterTrace.Warning(TracedObject + ErrorHandler.FailedToCloseConnection, err2); } aConnection.DuplexOutputChannel.ResponseMessageReceived -= OnResponseMessageReceived; aConnection.DuplexOutputChannel.ConnectionClosed -= OnRequestReceiverClosedConnection; myOpenConnections.Remove(aConnection); // Try next receiver. continue; } break; } } } }
public override void OnNewConnection(TConnection connection) { OnNewConnection(Parent.CreateTextConnection(connection, Binding), connection); }
public abstract void OnNewConnection(TConnection connection);
private TConnection OpenConnection(string responseReceiverId) { using (EneterTrace.Entering()) { using (ThreadLock.Lock(myConnectionsLock)) { // If the client is already connected. if (myOpenConnections.Any(x => x.ResponseReceiverId == responseReceiverId)) { throw new InvalidOperationException(TracedObject + "failed to open connection. " + responseReceiverId + " is already connected."); } // If there are no available receivers then the connection cannot be open. if (myAvailableReceivers.Count == 0) { string anErrorMessage1 = TracedObject + "cannot open the connection because the list with available receivers is empty."; throw new InvalidOperationException(anErrorMessage1); } // Round Robin loop via available connections starting with the last available connection. for (int i = 0; i < myAvailableReceivers.Count; ++i) { int j = (myAvailableReceiverIdx + i) % myAvailableReceivers.Count; string anAvailableChannelId = myAvailableReceivers[j]; IDuplexOutputChannel anOutputChannel = myOutputMessagingFactory.CreateDuplexOutputChannel(anAvailableChannelId); // Subscribe to be notified if the connection is broken. anOutputChannel.ConnectionClosed += OnOutputChannelConnectionClosed; // Subscribe for response messages that must be redirected back to the client. anOutputChannel.ResponseMessageReceived += OnOutputChannelResponseMessageReceived; // Try to open connection. try { anOutputChannel.OpenConnection(); // Store index of working output channel. // Note: The next new connection will try this output channel first. myAvailableReceiverIdx = j; // Store connected output channel. TConnection aConnetion = new TConnection(responseReceiverId, anOutputChannel); // Connection was established. return(aConnetion); } catch (Exception err) { anOutputChannel.ResponseMessageReceived -= OnOutputChannelResponseMessageReceived; anOutputChannel.ConnectionClosed -= OnOutputChannelConnectionClosed; // The opening failed so it continues with the next available outputchannel. EneterTrace.Warning(TracedObject + "failed to connect to receiver " + anAvailableChannelId, err); } } } NotifyAllRedirectionsFailed(); string anErrorMessage2 = TracedObject + "failed to open connection with all available receivers."; EneterTrace.Error(anErrorMessage2); throw new InvalidOperationException(anErrorMessage2); } }
public override void OnNewConnection(TConnection connection) { OnNewConnection(Parent.CreateBinaryConnection(connection, Binding)); }
public ProxyConnection(TConnection dbConnection) { this.dbConnection = dbConnection; }
public void Remove(TConnection connection) => AddRemoveCommon(connection, ref RemovedConnections, AddedConnections);
private void handle_disconnect(TConnection aConnection) { Debug.WriteLine(DateTime.Now + ": ## disconnected"); }
public void Add(TConnection connection) => AddRemoveCommon(connection, ref AddedConnections, RemovedConnections);
private double GetWeightedObjValue(Connection C, TravelMode Modes) { double Time = C.GetTravelTime(Date, ArrivalTime[C.GetSource()], Modes); /* GetTravelTime returns an infinity time if the route should not be considered */ if (Time != double.PositiveInfinity) { if (C is RConnection) { //Time *= routerFactors.WalkingFactor; Time += 30; //TEST } else if (C is TConnection) { /* This is a fix introduced in order to skip the Mobalt buses (which are considered carpooling means) if the weight is >=50 */ if (string.Compare(C.GetTimeTable().Entries.First().AgencyId, "Mobalt###Mobalt") == 0) { if (routerFactors.CarpoolingFactor >= 50) { return(double.PositiveInfinity); } } if (Parent[C.GetSource()] != null) { if (Parent[C.GetSource()] is TConnection) { TConnection PC = Parent[C.GetSource()] as TConnection; if ((C as TConnection).TimeTable.RouteId != PC.TimeTable.RouteId) { //Time *= routerFactors.TransportationChangeFactor; //BUG!!! If Time==0 => no delay added for transportation changes Time = (Time > 60) ? Time : 60; // since we have 1 minute step, add 1 minute delay if the original Time is 0 and we have a transportation change Time *= routerFactors.TransportationChangeFactor; //Time += routerFactors.TransportationChangeFactor; //TEST add X seconds for each PT change } } Time *= routerFactors.TransportationFactor; //Time += routerFactors.TransportationFactor*3; //TEST add X seconds for each PT change } } else if (C is CConnection) { if (Parent[C.GetSource()] != null) { if (Parent[C.GetSource()] is CConnection) { CConnection PC = Parent[C.GetSource()] as CConnection; Time *= routerFactors.CarpoolingFactor; if ((string.Compare(C.GetCarpoolerId(), PC.GetCarpoolerId()) != 0)) { return(double.PositiveInfinity); } } } } } double ObjValue = minObjValue + Time; return(ObjValue); }
public DynamicConnection(TConnection dbConnection) { this.dbConnection = dbConnection; }
private void OnConnectionDisconnected(object sender, EventArgs ea) { TConnection conn = sender as TConnection; OnConnectionDisconnected(conn); }