public void AdvancedReturnsSameSessionByDifferentInterface() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock<ISqlDialect>().Object, new Mock<IDbDriver>().Object, new SessionListeners()); var advancedSession = session.Advanced; Assert.Same(session, advancedSession); }
protected override void OnServerConnected(AsyncSession session) { if (_isConnect) { // http connect response SendConnectResponse(session); } else { // send header SendHeader(session); } }
private void SendToServer(int length, AsyncSession session) { _totalWrite += length; int bytesToSend; lock (_encryptionLock) { _encryptor.Encrypt(_connetionRecvBuffer, length, _connetionSendBuffer, out bytesToSend); } _tcprelay.UpdateOutboundCounter(_server, bytesToSend); _startSendingTime = DateTime.Now; session.Remote.BeginSend(_connetionSendBuffer, 0, bytesToSend, SocketFlags.None, new AsyncCallback(PipeRemoteSendCallback), session); IStrategy strategy = _controller.GetCurrentStrategy(); strategy?.UpdateLastWrite(_server); }
public void UpdateObjectDeltaThrowsMicroLiteExceptionIfItContainsNoChanges() { var objectDelta = new ObjectDelta(typeof(Customer), 1234); var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock <ISqlDialect>().Object, new Mock <IDbDriver>().Object, new SessionListeners()); var exception = Assert.Throws <AggregateException>( () => session.UpdateAsync(objectDelta).Result); Assert.IsType <MicroLiteException>(exception.InnerException); Assert.Equal(ExceptionMessages.ObjectDelta_MustContainAtLeastOneChange, exception.InnerException.Message); }
public void InsertInvokesListeners() { var customer = new Customer(); object identifier = 23543; var mockSqlDialect = new Mock <ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull <IObjectInfo>(), customer)).Returns(new SqlQuery("")); mockSqlDialect.Setup(x => x.BuildSelectInsertIdSqlQuery(It.IsNotNull <IObjectInfo>())).Returns(new SqlQuery("")); var mockCommand = new Mock <IDbCommand>(); mockCommand.Setup(x => x.ExecuteScalar()).Returns(identifier); var mockConnection = new Mock <IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock <IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); int counter = 0; var mockListener1 = new Mock <IInsertListener>(); mockListener1.Setup(x => x.AfterInsert(customer, identifier)).Callback(() => Assert.Equal(4, ++counter)); mockListener1.Setup(x => x.BeforeInsert(customer)).Callback(() => Assert.Equal(1, ++counter)); var mockListener2 = new Mock <IInsertListener>(); mockListener2.Setup(x => x.AfterInsert(customer, identifier)).Callback(() => Assert.Equal(3, ++counter)); mockListener2.Setup(x => x.BeforeInsert(customer)).Callback(() => Assert.Equal(2, ++counter)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new[] { mockListener1.Object, mockListener2.Object }, new IUpdateListener[0]); session.InsertAsync(customer).Wait(); mockListener1.VerifyAll(); mockListener2.VerifyAll(); }
public void DeleteTypeByIdentifierThrowsObjectDisposedExceptionIfDisposed() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock <ISqlDialect>().Object, new Mock <IDbDriver>().Object, new SessionListeners()); using (session) { } var exception = Assert.Throws <AggregateException>( () => session.DeleteAsync(typeof(Customer), 1234).Result); Assert.IsType <ObjectDisposedException>(exception.InnerException); }
public void ExecuteThrowsObjectDisposedExceptionIfDisposed() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock <ISqlDialect>().Object, new Mock <IDbDriver>().Object, new SessionListeners()); using (session) { } var exception = Assert.Throws <AggregateException>( () => session.ExecuteAsync(new SqlQuery("SELECT")).Result); Assert.IsType <ObjectDisposedException>(exception.InnerException); }
public void InsertThrowsObjectDisposedExceptionIfDisposed() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock <ISqlDialect>().Object, new Mock <IDbDriver>().Object, new SessionListeners()); using (session) { } var exception = Assert.Throws <AggregateException>( () => session.InsertAsync(new Customer()).Wait()); Assert.IsType <ObjectDisposedException>(exception.InnerException); }
public void InsertBuildsAndExecutesCombinedCommandIfIdentifierStrategyNotAssignedAndSqlDialectSupportsSelectInsertedIdentifierAndDbDriverSupportsBatchedQueries() { ObjectInfo.MappingConvention = new ConventionMappingConvention( UnitTest.GetConventionMappingSettings(IdentifierStrategy.DbGenerated)); var customer = new Customer(); var insertSqlQuery = new SqlQuery("INSERT"); var selectIdSqlQuery = new SqlQuery("SELECT"); var combinedSqlQuery = new SqlQuery("INSERT;SELECT"); object identifier = 23543; var mockSqlDialect = new Mock <ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull <IObjectInfo>(), customer)).Returns(insertSqlQuery); mockSqlDialect.Setup(x => x.BuildSelectInsertIdSqlQuery(It.IsNotNull <IObjectInfo>())).Returns(selectIdSqlQuery); mockSqlDialect.Setup(x => x.SupportsSelectInsertedIdentifier).Returns(true); var mockCommand = new Mock <IDbCommand>(); mockCommand.Setup(x => x.ExecuteScalar()).Returns(identifier); var mockConnection = new Mock <IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock <IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); mockDbDriver.Setup(x => x.SupportsBatchedQueries).Returns(true); mockDbDriver.Setup(x => x.Combine(insertSqlQuery, selectIdSqlQuery)).Returns(combinedSqlQuery); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); session.InsertAsync(customer).Wait(); mockSqlDialect.VerifyAll(); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
public void InsertBuildsAndExecutesAnInsertCommandOnlyIfIdentifierStrategyAssigned() { ObjectInfo.MappingConvention = new ConventionMappingConvention( UnitTest.GetConventionMappingSettings(IdentifierStrategy.Assigned)); var customer = new Customer { Id = 12345 }; var insertSqlQuery = new SqlQuery("INSERT"); var mockSqlDialect = new Mock <ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull <IObjectInfo>(), customer)).Returns(insertSqlQuery); mockSqlDialect.Setup(x => x.SupportsSelectInsertedIdentifier).Returns(false); var mockCommand = new Mock <IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1); var mockConnection = new Mock <IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock <IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); session.InsertAsync(customer).Wait(); mockSqlDialect.Verify(x => x.BuildInsertSqlQuery(It.IsNotNull <IObjectInfo>(), customer), Times.Once()); mockSqlDialect.Verify(x => x.BuildSelectInsertIdSqlQuery(It.IsAny <IObjectInfo>()), Times.Never()); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
protected void StartPipe(AsyncSession session) { if (Closed) { return; } try { _startReceivingTime = DateTime.Now; session.Remote.BeginReceive(RemoteRecvBuffer, 0, RecvSize, SocketFlags.None, PipeRemoteReceiveCallback, session); Connection.BeginReceive(ConnetionRecvBuffer, 0, RecvSize, SocketFlags.None, PipeConnectionReceiveCallback, session); } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
private void StartPipe(AsyncSession session) { if (_closed) { return; } try { _startReceivingTime = DateTime.Now; session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None, new AsyncCallback(PipeRemoteReceiveCallback), session); SendToServer(_firstPacketLength, session); } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
public void DeleteInstanceThrowsObjectDisposedExceptionIfDisposed() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock <ISqlDialect>().Object, new Mock <IDbDriver>().Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); using (session) { } var exception = Assert.Throws <AggregateException>( () => session.DeleteAsync(new Customer()).Result); Assert.IsType <ObjectDisposedException>(exception.InnerException); }
private void StartConnect() { try { CreateRemote(); // Setting up proxy IProxy remote; EndPoint proxyEP; if (_config.useProxy) { remote = new Socks5Proxy(); proxyEP = SocketUtil.GetEndPoint(_config.proxyServer, _config.proxyPort); } else { remote = new DirectConnect(); proxyEP = null; } var session = new AsyncSession(remote); _currentRemoteSession = session; ProxyTimer proxyTimer = new ProxyTimer(3000); proxyTimer.AutoReset = false; proxyTimer.Elapsed += proxyConnectTimer_Elapsed; proxyTimer.Enabled = true; proxyTimer.Session = session; proxyTimer.DestEndPoint = SocketUtil.GetEndPoint(server.server, server.server_port); proxyTimer.Server = server; _proxyConnected = false; // Connect to the proxy server. remote.BeginConnectProxy(proxyEP, new AsyncCallback(ProxyConnectCallback), new AsyncSession <ProxyTimer>(remote, proxyTimer)); } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
public void DeleteInstanceInvokesListeners() { var customer = new Customer { Id = 187224 }; var mockSqlDialect = new Mock<ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull<IObjectInfo>(), customer.Id)).Returns(new SqlQuery("")); var mockCommand = new Mock<IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1); var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); int counter = 0; var mockListener1 = new Mock<IDeleteListener>(); mockListener1.Setup(x => x.AfterDelete(customer, 1)).Callback(() => Assert.Equal(4, ++counter)); mockListener1.Setup(x => x.BeforeDelete(customer)).Callback(() => Assert.Equal(1, ++counter)); var mockListener2 = new Mock<IDeleteListener>(); mockListener2.Setup(x => x.AfterDelete(customer, 1)).Callback(() => Assert.Equal(3, ++counter)); mockListener2.Setup(x => x.BeforeDelete(customer)).Callback(() => Assert.Equal(2, ++counter)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new SessionListeners( new[] { mockListener1.Object, mockListener2.Object }, new IInsertListener[0], new IUpdateListener[0])); session.DeleteAsync(customer).Wait(); mockListener1.VerifyAll(); mockListener2.VerifyAll(); }
private void StartPipe(AsyncSession session) { if (_closed) { return; } try { _startReceivingTime = DateTime.Now; session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None, new AsyncCallback(PipeRemoteReceiveCallback), session); _connection.BeginReceive(_connetionRecvBuffer, 0, RecvSize, SocketFlags.None, new AsyncCallback(PipeConnectionReceiveCallback), new AsyncSession <bool>(session, true) /* to tell the callback this is the first time reading packet, and we haven't found the header yet. */); } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
private void ConnectCallback(IAsyncResult ar) { if (_closed) { return; } try { AsyncSession <ServerTimer> session = (AsyncSession <ServerTimer>)ar.AsyncState; ServerTimer timer = session.State; _server = timer.Server; timer.Elapsed -= DestConnectTimer_Elapsed; timer.Enabled = false; timer.Dispose(); IProxy remote = session.Remote; // Complete the connection. remote.EndConnectDest(ar); _destConnected = true; Logger.Debug($"Socket connected to ss server: {_server.ToString()}"); TimeSpan latency = DateTime.Now - _startConnectTime; OnConnected?.Invoke(this, new SSTCPConnectedEventArgs(_server, latency)); StartPipe(session); } catch (ArgumentException) { } catch (Exception e) { if (_server != null) { OnFailed?.Invoke(this, new SSRelayEventArgs(_server)); } ErrorClose(e); } }
private void StartPipe(AsyncSession session) { if (_closed) { manualResetEvent?.Set(); return; } try { _startReceivingTime = DateTime.Now; session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None, PipeRemoteReceiveCallback, session); SendToServer(session); } catch (Exception e) { Close(); } }
private void DestConnectTimer_Elapsed(object sender, ElapsedEventArgs e) { ServerTimer timer = (ServerTimer)sender; timer.Elapsed -= DestConnectTimer_Elapsed; timer.Enabled = false; timer.Dispose(); if (_destConnected || _closed) { return; } AsyncSession session = timer.Session; Server server = timer.Server; OnFailed?.Invoke(this, new SSRelayEventArgs(_server)); Logger.Info($"{server.ToString()} timed out"); session.Remote.Close(); Close(); }
public void DeleteInstanceThrowsMicroLiteExceptionIfExecuteNonQueryThrowsException() { var customer = new Customer { Id = 187224 }; var mockSqlDialect = new Mock <ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull <IObjectInfo>(), customer.Id)).Returns(new SqlQuery("")); var mockCommand = new Mock <IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()).Throws <InvalidOperationException>(); var mockConnection = new Mock <IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock <IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); var exception = Assert.Throws <AggregateException>(() => session.DeleteAsync(customer).Wait()); Assert.IsType <MicroLiteException>(exception.InnerException); Assert.IsType <InvalidOperationException>(exception.InnerException.InnerException); Assert.Equal(exception.InnerException.InnerException.Message, exception.InnerException.Message); // Command should still be disposed. mockCommand.VerifyAll(); }
public void UpdateInstanceThrowsMicroLiteExceptionIfIdentifierNotSet() { var customer = new Customer { Id = 0 }; var mockDbDriver = new Mock <IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(new Mock <IDbConnection>().Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock <ISqlDialect>().Object, mockDbDriver.Object, new SessionListeners()); var exception = Assert.Throws <AggregateException>(() => session.UpdateAsync(customer).Wait()); Assert.IsType <MicroLiteException>(exception.InnerException); Assert.Equal(ExceptionMessages.Session_IdentifierNotSetForUpdate, exception.InnerException.Message); }
public void UpdateInstanceBuildsAndExecutesQuery() { var customer = new Customer { Id = 187224 }; var rowsAffected = 1; var mockSqlDialect = new Mock <ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildUpdateSqlQuery(It.IsNotNull <IObjectInfo>(), customer)).Returns(new SqlQuery("")); var mockCommand = new Mock <IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(rowsAffected); var mockConnection = new Mock <IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock <IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); session.UpdateAsync(customer).Wait(); mockSqlDialect.VerifyAll(); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
public async Task Test_ConnectionManagement_WithAsyncSession() { var connection = new SqliteConnection(DatabaseHelper.TestDbConnectionString); QueryOptions options = new QueryOptions() { ConnectionFactory = () => connection, Schemas = DatabaseHelper.Default.Schemas, }; await using (var ado = new AsyncSession(options)) { await foreach (var r in ado.ExecuteAsync(new SqlOperation("SELECT 12; SELECT 12"), CancellationToken.None)) { (await r.ReadAsync()).ShouldBeTrue(); (await r.GetFieldValueAsync <int>(0)).ShouldBe(12); (await r.ReadAsync()).ShouldBeFalse(); } } connection.State.ShouldBe(ConnectionState.Closed); }
private void StartPipe(AsyncSession session) { if (_closed) { return; } try { _startReceivingTime = DateTime.Now; session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None, PipeRemoteReceiveCallback, session); TryReadAvailableData(); Logger.Debug($"_firstPacketLength = {_firstPacketLength}"); SendToServer(_firstPacketLength, session); } catch (Exception e) { Logger.LogUsefulException(e); Close(); } }
public void DeleteInstanceReturnsFalseIfNoRecordsDeleted() { var customer = new Customer { Id = 14556 }; var mockSqlDialect = new Mock <ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull <IObjectInfo>(), customer.Id)).Returns(new SqlQuery("")); var mockCommand = new Mock <IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(0); var mockConnection = new Mock <IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock <IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); Assert.False(session.DeleteAsync(customer).Result); mockSqlDialect.VerifyAll(); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
public void DeleteTypeByIdentifierThrowsMicroLiteExceptionIfExecuteNonQueryThrowsException() { var type = typeof(Customer); var identifier = 1234; var mockSqlDialect = new Mock <ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull <IObjectInfo>(), identifier)).Returns(new SqlQuery("")); var mockCommand = new Mock <IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()).Throws <InvalidOperationException>(); var mockConnection = new Mock <IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock <IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new SessionListeners()); var exception = Assert.Throws <AggregateException>(() => session.DeleteAsync(type, identifier).Result); Assert.IsType <MicroLiteException>(exception.InnerException); Assert.IsType <InvalidOperationException>(exception.InnerException.InnerException); Assert.Equal(exception.InnerException.InnerException.Message, exception.InnerException.Message); // Command should still be disposed. mockCommand.VerifyAll(); }
private void SendToServer(int length, AsyncSession session) { _totalWrite += length; int bytesToSend; lock (_encryptionLock) { try { _encryptor.Encrypt(_connetionRecvBuffer, length, _connetionSendBuffer, out bytesToSend); } catch (CryptoErrorException) { Logger.Debug("encryption error"); Close(); return; } } OnOutbound?.Invoke(this, new SSTransmitEventArgs(_server, bytesToSend)); _startSendingTime = DateTime.Now; session.Remote.BeginSend(_connetionSendBuffer, 0, bytesToSend, SocketFlags.None, PipeRemoteSendCallback, new object[] { session, bytesToSend }); }
private void SendToServer(AsyncSession session) { var length = data.Length; _totalWrite += length; int bytesToSend; Array.Copy(data, _connetionRecvBuffer, data.Length); lock (_encryptionLock) { try { _encryptor.Encrypt(_connetionRecvBuffer, length, _connetionSendBuffer, out bytesToSend); } catch (CryptoErrorException) { Close(); return; } } _startSendingTime = DateTime.Now; session.Remote.BeginSend(_connetionSendBuffer, 0, bytesToSend, SocketFlags.None, PipeRemoteSendCallback, new object[] { session, bytesToSend }); }
private void PipeRemoteSendCallback(IAsyncResult ar) { if (_closed) { return; } try { object[] container = (object[])ar.AsyncState; AsyncSession session = (AsyncSession)container[0]; int bytesShouldSend = (int)container[1]; int bytesSent = session.Remote.EndSend(ar); if (bytesSent > 0) { lastActivity = DateTime.Now; } int bytesRemaining = bytesShouldSend - bytesSent; if (bytesRemaining > 0) { Logger.Info("reconstruct _connetionSendBuffer to re-send"); Buffer.BlockCopy(_connetionSendBuffer, bytesSent, _connetionSendBuffer, 0, bytesRemaining); session.Remote.BeginSend(_connetionSendBuffer, 0, bytesRemaining, SocketFlags.None, PipeRemoteSendCallback, new object[] { session, bytesRemaining }); return; } _connection.BeginReceive(_connetionRecvBuffer, 0, RecvSize, SocketFlags.None, PipeConnectionReceiveCallback, session); } catch (Exception e) { ErrorClose(e); } }
private void StartConnect() { try { CreateRemote(); // Setting up proxy IProxy remote; EndPoint proxyEP = null; EndPoint serverEP = SocketUtil.GetEndPoint(_server.server, _server.server_port); EndPoint pluginEP = _controller.GetPluginLocalEndPointIfConfigured(_server); if (pluginEP != null) { serverEP = pluginEP; remote = new DirectConnect(); } else if (_config.proxy.useProxy) { switch (_config.proxy.proxyType) { case ProxyConfig.PROXY_SOCKS5: remote = new Socks5Proxy(); break; case ProxyConfig.PROXY_HTTP: remote = new HttpProxy(); break; default: throw new NotSupportedException("Unknown forward proxy."); } proxyEP = SocketUtil.GetEndPoint(_config.proxy.proxyServer, _config.proxy.proxyPort); } else { remote = new DirectConnect(); } var session = new AsyncSession(remote); lock (_closeConnLock) { if (_closed) { remote.Close(); return; } _currentRemoteSession = session; } ProxyTimer proxyTimer = new ProxyTimer(_proxyTimeout) { AutoReset = false }; proxyTimer.Elapsed += ProxyConnectTimer_Elapsed; proxyTimer.Enabled = true; proxyTimer.Session = session; proxyTimer.DestEndPoint = serverEP; proxyTimer.Server = _server; _proxyConnected = false; // Connect to the proxy server. remote.BeginConnectProxy(proxyEP, ProxyConnectCallback, new AsyncSession <ProxyTimer>(remote, proxyTimer)); } catch (Exception e) { Logger.LogUsefulException(e); Close(); } }
private void SendHeader(AsyncSession session) { var h = _headers.Dequeue() + HTTP_CRLF; var len = Encoding.UTF8.GetBytes(h, 0, h.Length, ConnetionRecvBuffer, 0); BeginSendToServer(len, session, HeaderSendCallback); }
public void InsertThrowsArgumentNullExceptionForNullInstance() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock<ISqlDialect>().Object, new Mock<IDbDriver>().Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); var exception = Assert.Throws<AggregateException>( () => session.InsertAsync(null).Wait()); Assert.Equal("instance", ((ArgumentNullException)exception.InnerException).ParamName); }
public void InsertThrowsObjectDisposedExceptionIfDisposed() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock<ISqlDialect>().Object, new Mock<IDbDriver>().Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); using (session) { } var exception = Assert.Throws<AggregateException>( () => session.InsertAsync(new Customer()).Wait()); Assert.IsType<ObjectDisposedException>(exception.InnerException); }
public void ExecuteThrowsObjectDisposedExceptionIfDisposed() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock<ISqlDialect>().Object, new Mock<IDbDriver>().Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); using (session) { } var exception = Assert.Throws<AggregateException>( () => session.ExecuteAsync(new SqlQuery("SELECT")).Result); Assert.IsType<ObjectDisposedException>(exception.InnerException); }
public void InsertBuildsAndExecutesIndividualCommandsIfIdentifierStrategyNotAssignedAndSqlDialectSupportsSelectInsertedIdentifierAndDbDriverDoesNotSupportBatchedQueries() { ObjectInfo.MappingConvention = new ConventionMappingConvention( UnitTest.GetConventionMappingSettings(IdentifierStrategy.DbGenerated)); var customer = new Customer(); var insertSqlQuery = new SqlQuery("INSERT"); var selectIdSqlQuery = new SqlQuery("SELECT"); object identifier = 23543; var mockSqlDialect = new Mock<ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(insertSqlQuery); mockSqlDialect.Setup(x => x.BuildSelectInsertIdSqlQuery(It.IsNotNull<IObjectInfo>())).Returns(selectIdSqlQuery); mockSqlDialect.Setup(x => x.SupportsSelectInsertedIdentifier).Returns(true); var mockCommand = new Mock<IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()); mockCommand.Setup(x => x.ExecuteScalar()).Returns(identifier); var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); mockDbDriver.Setup(x => x.SupportsBatchedQueries).Returns(false); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); session.InsertAsync(customer).Wait(); mockSqlDialect.VerifyAll(); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
public void DeleteTypeByIdentifierThrowsObjectDisposedExceptionIfDisposed() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock<ISqlDialect>().Object, new Mock<IDbDriver>().Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); using (session) { } var exception = Assert.Throws<AggregateException>( () => session.DeleteAsync(typeof(Customer), 1234).Result); Assert.IsType<ObjectDisposedException>(exception.InnerException); }
public void ExecuteScalarUsesTypeConvertersToResolveResultType() { var result = (byte)1; var mockSqlDialect = new Mock<ISqlDialect>(); var mockCommand = new Mock<IDbCommand>(); mockCommand.Setup(x => x.ExecuteScalar()).Returns(result); var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); Assert.Equal((CustomerStatus)result, session.ExecuteScalarAsync<CustomerStatus>(new SqlQuery("")).Result); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
private void SendConnectResponse(AsyncSession session) { var len = Encoding.UTF8.GetBytes(HTTP_CONNECT_200, 0, HTTP_CONNECT_200.Length, RemoteRecvBuffer, 0); _localSocket.BeginSend(RemoteRecvBuffer, 0, len, SocketFlags.None, Http200SendCallback, session); }
public void DeleteTypeByIdentifierReturnsTrueIfRecordDeleted() { var type = typeof(Customer); var identifier = 1234; var mockSqlDialect = new Mock<ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull<IObjectInfo>(), identifier)).Returns(new SqlQuery("")); var mockCommand = new Mock<IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1); var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); Assert.True(session.DeleteAsync(type, identifier).Result); mockSqlDialect.VerifyAll(); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
private void SendToServer(int length, AsyncSession session) { BeginSendToServer(length, session, PipeRemoteSendCallback); }
public void UpdateInstanceThrowsArgumentNullExceptionForNullInstance() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock<ISqlDialect>().Object, new Mock<IDbDriver>().Object, new SessionListeners()); var exception = Assert.Throws<AggregateException>( () => session.UpdateAsync((Customer)null).Result); Assert.Equal("instance", ((ArgumentNullException)exception.InnerException).ParamName); }
protected abstract void OnServerConnected(AsyncSession session);
private void SendToServer(int length, AsyncSession session) { _totalWrite += length; int bytesToSend; lock (_encryptionLock) { _encryptor.Encrypt(_connetionRecvBuffer, length, _connetionSendBuffer, out bytesToSend); } _tcprelay.UpdateOutboundCounter(_server, bytesToSend); _startSendingTime = DateTime.Now; session.Remote.BeginSend(_connetionSendBuffer, 0, bytesToSend, SocketFlags.None, new AsyncCallback(PipeRemoteSendCallback), session); IStrategy strategy = _controller.GetCurrentStrategy(); strategy?.UpdateLastWrite(_server); }
private void StartPipe(AsyncSession session) { if (_closed) return; try { _startReceivingTime = DateTime.Now; session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None, new AsyncCallback(PipeRemoteReceiveCallback), session); SendToServer(_firstPacketLength, session); } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
public void DeleteTypeByIdentifierThrowsArgumentNullExceptionForNullType() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock<ISqlDialect>().Object, new Mock<IDbDriver>().Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); var exception = Assert.Throws<AggregateException>( () => session.DeleteAsync(null, 1234).Result); Assert.Equal("type", ((ArgumentNullException)exception.InnerException).ParamName); }
public void DeleteInstanceReturnsFalseIfNoRecordsDeleted() { var customer = new Customer { Id = 14556 }; var mockSqlDialect = new Mock<ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull<IObjectInfo>(), customer.Id)).Returns(new SqlQuery("")); var mockCommand = new Mock<IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(0); var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new SessionListeners()); Assert.False(session.DeleteAsync(customer).Result); mockSqlDialect.VerifyAll(); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
public void ExecuteScalarBuildsAndExecutesCommand() { var result = new object(); var mockSqlDialect = new Mock<ISqlDialect>(); var mockCommand = new Mock<IDbCommand>(); mockCommand.Setup(x => x.ExecuteScalar()).Returns(result); var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); Assert.Equal(result, session.ExecuteScalarAsync<object>(new SqlQuery("")).Result); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
private void StartConnect() { try { CreateRemote(); // Setting up proxy IProxy remote; EndPoint proxyEP; if (_config.proxy.useProxy) { switch (_config.proxy.proxyType) { case ProxyConfig.PROXY_SOCKS5: remote = new Socks5Proxy(); break; case ProxyConfig.PROXY_HTTP: remote = new HttpProxy(); break; default: throw new NotSupportedException("Unknown forward proxy."); } proxyEP = SocketUtil.GetEndPoint(_config.proxy.proxyServer, _config.proxy.proxyPort); } else { remote = new DirectConnect(); proxyEP = null; } var session = new AsyncSession(remote); _currentRemoteSession = session; ProxyTimer proxyTimer = new ProxyTimer(_proxyTimeout); proxyTimer.AutoReset = false; proxyTimer.Elapsed += proxyConnectTimer_Elapsed; proxyTimer.Enabled = true; proxyTimer.Session = session; proxyTimer.DestEndPoint = SocketUtil.GetEndPoint(_server.server, _server.server_port); proxyTimer.Server = _server; _proxyConnected = false; // Connect to the proxy server. remote.BeginConnectProxy(proxyEP, new AsyncCallback(ProxyConnectCallback), new AsyncSession<ProxyTimer>(remote, proxyTimer)); } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
public void ExecuteThrowsArgumentNullExceptionForNullSqlQuery() { var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock<ISqlDialect>().Object, new Mock<IDbDriver>().Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); var exception = Assert.Throws<AggregateException>( () => session.ExecuteAsync(null).Result); Assert.Equal("sqlQuery", ((ArgumentNullException)exception.InnerException).ParamName); }
private void StartPipe(AsyncSession session) { if (_closed) return; try { _startReceivingTime = DateTime.Now; session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None, new AsyncCallback(PipeRemoteReceiveCallback), session); _connection.BeginReceive(_connetionRecvBuffer, 0, RecvSize, SocketFlags.None, new AsyncCallback(PipeConnectionReceiveCallback), new AsyncSession<bool>(session, true) /* to tell the callback this is the first time reading packet, and we haven't found the header yet. */); } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
public void InsertBuildsAndExecutesAnInsertCommandOnlyIfIdentifierStrategyAssigned() { ObjectInfo.MappingConvention = new ConventionMappingConvention( UnitTest.GetConventionMappingSettings(IdentifierStrategy.Assigned)); var customer = new Customer { Id = 12345 }; var insertSqlQuery = new SqlQuery("INSERT"); var mockSqlDialect = new Mock<ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(insertSqlQuery); mockSqlDialect.Setup(x => x.SupportsSelectInsertedIdentifier).Returns(false); var mockCommand = new Mock<IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1); var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); session.InsertAsync(customer).Wait(); mockSqlDialect.Verify(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer), Times.Once()); mockSqlDialect.Verify(x => x.BuildSelectInsertIdSqlQuery(It.IsAny<IObjectInfo>()), Times.Never()); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
protected override void OnServerConnected(AsyncSession session) { BeginSendToServer(_firstPacketLength, session, FirstPackageSendCallback); }
public void InsertInvokesListeners() { var customer = new Customer(); object identifier = 23543; var mockSqlDialect = new Mock<ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(new SqlQuery("")); mockSqlDialect.Setup(x => x.BuildSelectInsertIdSqlQuery(It.IsNotNull<IObjectInfo>())).Returns(new SqlQuery("")); var mockCommand = new Mock<IDbCommand>(); mockCommand.Setup(x => x.ExecuteScalar()).Returns(identifier); var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); int counter = 0; var mockListener1 = new Mock<IInsertListener>(); mockListener1.Setup(x => x.AfterInsert(customer, identifier)).Callback(() => Assert.Equal(4, ++counter)); mockListener1.Setup(x => x.BeforeInsert(customer)).Callback(() => Assert.Equal(1, ++counter)); var mockListener2 = new Mock<IInsertListener>(); mockListener2.Setup(x => x.AfterInsert(customer, identifier)).Callback(() => Assert.Equal(3, ++counter)); mockListener2.Setup(x => x.BeforeInsert(customer)).Callback(() => Assert.Equal(2, ++counter)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new[] { mockListener1.Object, mockListener2.Object }, new IUpdateListener[0]); session.InsertAsync(customer).Wait(); mockListener1.VerifyAll(); mockListener2.VerifyAll(); }
public void UpdateObjectDeltaReturnsTrueIfRecordUpdated() { var objectDelta = new ObjectDelta(typeof(Customer), 1234); objectDelta.AddChange("Name", "Fred Flintstone"); var mockSqlDialect = new Mock<ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildUpdateSqlQuery(objectDelta)).Returns(new SqlQuery("")); var mockCommand = new Mock<IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1); var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); Assert.True(session.UpdateAsync(objectDelta).Result); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
public void InsertThrowsMicroLiteExceptionIfExecuteScalarThrowsException() { var customer = new Customer(); var mockSqlDialect = new Mock<ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(new SqlQuery("")); mockSqlDialect.Setup(x => x.BuildSelectInsertIdSqlQuery(It.IsNotNull<IObjectInfo>())).Returns(new SqlQuery("")); var mockCommand = new Mock<IDbCommand>(); mockCommand.Setup(x => x.ExecuteScalar()).Throws<InvalidOperationException>(); var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); var exception = Assert.Throws<AggregateException>(() => session.InsertAsync(customer).Wait()); Assert.IsType<MicroLiteException>(exception.InnerException); Assert.IsType<InvalidOperationException>(exception.InnerException.InnerException); Assert.Equal(exception.InnerException.InnerException.Message, exception.InnerException.Message); // Command should still be disposed. mockCommand.VerifyAll(); }
public void UpdateObjectDeltaThrowsMicroLiteExceptionIfItContainsNoChanges() { var objectDelta = new ObjectDelta(typeof(Customer), 1234); var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock<ISqlDialect>().Object, new Mock<IDbDriver>().Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); var exception = Assert.Throws<AggregateException>( () => session.UpdateAsync(objectDelta).Result); Assert.IsType<MicroLiteException>(exception.InnerException); Assert.Equal(ExceptionMessages.ObjectDelta_MustContainAtLeastOneChange, exception.InnerException.Message); }
public void UpdateInstanceReturnsTrueIfRecordUpdated() { var customer = new Customer { Id = 187224 }; var mockSqlDialect = new Mock<ISqlDialect>(); mockSqlDialect.Setup(x => x.BuildUpdateSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(new SqlQuery("")); var mockCommand = new Mock<IDbCommand>(); mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1); var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, mockSqlDialect.Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); Assert.True(session.UpdateAsync(customer).Result); mockSqlDialect.VerifyAll(); mockDbDriver.VerifyAll(); mockCommand.VerifyAll(); }
public void DeleteInstanceThrowsMicroLiteExceptionIfIdentifierNotSet() { var customer = new Customer { Id = 0 }; var mockConnection = new Mock<IDbConnection>(); mockConnection.Setup(x => x.CreateCommand()).Returns(new Mock<IDbCommand>().Object); var mockDbDriver = new Mock<IDbDriver>(); mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object)); var session = new AsyncSession( ConnectionScope.PerTransaction, new Mock<ISqlDialect>().Object, mockDbDriver.Object, new IDeleteListener[0], new IInsertListener[0], new IUpdateListener[0]); var exception = Assert.Throws<AggregateException>( () => session.DeleteAsync(customer).Result); Assert.IsType<MicroLiteException>(exception.InnerException); Assert.Equal(ExceptionMessages.Session_IdentifierNotSetForDelete, exception.InnerException.Message); }
private void StartConnect() { try { CreateRemote(); // Setting up proxy IProxy remote; EndPoint proxyEP; if (_config.useProxy) { remote = new Socks5Proxy(); proxyEP = SocketUtil.GetEndPoint(_config.proxyServer, _config.proxyPort); } else { remote = new DirectConnect(); proxyEP = null; } var session = new AsyncSession(remote); _currentRemoteSession = session; ProxyTimer proxyTimer = new ProxyTimer(3000); proxyTimer.AutoReset = false; proxyTimer.Elapsed += proxyConnectTimer_Elapsed; proxyTimer.Enabled = true; proxyTimer.Session = session; proxyTimer.DestEndPoint = SocketUtil.GetEndPoint(server.server, server.server_port); proxyTimer.Server = server; _proxyConnected = false; // Connect to the proxy server. remote.BeginConnectProxy(proxyEP, new AsyncCallback(ProxyConnectCallback), new AsyncSession<ProxyTimer>(remote, proxyTimer)); } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
public Task Commit() { return(AsyncSession.SaveChangesAsync()); }