public void DisposedIsPassedOn() { var innerConnection = new TestConnection(); var outerConnection = new EncryptingConnection(innerConnection); outerConnection.Dispose(); Assert.IsTrue(innerConnection.Disposed); }
public TcpChannelTest() { _pipeline = new MyPipeline(); _sockets = SocketTestTools.CreateConnection(); _target = new TcpServerClientChannel(_pipeline); _target.AssignSocket(_sockets.Client); _target.StartChannel(); }
public void ConnectionString_WhenCalled_ReturnsOriginalConnectionString() { // ARRANGE string connectionString = Settings.Default.IntegrationTestConnection; var connection = new TestConnection(connectionString); // ACT var actualConnectionString = connection.ConnectionString; // ASSERT Assert.AreEqual(connectionString, actualConnectionString); }
public void SendMessageEncryptsMessage() { var innerConnection = new TestConnection(); var outerConnection = new EncryptingConnection(innerConnection); var request = new ServerRequest(); var expectedResponse = new Response(request); var actionName = "DoSomething"; string iv = null; string key = null; innerConnection.SendMessageAction = (a, r) => { Response sendResponse = null; if (a == "RetrievePublicKey") { sendResponse = this.GenerateKeyResponse(r); } else if (a == "InitialiseSecureConnection") { Assert.IsInstanceOf<LoginRequest>(r); sendResponse = this.GenerateConnectioResponse(r as LoginRequest, out iv, out key); } else if (a == "ProcessSecureRequest") { Assert.IsInstanceOf<EncryptedRequest>(r); var actualRequest = r as EncryptedRequest; Assert.AreEqual(actionName, actualRequest.Action); var crypto = new RijndaelManaged(); crypto.Key = Convert.FromBase64String(key); crypto.IV = Convert.FromBase64String(iv); var requestData = DecryptMessage(crypto, actualRequest.EncryptedData); Assert.AreEqual(request.ToString(), requestData); var encryptedResponse = new EncryptedResponse(); encryptedResponse.Result = ResponseResult.Success; encryptedResponse.EncryptedData = EncryptMessage(crypto, expectedResponse.ToString()); sendResponse = encryptedResponse; } else { Assert.Fail("Unknown action: " + a); } return sendResponse; }; var response = outerConnection.SendMessage(actionName, request); Assert.IsNotNull(response); Assert.AreEqual(expectedResponse.RequestIdentifier, response.RequestIdentifier); }
public void ConstructorWiresUpEvents() { var innerConnection = new TestConnection(); var outerConnection = new EncryptingConnection(innerConnection); var sendMessageFired = false; var requestSendingFired = false; var responseReceivedFired = false; outerConnection.SendMessageCompleted += (o, e) => { sendMessageFired = true; }; outerConnection.RequestSending += (o, e) => { requestSendingFired = true; }; outerConnection.ResponseReceived += (o, e) => { responseReceivedFired = true; }; innerConnection.TriggerSendMessageCompleted(null, null, false, null); innerConnection.TriggerRequestSending(null, null); innerConnection.TriggerResponseReceived(null, null); Assert.IsTrue(sendMessageFired); Assert.IsTrue(requestSendingFired); Assert.IsTrue(responseReceivedFired); }
public void PropertiesAreRetrievedFromInnerConnection() { var innerConnection = new TestConnection { Type = "innerTest", ServerName = "theServerName", Address = "http://lostintranslation", IsBusy = false }; var outerConnection = new EncryptingConnection(innerConnection); Assert.AreEqual(innerConnection.Type, outerConnection.Type); Assert.AreEqual(innerConnection.ServerName, outerConnection.ServerName); Assert.AreEqual(innerConnection.Address, outerConnection.Address); Assert.AreEqual(innerConnection.IsBusy, outerConnection.IsBusy); innerConnection.IsBusy = true; Assert.AreEqual(innerConnection.IsBusy, outerConnection.IsBusy); }
public void Close_AfterCalling_ConnectionStateIsClosed() { // ARRANGE string connectionString = Settings.Default.IntegrationTestConnection; var connection = new TestConnection(connectionString); ConnectionState actualConnectionState; // ACT try { connection.Open(); } finally { connection.Close(); actualConnectionState = connection.State; connection.Dispose(); } // ASSERT Assert.AreEqual(ConnectionState.Closed, actualConnectionState); }
public void Dispose_WhenCalled_DoesNotThrowException() { // ARRANGE string connectionString = Settings.Default.IntegrationTestConnection; var connection = new TestConnection(connectionString); // ACT connection.Dispose(); // ASSERT }
public override void TestFixtureSetUp() { base.TestFixtureSetUp(); _node = new MiniNode(PathName, enableTrustedAuth: true); try { _node.Start(); var userCreateEvent1 = new ManualResetEventSlim(); _node.Node.MainQueue.Publish( new UserManagementMessage.Create( new CallbackEnvelope( m => { Assert.IsTrue(m is UserManagementMessage.UpdateResult); var msg = (UserManagementMessage.UpdateResult)m; Assert.IsTrue(msg.Success); userCreateEvent1.Set(); }), SystemAccount.Principal, "user1", "Test User 1", new string[0], "pa$$1")); var userCreateEvent2 = new ManualResetEventSlim(); _node.Node.MainQueue.Publish( new UserManagementMessage.Create( new CallbackEnvelope( m => { Assert.IsTrue(m is UserManagementMessage.UpdateResult); var msg = (UserManagementMessage.UpdateResult)m; Assert.IsTrue(msg.Success); userCreateEvent2.Set(); }), SystemAccount.Principal, "user2", "Test User 2", new string[0], "pa$$2")); var adminCreateEvent2 = new ManualResetEventSlim(); _node.Node.MainQueue.Publish( new UserManagementMessage.Create( new CallbackEnvelope( m => { Assert.IsTrue(m is UserManagementMessage.UpdateResult); var msg = (UserManagementMessage.UpdateResult)m; Assert.IsTrue(msg.Success); adminCreateEvent2.Set(); }), SystemAccount.Principal, "adm", "Administrator User", new[] { SystemRoles.Admins }, "admpa$$")); Assert.IsTrue(userCreateEvent1.Wait(10000), "User 1 creation failed"); Assert.IsTrue(userCreateEvent2.Wait(10000), "User 2 creation failed"); Assert.IsTrue(adminCreateEvent2.Wait(10000), "Administrator User creation failed"); Connection = TestConnection.Create(_node.TcpEndPoint, TcpType.Normal, _userCredentials); Connection.ConnectAsync().Wait(); Connection.SetStreamMetadataAsync("noacl-stream", ExpectedVersion.NoStream, StreamMetadata.Build()) .Wait(); Connection.SetStreamMetadataAsync( "read-stream", ExpectedVersion.NoStream, StreamMetadata.Build().SetReadRole("user1")).Wait(); Connection.SetStreamMetadataAsync( "write-stream", ExpectedVersion.NoStream, StreamMetadata.Build().SetWriteRole("user1")).Wait(); Connection.SetStreamMetadataAsync( "metaread-stream", ExpectedVersion.NoStream, StreamMetadata.Build().SetMetadataReadRole("user1")).Wait(); Connection.SetStreamMetadataAsync( "metawrite-stream", ExpectedVersion.NoStream, StreamMetadata.Build().SetMetadataWriteRole("user1")).Wait(); Connection.SetStreamMetadataAsync( "$all", ExpectedVersion.Any, StreamMetadata.Build().SetReadRole("user1"), new UserCredentials("adm", "admpa$$")).Wait(); Connection.SetStreamMetadataAsync( "$system-acl", ExpectedVersion.NoStream, StreamMetadata.Build() .SetReadRole("user1") .SetWriteRole("user1") .SetMetadataReadRole("user1") .SetMetadataWriteRole("user1"), new UserCredentials("adm", "admpa$$")).Wait(); Connection.SetStreamMetadataAsync( "$system-adm", ExpectedVersion.NoStream, StreamMetadata.Build() .SetReadRole(SystemRoles.Admins) .SetWriteRole(SystemRoles.Admins) .SetMetadataReadRole(SystemRoles.Admins) .SetMetadataWriteRole(SystemRoles.Admins), new UserCredentials("adm", "admpa$$")).Wait(); Connection.SetStreamMetadataAsync( "normal-all", ExpectedVersion.NoStream, StreamMetadata.Build() .SetReadRole(SystemRoles.All) .SetWriteRole(SystemRoles.All) .SetMetadataReadRole(SystemRoles.All) .SetMetadataWriteRole(SystemRoles.All)).Wait(); Connection.SetStreamMetadataAsync( "$system-all", ExpectedVersion.NoStream, StreamMetadata.Build() .SetReadRole(SystemRoles.All) .SetWriteRole(SystemRoles.All) .SetMetadataReadRole(SystemRoles.All) .SetMetadataWriteRole(SystemRoles.All), new UserCredentials("adm", "admpa$$")).Wait(); } catch { if (_node != null) { try { _node.Shutdown(); } catch { } } throw; } }
virtual protected IEventStoreConnection BuildConnection(MiniNode node) { return(TestConnection.Create(node.TcpEndPoint)); }
public void ServerPipeDispatchConnections() { var pipeName = @"\\.\pipe\ServerPipeDispatchConnections" + Guid.NewGuid().ToString("n"); var loop = new UvLoopHandle(_logger); loop.Init(_uv); var serverConnectionPipe = default(UvPipeHandle); var serverConnectionPipeAcceptedEvent = new ManualResetEvent(false); var serverConnectionTcpDisposedEvent = new ManualResetEvent(false); var serverListenPipe = new UvPipeHandle(_logger); serverListenPipe.Init(loop, (a, b) => { }, false); serverListenPipe.Bind(pipeName); serverListenPipe.Listen(128, (handle, status, error, state) => { serverConnectionPipe = new UvPipeHandle(_logger); serverConnectionPipe.Init(loop, (a, b) => { }, true); try { serverListenPipe.Accept(serverConnectionPipe); serverConnectionPipeAcceptedEvent.Set(); } catch (Exception ex) { Console.WriteLine(ex); serverConnectionPipe.Dispose(); serverConnectionPipe = null; } }, null); var serverListenTcp = new UvTcpHandle(_logger); serverListenTcp.Init(loop, (a, b) => { }); var endPoint = new IPEndPoint(IPAddress.Loopback, 0); serverListenTcp.Bind(endPoint); var port = serverListenTcp.GetSockIPEndPoint().Port; serverListenTcp.Listen(128, (handle, status, error, state) => { var serverConnectionTcp = new UvTcpHandle(_logger); serverConnectionTcp.Init(loop, (a, b) => { }); serverListenTcp.Accept(serverConnectionTcp); serverConnectionPipeAcceptedEvent.WaitOne(); var writeRequest = new UvWriteReq(_logger); writeRequest.DangerousInit(loop); writeRequest.Write2( serverConnectionPipe, new ArraySegment <ArraySegment <byte> >(new ArraySegment <byte>[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4 }) }), serverConnectionTcp, (handle2, status2, error2, state2) => { writeRequest.Dispose(); serverConnectionTcp.Dispose(); serverConnectionTcpDisposedEvent.Set(); serverConnectionPipe.Dispose(); serverListenPipe.Dispose(); serverListenTcp.Dispose(); }, null); }, null); var worker = new Thread(() => { var loop2 = new UvLoopHandle(_logger); var clientConnectionPipe = new UvPipeHandle(_logger); var connect = new UvConnectRequest(_logger); loop2.Init(_uv); clientConnectionPipe.Init(loop2, (a, b) => { }, true); connect.DangerousInit(loop2); connect.Connect(clientConnectionPipe, pipeName, (handle, status, error, state) => { connect.Dispose(); var buf = loop2.Libuv.buf_init(Marshal.AllocHGlobal(64), 64); serverConnectionTcpDisposedEvent.WaitOne(); clientConnectionPipe.ReadStart( (handle2, cb, state2) => buf, (handle2, status2, state2) => { if (status2 == TestConstants.EOF) { clientConnectionPipe.Dispose(); return; } var clientConnectionTcp = new UvTcpHandle(_logger); clientConnectionTcp.Init(loop2, (a, b) => { }); clientConnectionPipe.Accept(clientConnectionTcp); var buf2 = loop2.Libuv.buf_init(Marshal.AllocHGlobal(64), 64); clientConnectionTcp.ReadStart( (handle3, cb, state3) => buf2, (handle3, status3, state3) => { if (status3 == TestConstants.EOF) { clientConnectionTcp.Dispose(); } }, null); }, null); }, null); loop2.Run(); loop2.Dispose(); }); var worker2 = new Thread(() => { try { serverConnectionPipeAcceptedEvent.WaitOne(); var socket = TestConnection.CreateConnectedLoopbackSocket(port); socket.Send(new byte[] { 6, 7, 8, 9 }); socket.Shutdown(SocketShutdown.Send); var cb = socket.Receive(new byte[64]); socket.Dispose(); } catch (Exception ex) { Console.WriteLine(ex); } }); worker.Start(); worker2.Start(); loop.Run(); loop.Dispose(); worker.Join(); worker2.Join(); }
public void CreateConnection() { var server = new TestConnection(true); Assert.IsTrue(true); }
protected virtual IEventStoreConnection BuildConnection(MiniNode <TLogFormat, TStreamId> node) { return(TestConnection <TLogFormat, TStreamId> .Create(node.TcpEndPoint)); }
public override void TestFixtureSetUp() { #if !MONO Helper.EatException(() => _dumpResponse = CreateDumpResponse()); Helper.EatException(() => _dumpResponse2 = CreateDumpResponse2()); Helper.EatException(() => _dumpRequest = CreateDumpRequest()); Helper.EatException(() => _dumpRequest2 = CreateDumpRequest2()); #endif base.TestFixtureSetUp(); _createdMiniNode = false; if (SetUpFixture._connection != null && SetUpFixture._node != null) { _tag = "_" + (++SetUpFixture._counter); _node = SetUpFixture._node; _connection = SetUpFixture._connection; } else { _createdMiniNode = true; _tag = "_1"; _node = CreateMiniNode(); _node.Start(); _connection = TestConnection.Create(_node.TcpEndPoint); _connection.ConnectAsync().Wait(); } _lastResponse = null; _lastResponseBody = null; _lastResponseBytes = null; _lastJsonException = null; try { Given(); When(); } catch { if (_createdMiniNode) { if (_connection != null) { try { _connection.Close(); } catch { } } if (_node != null) { try { _node.Shutdown(); } catch { } } } throw; } }
private IEventStoreConnection SetupConnection() { return(TestConnection.Create(TcpType.Normal, _userCredentials)); }
public void Setup() { _connection = new TestConnection(); _connection.Open(); }
private static async Task NtlmStage1And2Auth(TestServer server, TestConnection testConnection) { await NtlmStage1Auth(server, testConnection); await NtlmStage2Auth(server, testConnection); }
private static async Task KerberosStage1And2Auth(TestServer server, TestConnection testConnection) { await KerberosStage1Auth(server, testConnection); await KerberosStage2Auth(server, testConnection); }
// the host enumeration block we're using to enumerate all servers private static IEnumerable <UserLocation> _Find_DomainUserLocation(string[] ComputerName, string[] TargetUsers, string CurrentUser, bool Stealth, bool CheckAccess, IntPtr TokenHandle) { var LogonToken = IntPtr.Zero; if (TokenHandle != IntPtr.Zero) { // impersonate the the token produced by LogonUser()/Invoke-UserImpersonation LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation { TokenHandle = TokenHandle, Quiet = true }); } var UserLocations = new List <UserLocation>(); foreach (var TargetComputer in ComputerName) { var Up = TestConnection.Ping(TargetComputer, 1); if (Up) { var Sessions = GetNetSession.Get_NetSession(new Args_Get_NetSession { ComputerName = new[] { TargetComputer } }); foreach (var Session in Sessions) { var UserName = Session.UserName; var CName = Session.CName; if (!CName.IsNullOrEmpty() && CName.StartsWith(@"\\")) { CName = CName.TrimStart('\\'); } // make sure we have a result, and ignore computer$ sessions if ((UserName != null) && (UserName.Trim() != "") && (!UserName.IsRegexMatch(CurrentUser)) && (!UserName.IsRegexMatch(@"\$$"))) { if ((TargetUsers == null) || (TargetUsers.Contains(UserName))) { var UserLocation = new UserLocation { UserDomain = null, UserName = UserName, ComputerName = TargetComputer, SessionFrom = CName }; // try to resolve the DNS hostname of $Cname try { var CNameDNSName = System.Net.Dns.GetHostEntry(CName).HostName; UserLocation.SessionFromName = CNameDNSName; } catch { UserLocation.SessionFromName = null; } // see if we're checking to see if we have local admin access on this machine if (CheckAccess) { var Admin = TestAdminAccess.Test_AdminAccess(new Args_Test_AdminAccess { ComputerName = new[] { CName } }).FirstOrDefault(); UserLocation.LocalAdmin = Admin != null ? Admin.IsAdmin : false; } else { UserLocation.LocalAdmin = false; } UserLocations.Add(UserLocation); } } } if (!Stealth) { // if we're not 'stealthy', enumerate loggedon users as well var LoggedOn = GetNetLoggedon.Get_NetLoggedon(new Args_Get_NetLoggedon { ComputerName = new[] { TargetComputer } }); foreach (var User in LoggedOn) { var UserName = User.UserName; var UserDomain = User.LogonDomain; // make sure wet have a result if ((UserName != null) && (UserName.Trim() != "")) { if ((TargetUsers == null) || (TargetUsers.Contains(UserName)) && (!UserName.IsRegexMatch(@"\$$"))) { var IPAddress = ResolveIPAddress.Resolve_IPAddress(new Args_Resolve_IPAddress { ComputerName = new[] { TargetComputer } }).FirstOrDefault()?.IPAddress; var UserLocation = new UserLocation { UserDomain = UserDomain, UserName = UserName, ComputerName = TargetComputer, IPAddress = IPAddress, SessionFrom = null, SessionFromName = null }; // see if we're checking to see if we have local admin access on this machine if (CheckAccess) { var Admin = TestAdminAccess.Test_AdminAccess(new Args_Test_AdminAccess { ComputerName = new[] { TargetComputer } }).FirstOrDefault(); UserLocation.LocalAdmin = Admin.IsAdmin; } else { UserLocation.LocalAdmin = false; } UserLocations.Add(UserLocation); } } } } } } if (TokenHandle != IntPtr.Zero) { InvokeRevertToSelf.Invoke_RevertToSelf(LogonToken); } return(UserLocations); }
public void SqLiteTestConnection() { var testCon = new TestConnection(); }
public void ServerVersion_WhenCalled_ReturnsAInstantiatedServerVersionString() { // ARRANGE string connectionString = Settings.Default.IntegrationTestConnection; var connection = new TestConnection(connectionString); string actualServerVersion; // ACT try { connection.Open(); actualServerVersion = connection.ServerVersion; } finally { connection.Close(); connection.Dispose(); } // ASSERT Assert.IsNotNull(actualServerVersion); }
public SqlConnectionDialog() { InitializeComponent(); TestConnection.Focus(); }
public async Task SocketCanReadAndWrite() { var loop = new UvLoopHandle(_logger); loop.Init(_uv); var tcp = new UvTcpHandle(_logger); tcp.Init(loop, (a, b) => { }); var endPoint = new IPEndPoint(IPAddress.Loopback, 0); tcp.Bind(endPoint); var port = tcp.GetSockIPEndPoint().Port; tcp.Listen(10, (_, status, error, state) => { var tcp2 = new UvTcpHandle(_logger); tcp2.Init(loop, (a, b) => { }); tcp.Accept(tcp2); var data = Marshal.AllocCoTaskMem(500); tcp2.ReadStart( (a, b, c) => tcp2.Libuv.buf_init(data, 500), async(__, nread, state2) => { if (nread <= 0) { tcp2.Dispose(); } else { for (var x = 0; x < 2; x++) { var req = new UvWriteReq(_logger); req.DangerousInit(loop); var block = new ReadOnlySequence <byte>(new byte[] { 65, 66, 67, 68, 69 }); await req.WriteAsync( tcp2, block); } } }, null); tcp.Dispose(); }, null); var t = Task.Run(async() => { var socket = TestConnection.CreateConnectedLoopbackSocket(port); await socket.SendAsync(new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) }, SocketFlags.None); socket.Shutdown(SocketShutdown.Send); var buffer = new ArraySegment <byte>(new byte[2048]); while (true) { var count = await socket.ReceiveAsync(new[] { buffer }, SocketFlags.None); if (count <= 0) { break; } } socket.Dispose(); }); loop.Run(); loop.Dispose(); await t; }
protected IEventStoreConnection BuildConnection() { return(TestConnection.Create(TcpType.Normal)); }
public void not_throw_on_close_if_connect_was_not_called() { var connection = TestConnection.To(_node, _tcpType); Assert.DoesNotThrow(connection.Close); }
protected virtual IEventStoreConnection BuildConnection(MiniNode node) { return(TestConnection.To(node, TcpType.Normal)); }
protected virtual IEventStoreConnection BuildConnection() { return TestConnection.Create(_tcpType); }
protected virtual IEventStoreConnection BuildConnection(MiniNode <TLogFormat, TStreamId> node) { return(TestConnection.To(node, _tcpType)); }
public void Setup() { _parser = new NullityExpressionParser(new ParserLookup(new LowerSnakeCaseNameResolver(), new SqlFunctionNameResolver())); _connection = new TestConnection(); _connection.Open(); }
public void SetUp() { m_TestConnection = m_Mocks.StrictMock<TestConnection>(); m_PassingConnectionStatus = new ConnectionStatus(true, "", new List<DbObjectName>(), "datapath"); m_FailingConnectionStatus = new ConnectionStatus(false, "you're just plain wrong", new List<DbObjectName>(), ""); m_DefaultView = new StubbedLocalServerPickerView(null) .Instance("instance") .SecurityType(SecurityType.SqlServerAuth) .UserName("tiestv") .Password("rocks!"); m_DefaultConnection = new Connection("instance", SecurityType.SqlServerAuth, "tiestv", "rocks!"); m_GetLocalInstances = m_Mocks.PartialMock<StubbedGetLocalInstances>(); }
public void should_commit_when_writing_with_exp_ver_any_even_while_somene_is_writing_in_parallel() { const string stream = "should_commit_when_writing_with_exp_ver_any_even_while_somene_is_writing_in_parallel"; var transWritesCompleted = new ManualResetEventSlim(false); var writesToSameStreamCompleted = new ManualResetEventSlim(false); const int totalTranWrites = 500; const int totalPlainWrites = 500; //500 events during transaction ThreadPool.QueueUserWorkItem(_ => { Assert.DoesNotThrow(() => { using (var store = TestConnection.Create(_node.TcpEndPoint)) { store.ConnectAsync().Wait(); using (var transaction = store.StartTransactionAsync(stream, ExpectedVersion.Any).Result) { var writes = new List <Task>(); for (int i = 0; i < totalTranWrites; i++) { writes.Add(transaction.WriteAsync(TestEvent.NewTestEvent(i.ToString(), "trans write"))); } Task.WaitAll(writes.ToArray()); transaction.Commit(); transWritesCompleted.Set(); } } }); }); //500 events to same stream in parallel ThreadPool.QueueUserWorkItem(_ => { Assert.DoesNotThrow(() => { using (var store = TestConnection.Create(_node.TcpEndPoint)) { store.ConnectAsync().Wait(); var writes = new List <Task>(); for (int i = 0; i < totalPlainWrites; i++) { writes.Add(store.AppendToStreamAsync(stream, ExpectedVersion.Any, new[] { TestEvent.NewTestEvent(i.ToString(), "plain write") })); } Task.WaitAll(writes.ToArray()); writesToSameStreamCompleted.Set(); } }); }); transWritesCompleted.Wait(); writesToSameStreamCompleted.Wait(); // check all written using (var store = TestConnection.Create(_node.TcpEndPoint)) { store.ConnectAsync().Wait(); var slice = store.ReadStreamEventsForwardAsync(stream, 0, totalTranWrites + totalPlainWrites, false).Result; Assert.That(slice.Events.Length, Is.EqualTo(totalTranWrites + totalPlainWrites)); Assert.That(slice.Events.Count(ent => Helper.UTF8NoBom.GetString(ent.Event.Metadata) == "trans write"), Is.EqualTo(totalTranWrites)); Assert.That(slice.Events.Count(ent => Helper.UTF8NoBom.GetString(ent.Event.Metadata) == "plain write"), Is.EqualTo(totalPlainWrites)); } }
public async Task GracefulShutdownWorksWithMultipleRequestsInFlight_InProcess() { // The goal of this test is to have multiple requests currently in progress // and for app offline to be dropped. We expect that all requests are eventually drained // and graceful shutdown occurs. var deploymentParameters = Fixture.GetBaseDeploymentParameters(Fixture.InProcessTestSite); deploymentParameters.TransformArguments((a, _) => $"{a} IncreaseShutdownLimit"); var deploymentResult = await DeployAsync(deploymentParameters); var result = await deploymentResult.HttpClient.GetAsync("/HelloWorld"); // Send two requests that will hang until data is sent from the client. var connectionList = new List <TestConnection>(); for (var i = 0; i < 2; i++) { var connection = new TestConnection(deploymentResult.HttpClient.BaseAddress.Port); await connection.Send( "POST /ReadAndCountRequestBody HTTP/1.1", "Content-Length: 1", "Host: localhost", "Connection: close", "", ""); await connection.Receive( "HTTP/1.1 200 OK", ""); await connection.ReceiveHeaders(); await connection.Receive("1", $"{i + 1}"); connectionList.Add(connection); } // Send a request that will end once app lifetime is triggered (ApplicationStopping cts). var statusConnection = new TestConnection(deploymentResult.HttpClient.BaseAddress.Port); await statusConnection.Send( "GET /WaitForAppToStartShuttingDown HTTP/1.1", "Host: localhost", "Connection: close", "", ""); await statusConnection.Receive("HTTP/1.1 200 OK", ""); await statusConnection.ReceiveHeaders(); // Receiving some data means we are currently waiting for IHostApplicationLifetime. await statusConnection.Receive("5", "test1", ""); AddAppOffline(deploymentResult.ContentRoot); // Receive the rest of all open connections. await statusConnection.Receive("5", "test2", ""); for (var i = 0; i < 2; i++) { await connectionList[i].Send("a", ""); await connectionList[i].Receive("", "4", "done"); connectionList[i].Dispose(); } deploymentResult.AssertWorkerProcessStop(); // Shutdown should be graceful here! EventLogHelpers.VerifyEventLogEvent(deploymentResult, EventLogHelpers.InProcessShutdown(), Logger); }
public virtual IEventStoreConnection SetupConnection(MiniNode node) { return(TestConnection.Create(node.TcpEndPoint, TcpType.Normal, _userCredentials)); }
public bool TestConnection(string testDatabase) { initialCatalog_ = testDatabase; ConnectionType cnType = integratedSecurity_ ? ConnectionType.SSPI : ConnectionType.SQL; TestConnection tst = new TestConnection(cnType, serverName_); bool res; try{ if (cnType == ConnectionType.SQL){ tst.Password = password_; tst.UserId = userName_; } tst.InitialCatalog = testDatabase; res = tst.Test(); } catch (Exception){ res = false; } return res; }
public void CreateCommand_WhenCalled_ReturnsInstanceOfACommand() { // ARRANGE string connectionString = Settings.Default.IntegrationTestConnection; var connection = new TestConnection(connectionString); // ACT var actualCommand = connection.CreateCommand(); // ASSERT Assert.IsNotNull(actualCommand); }
public void DataSource_WhenCalled_ReturnsDataSourceOfOriginalConnectionString() { // ARRANGE string connectionString = Settings.Default.IntegrationTestConnection; SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString); string expectedDataSource = builder.DataSource; var connection = new TestConnection(connectionString); // ACT var actualDataSource = connection.DataSource; // ASSERT Assert.AreEqual(expectedDataSource, actualDataSource); }
// the host enumeration block we're using to enumerate all servers private static IEnumerable <ShareInfo> _Find_DomainShare(string[] ComputerName, bool CheckShareAccess, IntPtr TokenHandle) { var LogonToken = IntPtr.Zero; if (TokenHandle != IntPtr.Zero) { // impersonate the the token produced by LogonUser()/Invoke-UserImpersonation LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation { TokenHandle = TokenHandle, Quiet = true }); } var DomainShares = new List <ShareInfo>(); foreach (var TargetComputer in ComputerName) { var Up = TestConnection.Ping(TargetComputer, 1); if (Up) { // get the shares for this host and check what we find var Shares = GetNetShare.Get_NetShare(new Args_Get_NetShare { ComputerName = new[] { TargetComputer } }); foreach (var Share in Shares) { var ShareName = Share.Name; // $Remark = $Share.Remark var Path = @"\\" + TargetComputer + @"\" + ShareName; if ((!string.IsNullOrEmpty(ShareName)) && (ShareName.Trim() != "")) { // see if we want to check access to this share if (CheckShareAccess) { // check if the user has access to this path try { Directory.GetFiles(Path); DomainShares.Add(Share); } catch (Exception e) { Logger.Write_Verbose($@"Error accessing share path {Path} : {e}"); } } else { DomainShares.Add(Share); } } } } } if (TokenHandle != IntPtr.Zero) { InvokeRevertToSelf.Invoke_RevertToSelf(LogonToken); } return(DomainShares); }