Ejemplo n.º 1
1
        public void ExcuteSQLBulkCopy(DataTable Datatable, string TableName, ConnectionState connectionstate, ref bool executionSucceeded)
        {
            try
            {
                if (objConnection.State == System.Data.ConnectionState.Closed)
                {
                    objConnection.Open();
                }

                SqlBulkCopy.BatchSize = Datatable.Rows.Count;
                SqlBulkCopy.BulkCopyTimeout = 0;
                SqlBulkCopy.DestinationTableName = TableName;
                SqlBulkCopy.WriteToServer(Datatable);
                SqlBulkCopy.Close();
                executionSucceeded = true;
            }
            catch (Exception ex)
            {
                executionSucceeded = false;
                HandleExceptions(ex);
            }
            finally
            {
                //SqlBulkCopy.ColumnMappings.Clear();

                if (connectionstate == ConnectionState.CloseOnExit)
                {
                    if (objConnection.State == System.Data.ConnectionState.Open)
                    {
                        objConnection.Close();
                    }
                }
            }
        }
 public CqlConnection()
 {
     _ConnectionState = ConnectionState.Closed;
     _Config = new CqlConnectionConfiguration();
     _CurrentKeyspace = "";
     _ActualConnection = null;
 }
Ejemplo n.º 3
0
        public void AcceptCallback(IAsyncResult result)
        {
            // Get the socket that handles the client request
            // listener represents the connection 'server' (that waits for clients to connect) and not the
            // individual client connections
            Socket listener = (Socket)result.AsyncState;
            Socket handler = listener.EndAccept(result);

            // Tell the main client thread we got one client so that it can keep waiting for others :)
            gAllDone.Set();

            // From now on this is a separate thread :) cool!
            // Lets keep the state of this thing shall we?
            ConnectionState state = new ConnectionState();
            state.mSocket = handler;

            // TODO: Implement version control here
            // Valid connections start with a 'YELLOW' to which we respond 'SUP'
            byte[] yellowShakeBuffer = new byte[16];
            int read = handler.Receive(yellowShakeBuffer);
            string yellowString = ServerApi.CONNECTION_ENCODING.GetString(yellowShakeBuffer, 0, read);
            if (yellowString.Equals("YELLOW"))
            {
                // Answer and start waiting for data baby!
                handler.Send(ServerApi.CONNECTION_ENCODING.GetBytes("SUP"));
                handler.BeginReceive(state.mBuffer, 0, ConnectionState.BufferSize, SocketFlags.Peek,
                                    new AsyncCallback(ReadCallback), state);
            }
            else
            {
                // Ooops, not a valid client!
                handler.Close();
            }
        }
Ejemplo n.º 4
0
 public bool SendCSAFECommand(uint[] cmdData, ushort cmdDataCount, uint[] rspData, ref ushort rspDataCount)
 {
     if (IsOpen)
     {
         try
         {
             m_PM3.SendCSAFECommand(m_Port, cmdData, cmdDataCount, rspData, ref rspDataCount);
             return true;
         }
         catch (WriteFailedException e)
         {
             m_State = ConnectionState.SendError;
             Debug.WriteLine(string.Format("[Connection.SendCSAFECommand] {0}", e.Message));
         }
         catch (ReadTimeoutException e)
         {
             m_State = ConnectionState.SendError;
             Debug.WriteLine(string.Format("[Connection.SendCSAFECommand] {0}", e.Message));
         }
         catch (DeviceClosedException e)
         {
             m_State = ConnectionState.Disconnected;
             Debug.WriteLine(string.Format("[Connection.SendCSAFECommand] {0}", e.Message));
         }
     }
     return false;
 }
        public override void Open()
        {
            m_StorageAccount = CloudStorageAccount.Parse(m_ConnectionString);
            m_State = ConnectionState.Open;

            // TODO (Matt Magurany 8/14/2012): Consider creating an HTTP request for batching here
        }
 /// <summary>Executes behavior.</summary>
 /// <param name="state">Connection state.</param>
 public void Handle(ConnectionState state)
 {
     if (state == ConnectionState.Connected)
         _viewModel.IsBusy = false;
     else
         ErrorManager.Error(state.ToString());
 }
        private async void OnMessageReceived(object sender, MessageReceivedEventArgs args)
        {
            if (OnData == null) return;

            var exceptionOccured = false;
            try
            {
                var text = args.Message;
                OnData(sender, new DataReceivedEventArgs { TextData = text });
            }
            catch (Exception)
            {
                exceptionOccured = true;
            }
            // cannot await in catch
            if (exceptionOccured)
            {
                _connectionState = ConnectionState.Failed;
                try
                {
                    await Reconnect();
                }
                catch (Exception e)
                {
                    Error(e);
                }
            }
        }
Ejemplo n.º 8
0
        protected async Task BeginConnect(CancellationToken parentCancelToken)
        {
            try
            {
                using (await _lock.LockAsync().ConfigureAwait(false))
                {
                    _parentCancelToken = parentCancelToken;

                    await _taskManager.Stop().ConfigureAwait(false);
                    _taskManager.ClearException();
                    State = ConnectionState.Connecting;

                    _cancelSource = new CancellationTokenSource();
                    CancelToken = CancellationTokenSource.CreateLinkedTokenSource(_cancelSource.Token, parentCancelToken).Token;
                    _lastHeartbeat = DateTime.UtcNow;

                    await _engine.Connect(Host, CancelToken).ConfigureAwait(false);
                    await Run().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                //TODO: Should this be inside the lock?
                await _taskManager.SignalError(ex).ConfigureAwait(false);
                throw;
            }
        }
        public CiiClient()
        {
            logger = Logger.Instance;
            StatusCallbacks = new Dictionary<uint, ReceiveStatusHandler>();
            statusCallbacksLock = new object();

            loginAcceptEvent = new AutoResetEvent(false);
            messagesInFlight = new CiiMessagesInFlight();
            connectionState = ConnectionState.NotConnected;

            //
            //  Prebuild the Communications arrays
            //
            MessageTypeGet = BitConverter.GetBytes((uint)CiiMessageType.MtGetCommand);
            MessageTypeAction = BitConverter.GetBytes((uint)CiiMessageType.MtActionCommand);
            BytesLogin = BitConverter.GetBytes((uint)CiiMessageType.MtLogin);

            asyncErrorEvent = new AutoResetEvent(false);
            asyncErrors = new Queue<string>();
            asyncErrorsLock = new object();
            asyncErrorThread = new Thread(AsyncErrorThread);
            asyncErrorThread.IsBackground = true;
            asyncErrorThread.Priority = ThreadPriority.AboveNormal;
            asyncErrorThread.Name = "AsyncErrorThread";
            asyncErrorThread.Start();
        }
 public void OnStateChanged(ConnectionState connectionState)
 {
     if (callback != null)
     {
         callback(connectionState);
     }
 }
Ejemplo n.º 11
0
        void IConnectionControl.End(ProduceEndType endType)
        {
            lock (_stateLock)
            {
                switch (endType)
                {
                    case ProduceEndType.SocketShutdownSend:
                        if (_connectionState != ConnectionState.Open)
                        {
                            return;
                        }
                        _connectionState = ConnectionState.Shutdown;

                        KestrelTrace.Log.ConnectionWriteFin(_connectionId, 0);
                        Thread.Post(
                            x =>
                            {
                                KestrelTrace.Log.ConnectionWriteFin(_connectionId, 1);
                                var self = (Connection)x;
                                var shutdown = new UvShutdownReq();
                                shutdown.Init(self.Thread.Loop);
                                shutdown.Shutdown(self._socket, (req, status, state) =>
                                {
                                    KestrelTrace.Log.ConnectionWriteFin(_connectionId, 1);
                                    req.Dispose();
                                }, null);
                            },
                            this);
                        break;
                    case ProduceEndType.ConnectionKeepAlive:
                        if (_connectionState != ConnectionState.Open)
                        {
                            return;
                        }

                        KestrelTrace.Log.ConnectionKeepAlive(_connectionId);
                        _frame = new Frame(this);
                        Thread.Post(
                            x => ((Frame)x).Consume(),
                            _frame);
                        break;
                    case ProduceEndType.SocketDisconnect:
                        if (_connectionState == ConnectionState.Disconnected)
                        {
                            return;
                        }
                        _connectionState = ConnectionState.Disconnected;

                        KestrelTrace.Log.ConnectionDisconnect(_connectionId);
                        Thread.Post(
                            x =>
                            {
                                KestrelTrace.Log.ConnectionStop(_connectionId);
                                ((UvHandle)x).Dispose();
                            },
                            _socket);
                        break;
                }
            }
        }
Ejemplo n.º 12
0
        void CheckLoop()
        {
            while (ButterflyEnvironment.isOnline && notInDemoMode)
            {
#if DEBUG
                //Console.WriteLine("Connection state: {0}", state);
#endif
                switch (state)
                {
                    case ConnectionState.failed:
                        Thread.Sleep(5000);
                        this.state = ConnectionState.closed;
                        break;
                    case ConnectionState.closed:
                        this.Reconnect();
                        break;
                    case ConnectionState.connecting:
                    case ConnectionState.open:
                        Thread.Sleep(5000);
                        break;
                }
                Thread.Sleep(100);
            }
            this.ClientModule.Dispose();
        }
Ejemplo n.º 13
0
 public Connection(String host, int port)
 {
     this._host = host;
     this._port = port;
     this.state = ConnectionState.Closed;
     _disposed = false;
 }
Ejemplo n.º 14
0
        public override void Close()
        {
            if (State == ConnectionState.Closed)
                throw new Exception("Connection is already closed");

            _state = ConnectionState.Closed;
        }
Ejemplo n.º 15
0
 private void connectionChanged(ConnectionInformation information, ConnectionState state)
 {
     if (state == ConnectionState.CLOSED)
     {
         CloseConnection(information);
     }
 }
Ejemplo n.º 16
0
 private SerialConnection()
 {
     Devices = new ObservableCollection<DeviceInformation>();
     State = ConnectionState.Disconnected;
     Debugger = Debugger.Instance;
     LookForBluetoothDevices();
 }
Ejemplo n.º 17
0
        public override void Open()
        {
            if (State == ConnectionState.Open)
                throw new Exception("Connection is already open");

            _state = ConnectionState.Open;
        }
Ejemplo n.º 18
0
        public AudioClient(DiscordClient client, Server server, int id)
		{
            Id = id;
            _config = client.Config;
            Service = client.Services.Get<AudioService>();
            Config = Service.Config;
            Serializer = client.Serializer;
            _gatewayState = (int)ConnectionState.Disconnected;

            //Logging
            Logger = client.Log.CreateLogger($"AudioClient #{id}");

            //Async
            _taskManager = new TaskManager(Cleanup, false);
            _connectionLock = new AsyncLock();
            CancelToken = new CancellationToken(true);

            //Networking
            if (Config.EnableMultiserver)
            {
                ClientAPI = new JsonRestClient(_config, DiscordConfig.ClientAPIUrl, client.Log.CreateLogger($"ClientAPI #{id}"));
                GatewaySocket = new GatewaySocket(_config, client.Serializer, client.Log.CreateLogger($"Gateway #{id}"));
                GatewaySocket.Connected += (s, e) =>
                {
                    if (_gatewayState == ConnectionState.Connecting)
                        EndGatewayConnect();
                };
            }
            else
                GatewaySocket = client.GatewaySocket;
            GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e);
            VoiceSocket = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}"));
            VoiceSocket.Server = server;
            OutputStream = new OutStream(this);
        }
Ejemplo n.º 19
0
        public void ConnectTo(string hostName, ushort port = 80)
        {
            // Disconnect from any existing connection
            Disconnect();

            // Get the IP address from the host name string
            IPAddress[] addresses = Dns.GetHostAddresses(hostName);
            if( addresses.Length > 0 )
            {
                try
                {
                    mSocket.Connect(addresses[0], port);
                    mState = ConnectionState.Connecting;
                }
                catch( SocketException ex )
                {
                    if (ex.ErrorCode == 10035)
                    {
                        // Would Block
                        mState = ConnectionState.Connecting;
                    }
                    else
                        Console.WriteLine(ex.Message);
                }
            }
        }
Ejemplo n.º 20
0
        public bool Open()
        {
            if (m_State == ConnectionState.Disconnected)
            {
                int numUnits = m_PM3.DiscoverUnits();
                if (numUnits > 0)
                {
                    try
                    {
                        m_Port = 0;
                        m_State = ConnectionState.Connected;
                    }
                    catch (PM3Exception e)
                    {
                        Debug.WriteLine(string.Format("[Connection.Open] {0}", e.Message));
                    }
                }
            }
            else
            {
                Debug.WriteLine("[Connection.Open] Connection already open");
            }

            return IsOpen;
        }
Ejemplo n.º 21
0
        private static Uri uri = new Uri("net.tcp://localhost:57000"); // объектное представление универсального кода ресурсов (URI)

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Инициализирует новый экземпляр класса
        /// </summary>
        private DevManClient()
        {
            devContext = new DevManClientContext();
            devContext.onUpdate += new EventHandler(devContext_onUpdate);

            connectionState = ConnectionState.Default;
        }
Ejemplo n.º 22
0
 private void SetState(ConnectionState state)
 {
     var originalState = this.state;
     this.state = state;
     var e = new StateChangeEventArgs(originalState, state);
     OnStateChange(e);
 }
Ejemplo n.º 23
0
        /**
         * Post a state change. If the manager is already in that state the change
         * is ignored. Otherwise the change is queued for listeners.
         *
         * @param newConnectionState new state
         * @return true if the state actually changed, false if it was already at that state
         */
        public bool addStateChange(ConnectionState newConnectionState)
        {
            lock (_setStateChangedLock)
            {
                if (state.Get() != STARTED)
                {
                    return false;
                }

                ConnectionState previousState = currentConnectionState;
                if (previousState == newConnectionState)
                {
                    return false;
                }
                currentConnectionState = newConnectionState;

                ConnectionState localState = newConnectionState;
                bool isNegativeMessage = ((newConnectionState == ConnectionState.LOST) || (newConnectionState == ConnectionState.SUSPENDED) || (newConnectionState == ConnectionState.READ_ONLY));
                if (!isNegativeMessage && initialConnectMessageSent.compareAndSet(false, true))
                {
                    localState = ConnectionState.CONNECTED;
                }

                postState(localState);

                return true;
            }
        }
Ejemplo n.º 24
0
 public WorkerProxy(NagCoordinator coordinator, Socket socket)
 {
     Worker = new TCPConnection(socket, false, ProcesLine, null);
     NagCoordinator = coordinator;
     State = ConnectionState.Negotiating;
     Negotiate();
 }
Ejemplo n.º 25
0
 private void OnStateChanged(ConnectionState newState)
 {
     if (_stateChanged != null)
     {
         _stateChanged(this, newState);
     }
 }
Ejemplo n.º 26
0
		private void connectionChanged(ConnectionInformation information, ConnectionState state)
		{
			if (state == ConnectionState.closed)
			{
				this.CloseConnection(information);
			}
		}
Ejemplo n.º 27
0
        public ConnectionScope(IDbConnection connection)
        {
            if (connection == null) throw new ArgumentNullException(nameof(connection));

            _connection = connection;
            _initState = connection.State;

        }
Ejemplo n.º 28
0
 private void connectionChanged(ConnectionInformation information, ConnectionState state)
 {
     if (state == ConnectionState.closed)
     {
         CloseConnection(information.getConnectionID());
         liveConnections.Remove(information.getConnectionID());
     }
 }
Ejemplo n.º 29
0
 private void ClientModule_connectionChanged(ConnectionState state)
 {
     this.state = state;
     if (state == ConnectionState.open)
     {
         RequestLoadUserdata();
     }
 }
		public SqliteConnection ()
		{
			db_file = null;
			db_mode = 0644;
			db_version = 2;
			state = ConnectionState.Closed;
			sqlite_handle = IntPtr.Zero;
		}
Ejemplo n.º 31
0
 internal static Exception OpenConnectionPropertySet(string property, ConnectionState state)
 {
     return(InvalidOperation(SR.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state))));
 }
Ejemplo n.º 32
0
 // Construct an "empty" connection
 protected DbConnectionClosed(ConnectionState state, bool hidePassword, bool allowSetConnectionString) : base(state, hidePassword, allowSetConnectionString)
 {
 }
Ejemplo n.º 33
0
        internal void Update(int deltaTime)
        {
            _timeSinceLastPacket += deltaTime;
            switch (_connectionState)
            {
            case ConnectionState.Connected:
                if (_timeSinceLastPacket > _netManager.DisconnectTimeout)
                {
                    NetUtils.DebugWrite(
                        "[UPDATE] Disconnect by timeout: {0} > {1}",
                        _timeSinceLastPacket,
                        _netManager.DisconnectTimeout);
                    _netManager.DisconnectPeer(this, DisconnectReason.Timeout, 0, true, null, 0, 0);
                    return;
                }
                break;

            case ConnectionState.ShutdownRequested:
                if (_timeSinceLastPacket > _netManager.DisconnectTimeout)
                {
                    _connectionState = ConnectionState.Disconnected;
                }
                else
                {
                    _netManager.SendRaw(_shutdownPacket, _remoteEndPoint);
                }
                return;

            case ConnectionState.InProgress:
                _connectTimer += deltaTime;
                if (_connectTimer > _netManager.ReconnectDelay)
                {
                    _connectTimer = 0;
                    _connectAttempts++;
                    if (_connectAttempts > _netManager.MaxConnectAttempts)
                    {
                        _netManager.DisconnectPeer(this, DisconnectReason.ConnectionFailed, 0, true, null, 0, 0);
                        return;
                    }

                    //else send connect again
                    _netManager.SendRaw(_connectRequestPacket, _remoteEndPoint);
                }
                return;

            case ConnectionState.Disconnected:
                return;
            }

            //Send ping
            _pingSendTimer += deltaTime;
            if (_pingSendTimer >= _netManager.PingInterval)
            {
                NetUtils.DebugWrite("[PP] Send ping...");

                //reset timer
                _pingSendTimer = 0;

                //send ping
                _pingPacket.Sequence = _pingSequence;
                SendRawData(_pingPacket);

                //reset timer
                _pingTimeStart = DateTime.UtcNow;
            }

            //RTT - round trip time
            _rttResetTimer += deltaTime;
            if (_rttResetTimer >= RttResetDelay)
            {
                _rttResetTimer = 0;
                //Rtt update
                _rtt  = _avgRtt;
                _ping = _avgRtt;
                _netManager.ConnectionLatencyUpdated(this, _ping);
                _rttCount = 1;
            }

            //MTU - Maximum transmission unit
            if (!_finishMtu)
            {
                _mtuCheckTimer += deltaTime;
                if (_mtuCheckTimer >= MtuCheckDelay)
                {
                    _mtuCheckTimer = 0;
                    _mtuCheckAttempts++;
                    if (_mtuCheckAttempts >= MaxMtuCheckAttempts)
                    {
                        _finishMtu = true;
                    }
                    else
                    {
                        lock (_mtuMutex)
                        {
                            //Send increased packet
                            if (_mtuIdx < NetConstants.PossibleMtu.Length - 1)
                            {
                                int newMtu = NetConstants.PossibleMtu[_mtuIdx + 1] - NetConstants.HeaderSize;
                                var p      = _packetPool.GetWithProperty(PacketProperty.MtuCheck, newMtu);
                                p.RawData[1] = (byte)(_mtuIdx + 1);

                                //Must check result for MTU fix
                                if (!_netManager.SendRawAndRecycle(p, _remoteEndPoint))
                                {
                                    _finishMtu = true;
                                }
                            }
                        }
                    }
                }
            }
            //MTU - end
            //Pending send
            Flush();
        }
Ejemplo n.º 34
0
        public virtual int Insert(string p1, uint p2, double?p3, string p4, double?p5, string p6)
        {
            int num2;

            if (p1 == null)
            {
                this.Adapter.InsertCommand.Parameters[0].Value = DBNull.Value;
            }
            else
            {
                this.Adapter.InsertCommand.Parameters[0].Value = p1;
            }
            this.Adapter.InsertCommand.Parameters[1].Value = p2;
            if (p3.HasValue)
            {
                this.Adapter.InsertCommand.Parameters[2].Value = p3.Value;
            }
            else
            {
                this.Adapter.InsertCommand.Parameters[2].Value = DBNull.Value;
            }
            if (p4 == null)
            {
                throw new ArgumentNullException("p4");
            }
            this.Adapter.InsertCommand.Parameters[3].Value = p4;
            if (p5.HasValue)
            {
                this.Adapter.InsertCommand.Parameters[4].Value = p5.Value;
            }
            else
            {
                this.Adapter.InsertCommand.Parameters[4].Value = DBNull.Value;
            }
            if (p6 == null)
            {
                this.Adapter.InsertCommand.Parameters[5].Value = DBNull.Value;
            }
            else
            {
                this.Adapter.InsertCommand.Parameters[5].Value = p6;
            }
            ConnectionState state = this.Adapter.InsertCommand.Connection.State;

            if ((this.Adapter.InsertCommand.Connection.State & ConnectionState.Open) != ConnectionState.Open)
            {
                this.Adapter.InsertCommand.Connection.Open();
            }
            try
            {
                num2 = this.Adapter.InsertCommand.ExecuteNonQuery();
            }
            finally
            {
                if (state == ConnectionState.Closed)
                {
                    this.Adapter.InsertCommand.Connection.Close();
                }
            }
            return(num2);
        }
Ejemplo n.º 35
0
        private static async Task ProduceResponse(ConnectionState state, IPipeConnection connection, HttpResponseMessage response)
        {
            // TODO: pipelining support!
            while (true)
            {
                var result = await connection.Input.ReadAsync();

                var responseBuffer = result.Buffer;

                var consumed = responseBuffer.Start;

                var needMoreData = true;

                try
                {
                    if (consumed == state.Consumed)
                    {
                        var oldBody = responseBuffer.Slice(0, state.PreviousContentLength);

                        if (oldBody.Length != state.PreviousContentLength)
                        {
                            // Not enough data
                            continue;
                        }

                        // The caller didn't read the body
                        responseBuffer = responseBuffer.Slice(state.PreviousContentLength);
                        consumed       = responseBuffer.Start;

                        state.Consumed = default;
                    }

                    if (responseBuffer.IsEmpty && result.IsCompleted)
                    {
                        break;
                    }
                    if (!responseBuffer.TrySliceTo((byte)'\r', (byte)'\n', out ReadOnlyBuffer responseLine, out Position delim))
                    {
                        continue;
                    }

                    responseBuffer = responseBuffer.Slice(delim).Slice(2);

                    if (!responseLine.TrySliceTo((byte)' ', out ReadOnlyBuffer httpVersion, out delim))
                    {
                        // Bad request
                        throw new InvalidOperationException();
                    }

                    consumed = responseBuffer.Start;

                    responseLine = responseLine.Slice(delim).Slice(1);

                    if (!responseLine.TrySliceTo((byte)' ', out ReadOnlyBuffer statusCode, out delim))
                    {
                        // Bad request
                        throw new InvalidOperationException();
                    }

                    response.StatusCode = (HttpStatusCode)statusCode.GetUInt32();
                    responseLine        = responseLine.Slice(delim).Slice(1);

                    if (!responseLine.TrySliceTo((byte)' ', out ReadOnlyBuffer remaining, out delim))
                    {
                        // Bad request
                        throw new InvalidOperationException();
                    }

                    while (!responseBuffer.IsEmpty)
                    {
                        if (responseBuffer.Length == 0)
                        {
                            break;
                        }

                        int ch = responseBuffer.First.Span[0];

                        if (ch == '\r')
                        {
                            // Check for final CRLF.
                            responseBuffer = responseBuffer.Slice(1);
                            if (responseBuffer.Length == 0)
                            {
                                break;
                            }
                            ch             = responseBuffer.First.Span[0];
                            responseBuffer = responseBuffer.Slice(1);

                            if (ch == '\n')
                            {
                                consumed     = responseBuffer.Start;
                                needMoreData = false;
                                break;
                            }

                            // Headers don't end in CRLF line.
                            throw new Exception();
                        }

                        // End of the header
                        // \n
                        if (!responseBuffer.TrySliceTo((byte)'\n', out ReadOnlyBuffer headerPair, out delim))
                        {
                            break;
                        }

                        responseBuffer = responseBuffer.Slice(delim).Slice(1);

                        // :
                        if (!headerPair.TrySliceTo((byte)':', out ReadOnlyBuffer headerName, out delim))
                        {
                            throw new Exception();
                        }

                        headerName = headerName.TrimStart();
                        headerPair = headerPair.Slice(headerName.End).Slice(1);

                        // \r
                        if (!headerPair.TrySliceTo((byte)'\r', out ReadOnlyBuffer headerValue, out delim))
                        {
                            // Bad request
                            throw new Exception();
                        }

                        headerValue = headerValue.TrimStart();
                        var hKey   = headerName.GetAsciiString();
                        var hValue = headerValue.GetAsciiString();

                        if (!response.Content.Headers.TryAddWithoutValidation(hKey, hValue))
                        {
                            response.Headers.TryAddWithoutValidation(hKey, hValue);
                        }

                        // Move the consumed
                        consumed = responseBuffer.Start;
                    }
                }
                catch (Exception ex)
                {
                    // Close the connection
                    connection.Output.Complete(ex);
                    break;
                }
                finally
                {
                    connection.Input.Advance(consumed);
                }

                if (needMoreData)
                {
                    continue;
                }

                // Only handle content length for now
                var length = response.Content.Headers.ContentLength;

                if (!length.HasValue)
                {
                    throw new NotSupportedException();
                }

                checked
                {
                    // BAD but it's a proof of concept ok?
                    state.PreviousContentLength = (int)length.Value;
                    ((PipelineHttpContent)response.Content).ContentLength = (int)length;
                    state.Consumed = consumed;
                }

                break;
            }
        }
Ejemplo n.º 36
0
        private void _connect(Dictionary <string, string> data = null)
        {
            for (int i = 0; i < _ipAddresses.Count; i++)
            {
                try
                {
                    // if the IP address is not supported then skip, e.g. IPv6 address but not supported by network card
                    if (_ipAddresses[i] == null ||
                        (_ipAddresses[i].AddressFamily == AddressFamily.InterNetwork && !Socket.OSSupportsIPv4) ||
                        (_ipAddresses[i].AddressFamily == AddressFamily.InterNetworkV6 && !Socket.OSSupportsIPv6))
                    {
                        continue;
                    }

                    // attempt to connect to remote endpoint (will throw if not available)
                    _tcpClient     = ComponentFactory.BuildTcpClient(_ipAddresses[i].ToString(), _port, _sslSettings);
                    _networkStream = _tcpClient.GetStream();
                    _networkStream.AuthenticateAsClient();

                    Log.InfoFormat("[{0}] Connected to {1}:{2}", ID, _ipAddresses[i], _port);

                    break;
                }
                catch (Exception e)
                {
                    Log.ErrorFormat($"Unable to connect to remote endpoint: {e.Message}");

                    _tcpClient     = null;
                    _networkStream = null;
                }
            }

            // did one of the addresses make a connection
            if (_tcpClient != null && _networkStream != null)
            {
                // create and start the frame decoder
                _streamDecoderTask = _decodeStreamAsync(_networkStream, _cts.Token);

                // update state and send start frame
                State = ConnectionState.ConnectionStartSent;
                _sendFrame(FrameType.ConnectionStart, Frame.CreateConnectionStartFrame(data));

                // block until the connection is established, errors, or times out
                var index = WaitHandle.WaitAny(new[] { _connectionOpen, _connectionError }, 2000);

                // what was the result?
                switch (index)
                {
                // success - return the established connection
                case 0: return;

                // the connection failed
                case 1: throw new ConnectionException("Unable to establish connection");

                // establishing the connection timed out
                case WaitHandle.WaitTimeout: throw new ConnectionTimeoutException("Establishing a conneciton the remote endpoint timed out");

                // should never each this point
                default: throw new Exception();
                }
            }
            else
            {
                // failed to connect to the remote endpoint
                throw new ConnectionException("Unable to establish connection");
            }
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Asynchronous task for decoding frames off the networking stream. The method calls _receiveFrame for each frame received
        /// which determines what to do with it based on the current Connection state, frame type, and frame contents
        /// </summary>
        /// <param name="stream">The network stream from which frames will be decoded</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>The asynchronous task</returns>
        private Task _decodeStreamAsync(INetworkStream stream, CancellationToken ct)
        {
            return(Task.Run(() =>
            {
                var frameSizeUsed = Frame.MaxFrameSize;
                byte[] buffer = new byte[Frame.MaxFrameSize * 3];
                int bufferOffset = 0;
                int availableBytes = 0;

                while (!ct.IsCancellationRequested && State != ConnectionState.End && State != ConnectionState.ConnectionError)
                {
                    int read = 0;
                    while ((read = stream.Read(buffer, bufferOffset + availableBytes, buffer.Length - (bufferOffset + availableBytes))) > 0)
                    {
                        availableBytes += read;

                        var frames = Frame.DecodeFrameBuffer(buffer, bufferOffset, availableBytes, out bufferOffset, out availableBytes);
                        foreach (var frame in frames)
                        {
                            // pass for processing
                            _processFrame(frame);
                        }

                        // shift any remaining data to the beginning of the buffer
                        if (bufferOffset > 0 && availableBytes > 0)
                        {
                            Log.DebugFormat("[{0}] Moving remaining bytes to beginning of buffer: Offset [{1}], Available [{2}]", ID, bufferOffset, availableBytes);

                            Array.Copy(buffer, bufferOffset, buffer, 0, availableBytes);
                            bufferOffset = 0;
                        }

                        if (frameSizeUsed != Frame.MaxFrameSize)
                        {
                            Log.DebugFormat("[{0}] Resizing frame buffer: Current [{1}], New [{2}]", ID, frameSizeUsed, Frame.MaxFrameSize);

                            // the protocol negotiation has adjusted the frame size - resize buffer
                            var resizedBuffer = new byte[Frame.MaxFrameSize * 3];
                            Array.Copy(buffer, bufferOffset, resizedBuffer, 0, availableBytes);
                            buffer = resizedBuffer;
                            bufferOffset = 0;
                            frameSizeUsed = Frame.MaxFrameSize;
                        }
                    }
                }
            }).ContinueWith(t =>
            {
                if (t.Exception != null)
                {
                    // change state to error
                    State = ConnectionState.ConnectionError;

                    // close dependent components and resources
                    _closeInternal();

                    // raise error event
                    OnError?.Invoke(this, null);
                }

                Log.DebugFormat("Decode stream task has ended");
            }));
        }
Ejemplo n.º 38
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="ConnectionException" /> class.
 /// </summary>
 /// <param name="message">The message.</param>
 public ConnectionException(string message)
     : base(message)
 {
     ConnectionState = ConnectionState.Disconnected;
 }
Ejemplo n.º 39
0
 protected DbConnectionBusy(ConnectionState state) : base(state, true, false)
 {
 }
Ejemplo n.º 40
0
        public void Update()
        {
            List <Socket> recvList   = new List <Socket>();
            List <Socket> sendList   = new List <Socket>();
            List <Socket> exceptList = new List <Socket>();

            recvList.Add(mSocket);
            sendList.Add(mSocket);
            exceptList.Add(mSocket);

            Socket.Select(recvList, sendList, exceptList, 1000);
            int result = recvList.Count + sendList.Count + exceptList.Count;

            if (result > 0)
            {
                mCanRead  = recvList.Count > 0;
                mCanWrite = sendList.Count > 0;

                if (mState == ConnectionState.Connecting)
                {
                    if (sendList.Count > 0)
                    {
                        mState = ConnectionState.Connected;
                        SendIdentityPacket();
                    }
                    else if (exceptList.Count > 0)
                    {
                        mState = ConnectionState.Disconnected;
                    }
                }
            }

            if (mCanRead && mState == ConnectionState.Connected)
            {
                try
                {
                    byte[] dataBuffer = new byte[1024];
                    int    bytesRead  = mSocket.Receive(dataBuffer, 0);
                    mAliveTime = DateTime.Now;
                    if (bytesRead > 0)
                    {
                        Array.Copy(dataBuffer, 0, mInputBuffer, mInputBufferBytes, bytesRead);
                        mInputBufferBytes += bytesRead;
                        ProcessPackets();
                    }
                    else if (bytesRead == 0)
                    {
                        // Connection closed
                        Disconnect();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Disconnect();
                }
            }

            if (mState == ConnectionState.Connected)
            {
                TimeSpan timeSinceSeen = DateTime.Now - mAliveTime;
                if (timeSinceSeen.TotalSeconds > 5)
                {
                    SendPing();
                    mAliveTime = DateTime.Now;
                }
            }
        }
Ejemplo n.º 41
0
        internal static InvalidOperationException UpdateOpenConnectionRequired(StatementType statementType, bool isRowUpdatingCommand, ConnectionState state)
        {
            string resource;

            if (isRowUpdatingCommand)
            {
                resource = SR.ADP_OpenConnectionRequired_Clone;
            }
            else
            {
                switch (statementType)
                {
                case StatementType.Insert:
                    resource = SR.ADP_OpenConnectionRequired_Insert;
                    break;

                case StatementType.Update:
                    resource = SR.ADP_OpenConnectionRequired_Update;
                    break;

                case StatementType.Delete:
                    resource = SR.ADP_OpenConnectionRequired_Delete;
                    break;

#if DEBUG
                case StatementType.Select:
                    Debug.Fail("shouldn't be here");
                    goto default;

                case StatementType.Batch:
                    Debug.Fail("isRowUpdatingCommand should have been true");
                    goto default;
#endif
                default:
                    throw ADP.InvalidStatementType(statementType);
                }
            }
            return(InvalidOperation(SR.Format(resource, ADP.ConnectionStateMsg(state))));
        }
Ejemplo n.º 42
0
        internal static ServiceBusPrivateEndpointConnectionData DeserializeServiceBusPrivateEndpointConnectionData(JsonElement element)
        {
            ResourceIdentifier                   id              = default;
            string                               name            = default;
            ResourceType                         type            = default;
            SystemData                           systemData      = default;
            Optional <WritableSubResource>       privateEndpoint = default;
            Optional <ConnectionState>           privateLinkServiceConnectionState = default;
            Optional <EndpointProvisioningState> provisioningState = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("privateEndpoint"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            privateEndpoint = JsonSerializer.Deserialize <WritableSubResource>(property0.Value.ToString());
                            continue;
                        }
                        if (property0.NameEquals("privateLinkServiceConnectionState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            privateLinkServiceConnectionState = ConnectionState.DeserializeConnectionState(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = new EndpointProvisioningState(property0.Value.GetString());
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new ServiceBusPrivateEndpointConnectionData(id, name, type, systemData, privateEndpoint, privateLinkServiceConnectionState.Value, Optional.ToNullable(provisioningState)));
        }
Ejemplo n.º 43
0
 internal static Exception ConnectionAlreadyOpen(ConnectionState state)
 {
     return(InvalidOperation(SR.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state))));
 }
Ejemplo n.º 44
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="ConnectionException" /> class.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="innerException">The exception that caused the connection problem</param>
 public ConnectionException(string message, Exception innerException)
     : base(message, innerException)
 {
     ConnectionState = ConnectionState.Disconnected;
 }
Ejemplo n.º 45
0
 internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state)
 {
     return(InvalidOperation(SR.GetString(SR.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state))));
 }
Ejemplo n.º 46
0
 public override void Close()
 {
     CloseCount++;
     _state = ConnectionState.Closed;
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Processes a received frame depending on frame type and current connection state
        /// </summary>
        /// <param name="frame">The frame to process</param>
        private void _processFrame(Frame frame)
        {
            // do NOT process anything if in a closed or errored state
            if (State == ConnectionState.End || State == ConnectionState.ConnectionError)
            {
                return;
            }

            switch (frame.Type)
            {
                #region Connection Frame Handling

            case FrameType.ConnectionStart:
            {
                if (State == ConnectionState.Start)
                {
                    Log.DebugFormat("[{0}] FrameType.ConnectionStart received", ID);

                    // decode connection descriptor content
                    var descriptor = BsonCodec.Decode <ConnectionDescriptor>(frame.Payload);

                    // store any data in the property - used by application to provide details about the connection
                    Data = descriptor.Data;

                    // is the protocol compatible
                    if (descriptor.ProtocolVersion.Major == Frame.ProtocolVersion.Major)
                    {
                        if (descriptor.MaxFrameSize < Frame.MaxFrameSize)
                        {
                            // protocol will use the smallest of the two max frame sizes
                            Frame.MaxFrameSize = descriptor.MaxFrameSize;
                        }

                        // update connection state
                        State = ConnectionState.ConnectionAcceptSent;

                        // send accept frame (version and (new) frame size will be returned)
                        _sendFrame(FrameType.ConnectionAccept, Frame.CreateConnectionAcceptFrame());
                    }
                    else
                    {
                        // set state
                        State = ConnectionState.End;

                        // reject the connection (description of why provided)
                        _sendFrame(FrameType.ConnectionReject, Frame.CreateConnectionRejectFrame("Protocol version incompatible"));

                        // should close here
                        _closeInternal();
                    }
                }
            } break;

            case FrameType.ConnectionAccept:
            {
                if (State == ConnectionState.ConnectionStartSent)
                {
                    Log.DebugFormat("[{0}] FrameType.ConnectionAccept received", ID);

                    // now in open state
                    State = ConnectionState.Open;

                    // send the open frame to the endpoint
                    _sendFrame(FrameType.ConnectionOpen, Frame.CreateConnectionOpenFrame());

                    // signal that the connection is open
                    _connectionOpen.Set();
                }
            } break;

            case FrameType.ConnectionReject:
            {
                if (State == ConnectionState.ConnectionStartSent)
                {
                    Log.DebugFormat("[{0}] FrameType.ConnectionReject received", ID);

                    // transition to end state
                    State = ConnectionState.End;

                    // close everything
                    _closeInternal();
                }
            } break;

            case FrameType.ConnectionOpen:
            {
                // used for both client and server endpoints
                if (State == ConnectionState.ConnectionAcceptSent || State == ConnectionState.ConnectionOpenSent)
                {
                    Log.DebugFormat("[{0}] FrameType.ConnectionOpen received", ID);

                    // connection is now open - set state
                    State = ConnectionState.Open;

                    // signal that connection is open
                    _connectionOpen.Set();
                }
            } break;

            case FrameType.ConnectionClose:
            {
                // valid in any state (except errored - but shoulnd't have received it in the first place)

                Log.DebugFormat("[{0}] FrameType.ConnectionClose received", ID);

                // close the connection
                State = ConnectionState.End;

                // close the physcial connection and any associated components
                _closeInternal();

                // raise the closed event
                OnClosed?.Invoke(this, null);
            } break;

                #endregion

                #region Session Frame Handling

            case FrameType.SessionStart:
            {
                var descriptor = BsonCodec.Decode <SessionDescriptor>(frame.Payload);

                // TODO: getting a null descriptor here!
                Log.DebugFormat("[{0}] FrameType.SessionStart received: ID [{1}], Name [{2}]", ID, frame.SessionID, descriptor.Name);

                // validate
                if (_pendingSessions.ContainsKey(frame.SessionID))
                {
                    Log.DebugFormat("[{0}] Received SessionStart from when one is already pending", ID);
                    return;
                }

                if (_activeSessions.ContainsKey(frame.SessionID))
                {
                    Log.DebugFormat("[{0}] Received SessionStart from when one is already active", ID);
                    return;
                }

                // create the incoming session and add to the pending dictionary
                var session = new Session(this, descriptor, frame.SessionID);
                _pendingSessions.Add(frame.SessionID, session);

                // notify application
                _ = Task.Run(() => OnSession?.Invoke(this, session));
            } break;

            case FrameType.SessionAccept:
            {
                Log.DebugFormat("[{0}] FrameType.SessionAccept received: ID [{1}]", ID, frame.SessionID);

                // move to active session but do not trigger Settle until Open received
                Session session;
                if (_pendingSessions.Remove(frame.SessionID, out session))
                {
                    // move session from pending to active
                    _activeSessions.Add(frame.SessionID, session);

                    Log.DebugFormat("[{0}] Session moved from pending to active: ID [{1}], Pending [{2}], Active [{3}]", ID, frame.SessionID, _pendingSessions.Count, _activeSessions.Count);

                    // send session open
                    _sendFrame(FrameType.SessionOpen, Frame.CreateSessionOpenFrame(frame.SessionID, null));
                }
            } break;

            case FrameType.SessionReject:
            {
                Log.DebugFormat("[{0}] FrameType.SessionReject received: ID [{1}]", ID, frame.SessionID);

                _pendingSessions.Remove(frame.SessionID);

                Log.DebugFormat("[{0}] Session removed from pending sessions: ID [{1}], Pending [{2}], Active [{3}]", ID, frame.SessionID, _pendingSessions.Count, _activeSessions.Count);
            } break;

            case FrameType.SessionOpen:
            {
                Log.DebugFormat("[{0}] FrameType.SessionOpen received: ID [{1}]", ID, frame.SessionID);

                Session session;
                if (_pendingSessions.Remove(frame.SessionID, out session))
                {
                    // move session from pending to active
                    _activeSessions.Add(frame.SessionID, session);

                    Log.DebugFormat("[{0}] Session moved from pending to active: ID [{1}], Pending [{2}], Active [{3}]", ID, frame.SessionID, _pendingSessions.Count, _activeSessions.Count);

                    // respond with session open
                    _sendFrame(FrameType.SessionOpen, Frame.CreateSessionOpenFrame(frame.SessionID, null));

                    // signal that the session is now Open
                    session.NotifySessionOpen();
                }
                else if (_activeSessions.ContainsKey(frame.SessionID))
                {
                    // signal that the session is now Open
                    _activeSessions[frame.SessionID].NotifySessionOpen();
                }
            }
            break;

            case FrameType.SessionClose:
            {
                Log.DebugFormat("[{0}] FrameType.SessionClose received: ID [{1}]", ID, frame.SessionID);

                Session session;
                if (_activeSessions.Remove(frame.SessionID, out session))
                {
                    // remove session from active collection
                    _activeSessions.Remove(frame.SessionID);

                    // call close on the session
                    session.Close();
                }
            } break;

                #endregion

                #region Message Frame Handling

            case FrameType.MessageSend:
            case FrameType.MessageAccept:
            case FrameType.MessageReject:
            {
                Log.DebugFormat("[{0}] {1} received", ID, frame.Type.ToString());

                var sessionId = frame.SessionID;
                if (_activeSessions.ContainsKey(sessionId))
                {
                    _activeSessions[sessionId].NotifyMessage(frame.Type, frame.MessageID, frame.Payload);
                }
            } break;

                #endregion

            default:
                break;
            }
        }
Ejemplo n.º 48
0
 public void SetState(ConnectionState state)
 => _state = state;
Ejemplo n.º 49
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="ClientIdentifierException" /> class.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="connectionState">The current connection state.</param>
 public ConnectionException(string message, ConnectionState connectionState)
     : this(message) {
     ConnectionState = connectionState;
 }
Ejemplo n.º 50
0
        public virtual int Update(string p1, uint p2, double?p3, string p4, double?p5, string p6, uint p7, string p9, uint p10, double?p12, string p13, double?p15, string p17)
        {
            int num2;

            if (p1 == null)
            {
                this.Adapter.UpdateCommand.Parameters[0].Value = DBNull.Value;
            }
            else
            {
                this.Adapter.UpdateCommand.Parameters[0].Value = p1;
            }
            this.Adapter.UpdateCommand.Parameters[1].Value = p2;
            if (p3.HasValue)
            {
                this.Adapter.UpdateCommand.Parameters[2].Value = p3.Value;
            }
            else
            {
                this.Adapter.UpdateCommand.Parameters[2].Value = DBNull.Value;
            }
            if (p4 == null)
            {
                throw new ArgumentNullException("p4");
            }
            this.Adapter.UpdateCommand.Parameters[3].Value = p4;
            if (p5.HasValue)
            {
                this.Adapter.UpdateCommand.Parameters[4].Value = p5.Value;
            }
            else
            {
                this.Adapter.UpdateCommand.Parameters[4].Value = DBNull.Value;
            }
            if (p6 == null)
            {
                this.Adapter.UpdateCommand.Parameters[5].Value = DBNull.Value;
            }
            else
            {
                this.Adapter.UpdateCommand.Parameters[5].Value = p6;
            }
            this.Adapter.UpdateCommand.Parameters[6].Value = p7;
            if (p9 == null)
            {
                this.Adapter.UpdateCommand.Parameters[7].Value = 1;
                this.Adapter.UpdateCommand.Parameters[8].Value = DBNull.Value;
            }
            else
            {
                this.Adapter.UpdateCommand.Parameters[7].Value = 0;
                this.Adapter.UpdateCommand.Parameters[8].Value = p9;
            }
            this.Adapter.UpdateCommand.Parameters[9].Value = p10;
            if (p12.HasValue)
            {
                this.Adapter.UpdateCommand.Parameters[10].Value = 0;
                this.Adapter.UpdateCommand.Parameters[11].Value = p12.Value;
            }
            else
            {
                this.Adapter.UpdateCommand.Parameters[10].Value = 1;
                this.Adapter.UpdateCommand.Parameters[11].Value = DBNull.Value;
            }
            if (p13 == null)
            {
                throw new ArgumentNullException("p13");
            }
            this.Adapter.UpdateCommand.Parameters[12].Value = p13;
            if (p15.HasValue)
            {
                this.Adapter.UpdateCommand.Parameters[13].Value = 0;
                this.Adapter.UpdateCommand.Parameters[14].Value = p15.Value;
            }
            else
            {
                this.Adapter.UpdateCommand.Parameters[13].Value = 1;
                this.Adapter.UpdateCommand.Parameters[14].Value = DBNull.Value;
            }
            if (p17 == null)
            {
                this.Adapter.UpdateCommand.Parameters[15].Value   = 1;
                this.Adapter.UpdateCommand.Parameters[0x10].Value = DBNull.Value;
            }
            else
            {
                this.Adapter.UpdateCommand.Parameters[15].Value   = 0;
                this.Adapter.UpdateCommand.Parameters[0x10].Value = p17;
            }
            ConnectionState state = this.Adapter.UpdateCommand.Connection.State;

            if ((this.Adapter.UpdateCommand.Connection.State & ConnectionState.Open) != ConnectionState.Open)
            {
                this.Adapter.UpdateCommand.Connection.Open();
            }
            try
            {
                num2 = this.Adapter.UpdateCommand.ExecuteNonQuery();
            }
            finally
            {
                if (state == ConnectionState.Closed)
                {
                    this.Adapter.UpdateCommand.Connection.Close();
                }
            }
            return(num2);
        }
Ejemplo n.º 51
0
 public override void Open()
 {
     OpenCount++;
     _state = ConnectionState.Open;
 }
Ejemplo n.º 52
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="ClientIdentifierException" /> class.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="innerException">The inner exception.</param>
 /// <param name="connectionState">The current connection state.</param>
 public ConnectionException(string message, ConnectionState connectionState, Exception innerException)
     : this(message, innerException)
 {
     ConnectionState = connectionState;
 }
Ejemplo n.º 53
0
        //Process incoming packet
        internal void ProcessPacket(NetPacket packet)
        {
            _timeSinceLastPacket = 0;

            NetUtils.DebugWrite("[RR]PacketProperty: {0}", packet.Property);
            switch (packet.Property)
            {
            case PacketProperty.ConnectRequest:
                //response with connect
                SendConnectAccept();
                _packetPool.Recycle(packet);
                break;

            case PacketProperty.Merged:
                int pos = NetConstants.HeaderSize;
                while (pos < packet.Size)
                {
                    ushort size = BitConverter.ToUInt16(packet.RawData, pos);
                    pos += 2;
                    NetPacket mergedPacket = _packetPool.GetPacket(size, false);
                    if (!mergedPacket.FromBytes(packet.RawData, pos, size))
                    {
                        _packetPool.Recycle(packet);
                        break;
                    }
                    pos += size;
                    ProcessPacket(mergedPacket);
                }
                break;

            //If we get ping, send pong
            case PacketProperty.Ping:
                if (NetUtils.RelativeSequenceNumber(packet.Sequence, _remotePingSequence) < 0)
                {
                    _packetPool.Recycle(packet);
                    break;
                }
                NetUtils.DebugWrite("[PP]Ping receive, send pong");
                _remotePingSequence = packet.Sequence;
                _packetPool.Recycle(packet);

                //send
                _pongPacket.Sequence = _remotePingSequence;
                _netManager.SendRaw(_pongPacket, _remoteEndPoint);
                break;

            //If we get pong, calculate ping time and rtt
            case PacketProperty.Pong:
                if (NetUtils.RelativeSequenceNumber(packet.Sequence, _pingSequence) < 0)
                {
                    _packetPool.Recycle(packet);
                    break;
                }
                _pingSequence = packet.Sequence;
                int rtt = (int)(DateTime.UtcNow - _pingTimeStart).TotalMilliseconds;
                UpdateRoundTripTime(rtt);
                NetUtils.DebugWrite("[PP]Ping: {0}", rtt);
                _packetPool.Recycle(packet);
                break;

            //Process ack
            case PacketProperty.AckReliable:
                _reliableUnorderedChannel.ProcessAck(packet);
                _packetPool.Recycle(packet);
                break;

            case PacketProperty.AckReliableOrdered:
                _reliableOrderedChannel.ProcessAck(packet);
                _packetPool.Recycle(packet);
                break;

            //Process in order packets
            case PacketProperty.Sequenced:
                _sequencedChannel.ProcessPacket(packet);
                break;

            case PacketProperty.ReliableUnordered:
                _reliableUnorderedChannel.ProcessPacket(packet);
                break;

            case PacketProperty.ReliableOrdered:
                _reliableOrderedChannel.ProcessPacket(packet);
                break;

            case PacketProperty.ReliableSequenced:
                _reliableSequencedChannel.ProcessPacket(packet);
                break;

            //Simple packet without acks
            case PacketProperty.Unreliable:
                AddIncomingPacket(packet);
                return;

            case PacketProperty.MtuCheck:
            case PacketProperty.MtuOk:
                ProcessMtuPacket(packet);
                break;

            case PacketProperty.ShutdownOk:
            case PacketProperty.Disconnect:
                _connectionState = ConnectionState.Disconnected;
                _packetPool.Recycle(packet);
                break;

            default:
                NetUtils.DebugWriteError("Error! Unexpected packet type: " + packet.Property);
                break;
            }
        }
Ejemplo n.º 54
0
        public virtual int Delete(uint p1, string p3, uint p4, double?p6, string p7, double?p9, string p11)
        {
            int num2;

            this.Adapter.DeleteCommand.Parameters[0].Value = p1;
            if (p3 == null)
            {
                this.Adapter.DeleteCommand.Parameters[1].Value = 1;
                this.Adapter.DeleteCommand.Parameters[2].Value = DBNull.Value;
            }
            else
            {
                this.Adapter.DeleteCommand.Parameters[1].Value = 0;
                this.Adapter.DeleteCommand.Parameters[2].Value = p3;
            }
            this.Adapter.DeleteCommand.Parameters[3].Value = p4;
            if (p6.HasValue)
            {
                this.Adapter.DeleteCommand.Parameters[4].Value = 0;
                this.Adapter.DeleteCommand.Parameters[5].Value = p6.Value;
            }
            else
            {
                this.Adapter.DeleteCommand.Parameters[4].Value = 1;
                this.Adapter.DeleteCommand.Parameters[5].Value = DBNull.Value;
            }
            if (p7 == null)
            {
                throw new ArgumentNullException("p7");
            }
            this.Adapter.DeleteCommand.Parameters[6].Value = p7;
            if (p9.HasValue)
            {
                this.Adapter.DeleteCommand.Parameters[7].Value = 0;
                this.Adapter.DeleteCommand.Parameters[8].Value = p9.Value;
            }
            else
            {
                this.Adapter.DeleteCommand.Parameters[7].Value = 1;
                this.Adapter.DeleteCommand.Parameters[8].Value = DBNull.Value;
            }
            if (p11 == null)
            {
                this.Adapter.DeleteCommand.Parameters[9].Value  = 1;
                this.Adapter.DeleteCommand.Parameters[10].Value = DBNull.Value;
            }
            else
            {
                this.Adapter.DeleteCommand.Parameters[9].Value  = 0;
                this.Adapter.DeleteCommand.Parameters[10].Value = p11;
            }
            ConnectionState state = this.Adapter.DeleteCommand.Connection.State;

            if ((this.Adapter.DeleteCommand.Connection.State & ConnectionState.Open) != ConnectionState.Open)
            {
                this.Adapter.DeleteCommand.Connection.Open();
            }
            try
            {
                num2 = this.Adapter.DeleteCommand.ExecuteNonQuery();
            }
            finally
            {
                if (state == ConnectionState.Closed)
                {
                    this.Adapter.DeleteCommand.Connection.Close();
                }
            }
            return(num2);
        }
Ejemplo n.º 55
0
 internal void SetConnectionState(ConnectionState cs)
 {
     ConnectionState = cs;
 }
Ejemplo n.º 56
0
        override public void Close()
        {
            ConnectionState previousState = State;
            Guid            operationId;
            Guid            clientConnectionId;

            // during the call to Dispose() there is a redundant call to
            // Close(). because of this, the second time Close() is invoked the
            // connection is already in a closed state. this doesn't seem to be a
            // problem except for logging, as we'll get duplicate Before/After/Error
            // log entries
            if (previousState != ConnectionState.Closed)
            {
                operationId = s_diagnosticListener.WriteConnectionCloseBefore(this);
                // we want to cache the ClientConnectionId for After/Error logging, as when the connection
                // is closed then we will lose this identifier
                //
                // note: caching this is only for diagnostics logging purposes
                clientConnectionId = ClientConnectionId;
            }

            SqlStatistics statistics = null;

            Exception e = null;

            try
            {
                statistics = SqlStatistics.StartTimer(Statistics);

                Task reconnectTask = _currentReconnectionTask;
                if (reconnectTask != null && !reconnectTask.IsCompleted)
                {
                    CancellationTokenSource cts = _reconnectionCancellationSource;
                    if (cts != null)
                    {
                        cts.Cancel();
                    }
                    AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection
                    if (State != ConnectionState.Open)
                    {                                                                                // if we cancelled before the connection was opened
                        OnStateChange(DbConnectionInternal.StateChangeClosed);
                    }
                }
                CancelOpenAndWait();
                CloseInnerConnection();
                GC.SuppressFinalize(this);

                if (null != Statistics)
                {
                    ADP.TimerCurrent(out _statistics._closeTimestamp);
                }
            }
            catch (Exception ex)
            {
                e = ex;
                throw;
            }
            finally
            {
                SqlStatistics.StopTimer(statistics);

                // we only want to log this if the previous state of the
                // connection is open, as that's the valid use-case
                if (previousState != ConnectionState.Closed)
                {
                    if (e != null)
                    {
                        s_diagnosticListener.WriteConnectionCloseError(operationId, clientConnectionId, this, e);
                    }
                    else
                    {
                        s_diagnosticListener.WriteConnectionCloseAfter(operationId, clientConnectionId, this);
                    }
                }
            }
        }
        private bool OnPacketRead(byte[] data, int length, CSteamID userId)
        {
            if (!_connectionStateMap.ContainsKey(userId) || _connectionStateMap[userId] == ConnectionState.Inactive)
            {
                P2PSessionRequest_t result = default(P2PSessionRequest_t);
                result.m_steamIDRemote = userId;
                OnP2PSessionRequest(result);
                if (!_connectionStateMap.ContainsKey(userId) || _connectionStateMap[userId] == ConnectionState.Inactive)
                {
                    return(false);
                }
            }
            ConnectionState connectionState = _connectionStateMap[userId];

            if (connectionState == ConnectionState.Authenticating)
            {
                if (length < 3)
                {
                    return(false);
                }
                int num = (data[1] << 8) | data[0];
                if (num != length)
                {
                    return(false);
                }
                if (data[2] != 93)
                {
                    return(false);
                }
                byte[] array = new byte[data.Length - 3];
                Array.Copy(data, 3, array, 0, array.Length);
                switch (SteamUser.BeginAuthSession(array, array.Length, userId))
                {
                case EBeginAuthSessionResult.k_EBeginAuthSessionResultOK:
                    _connectionStateMap[userId] = ConnectionState.Connected;
                    BroadcastConnectedUsers();
                    break;

                case EBeginAuthSessionResult.k_EBeginAuthSessionResultDuplicateRequest:
                    Close(userId);
                    break;

                case EBeginAuthSessionResult.k_EBeginAuthSessionResultExpiredTicket:
                    Close(userId);
                    break;

                case EBeginAuthSessionResult.k_EBeginAuthSessionResultGameMismatch:
                    Close(userId);
                    break;

                case EBeginAuthSessionResult.k_EBeginAuthSessionResultInvalidTicket:
                    Close(userId);
                    break;

                case EBeginAuthSessionResult.k_EBeginAuthSessionResultInvalidVersion:
                    Close(userId);
                    break;
                }
                return(false);
            }
            return(connectionState == ConnectionState.Connected);
        }
Ejemplo n.º 58
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="ConnectionException" /> class.
 /// </summary>
 /// <param name="connectionState">State of the connection.</param>
 /// <param name="innerException">The inner exception.</param>
 public ConnectionException(ConnectionState connectionState, Exception innerException)
     : base(String.Format(MessageTemplate, connectionState), innerException)
 {
     ConnectionState = connectionState;
 }
 internal ServiceBusPrivateEndpointConnectionData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, WritableSubResource privateEndpoint, ConnectionState privateLinkServiceConnectionState, EndpointProvisioningState?provisioningState) : base(id, name, resourceType, systemData)
 {
     PrivateEndpoint = privateEndpoint;
     PrivateLinkServiceConnectionState = privateLinkServiceConnectionState;
     ProvisioningState = provisioningState;
 }
Ejemplo n.º 60
0
        private void ConnectionProcessorThread()
        {
            while (threadCancellationSignal)
            {
                try
                {
                    if (connectionState == ConnectionState.DISCONNECTED)
                    {
                        numberOfConnectionRetries = 0;
                        connection.Connect();
                        while (numberOfConnectionRetries < 10)
                        {
                            if (connection.CheckState())
                            {
                                this.connectionState      = ConnectionState.CONNECTED;
                                numberOfConnectionRetries = 0;
                                break;
                            }
                            else
                            {
                                numberOfConnectionRetries++;
                                if (numberOfConnectionRetries == 10)
                                {
                                    connection.Disconect();
                                    connectionState = ConnectionState.DISCONNECTED;
                                }
                            }
                        }
                    }
                    else
                    {
                        processConnection.WaitOne();
                        while (commandQueue.TryDequeue(out currentCommand))
                        {
                            lock (lockObj)
                            {
                                connection.Send(currentCommand.PackRequest());
                                byte[] message;
                                byte[] header     = connection.Recv(10);
                                int    recvLen    = CalculateRecvLength(header[2]);
                                byte[] dataChunks = connection.Recv(recvLen);
                                message = new byte[header.Length + recvLen];
                                Buffer.BlockCopy(header, 0, message, 0, 10);
                                Buffer.BlockCopy(dataChunks, 0, message, 10, recvLen);

                                bool unsolicited = CheckIfUnsolicited(message[11]);
                                if (unsolicited)
                                {
                                    HandleReceivedBytes(message, unsolicited);
                                    DNP3ConfirmCommandParamters dnp3Param = new DNP3ConfirmCommandParamters(0xc0, (byte)DNP3FunctionCode.CONFIRM, 0xc0); //podesiti parametre
                                    IDNP3Function function = DNP3FunctionFactory.CreateConfirmFunction(dnp3Param);
                                    connection.Send(function.PackRequest());
                                }
                                else
                                {
                                    HandleReceivedBytes(message, unsolicited);
                                }
                                currentCommand = null;
                            }
                        }
                    }
                }
                catch (SocketException se)
                {
                    currentCommand  = null;
                    connectionState = ConnectionState.DISCONNECTED;
                    Log().Log(new LogEventModel()
                    {
                        EventType = LogEventType.ERROR, Message = $"{se.Message}"
                    }).GetAwaiter().GetResult();
                }
                catch (Exception ex)
                {
                    currentCommand = null;
                    Log().Log(new LogEventModel()
                    {
                        EventType = LogEventType.WARN, Message = $"{ex.Message}"
                    }).GetAwaiter().GetResult();
                }
            }
        }