static async Task TestStreaming(HybridConnectionListener listener, RelayConnectionStringBuilder connectionString, TraceSource traceSource) { traceSource.TraceInformation("Testing Streaming (WebSocket) mode"); RunAcceptPump(listener); var client = new HybridConnectionClient(connectionString.ToString()); var requestBytes = Encoding.UTF8.GetBytes("<data>Request payload from sender</data>"); HybridConnectionStream stream = await client.CreateConnectionAsync(); string connectionName = $"S:HybridConnectionStream({stream.TrackingContext.TrackingId})"; RelayTraceSource.TraceInfo($"{connectionName} initiated"); RunConnectionPump(stream, connectionName); for (int i = 0; i < 2; i++) { await stream.WriteAsync(requestBytes, 0, requestBytes.Length); RelayTraceSource.TraceVerbose($"{connectionName} wrote {requestBytes.Length} bytes"); } using (var closeCts = new CancellationTokenSource(TimeSpan.FromSeconds(5))) { RelayTraceSource.TraceVerbose($"{connectionName} closing"); await stream.CloseAsync(closeCts.Token); RelayTraceSource.TraceInfo($"{connectionName} closed"); } await Task.Delay(TimeSpan.FromMilliseconds(100)); }
private static async Task RunAsync() { // Create a new hybrid connection client. var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key); var client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider); // Initiate the connection. var relayConnection = await client.CreateConnectionAsync(); Console.WriteLine("Enter lines of text to send to the server with ENTER"); var reader = new StreamReader(relayConnection); var writer = new StreamWriter(relayConnection) { AutoFlush = true }; while (true) { var messageToSend = Console.ReadLine(); if (string.IsNullOrEmpty(messageToSend)) { break; } await writer.WriteLineAsync(messageToSend); var textFromListener = await reader.ReadLineAsync(); Console.WriteLine(textFromListener); } await relayConnection.CloseAsync(CancellationToken.None); }
async Task NonExistantHCEntityTest() { HybridConnectionListener listener = null; try { TestUtility.Log("Setting ConnectionStringBuilder.EntityPath to a new GUID"); var fakeEndpointConnectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString) { EntityPath = Guid.NewGuid().ToString() }; var fakeEndpointConnectionString = fakeEndpointConnectionStringBuilder.ToString(); listener = new HybridConnectionListener(fakeEndpointConnectionString); var client = new HybridConnectionClient(fakeEndpointConnectionString); #if NET451 await Assert.ThrowsAsync <EndpointNotFoundException>(() => listener.OpenAsync()); await Assert.ThrowsAsync <EndpointNotFoundException>(() => client.CreateConnectionAsync()); #else await Assert.ThrowsAsync <RelayException>(() => listener.OpenAsync()); await Assert.ThrowsAsync <RelayException>(() => client.CreateConnectionAsync()); #endif } finally { await this.SafeCloseAsync(listener); } }
private void InitConnection(RelayConfig relayConfig) { Client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", relayConfig.RelayNamespace, relayConfig.ConnectionName)), TokenProvider); }
private async Task InitializeDataChannel() { var dataChannelFactory = new HybridConnectionClient(_relay, _tokenProvider); var stream = await dataChannelFactory.CreateConnectionAsync(); _log.Information("Relay: {relay}. New data channel is established", _relay); try { await _tunnelPreamble.WriteAsync(stream); EnsureDownlinkPump(stream); _canAcceptUntil = DateTime.UtcNow.Add(_ttl); } catch (AuthorizationFailedException e) { _log.Error(e, "Relay: {relay}. Authorization failed", _relay); CloseDataChannel(); throw; } catch (Exception e) { _log.Error(e, "Relay: {relay}. Unable to establish data channel", _relay); CloseDataChannel(); throw; } }
public void Start() { // Create a new hybrid connection client _tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(_conn.SharedAccessKeyName, _conn.SharedAccessKey); _client = new HybridConnectionClient(_conn.Endpoint, _tokenProvider); _runClient = true; RunAsync().GetAwaiter().GetResult(); }
public RelaySender(IOptions <RelayOptions> relayOptions, FeatureSerializerManager featureSerializerManager) : base(relayOptions) { var clientsPoolProvider = new DefaultObjectPoolProvider { MaximumRetained = relayOptions.Value.ClientsPoolSize }; var hybridConnectionClient = new HybridConnectionClient(relayOptions.Value.ConnectionString); _clientsPool = clientsPoolProvider.Create(new RelayClientPooledObjectPolicy(hybridConnectionClient, featureSerializerManager)); }
public RecieveResponseFromRequest(string relayConnectionString, string relayName) { //https://docs.microsoft.com/en-us/azure/service-bus-relay/relay-hybrid-connections-dotnet-api-overview connectionStringBuilder = new RelayConnectionStringBuilder(relayConnectionString) { EntityPath = relayName }; client = new HybridConnectionClient(connectionStringBuilder.ToString()); connectionTask = client.CreateConnectionAsync(); this.relayName = relayName; }
private static async Task RunAsync() { Console.WriteLine("Enter lines of text to send to the server with ENTER"); // Create a new hybrid connection client var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key); var client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider); // Initiate the connection var relayConnection = await client.CreateConnectionAsync(); var reads = Task.Run(async() => { var reader = new StreamReader(relayConnection); var writer = Console.Out; do { // Read a full line of UTF-8 text up to newline string line = await reader.ReadLineAsync(); // if the string is empty or null, we are done. if (String.IsNullOrEmpty(line)) { break; } // Write to the console await writer.WriteLineAsync(line); } while (true); }); // Read from the console and write to the hybrid connection var writes = Task.Run(async() => { var reader = Console.In; var writer = new StreamWriter(relayConnection) { AutoFlush = true }; do { // Read a line form the console string line = await reader.ReadLineAsync(); await writer.WriteLineAsync(line); if (String.IsNullOrEmpty(line)) { break; } } while (true); }); await Task.WhenAll(reads, writes); await relayConnection.CloseAsync(CancellationToken.None); }
void EnsureConnection() { lock (connectLock) { if (dataChannel == null) { multiplexedOutputStream = new ThrottledQueueBufferedStream(10); QueueBufferedStream multiplexedInputStream = new QueueBufferedStream(); dataChannelFactory = new HybridConnectionClient(endpointVia, tokenProvider); dataChannel = dataChannelFactory.CreateConnectionAsync().GetAwaiter().GetResult(); try { var preambleWriter = new BinaryWriter(dataChannel); preambleWriter.Write("np:" + toPipe); rawInputPump = new StreamBufferWritePump(dataChannel, multiplexedInputStream.Write); rawInputPump.BeginRunPump(RawInputPumpCompleted, false); inputPump = new MultiplexConnectionInputPump(multiplexedInputStream.Read, CorrelateConnection, null); inputPump.Run(false); outputPump = new StreamBufferWritePump(multiplexedOutputStream, WriteToDataChannel); outputPump.BeginRunPump(MultiplexPumpCompleted, null); } catch (AuthorizationFailedException af) { Trace.TraceError("Authorization failed: {0}", af.Message); if (dataChannel != null) { DataChannelClose(); dataChannel = null; } throw; } catch (Exception ex) { Trace.TraceError("Unable to establish data channel: {0}", ex.Message); if (dataChannel != null) { DataChannelClose(); dataChannel = null; } throw; } } } }
public void ManagedIdentityConnectionStringTest() { string connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;Authentication=Managed Identity"; TestUtility.Log("Testing connectionstring: " + connectionString); Type managedIdentityTokenProviderType = TokenProvider.CreateManagedIdentityTokenProvider().GetType(); var connectionStringBuilder = new RelayConnectionStringBuilder(connectionString); Assert.Equal(RelayConnectionStringBuilder.AuthenticationType.ManagedIdentity, connectionStringBuilder.Authentication); HybridConnectionListener listener = new HybridConnectionListener(connectionString); Assert.Equal(managedIdentityTokenProviderType, listener.TokenProvider.GetType()); HybridConnectionClient client = new HybridConnectionClient(connectionString); Assert.Equal(managedIdentityTokenProviderType, client.TokenProvider.GetType()); connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;Authentication=ManagedIdentity"; TestUtility.Log("Testing connectionstring: " + connectionString); connectionStringBuilder = new RelayConnectionStringBuilder(connectionString); Assert.Equal(RelayConnectionStringBuilder.AuthenticationType.ManagedIdentity, connectionStringBuilder.Authentication); listener = new HybridConnectionListener(connectionString); Assert.Equal(managedIdentityTokenProviderType, listener.TokenProvider.GetType()); client = new HybridConnectionClient(connectionString); Assert.Equal(managedIdentityTokenProviderType, client.TokenProvider.GetType()); connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;Authentication=Garbage"; TestUtility.Log("Testing connectionstring: " + connectionString); connectionStringBuilder = new RelayConnectionStringBuilder(connectionString); Assert.Equal(RelayConnectionStringBuilder.AuthenticationType.Other, connectionStringBuilder.Authentication); // We should not be allowing intergers to be parsed as a valid AuthenticationType value connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;Authentication=1"; TestUtility.Log("Testing connectionstring: " + connectionString); connectionStringBuilder = new RelayConnectionStringBuilder(connectionString); Assert.Equal(RelayConnectionStringBuilder.AuthenticationType.Other, connectionStringBuilder.Authentication); // Do not allow SharedAccessKeyName/SharedAccessKey to co-exist with AuthenticationType.ManagedIdentity connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SomeKeyString;Authentication=Managed Identity"; TestUtility.Log("Testing connectionstring: " + connectionString); connectionStringBuilder = new RelayConnectionStringBuilder(connectionString); Assert.Throws <ArgumentException>(() => connectionStringBuilder.ToString()); // Do not allow SharedAccessSignature to co-exist with AuthenticationType.ManagedIdentity connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;SharedAccessSignature=SomeKeySignature;Authentication=Managed Identity"; TestUtility.Log("Testing connectionstring: " + connectionString); connectionStringBuilder = new RelayConnectionStringBuilder(connectionString); Assert.Throws <ArgumentException>(() => connectionStringBuilder.ToString()); }
private static async Task RunAsync() { Console.WriteLine("Enter lines of text to send to the server with ENTER"); var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key); var client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider); var relayConnection = await client.CreateConnectionAsync(); var reads = Task.Run(async() => { var reader = new StreamReader(relayConnection); var writer = Console.Out; do { string line = await reader.ReadLineAsync(); if (String.IsNullOrEmpty(line)) { break; } await writer.WriteLineAsync(line); }while (true); }); var writes = Task.Run(async() => { var reader = Console.In; var writer = new StreamWriter(relayConnection) { AutoFlush = true }; do { string line = await reader.ReadLineAsync(); await writer.WriteLineAsync(line); if (String.IsNullOrEmpty(line)) { break; } }while (true); }); await Task.WhenAll(reads, writes); await relayConnection.CloseAsync(CancellationToken.None); }
async Task ClientNonExistantHybridConnectionTest() { TestUtility.Log("Setting ConnectionStringBuilder.EntityPath to a new GUID"); var fakeEndpointConnectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString) { EntityPath = Guid.NewGuid().ToString() }; var client = new HybridConnectionClient(fakeEndpointConnectionStringBuilder.ToString()); // Endpoint does not exist. TrackingId:GUID_G52, SystemTracker:sb://contoso.servicebus.windows.net/GUID, Timestamp:5/7/2018 5:51:25 PM var exception = await Assert.ThrowsAsync <EndpointNotFoundException>(() => client.CreateConnectionAsync()); Assert.Contains("Endpoint does not exist", exception.Message); Assert.Contains(fakeEndpointConnectionStringBuilder.EntityPath, exception.Message); }
async Task NonExistantNamespaceTest(EndpointTestType endpointTestType) { string badAddress = $"sb://fakeendpoint.{Guid.NewGuid()}.com"; HybridConnectionListener listener = null; try { TestUtility.Log($"Setting ConnectionStringBuilder.Endpoint to '{badAddress}'"); var fakeEndpointConnectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString) { Endpoint = new Uri(badAddress) }; if (endpointTestType == EndpointTestType.Authenticated) { fakeEndpointConnectionStringBuilder.EntityPath = Constants.AuthenticatedEntityPath; } else { fakeEndpointConnectionStringBuilder.EntityPath = Constants.UnauthenticatedEntityPath; } var fakeEndpointConnectionString = fakeEndpointConnectionStringBuilder.ToString(); listener = new HybridConnectionListener(fakeEndpointConnectionString); var client = new HybridConnectionClient(fakeEndpointConnectionString); TestUtility.Log($"Opening Listener"); var relayException = await Assert.ThrowsAsync <RelayException>(() => listener.OpenAsync()); TestUtility.Log($"Received Exception {relayException.ToStringWithoutCallstack()}"); Assert.True(relayException.IsTransient, "Listener.Open() should return a transient Exception"); TestUtility.Log($"Opening Client"); relayException = await Assert.ThrowsAsync <RelayException>(() => client.CreateConnectionAsync()); TestUtility.Log($"Received Exception {relayException.ToStringWithoutCallstack()}"); Assert.True(relayException.IsTransient, "Client.Open() should return a transient Exception"); } finally { await this.SafeCloseAsync(listener); } }
public ClientTcpHybridConnectionMultiplexer( string relayNamespace, string connectionName, string keyName, string key, ILogger logger) { _relayNamespace = relayNamespace; _connectionName = connectionName; _keyName = keyName; _key = key; _logger = logger; var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(_keyName, _key); _hybridConnectionClient = new HybridConnectionClient( new Uri(String.Format("sb://{0}/{1}", _relayNamespace, _connectionName)), tokenProvider); }
async Task NonExistantNamespaceTest(EndpointTestType endpointTestType) { HybridConnectionListener listener = null; try { TestUtility.Log("Setting ConnectionStringBuilder.Endpoint to 'sb://fakeendpoint.com'"); var fakeEndpointConnectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString) { Endpoint = new Uri("sb://fakeendpoint.com") }; if (endpointTestType == EndpointTestType.Authenticated) { fakeEndpointConnectionStringBuilder.EntityPath = Constants.AuthenticatedEntityPath; } else { fakeEndpointConnectionStringBuilder.EntityPath = Constants.UnauthenticatedEntityPath; } var fakeEndpointConnectionString = fakeEndpointConnectionStringBuilder.ToString(); listener = new HybridConnectionListener(fakeEndpointConnectionString); var client = new HybridConnectionClient(fakeEndpointConnectionString); // TODO: Remove this once .NET Core supports inspecting the StatusCode/Description. https://github.com/dotnet/corefx/issues/13773 #if NET451 await Assert.ThrowsAsync <EndpointNotFoundException>(() => listener.OpenAsync()); await Assert.ThrowsAsync <EndpointNotFoundException>(() => client.CreateConnectionAsync()); #else await Assert.ThrowsAsync <RelayException>(() => listener.OpenAsync()); await Assert.ThrowsAsync <RelayException>(() => client.CreateConnectionAsync()); #endif } finally { await this.SafeCloseAsync(listener); } }
public async Task ExecuteAsync(IServiceProvider serviceProvider) { IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = factory.CreateOrganizationService(context.UserId); Entity entity = (Entity)context.InputParameters["Target"]; GisObject gisObject = new GisObject { Latitude = (double)entity["Latitude"], Longitude = (double)entity["Longitude"] }; // Create a new hybrid connection client var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key); var client = new HybridConnectionClient(new Uri($"sb://{relayNamespace}/{connectionName}"), tokenProvider); // Initiate the connection var relayConnection = await client.CreateConnectionAsync(); // Bi-directional sync of GIS data: // 1. Send a GIS object to the relay // 2. Receive a GIS object with the resolved address and update the entity // 3. Close the relay connection await new Task( () => SendToRelay(relayConnection, gisObject) .ContinueWith(async(t) => { GisObject resolved = await ReadFromRelay(relayConnection); ShowAddress(resolved); }) .ContinueWith(async(t) => await relayConnection.CloseAsync(CancellationToken.None)) .Start()); void ShowAddress(GisObject resolved) { var addr = resolved.Address; entity["Address"] = $"{addr.Line}, {addr.ZipCode} {addr.City}, {addr.Country}"; service.Update(entity); } }
static void Main(string[] args) { HybridConnectionClient client = new HybridConnectionClient("Endpoint=sb://relayzs.servicebus.windows.net/;SharedAccessKeyName=sas;SharedAccessKey=WBhKG1Fb51sYz4I1Nsv/mZsLhnru+O08YQxeq+SyRfo=;EntityPath=hybirdconn1"); Task <HybridConnectionStream> task = client.CreateConnectionAsync(); while (!task.IsCompleted) { } HybridConnectionStream stream = task.Result; StreamWriter writer = new StreamWriter(stream); StreamReader reader = new StreamReader(stream); writer.WriteLine("Hello Server!"); writer.Flush(); String line = reader.ReadLine(); Console.WriteLine(line); reader.Close(); writer.Close(); }
public async Task ExecuteAsync(ParcelTrackingEntity parcel) { GisObject gisObject = new GisObject { Latitude = parcel.Latitude, Longitude = parcel.Longitude }; // Create a new hybrid connection client var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key); var client = new HybridConnectionClient(new Uri($"sb://{relayNamespace}/{connectionName}"), tokenProvider); // Initiate the connection var relayConnection = await client.CreateConnectionAsync(); // Bi-directional sync of GIS data: // 1. Send a GIS object to the relay // 2. Receive a GIS object with the resolved address and update the entity // 3. Close the relay connection await new Task( () => SendToRelay(relayConnection, gisObject) .ContinueWith(async(t) => { GisObject resolved = await ReadFromRelay(relayConnection); ShowAddress(resolved); }) .ContinueWith(async(t) => await relayConnection.CloseAsync(CancellationToken.None)) .Start()); void ShowAddress(GisObject resolved) { var addr = resolved.Address; parcel.Address = $"{addr.Line}, {addr.ZipCode} {addr.City}, {addr.Country}"; Update(parcel); // Update the tracking information in the system } }
async Task NonExistantNamespaceTest(EndpointTestType endpointTestType) { HybridConnectionListener listener = null; try { TestUtility.Log("Setting ConnectionStringBuilder.Endpoint to 'sb://fakeendpoint.com'"); var fakeEndpointConnectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString) { Endpoint = new Uri("sb://fakeendpoint.com") }; if (endpointTestType == EndpointTestType.Authenticated) { fakeEndpointConnectionStringBuilder.EntityPath = Constants.AuthenticatedEntityPath; } else { fakeEndpointConnectionStringBuilder.EntityPath = Constants.UnauthenticatedEntityPath; } var fakeEndpointConnectionString = fakeEndpointConnectionStringBuilder.ToString(); listener = new HybridConnectionListener(fakeEndpointConnectionString); var client = new HybridConnectionClient(fakeEndpointConnectionString); await Assert.ThrowsAsync <EndpointNotFoundException>(() => listener.OpenAsync()); await Assert.ThrowsAsync <EndpointNotFoundException>(() => client.CreateConnectionAsync()); } finally { await this.SafeCloseAsync(listener); } }
async Task ClientAuthenticationFailureTest() { var badAuthConnectionString = new RelayConnectionStringBuilder(this.ConnectionString) { EntityPath = Constants.AuthenticatedEntityPath }; if (!string.IsNullOrEmpty(badAuthConnectionString.SharedAccessKeyName)) { badAuthConnectionString.SharedAccessKey += "BAD"; } else if (!string.IsNullOrEmpty(badAuthConnectionString.SharedAccessSignature)) { badAuthConnectionString.SharedAccessSignature += "BAD"; } var client = new HybridConnectionClient(badAuthConnectionString.ToString()); // The token has an invalid signature. TrackingId:[Guid]_G63, SystemTracker:sb://contoso.servicebus.windows.net/authenticated, Timestamp:5/7/2018 5:20:05 PM var exception = await Assert.ThrowsAsync <AuthorizationFailedException>(() => client.CreateConnectionAsync()); Assert.Contains("token", exception.Message); Assert.Contains(badAuthConnectionString.EntityPath, exception.Message, StringComparison.OrdinalIgnoreCase); }
Task <HybridConnectionStream> ConnectClientSocketAsync(Uri address) { var client = new HybridConnectionClient(address, tokenProvider); return(client.CreateConnectionAsync()); }
static async Task RunAsync(string[] args) { if (args.Length < 4) { Console.WriteLine("client [ns] [hc] [keyname] [key]"); return; } Console.WriteLine("Enter lines of text to send to the server with ENTER"); var ns = args[0]; var hc = args[1]; var keyname = args[2]; var key = args[3]; // Create a new hybrid connection client var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyname, key); var client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", ns, hc)), tokenProvider); // Initiate the connection var relayConnection = await client.CreateConnectionAsync(); // We run two conucrrent loops on the connection. One // reads input from the console and writes it to the connection // with a stream writer. The other reads lines of input from the // connection with a stream reader and writes them to the console. // Entering a blank line will shut down the write task after // sending it to the server. The server will then cleanly shut down // the connection will will terminate the read task. var reads = Task.Run(async() => { // initialize the stream reader over the connection var reader = new StreamReader(relayConnection); var writer = Console.Out; do { // read a full line of UTF-8 text up to newline string line = await reader.ReadLineAsync(); // if the string is empty or null, we are done. if (String.IsNullOrEmpty(line)) { break; } // write to the console await writer.WriteLineAsync(line); }while (true); }); // read from the console and write to the hybrid connection var writes = Task.Run(async() => { var reader = Console.In; var writer = new StreamWriter(relayConnection) { AutoFlush = true }; do { // read a line form the console string line = await reader.ReadLineAsync(); // write the line out, also when it's empty await writer.WriteLineAsync(line); // quit when the line was empty if (String.IsNullOrEmpty(line)) { break; } }while (true); }); // wait for both tasks to complete await Task.WhenAll(reads, writes); await relayConnection.CloseAsync(CancellationToken.None); }
static void Main(string[] args) { if (args.Length < 4) { Console.WriteLine("server [ns] [hc] [keyname] [key]"); return; } var ns = args[0]; var hc = args[1]; var keyname = args[2]; var key = args[3]; var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyname, key); var sendAddress = new Uri($"sb://{ns}/{hc}"); var relayClient = new HybridConnectionClient(sendAddress, tokenProvider); try { var relayConnection = relayClient.CreateConnectionAsync().GetAwaiter().GetResult(); TTransport transport = new TStreamTransport(relayConnection, relayConnection); TProtocol protocol = new TBinaryProtocol(transport); Calculator.Client client = new Calculator.Client(protocol); transport.Open(); try { client.ping(); Console.WriteLine("ping()"); int sum = client.add(1, 1); Console.WriteLine("1+1={0}", sum); Work work = new Work(); work.Op = Operation.DIVIDE; work.Num1 = 1; work.Num2 = 0; try { int quotient = client.calculate(1, work); Console.WriteLine("Whoa we can divide by 0"); } catch (InvalidOperation io) { Console.WriteLine("Invalid operation: " + io.Why); } work.Op = Operation.SUBTRACT; work.Num1 = 15; work.Num2 = 10; try { int diff = client.calculate(1, work); Console.WriteLine("15-10={0}", diff); } catch (InvalidOperation io) { Console.WriteLine("Invalid operation: " + io.Why); } SharedStruct log = client.getStruct(1); Console.WriteLine("Check log: {0}", log.Value); } finally { transport.Close(); } } catch (TApplicationException x) { Console.WriteLine(x.StackTrace); } }
RelayClintObservableInitializeAsync( string relayNamespace, string connectionName, string keyName, string key) { if (_isInitialized) { throw new RelayClientException("Relay client can only be initialized once. Create a new instance, if multiple clients are needed."); } _isInitialized = true; var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key); var client = new HybridConnectionClient(new Uri($"sb://{relayNamespace}/{connectionName}"), tokenProvider); // Initiate the connection. _relayConnection = await client.CreateConnectionAsync(); _writer = new StreamWriter(_relayConnection) { AutoFlush = true }; var reader = new StreamReader(_relayConnection); var readerObservable = Observable.FromAsync(reader.ReadLineAsync); var observableMessages = Observable.Create <string>(obs => { var disposableReader = Observable.While( () => true, readerObservable) .Subscribe(stringLine => { Debug.WriteLine(stringLine); // If there's no input data, signal that // you will no longer send data on this connection. // Then, break out of the processing loop. if (string.IsNullOrEmpty(stringLine)) { obs.OnCompleted(); } obs.OnNext(stringLine); }, ex => { Debug.WriteLine(ex.ToString()); if (ex is IOException) { // Catch an I/O exception. This likely occurred when // the client disconnected. } else { obs.OnError(ex); } }, obs.OnCompleted); return(new CompositeDisposable( disposableReader, Disposable.Create(() => { reader?.Dispose(); _writer?.Dispose(); _relayConnection?.Dispose(); }))); }).Publish().RefCount(); return(observableMessages); }
public SocketLocalForwardBridge(Config config, RelayConnectionStringBuilder connectionString, string portName) { PortName = portName; this.config = config; this.hybridConnectionClient = new HybridConnectionClient(connectionString.ToString()); }
private static async Task RunAsync() { Console.WriteLine("Enter lines of text to send to the server with ENTER"); // Create a new hybrid connection client var client = new HybridConnectionClient(ConnectionString); // Initiate the connection var relayConnection = await client.CreateConnectionAsync(); // We run two conucrrent loops on the connection. One // reads input from the console and writes it to the connection // with a stream writer. The other reads lines of input from the // connection with a stream reader and writes them to the console. // Entering a blank line will shut down the write task after // sending it to the server. The server will then cleanly shut down // the connection which will terminate the read task. var reads = Task.Run(async() => { // Initialize the stream reader over the connection var reader = new StreamReader(relayConnection); var writer = Console.Out; do { // Read a full line of UTF-8 text up to newline string line = await reader.ReadLineAsync(); // If the string is empty or null, we are done. if (String.IsNullOrEmpty(line)) { break; } // Write to the console await writer.WriteLineAsync(line); }while (true); }); // Read from the console and write to the hybrid connection var writes = Task.Run(async() => { var reader = Console.In; var writer = new StreamWriter(relayConnection) { AutoFlush = true }; do { // Read a line form the console string line = await reader.ReadLineAsync(); // Write the line out, also when it's empty await writer.WriteLineAsync(line); // Quit when the line was empty if (String.IsNullOrEmpty(line)) { break; } }while (true); }); // Wait for both tasks to complete await Task.WhenAll(reads, writes); await relayConnection.CloseAsync(CancellationToken.None); }
private static async Task RunAsync() { Console.BackgroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine("Client ready"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Enter lines of text to send to the server with ENTER"); // Create a new hybrid connection client var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, myKey); var client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider); // Initiate the connection var relayConnection = await client.CreateConnectionAsync(); try { // We run two conucrrent loops on the connection. One // reads input from the console and writes it to the connection // with a stream writer. The other reads lines of input from the // connection with a stream reader and writes them to the console. // Entering a blank line will shut down the write task after // sending it to the server. The server will then cleanly shut down // the connection which will terminate the read task. var reads = Task.Run(async() => { // Initialize the stream reader over the connection var reader = new StreamReader(relayConnection); var writer = Console.Out; do { // Read a full line of UTF-8 text up to newline string line = await reader.ReadLineAsync(); // if the string is empty or null, we are done. if (String.IsNullOrEmpty(line)) { break; } // Write to the console Console.ForegroundColor = ConsoleColor.Yellow; await writer.WriteLineAsync(line); Console.ForegroundColor = ConsoleColor.White; }while (true); }); // Read from the console and write to the hybrid connection var writes = Task.Run(async() => { var reader = Console.In; var writer = new StreamWriter(relayConnection) { AutoFlush = true }; do { // Read a line form the console string line = await reader.ReadLineAsync(); // Write the line out, also when it's empty await writer.WriteLineAsync(line); // Quit when the line was empty if (String.IsNullOrEmpty(line)) { break; } }while (true); }); // Wait for both tasks to complete await Task.WhenAll(reads, writes); await relayConnection.CloseAsync(CancellationToken.None); } catch (Exception ex) { Console.WriteLine("\n\nAn error occurred trying to reach the server:\n" + ex.InnerException); Console.WriteLine("Hit ENTER to exit"); Console.ReadLine(); } }
public TcpLocalForwardBridge(RelayConnectionStringBuilder connectionString) { this.hybridConnectionClient = new HybridConnectionClient(connectionString.ToString()); }
public RelayClient(HybridConnectionClient client, FeatureSerializerManager featureSerializerManager) { _client = client; _featureSerializerManager = featureSerializerManager; GoodStatus = true; }