public async Task <string[]> GenerateSeed(string aezeedPassphrase = default(string)) { var genSeedResponse = new GenSeedResponse(); try { walletRpcChannel = new Grpc.Core.Channel(HostName, new SslCredentials(Cert)); walletUnlocker = new WalletUnlocker.WalletUnlockerClient(walletRpcChannel); await walletRpcChannel.ConnectAsync(); var genSeedRequest = new GenSeedRequest(); if (!string.IsNullOrEmpty(aezeedPassphrase)) { genSeedRequest.AezeedPassphrase = ByteString.CopyFromUtf8(aezeedPassphrase); } genSeedResponse = await walletUnlocker.GenSeedAsync(genSeedRequest); walletRpcChannel.ShutdownAsync().Wait(); } catch (RpcException e) { walletRpcChannel.ShutdownAsync().Wait(); return(new string[] { e.Status.Detail }); } return(genSeedResponse.CipherSeedMnemonic.ToArray());; }
private const string ProjectName = "apiarydotnetclienttesting"; // this is actually gRPC, but I had that project handy #endregion Fields #region Methods static void Main(string[] args) { // Prerequisites // 1. create a new cloud project with your google account // 2. enable cloud datastore API on that project // 3. 'gcloud auth login' to store your google credential in a well known location (from where GoogleCredential.GetApplicationDefaultAsync() can pick it up). var credentials = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result; Channel channel = new Channel("datastore.googleapis.com", credentials.ToChannelCredentials()); var datastoreClient = new Google.Datastore.V1Beta3.Datastore.DatastoreClient(channel); var result = datastoreClient.RunQuery(new RunQueryRequest { ProjectId = ProjectName, GqlQuery = new GqlQuery { QueryString = "SELECT * FROM Foo" } }); Console.WriteLine(result); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); channel.ShutdownAsync(); }
private async static void TestStream(string server) { while (true) { var channel = new Grpc.Core.Channel(server, ChannelCredentials.Insecure); var client = new RouteGuideClient(channel); using (var call = client.ListFeatures(new Rectangle())) { try { while (await call.ResponseStream.MoveNext()) { Feature feature = call.ResponseStream.Current; Console.WriteLine($"Received {feature}"); } break; } catch (Exception ex) { Console.WriteLine($"{ex.Message}"); System.Threading.Thread.Sleep(1000); ; // loop } } channel.ShutdownAsync().Wait(); } Console.WriteLine("Finished TestStream"); }
public static async Task<WalletClient> ConnectAsync(string networkAddress, string rootCertificate) { if (networkAddress == null) throw new ArgumentNullException(nameof(networkAddress)); if (rootCertificate == null) throw new ArgumentNullException(nameof(rootCertificate)); var channel = new Channel(networkAddress, new SslCredentials(rootCertificate)); var deadline = DateTime.UtcNow.AddSeconds(3); try { await channel.ConnectAsync(deadline); } catch (TaskCanceledException) { await channel.ShutdownAsync(); throw new ConnectTimeoutException(); } // Ensure the server is running a compatible version. var versionClient = new VersionService.VersionServiceClient(channel); var response = await versionClient.VersionAsync(new VersionRequest(), deadline: deadline); var serverVersion = new SemanticVersion(response.Major, response.Minor, response.Patch); SemanticVersion.AssertCompatible(RequiredRpcServerVersion, serverVersion); return new WalletClient(channel); }
// OnDisable shuts down the gRPC channel private void OnDisable() { if (_grpc_channel != null) { _grpc_channel.ShutdownAsync().Wait(); } }
public static void Main(string[] args) { // This code doesn't do much but makes sure the native extension is loaded // which is what we are testing here. Channel c = new Channel("127.0.0.1:1000", ChannelCredentials.Insecure); c.ShutdownAsync().Wait(); Console.WriteLine("Success!"); }
public async UniTask DisposeAsync() { await _client.DisposeAsync(); await _channel.ShutdownAsync(); _channel = null; }
static void Main(string[] args) { var channel = new Channel("127.0.0.1:9007", ChannelCredentials.Insecure); var client = new gRPC.gRPCClient(channel); var replay = client.SayHello(new HelloRequest { Name = "shoy" }); Console.WriteLine(replay.Message); channel.ShutdownAsync().Wait(); Console.ReadKey(); }
static async Task RunAsync(string endpoint, string prefix, ChannelOption[] options) { var channel = new Grpc.Core.Channel(endpoint, ChannelCredentials.Insecure, options); var client = new Greeter.GreeterClient(channel); var user = "******"; var reply = client.SayHello(new HelloRequest { Name = user }); Console.WriteLine("Greeting: " + reply.Message); // duplex var requestHeaders = new Metadata { { "x-host-port", "10-0-0-10" }, }; using var streaming = client.StreamingBothWays(requestHeaders); var readTask = Task.Run(async() => { while (await streaming.ResponseStream.MoveNext()) { var response = streaming.ResponseStream.Current; Console.WriteLine($"{prefix} {response.Message}"); } }); var i = 0; while (i++ < 100) { try { await streaming.RequestStream.WriteAsync(new HelloRequest { Name = $"{prefix} {i}", }); } catch (Exception ex) { Console.WriteLine($"{prefix} error {channel.State} {ex.Message} {ex.StackTrace}"); } await Task.Delay(TimeSpan.FromSeconds(1)); } await streaming.RequestStream.CompleteAsync(); await readTask; channel.ShutdownAsync().Wait(); }
public async Task <string> UnlockWallet(string walletPassword, string[] mnemonic) { walletRpcChannel = new Grpc.Core.Channel(HostName, new SslCredentials(Cert)); walletUnlocker = new WalletUnlocker.WalletUnlockerClient(walletRpcChannel); await walletRpcChannel.ConnectAsync(); var initWalletRequest = new InitWalletRequest(); initWalletRequest.WalletPassword = ByteString.CopyFromUtf8(walletPassword); initWalletRequest.CipherSeedMnemonic.AddRange(mnemonic); try { var initWalletResponse = await walletUnlocker.InitWalletAsync(initWalletRequest); walletRpcChannel.ShutdownAsync().Wait(); return("unlocked"); } catch (RpcException e) { if (e.Status.Detail == "wallet already exists") { var unlockWalletRequest = new UnlockWalletRequest() { WalletPassword = ByteString.CopyFromUtf8(walletPassword) }; var unlockWalletResponse = await walletUnlocker.UnlockWalletAsync(unlockWalletRequest); walletRpcChannel.ShutdownAsync().Wait(); return("unlocked"); } Debug.Log(e); } walletRpcChannel.ShutdownAsync().Wait(); return("not unlocked"); }
public static void Main(string[] args) { Channel channel = new Channel("127.0.0.1:50051", Credentials.Insecure); var client = Greeter.NewClient(channel); String user = "******"; var reply = client.SayHello(new HelloRequest { Name = user }); Console.WriteLine("Greeting: " + reply.Message); channel.ShutdownAsync().Wait(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
public static async Task MainAsync() { var channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure); var client = new Greeter.GreeterClient(channel); var user = Environment.UserName; var reply = client.SayHello(new HelloRequest { Name = user }); Console.WriteLine("Greeting: {0}", reply.Message); await channel.ShutdownAsync().ConfigureAwait(false); Console.ReadLine(); }
public void Shutdown() { if (_invoiceStream != null) { _invoiceStream.Dispose(); } if (_graphStream != null) { _graphStream.Dispose(); } if (_transactionStream != null) { _transactionStream.Dispose(); } rpcChannel.ShutdownAsync().Wait(); }
public static void Main(string[] args) { var channel = new Channel("127.0.0.1", 23456, ChannelCredentials.Insecure); Math.IMathClient client = new Math.MathClient(channel); MathExamples.DivExample(client); MathExamples.DivAsyncExample(client).Wait(); MathExamples.FibExample(client).Wait(); MathExamples.SumExample(client).Wait(); MathExamples.DivManyExample(client).Wait(); MathExamples.DependendRequestsExample(client).Wait(); channel.ShutdownAsync().Wait(); }
static async System.Threading.Tasks.Task Main(string[] args) { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); var httpClientHandler = new HttpClientHandler(); // Return `true` to allow certificates that are untrusted/invalid httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; var httpClient = new HttpClient(httpClientHandler); IConfiguration config = new ConfigurationBuilder() .Add(new JsonConfigurationSource { Path = "config/servers.json", ReloadOnChange = true }) .Build(); // var url=GrpcServiceManager.GetGrpcServicesHosts("Horizon.Sample.GrpcServices", "", config); // url = "http://" + url; // var channel = GrpcChannel.ForAddress(url, new GrpcChannelOptions { HttpClient = httpClient }); var channel = new Channel("127.0.0.1:5021", ChannelCredentials.Insecure); var clinet = new Greeter.GreeterClient(channel); var reply = await clinet.SayHelloAsync(new HelloRequest { Name = "Toomy" }); Console.WriteLine("Hello World!" + reply.Message); await channel.ShutdownAsync(); Console.ReadKey(); }
static void Main(string[] args) { var rpcChannel = new Channel("localhost:1337", ChannelCredentials.Insecure); var rpcClient = new GameAdminServiceClient(GameAdminService.NewClient(rpcChannel)); rpcChannel.ConnectAsync().Wait(); Log($"GameAdminServiceClient connected to {rpcChannel.ResolvedTarget}, channel state = {rpcChannel.State}"); rpcClient.GetAccountAsync(1234).Wait(); rpcClient.GetChatHistoryAsync(Enumerable.Range(1, 2), CancellationToken.None).Wait(); rpcClient.ListenChatAsync(1234).Wait(); rpcClient.ChatAsync().Wait(); Log($"GameAdminServiceClient disconnecting from {rpcChannel.ResolvedTarget}, channel state = {rpcChannel.State}", true); rpcChannel.ShutdownAsync().Wait(); Console.WriteLine("Press any key to stop the client..."); Console.ReadKey(); }
static async Task Main(string[] args) { Grpc.Core.Channel channel = new Grpc.Core.Channel(connection, Grpc.Core.ChannelCredentials.Insecure); await channel.ConnectAsync().ContinueWith((task) => { if (task.Status == System.Threading.Tasks.TaskStatus.RanToCompletion) { Console.WriteLine("The client connected to server: " + connection); } else { Console.WriteLine(task.Status.ToString()); } }); var client = new Greeting.GreetingService.GreetingServiceClient(channel); //new DummyService.DummyServiceClient(channel); //var greetingObject = new Greeting.Greeting() { FirstName = "Ahmed", LastName = "Tawfik" }; //var responseTask = client.GreetAsync(new Greeting.GreetingRequest() { Greeting = greetingObject}).ResponseAsync; //Console.WriteLine(responseTask.Result.Result); var greetingObject = new Greeting.Greeting() { FirstName = "Ahmed", LastName = "Tawfik" }; var responseStream = client.GreetManyTimes(new Greeting.GreetManyTimesRequest() { Greeting = greetingObject }); while (await responseStream.ResponseStream.MoveNext()) { Console.WriteLine(responseStream.ResponseStream.Current.Result); await Task.Delay(2000); } channel.ShutdownAsync().Wait(); Console.ReadKey(); }
public static async Task<WalletClient> ConnectAsync(string networkAddress) { if (networkAddress == null) throw new ArgumentNullException(nameof(networkAddress)); var rootCertificate = await TransportSecurity.ReadCertificate(); var channel = new Channel(networkAddress, new SslCredentials(rootCertificate)); var deadline = DateTime.UtcNow.AddSeconds(1); try { await channel.ConnectAsync(deadline); } catch (TaskCanceledException) { await channel.ShutdownAsync(); throw new ConnectTimeoutException(); } return new WalletClient(channel); }
private static void TestNormal(string server) { var channel = new Grpc.Core.Channel(server, ChannelCredentials.Insecure); var client = new RouteGuideClient(channel); // Looking for a valid feature var pt = new Routeguide.Point(); Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < 20; i++) { var f = client.GetFeature(pt); //Console.WriteLine($" {f} {sw.ElapsedMilliseconds}"); } sw.Stop(); Console.WriteLine($".NET Elapsed {sw.ElapsedMilliseconds}"); Console.WriteLine("Press any key to exit..."); channel.ShutdownAsync().Wait(); }
static void Main(string[] args) { var channel = new Channel("localhost", 1337, new SslCredentials(File.ReadAllText("certificates\\ca.crt"))); var client = new ServiceClient(PlaygroundService.NewClient(channel)); var listenTask = client.ListenForNewPeopleAsync(); client.CreatePersonAsync(new List<Person> { new Person { Id = 1, Name = "John Doe" }, new Person { Id = 2, Name = "Lisa Simpson" }, new Person { Id = 3, Name = "Michael Jackson" }, new Person { Id = 4, Name = "Mike Bully" }, new Person { Id = 5, Name = "Mark Commet" }, new Person { Id = 6, Name = "Alfred Punstar" }, }).Wait(); var person = client.GetPersonByIdAsync(5).Result; var personList = client.GetPersonListAsync().Result; channel.ShutdownAsync().Wait(); }
/// <summary> /// dispose本体 /// </summary> /// <returns></returns> private async UniTask onDisposing() { cancellationTokenSource.Cancel(); if (ServerImpl != null) { Debug.Log("ServerImpl DisposeAsync Start"); await ServerImpl.DisposeAsync(); Debug.Log("ServerImpl DisposeAsync Complete"); ServerImpl = default; } if (channel != null) { Debug.Log("channel Shutdown Async Start"); await channel.ShutdownAsync(); Debug.Log("channel Shutdown Async Complete"); channel = null; } ClientImpl = default; }
private static void updateStatus() { string addr = String.Format("{0}:50051", ipAddr); Channel channel = new Channel(addr, ChannelCredentials.Insecure); McServer.McServerClient client = new McServer.McServerClient(channel); Empty statusReq = new Empty(); BrewStatusReply rep = client.GetStatus(statusReq); channel.ShutdownAsync().Wait(); status.RemainingMashStepList.Clear(); foreach (MashProfileStep statusMp in rep.RemainingMashSteps) { var mps = new GFCalc.Domain.MashProfileStep(); mps.Temperature = statusMp.Temperature; mps.StepTime = statusMp.StepTime; status.RemainingMashStepList.Add(mps); } var ol = status.RemainingMashStepList.OrderBy(x => x.Temperature).ToList(); status.RemainingMashStepList.Clear(); foreach (GFCalc.Domain.MashProfileStep ms in ol) { status.RemainingMashStepList.Add(ms); } status.Temperature = (int)(Math.Round(rep.MashTemperature)); status.RemainingBoilTime = rep.RemainingBoilTime; status.State = rep.CurrentBrewStep; status.Progress = rep.Progress; }
public async Task AfterAll() { await _channel.ShutdownAsync(); await _server.ShutdownAsync(); }
public void Shutdown_AllowedOnlyOnce() { var channel = new Channel("localhost", ChannelCredentials.Insecure); channel.ShutdownAsync().Wait(); Assert.Throws(typeof(InvalidOperationException), () => channel.ShutdownAsync().GetAwaiter().GetResult()); }
public void ResolvedTarget() { var channel = new Channel("127.0.0.1", ChannelCredentials.Insecure); Assert.IsTrue(channel.ResolvedTarget.Contains("127.0.0.1")); channel.ShutdownAsync().Wait(); }
public void WaitForStateChangedAsync_InvalidArgument() { var channel = new Channel("localhost", ChannelCredentials.Insecure); Assert.Throws(typeof(ArgumentException), () => channel.WaitForStateChangedAsync(ChannelState.FatalFailure)); channel.ShutdownAsync().Wait(); }
public void State_IdleAfterCreation() { var channel = new Channel("localhost", ChannelCredentials.Insecure); Assert.AreEqual(ChannelState.Idle, channel.State); channel.ShutdownAsync().Wait(); }
public void ProcessException(Exception e, CancellationToken token = default(CancellationToken)) { logger.Debug("{ToString()} Processing Exception " + e.Message + " Cancelation afterwards"); dtask.Cancel(); Exception fnal = null; if (e is TimeoutException) { string msg = $"Channel {channelName} connect time exceeded for peer eventing service {name}, timed out at {peerEventRegistrationWaitTimeMilliSecs} ms."; TransactionException ex = new TransactionException(msg, e); logger.ErrorException($"{ToString()}{msg}", e); fnal = ex; } else if (e is RpcException sre) { logger.Error($"{ToString()} grpc status Code:{sre.StatusCode}, Description {sre.Status.Detail} {sre.Message}"); } else if (e is OperationCanceledException) { logger.Error($"{ToString()} Peer Eventing service {name} canceled on channel {channelName}"); } else if (e is TransactionException tra) { fnal = tra; } if (fnal == null) { fnal = new TransactionException($"{ToString()} Channel {channelName}, send eventing service failed on orderer {name}. Reason: {e.Message}", e); } Channel lmanagedChannel = managedChannel; if (lmanagedChannel != null) { try { lmanagedChannel.ShutdownAsync().GetAwaiter().GetResult(); managedChannel = null; } catch (Exception) { logger.WarnException($"{ToString()} Received error on peer eventing service on channel {channelName}, peer {name}, url {url}, attempts {(peer?.ReconnectCount ?? -1).ToString()}. {e.Message} shut down of grpc channel.", e); } } if (!shutdown) { if (peer != null) { long reconnectCount = peer.ReconnectCount; if (PEER_EVENT_RECONNECTION_WARNING_RATE > 1 && reconnectCount % PEER_EVENT_RECONNECTION_WARNING_RATE == 1) { logger.Warn($"{ToString()} Received error on peer eventing service on channel {channelName}, peer {name}, url {url}, attempts {reconnectCount}. {e.Message}"); } else { logger.Trace($"{ToString()} Received error on peer eventing service on channel {channelName}, peer {name}, url {url}, attempts {reconnectCount}. {e.Message}"); } if (retry) { peer.ReconnectPeerEventServiceClient(this, fnal, token); } } retry = false; } else { logger.Trace($"{ToString()} was shutdown."); } }
private async Task Run() { var credentials = await CreateCredentialsAsync(); List<ChannelOption> channelOptions = null; if (!string.IsNullOrEmpty(options.ServerHostOverride)) { channelOptions = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, options.ServerHostOverride) }; } var channel = new Channel(options.ServerHost, options.ServerPort, credentials, channelOptions); await RunTestCaseAsync(channel, options); await channel.ShutdownAsync(); }
private async Task Run() { Credentials credentials = null; if (options.useTls) { credentials = TestCredentials.CreateTestClientCredentials(options.useTestCa); } List<ChannelOption> channelOptions = null; if (!string.IsNullOrEmpty(options.serverHostOverride)) { channelOptions = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, options.serverHostOverride) }; } var channel = new Channel(options.serverHost, options.serverPort.Value, credentials, channelOptions); TestService.TestServiceClient client = new TestService.TestServiceClient(channel); await RunTestCaseAsync(options.testCase, client); channel.ShutdownAsync().Wait(); }
private void handleBrewProcess(GrainBrainStatus status) { if (status.State == BrewStep.StrikeWaterTempReached) { //dispatcherTimer.Tick -= brewProcessTimer_Tick; dispatcherTimer.IsEnabled = false; var swrw = new StrikeWaterReachedWindow(); swrw.ShowDialog(); IPAddress ipAddr; if (!GrainbrainNetDiscovery.GetGrainBrainAddress(out ipAddr)) return; string addr = String.Format("{0}:50051", ipAddr); Channel ch = new Channel(addr, ChannelCredentials.Insecure); McServer.McServerClient cl = new McServer.McServerClient(ch); GrainsAddedNotify req = new GrainsAddedNotify(); Empty resp = cl.GrainsAdded(req); ch.ShutdownAsync().Wait(); //dispatcherTimer.Tick += brewProcessTimer_Tick; dispatcherTimer.IsEnabled = true; } if (status.State == BrewStep.MashDoneStartSparge) { dispatcherTimer.IsEnabled = false; var sdw = new SpargeDoneWindow(); sdw.ShowDialog(); IPAddress ipAddr; if (!GrainbrainNetDiscovery.GetGrainBrainAddress(out ipAddr)) return; string addr = String.Format("{0}:50051", ipAddr); Channel ch = new Channel(addr, ChannelCredentials.Insecure); McServer.McServerClient cl = new McServer.McServerClient(ch); SpargeDoneNotify req = new SpargeDoneNotify(); Empty resp = cl.SpargeDone(req); ch.ShutdownAsync().Wait(); dispatcherTimer.IsEnabled = true; } if (status.State == BrewStep.BoilDone) { dispatcherTimer.IsEnabled = false; var wcsw = new WortChillerSanitizedWindow(); wcsw.ShowDialog(); IPAddress ipAddr; if (!GrainbrainNetDiscovery.GetGrainBrainAddress(out ipAddr)) return; string addr = String.Format("{0}:50051", ipAddr); Channel ch = new Channel(addr, ChannelCredentials.Insecure); McServer.McServerClient cl = new McServer.McServerClient(ch); WortChillerSanitizedDoneNotify req = new WortChillerSanitizedDoneNotify(); Empty resp = cl.WortChillerSanitizedDone(req); ch.ShutdownAsync().Wait(); dispatcherTimer.IsEnabled = true; } }
public async Task StateIsShutdownAfterShutdown() { var channel = new Channel("localhost", ChannelCredentials.Insecure); await channel.ShutdownAsync(); Assert.AreEqual(ChannelState.Shutdown, channel.State); }
static void Main(string[] args) { // Prerequisites // 1. create a new cloud project with your google account // 2. enable cloud pubsub API on that project // 3. 'gcloud auth login' to store your google credential in a well known location (from where GoogleCredential.GetApplicationDefaultAsync() can pick it up). var credentials = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result; Channel channel = new Channel("pubsub-experimental.googleapis.com", credentials.ToChannelCredentials()); var publisherClient = new Google.Pubsub.V1.Publisher.PublisherClient(channel); var subscriberClient = new Google.Pubsub.V1.Subscriber.SubscriberClient(channel); var topics = publisherClient.ListTopics(new ListTopicsRequest { Project = ProjectName }).Topics; // create the topic if it doesn't exist yet var topic = new Topic { Name = TopicName }; if (!topics.Contains(topic)) { Console.WriteLine("Creating topic {0}.", TopicName); topic = publisherClient.CreateTopic(topic); } else { Console.WriteLine("Topic {0} already exists.", TopicName); } // create a subscription if it doesn't exist yet. try { subscriberClient.CreateSubscription(new Subscription { Name = SubscriptionName, Topic = TopicName }); } catch (RpcException e) { // if we created the subscription before, that's fine. if (e.Status.StatusCode != StatusCode.AlreadyExists) { throw; } } // publish something publisherClient.Publish(new PublishRequest { Topic = topic.Name, // TODO: try use attributes Messages = { new PubsubMessage { Data = ByteString.CopyFrom(1, 2, 3) }, new PubsubMessage { Data = ByteString.CopyFrom(0xaa, 0xff) } } }); // try to read what we published. var receivedMessages = subscriberClient.Pull(new PullRequest { Subscription = SubscriptionName, MaxMessages = 100, ReturnImmediately = false }).ReceivedMessages; foreach (var msg in receivedMessages) { Console.WriteLine("Received message with Id {0} and data {1}", msg.Message.MessageId, msg.Message.Data); } // TODO: we need to Ack the messages so that they don't show up again after ack deadline. Console.WriteLine("Press any key to continue..."); Console.ReadKey(); channel.ShutdownAsync(); }
public async Task OperationsThrowAfterShutdown() { var channel = new Channel("localhost", ChannelCredentials.Insecure); await channel.ShutdownAsync(); Assert.ThrowsAsync(typeof(ObjectDisposedException), async () => await channel.WaitForStateChangedAsync(ChannelState.Idle)); Assert.Throws(typeof(ObjectDisposedException), () => { var x = channel.ResolvedTarget; }); Assert.ThrowsAsync(typeof(TaskCanceledException), async () => await channel.ConnectAsync()); }
public async Task ShutdownFinishesWaitForStateChangedAsync() { var channel = new Channel("localhost", ChannelCredentials.Insecure); var stateChangedTask = channel.WaitForStateChangedAsync(ChannelState.Idle); var shutdownTask = channel.ShutdownAsync(); await stateChangedTask; await shutdownTask; }
public async Task AfterAll() { await _channel.ShutdownAsync().ConfigureAwait(false); await _server.ShutdownAsync().ConfigureAwait(false); }
private void MenuItem_GrainbrainStop(object sender, RoutedEventArgs e) { var sbpw = new StopBrewingProcessWindow(); sbpw.ShowDialog(); if (sbpw.Abort) { IPAddress ipAddr; if (!GrainbrainNetDiscovery.GetGrainBrainAddress(out ipAddr)) return; string addr = String.Format("{0}:50051", ipAddr); Channel ch = new Channel(addr, ChannelCredentials.Insecure); McServer.McServerClient cl = new McServer.McServerClient(ch); StartStopRequest req = new StartStopRequest(); req.StartStop = StartStopRequest.Types.StartStop.Stop; SuccessReply resp = cl.StartStopAbort(req); ch.ShutdownAsync().Wait(); } }
protected override void OnApplicationQuit() { base.OnApplicationQuit(); channel.ShutdownAsync().Wait(); }
private async Task Run() { var credentials = options.UseTls ? TestCredentials.CreateTestClientCredentials(options.UseTestCa) : Credentials.Insecure; List<ChannelOption> channelOptions = null; if (!string.IsNullOrEmpty(options.ServerHostOverride)) { channelOptions = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, options.ServerHostOverride) }; } Console.WriteLine(options.ServerHost); Console.WriteLine(options.ServerPort); var channel = new Channel(options.ServerHost, options.ServerPort, credentials, channelOptions); TestService.TestServiceClient client = new TestService.TestServiceClient(channel); await RunTestCaseAsync(client, options); channel.ShutdownAsync().Wait(); }
static void Main(string[] args) { var channel = new Channel("127.0.0.1:50052", ChannelCredentials.Insecure); var client = new RouteGuideClient(RouteGuide.NewClient(channel)); // Looking for a valid feature client.GetFeature(409146138, -746188906); // Feature missing. client.GetFeature(0, 0); // Looking for features between 40, -75 and 42, -73. client.ListFeatures(400000000, -750000000, 420000000, -730000000).Wait(); // Record a few randomly selected points from the features file. client.RecordRoute(RouteGuideUtil.ParseFeatures(RouteGuideUtil.DefaultFeaturesFile), 10).Wait(); // Send and receive some notes. client.RouteChat().Wait(); channel.ShutdownAsync().Wait(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
async Task Run() { var metricsServer = new Server() { Services = { MetricsService.BindService(new MetricsServiceImpl(histogram)) }, Ports = { { "[::]", options.MetricsPort, ServerCredentials.Insecure } } }; metricsServer.Start(); if (options.TestDurationSecs >= 0) { finishedTokenSource.CancelAfter(TimeSpan.FromSeconds(options.TestDurationSecs)); } var tasks = new List<Task>(); var channels = new List<Channel>(); foreach (var serverAddress in serverAddresses) { for (int i = 0; i < options.NumChannelsPerServer; i++) { var channel = new Channel(serverAddress, ChannelCredentials.Insecure); channels.Add(channel); for (int j = 0; j < options.NumStubsPerChannel; j++) { var client = TestService.NewClient(channel); var task = Task.Factory.StartNew(() => RunBodyAsync(client).GetAwaiter().GetResult(), TaskCreationOptions.LongRunning); tasks.Add(task); } } } await Task.WhenAll(tasks); foreach (var channel in channels) { await channel.ShutdownAsync(); } await metricsServer.ShutdownAsync(); }
public async Task ShutdownTokenCancelledAfterShutdown() { var channel = new Channel("localhost", ChannelCredentials.Insecure); Assert.IsFalse(channel.ShutdownToken.IsCancellationRequested); var shutdownTask = channel.ShutdownAsync(); Assert.IsTrue(channel.ShutdownToken.IsCancellationRequested); await shutdownTask; }
public void Shutdown(bool force) { if (shutdown) { return; } string me = ToString(); logger.Debug($"{me} is shutting down."); try { dtask.Cancel(); } catch (Exception e) { logger.Error(ToString() + " error message: " + e.Message, e); } shutdown = true; Channel lchannel = managedChannel; managedChannel = null; if (lchannel != null) { if (force) { try { lchannel.ShutdownAsync().GetAwaiter().GetResult(); } catch (Exception e) { logger.WarnException(e.Message, e); } } else { bool isTerminated = false; try { isTerminated = lchannel.ShutdownAsync().Wait(3 * 1000); } catch (Exception e) { logger.DebugException(e.Message, e); //best effort } if (!isTerminated) { try { lchannel.ShutdownAsync().GetAwaiter().GetResult(); } catch (Exception e) { logger.Debug(me + " error message: " + e.Message, e); //best effort } } } } channelEventQue = null; logger.Debug($"{me} is down."); }