private void _requestBtn_Click(object sender, EventArgs e) { string msg = _requestMessage.Text; if (string.IsNullOrEmpty(msg)) { this.InformUser("Please add a request message. Just type in whatever you like."); return; } ExampleRequest request = new ExampleRequest(msg); TimeSpan fiveSeconds = new TimeSpan(0, 0, 5); try { ExampleResponse response = this.EventBus.GetResponseTo <ExampleResponse>(request, fiveSeconds); if (null == response) { this.Log("Did not get a response to the request within 5 seconds. Ensure there is another .NET Consumer & Producer running"); } else { this.Log(string.Format("Got a response to '{0}': '{1}'", response.OriginalMessage, response.ResponseMessage)); } } catch (Exception ex) { this.Log("Could not send the request: " + ex.ToString()); } }
public static async Task <IActionResult> AddItemToCosmos( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log) { //Read json from post //Can be message from IoTHub etc... string json = await new StreamReader(req.Body).ReadToEndAsync(); //Cast json to the required object ExampleRequest request = JsonConvert.DeserializeObject <ExampleRequest>(json); //MANDATORY property has to be created called id request.id = Guid.NewGuid().ToString(); //Create Cosmos client CosmosClientOptions options = new CosmosClientOptions(); options.ConnectionMode = ConnectionMode.Gateway; //connect to database CosmosClient client = new CosmosClient(Environment.GetEnvironmentVariable("cosmos"), options); //get container in a database Container container = client.GetContainer("NameOfDatabase", "NameOfContainer"); //Get the response ItemResponse <ExampleRequest> response = await container.CreateItemAsync(request, new PartitionKey(request.name)); return(new OkObjectResult("")); }
public override Task <ExampleResponse> UnaryCall(ExampleRequest request, ServerCallContext context) { var response = new ExampleResponse { TotalCount = request.PageIndex * request.PageSize, Message = $"--From Server-- Current index from service is {request.PageIndex}" }; return(Task.FromResult(response)); }
public override Task <ExampleResponse> ChamadaTesteService(ExampleRequest exampleRequest, ServerCallContext serverCallContext) { var response = new ExampleResponse { Id = exampleRequest.Status, Nome = $"{exampleRequest.Mensagem} Testado: {exampleRequest.Testado}" }; return(Task.FromResult(response)); }
public static void QueueTrigger([QueueTrigger("queue_name", Connection = "change_me")] string myQueueItem, ILogger log) { log.LogInformation($"C# Queue trigger function processed: {myQueueItem}"); //Converting data to required object (ExampleRequest) //Only works when sent data is JSON ExampleRequest exampleRequest = JsonConvert.DeserializeObject <ExampleRequest>(myQueueItem); }
public override async Task <ExampleResponse> UnaryCall(ExampleRequest request, ServerCallContext context) { var response = new ExampleResponse { PageIndex = 1, PageData = $"This is UnaryCall- Request-pageIndex {request.PageIndex}" }; return(await Task.FromResult(response)); }
//一元方法 public override Task <ExampleResponse> UnaryCall(ExampleRequest request, ServerCallContext context) { var response = new ExampleResponse() { Message = "UnaryCall" }; return(Task.FromResult(response)); }
private static async Task UnaryCallExample(ExampleService.ExampleServiceClient client) { var request = new ExampleRequest { PageIndex = 0, PageSize = 20, IsDescending = true }; var response = await client.UnaryCallAsync(request); Console.WriteLine("Received " + response.PageData); }
//服务器流式处理方法 public override async Task StreamingFromServer(ExampleRequest request, IServerStreamWriter <ExampleResponse> responseStream, ServerCallContext context) { for (var i = 0; i < 5; i++) { await responseStream.WriteAsync(new ExampleResponse { Message = i.ToString() }); await Task.Delay(TimeSpan.FromSeconds(1)); } }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public override async Task <ExampleResponse> UnaryCall(ExampleRequest request, ServerCallContext context) { var response = new ExampleResponse() { Result = $"{request.ReqStr} World" }; return(response); }
private async Task PerformPostFromExampleAsync(ExampleRequest request) { try { apiResponse = await exampleRestApiClient.PostResultFromExampleAsync(request); } catch (ApiException ex) { apiException = ex; } }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public override Task <ExampleResponse> SayHello(ExampleRequest request, ServerCallContext context) { var userAgent = context.RequestHeaders.ToList(); var tempKey = userAgent[0].Key; var tempVal_ = userAgent[0].Value; return(Task.FromResult(new ExampleResponse { Result = request.ReqStr + "World" })); }
private static async Task ServerStreamingCallExample(ExampleService.ExampleServiceClient client) { var request = new ExampleRequest { PageIndex = 0, PageSize = 20, IsDescending = true }; using var call = client.StreamingFromServer(request); await foreach (var response in call.ResponseStream.ReadAllAsync()) { Console.WriteLine("Received " + response.PageData); } }
public override async Task StreamingFromServer(ExampleRequest request, IServerStreamWriter <ExampleResponse> responseStream, ServerCallContext context) { for (var i = 0; i < 5; i++) { // È¡Ïû²Ù×÷ while (!context.CancellationToken.IsCancellationRequested) { await responseStream.WriteAsync(new ExampleResponse()); await Task.Delay(TimeSpan.FromSeconds(1)); } } }
public override async Task <ExampleResponse> Unary(ExampleRequest request, ServerCallContext context) { // by default, the server always writes some custom response headers if (!request.DisableSendingExampleResponseHeaders) { await context.WriteResponseHeadersAsync(new Metadata { { "server-header", "server header value" }, { "server-header", "server header value duplicate" }, { "server-header-bin", Encoding.UTF8.GetBytes("server header binary value") }, }); } // always add some response trailers context.ResponseTrailers.Add("server-trailer", "server trailer value"); context.ResponseTrailers.Add("server-trailer", "server trailer value duplicate"); context.ResponseTrailers.Add("server-trailer-bin", Encoding.UTF8.GetBytes("server trailer binary value")); // wait for the requested amount of milliseconds await Task.Delay(request.PleaseDelayResponseMs, context.CancellationToken); // are we requested to fail? set an error status or even throw switch (request.PleaseFail) { case FailRequest.MessageThenErrorStatus: context.Status = new Status(StatusCode.ResourceExhausted, "you requested an error"); break; case FailRequest.ErrorStatusOnly: throw new RpcException( new Status(StatusCode.ResourceExhausted, "you requested an error, no message"), new Metadata { { "server-trailer", "created by rpc exception on server" } } ); case FailRequest.None: context.Status = new Status(StatusCode.OK, "great!"); break; } return(new ExampleResponse { Answer = $"You asked: {request.Question}", YourDeadline = context.Deadline.ToString(CultureInfo.InvariantCulture), YourRequestHeaders = { MetadataToMap(context.RequestHeaders) }, YourFailRequest = request.PleaseFail, }); }
private async void gRPCUnaryTry() { AppendText("starting unary calling..."); var channel = GrpcChannel.ForAddress(DefaultChannelAddress); var client = new StreamShoper.StreamShoperClient(channel); var request = new ExampleRequest { PageIndex = 2, PageSize = 10, IsDescending = true }; var response = await client.UnaryCallAsync(request); AppendText(response.Message); }
public ActionResult atualizaPost([FromBody] ExampleRequest request) { try { var example = _context.Example.Single(a => a.Id == request.Id); example.Nome = request.Nome; _context.SaveChanges(); return(Ok("Registro de exemplo atualizado com sucesso!")); } catch (Exception) { return(NotFound("Exemplo não encontrada!")); } }
/* * * Will send data to the queue * */ private static async Task PutItemInQueue(ExampleRequest request) { //connect to queue string connection = Environment.GetEnvironmentVariable("ConnectionStringStorage"); //Enter right Queue name QueueClient queueClient = new QueueClient(connection, "registrations"); await queueClient.CreateIfNotExistsAsync(); // Creates queue if not exists string json = JsonConvert.SerializeObject(request); //has to be converted to json then to Bytes var valueBytes = Encoding.UTF8.GetBytes(json); // then to bytes // put the message in the queue await queueClient.SendMessageAsync(Convert.ToBase64String(valueBytes)); //Has to be base64 encoded }
public void OnGUI() { if (!GUI.Button(new Rect(0, 0, 400, 50), "Get stuff over 9000! (see console for output)")) return; var stuffOver9000Request = new ExampleRequest(9000); Messenger.Publish(stuffOver9000Request); Messenger.Publish(new NewInformationMessage("You just requested game objects that are over 9000!\nThe results are in the console :)")); print("Stuff over 9000:\n"); foreach (var res in stuffOver9000Request.RequestResult) { print(res + "\n"); } }
public ActionResult inserePost([FromBody] ExampleRequest request) { try { var example = new Example { Nome = request.Nome }; _context.Add <Example>(example); _context.SaveChanges(); return(Ok("Registro de exemplo inserido com sucesso!")); } catch (Exception) { return(NotFound("Não foi possível inserir o exemplo!")); } }
public void Handle_ExampleRequest(ExampleRequest request, IDictionary <string, string> headers) { ExampleResponse response = new ExampleResponse(); response.OriginalMessage = request.Message; response.ResponseMessage = string.Format("{0}, eh? Fascinating.", request.Message); try { this.Log(string.Format("Responding to {0} with {1}", response.OriginalMessage, response.ResponseMessage)); this.EventBus.RespondTo(headers, response); } catch (Exception ex) { this.Log(ex.ToString()); } }
public void OnGUI() { if (!GUI.Button(new Rect(0, 0, 400, 50), "Get stuff over 9000! (see console for output)")) { return; } var stuffOver9000Request = new ExampleRequest(9000); Messenger.Publish(stuffOver9000Request); Messenger.Publish(new NewInformationMessage("You just requested game objects that are over 9000!\nThe results are in the console :)")); print("Stuff over 9000:\n"); foreach (var res in stuffOver9000Request.RequestResult) { print(res + "\n"); } }
public async Task <IActionResult> GetWithValidator(string text) { var request = new ExampleRequest(); request.text = text; var res = await mediator.HandleRequest(request); if (res.Any(o => o.AnyError)) { return(BadRequest(res)); } else { var result = res.GetResponse <ExampleResponse>(); return(Ok(result)); } }
public override async Task StreamingFromServer(ExampleRequest request, IServerStreamWriter <ExampleResponse> responseStream, ServerCallContext context) { int startIndex = 1; startIndex = request.PageIndex; while (!context.CancellationToken.IsCancellationRequested) { var response = new ExampleResponse { TotalCount = startIndex, Message = $"--From Server-- Current index is {startIndex}" }; startIndex++; await responseStream.WriteAsync(response); await Task.Delay(TimeSpan.FromSeconds(1)); } return; }
private async void gRPCBothStreamTry() { try { AppendText("starting Both Steam Calling..."); var channel = GrpcChannel.ForAddress(DefaultChannelAddress); var client = new StreamShoper.StreamShoperClient(channel); var cancelSource = new CancellationTokenSource(); var token = cancelSource.Token; var call = client.StreamingBothWays(null, null, token); for (int i = 8; i >= 0; i--) { AppendText($"#From Client# the index is {i}"); var request = new ExampleRequest { PageIndex = i, PageSize = 10, IsDescending = true }; await call.RequestStream.WriteAsync(request); await call.ResponseStream.MoveNext(token); var response = call.ResponseStream.Current; AppendText(response.Message); AppendText("Waiting 2 seconds..."); await Task.Delay(2000); //await Task.Delay(100); } AppendText("Starting cancelling..."); cancelSource.Cancel(); } catch (Exception ex) { AppendText("Cancelling..."); } }
static void Main(string[] args) { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); var channel = GrpcChannel.ForAddress("http://localhost:5000", new GrpcChannelOptions()); var client = new ExampleService.ExampleServiceClient(channel); try { var deadline = DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)); var request = new ExampleRequest { PleaseFail = FailRequest.None }; // MakeServerStreamingCall(client, deadline, request).GetAwaiter().GetResult(); MakeUnaryCall(client, deadline, request).GetAwaiter().GetResult(); } catch (Exception exception) { Console.WriteLine($"ERROR"); Console.WriteLine($"{exception.Message}"); } }
private async void gRPCServerStreamTry() { AppendText("starting server stream..."); var channel = GrpcChannel.ForAddress(@"https://localhost:5001"); var client = new StreamShoper.StreamShoperClient(channel); var request = new ExampleRequest { PageIndex = 2, PageSize = 10, IsDescending = true }; var cancelSource = new CancellationTokenSource(); var token = cancelSource.Token; using var call = client.StreamingFromServer(request, null, null, token); int maxIndex = 10; while (true) { try { await call.ResponseStream.MoveNext(token); var response = call.ResponseStream.Current; AppendText(response.Message); if (response.TotalCount >= 10) { AppendText("Meet max, cancelling..."); cancelSource.Cancel(); } } catch (Exception ex) { AppendText("Exit..."); break; } } }
public Example Get(ExampleRequest request) { return new Example { Greeting = "Hello, MD!" }; }
/// <summary> /// Create a result from example api. /// POST - {exampleService}/result /// </summary> /// <param name="exampleRequest">The example request.</param> /// <returns>The <see cref="Task{TResult}"/></returns> public async Task <ApiGenericResponse <ExampleResponse> > PostResultFromExampleAsync(ExampleRequest exampleRequest) { var url = $"{exampleService}{resultAttribute}"; var response = await HttpClientFactory.StandardHttpClient.PostAsync(url, exampleRequest); return(await CreateApiGenericResponse <ExampleResponse>(response)); }
private static async Task MakeServerStreamingCall(ExampleService.ExampleServiceClient client, DateTime deadline, ExampleRequest request) { Console.WriteLine("starting call..."); var call = client.ServerStream(request, Metadata.Empty, deadline, CancellationToken.None); var headers = call.ResponseHeadersAsync; Console.WriteLine("got response headers: " + headers); Console.WriteLine("reading response stream..."); await foreach (var m in call.ResponseStream.ReadAllAsync()) { Console.WriteLine("read message: " + m); } Console.WriteLine("finished reading response stream."); var status = call.GetStatus(); Console.WriteLine("read status: " + status); var trailers = call.GetTrailers(); Console.WriteLine("read trailers: " + trailers); }
private static async Task MakeUnaryCall(ExampleService.ExampleServiceClient client, DateTime deadline, ExampleRequest request) { Console.WriteLine("starting call..."); var call = client.UnaryAsync(request, Metadata.Empty, deadline, CancellationToken.None); var headers = await call.ResponseHeadersAsync; Console.WriteLine("got response headers: " + headers); Console.WriteLine("reading response..."); var msg = await call.ResponseAsync; Console.WriteLine("got response message: " + msg); var status = call.GetStatus(); Console.WriteLine("read status: " + status); var trailers = call.GetTrailers(); Console.WriteLine("read trailers: " + trailers); }
public IActionResult Post([FromBody] ExampleRequest request) { return(Response(0, null)); }