public static async Task Main(string[] args) { Console.WriteLine("Hello World!"); var jsonOptions = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, }; var client = new DaprClientBuilder() .UseJsonSerializationOptions(jsonOptions) .Build(); Console.WriteLine("Retrieving weather forecast..."); var httpExtension = new HTTPExtension { Verb = HTTPVerb.Get }; var response = await client.InvokeMethodAsync <WeatherForecastModel[]>("weather-forecast", "weather", httpExtension); Console.WriteLine("Weather forecast received:"); foreach (var thisForecast in response) { Console.WriteLine(thisForecast); } }
internal static async Task InvokeThrowExceptionOperationAsync(DaprClient client) { Console.WriteLine("Invoking ThrowException"); var data = new { id = "17", amount = (decimal)10, }; HTTPExtension httpExtension = new HTTPExtension() { Verb = HTTPVerb.Post }; try { // Invokes a POST method named "throwException" that takes input of type "Transaction" as defined in the ControllerSample. await client.InvokeMethodAsync("controller", "throwException", data, httpExtension); } catch (RpcException ex) { var entry = ex.Trailers.Get(grpcStatusDetails); var status = Google.Rpc.Status.Parser.ParseFrom(entry.ValueBytes); Console.WriteLine("Grpc Exception Message: " + status.Message); Console.WriteLine("Grpc Statuscode: " + status.Code); foreach (var detail in status.Details) { if (Google.Protobuf.WellKnownTypes.Any.GetTypeName(detail.TypeUrl) == grpcErrorInfoDetail) { var rpcError = detail.Unpack <Google.Rpc.ErrorInfo>(); Console.WriteLine("Grpc Exception: Http Error Message: " + rpcError.Metadata[daprErrorInfoHTTPErrorMetadata]); Console.WriteLine("Grpc Exception: Http Status Code: " + rpcError.Metadata[daprErrorInfoHTTPCodeMetadata]); } } } }
public async Task <ActionResult <Guid> > SubmitOrder(Order order, [FromServices] DaprClient daprClient) { Console.WriteLine("Enter submit order"); order.Id = Guid.NewGuid(); HTTPExtension httpExtension = new HTTPExtension() { Verb = HTTPVerb.Post }; foreach (var item in order.Items) { /* a dynamic type is passed to sample.microservice.reservation and not * the Order in scope of sample.microservice.order, you could use DTO instead */ var data = new { sku = item.ProductCode, quantity = item.Quantity }; var result = await daprClient.InvokeMethodAsync <object, dynamic>("reservation-service", "reserve", data, httpExtension); Console.WriteLine($"sku: {result.GetProperty("sku")} === new quantity: {result.GetProperty("quantity")}"); } Console.WriteLine($"Submitted order {order.Id}"); return(order.Id); }
static async Task Main(string[] args) { var jsonOptions = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, }; var client = new DaprClientBuilder() .UseJsonSerializationOptions(jsonOptions) .Build(); var data = new { Time = DateTime.Now.ToLongDateString(), Id = "This is Client A" }; HTTPExtension httpExtension = new HTTPExtension() { Verb = HTTPVerb.Post }; while (true) { var a = await client.InvokeMethodAsync <object, SomeResponseBody>("dotnet-server-b", "talk", data, httpExtension); Console.WriteLine(a.Msg); await Task.Delay(5 * 1000); } }
private async Task <Autogenerated.InvokeResponse> MakeInvokeRequestAsync( string appId, string methodName, Any data, HTTPExtension httpExtension, CancellationToken cancellationToken = default) { var protoHTTPExtension = new Autogenerated.HTTPExtension(); var contentType = ""; Metadata headers = null; if (httpExtension != null) { protoHTTPExtension.Verb = ConvertHTTPVerb(httpExtension.Verb); if (httpExtension.QueryString != null) { foreach (var(key, value) in httpExtension.QueryString) { protoHTTPExtension.Querystring.Add(key, value); } } if (httpExtension.Headers != null) { headers = new Metadata(); foreach (var(key, value) in httpExtension.Headers) { headers.Add(key, value); } } contentType = httpExtension.ContentType ?? Constants.ContentTypeApplicationJson; } else { protoHTTPExtension.Verb = Autogenerated.HTTPExtension.Types.Verb.Post; contentType = Constants.ContentTypeApplicationJson; } var invokeRequest = new Autogenerated.InvokeRequest() { Method = methodName, Data = data, ContentType = contentType, HttpExtension = protoHTTPExtension }; var request = new Autogenerated.InvokeServiceRequest() { Id = appId, Message = invokeRequest, }; return(await this.MakeGrpcCallHandleError( options => client.InvokeServiceAsync(request, options), headers, cancellationToken)); }
public async Task <IActionResult> Index([FromServices] DaprClient client) { var httpExtension = new HTTPExtension { Verb = HTTPVerb.Get }; var weatherForecast = await client.InvokeMethodAsync <WeatherForecastModel[]>("weather-forecast", "weather", httpExtension); return(View(weatherForecast)); }
public override async Task InvokeMethodAsync( string appId, string methodName, HTTPExtension httpExtension = default, CancellationToken cancellationToken = default) { ArgumentVerifier.ThrowIfNullOrEmpty(appId, nameof(appId)); ArgumentVerifier.ThrowIfNullOrEmpty(methodName, nameof(methodName)); _ = await this.MakeInvokeRequestAsync(appId, methodName, null, httpExtension, cancellationToken); }
/// <summary> /// This example shows how to invoke a GET method on a service listening on http. /// Example: curl -X GET http://127.0.0.1:5000/17 /// </summary> /// <param name="client"></param> /// <remarks> /// Before invoking this method, please first run RoutingSample. /// </remarks> /// <returns></returns> internal static async Task InvokeBalanceServiceOperationAsync(DaprClient client) { Console.WriteLine("Invoking balance"); // Invokes a GET method named "hello" that takes input of type "MyData" and returns a string. HTTPExtension httpExtension = new HTTPExtension() { Verb = HTTPVerb.Get }; var res = await client.InvokeMethodAsync <Account>("routing", "17", httpExtension); Console.WriteLine($"Received balance {res.Balance}"); }
public override async ValueTask <TResponse> InvokeMethodAsync <TResponse>( string appId, string methodName, HTTPExtension httpExtension = default, CancellationToken cancellationToken = default) { ArgumentVerifier.ThrowIfNullOrEmpty(appId, nameof(appId)); ArgumentVerifier.ThrowIfNullOrEmpty(methodName, nameof(methodName)); var response = await this.MakeInvokeRequestAsync(appId, methodName, null, httpExtension, cancellationToken); return(response.Data.Value.IsEmpty ? default : TypeConverters.FromAny <TResponse>(response.Data, this.jsonSerializerOptions)); }
public async Task <IActionResult> Index() { var httpExtension = new HTTPExtension { Verb = HTTPVerb.Get }; var weatherForecastResult = await _daprClient.InvokeMethodAsync <object>("server-app", "WeatherForecast", httpExtension); ViewBag.WeatherForecast = weatherForecastResult; return(View()); }
public async Task <DTO.TokenOutput> RegisterUserAsync(DTO.RegistrationInput registration) { var errors = new List <string>(); var existingEmail = await UserManager.FindByEmailAsync(registration.Email); if (existingEmail != null) { errors.Add("This email already exists."); } var existingUserName = await UserManager.FindByNameAsync(registration.UserName); if (existingUserName != null) { errors.Add("This username already exists."); } if (errors.Count != 0) { throw new BadRequestException(errors); } var result = await UserManager.CreateAsync(new IdentityUser { UserName = registration.UserName, Email = registration.Email }, registration.Password); if (!result.Succeeded) { throw new BadRequestException(result.Errors.Select(error => error.Description).ToList()); } var insertedUser = await UserManager.FindByNameAsync(registration.UserName); var tokenResult = await GenerateAuthenticationTokenAsync(insertedUser); var httpExtension = new HTTPExtension { ContentType = "application/json", Verb = HTTPVerb.Post }; httpExtension.Headers.Add("Authorization", $"Bearer {tokenResult.Token}"); _ = DaprClient.InvokeMethodAsync <DTO.AddressInput, DTO.SuccessResponse <DTO.AddressOutput> >( "farmerzon-address", "address", registration.Address, httpExtension); return(tokenResult); }
public async Task <SomeResponseBody> Talk(SomeRequestBody someRequestBody) { var data = new { Time = DateTime.Now.ToLongDateString(), Id = "This is Service C." }; HTTPExtension httpExtension = new HTTPExtension() { Verb = HTTPVerb.Post }; SomeResponseBody responseBody = await daprClient.InvokeMethodAsync <object, SomeResponseBody>("dotnet-server-c", "talk", data, httpExtension); Console.WriteLine(string.Format("{0}:{1} \n recieve message:{2}", someRequestBody.Id, someRequestBody.Time, responseBody.Msg)); return(await Task.FromResult(new SomeResponseBody { Msg = "This is ServiceB" })); }
/// <summary> /// This example shows how to invoke a POST method on a service listening on http. /// Example: curl -X POST http://127.0.0.1:5000/deposit -H "Content-Type: application/json" -d "{ \"id\": \"17\", \"amount\": 120 }" /// </summary> /// <param name="client"></param> /// <remarks> /// Before invoking this method, please first run RoutingSample. /// </remarks> /// <returns></returns> internal static async Task InvokeWithdrawServiceOperationAsync(DaprClient client) { Console.WriteLine("Invoking withdraw"); var data = new { id = "17", amount = (decimal)10, }; HTTPExtension httpExtension = new HTTPExtension() { Verb = HTTPVerb.Post }; // Invokes a POST method named "Withdraw" that takes input of type "Transaction" as define in the RoutingSample. await client.InvokeMethodAsync <object>("routing", "Withdraw", data, httpExtension); Console.WriteLine("Completed"); }
private HTTPExtension GenerateExtension(HTTPVerb type, IDictionary <string, string> queryParameters = null) { var httpExtension = new HTTPExtension { ContentType = "application/json", Verb = type }; httpExtension.Headers.Add("Authorization", $"Bearer {TokenManager.Token}"); if (queryParameters != null) { httpExtension.QueryString = queryParameters; } return(httpExtension); }
internal static async Task DepositUsingServiceInvocation(DaprClient client) { Console.WriteLine("DepositUsingServiceInvocation"); var data = new { id = "17", amount = (decimal)99 }; HTTPExtension httpExtension = new HTTPExtension() { Verb = HTTPVerb.Post }; // Invokes a POST method named "depoit" that takes input of type "Transaction" as define in the RoutingSample. Console.WriteLine("invoking"); var a = await client.InvokeMethodAsync <object, Account>("routing", "deposit", data, httpExtension); Console.WriteLine("Returned: id:{0} | Balance:{1}", a.Id, a.Balance); Console.WriteLine("Completed"); }
public override async Task InvokeMethodAsync <TRequest>( string appId, string methodName, TRequest data, HTTPExtension httpExtension = default, CancellationToken cancellationToken = default) { ArgumentVerifier.ThrowIfNullOrEmpty(appId, nameof(appId)); ArgumentVerifier.ThrowIfNullOrEmpty(methodName, nameof(methodName)); Any serializedData = null; if (data != null) { serializedData = TypeConverters.ToAny(data, this.jsonSerializerOptions); } _ = await this.MakeInvokeRequestAsync(appId, methodName, serializedData, httpExtension, cancellationToken); }
public override async Task<InvocationResponse<byte[]>> InvokeMethodRawAsync( string appId, string methodName, byte[] data, HTTPExtension httpExtension = default, CancellationToken cancellationToken = default) { ArgumentVerifier.ThrowIfNullOrEmpty(appId, nameof(appId)); ArgumentVerifier.ThrowIfNullOrEmpty(methodName, nameof(methodName)); var request = new InvocationRequest<byte[]> { AppId = appId, MethodName = methodName, Body = data, HttpExtension = httpExtension, }; var invokeResponse = await this.MakeInvokeRequestAsyncWithResponse<byte[], byte[]>(request, true, cancellationToken); return invokeResponse; }
public override async ValueTask<TResponse> InvokeMethodAsync<TRequest, TResponse>( string appId, string methodName, TRequest data, HTTPExtension httpExtension = default, CancellationToken cancellationToken = default) { ArgumentVerifier.ThrowIfNullOrEmpty(appId, nameof(appId)); ArgumentVerifier.ThrowIfNullOrEmpty(methodName, nameof(methodName)); var request = new InvocationRequest<TRequest> { AppId = appId, MethodName = methodName, Body = data, HttpExtension = httpExtension, }; var invokeResponse = await this.MakeInvokeRequestAsyncWithResponse<TRequest, TResponse>(request, false, cancellationToken); return invokeResponse.Body; }
public async Task <ActionResult <Guid> > SubmitOrder(Order order, [FromServices] DaprClient daprClient) { Console.WriteLine("Enter submit order"); order.Id = Guid.NewGuid(); var state = await daprClient.GetStateEntryAsync <OrderState>(StoreName, order.Id.ToString()); state.Value ??= new OrderState() { CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow, Order = order }; HTTPExtension httpExtension = new HTTPExtension() { Verb = HTTPVerb.Post }; foreach (var item in order.Items) { var data = new Item() { SKU = item.ProductCode, Quantity = item.Quantity }; var result = await daprClient.InvokeMethodAsync <Item, Item>("reservation-service", "reserve", data, httpExtension); } // Console.WriteLine($"ETag {state.ETag}"); // var options = new StateOptions() {Concurrency = ConcurrencyMode.FirstWrite, Consistency = ConsistencyMode.Strong}; // await state.SaveAsync(options); // var metadata = new Dictionary<string,string>(); // metadata.Add("partitionKey","something_else"); // await state.SaveAsync(metadata: metadata); await state.SaveAsync(); Console.WriteLine($"Submitted order {order.Id}"); return(order.Id); }
async Task <bool> GetOrder(Guid id) { HTTPExtension ext = new HTTPExtension(); ext.Verb = HTTPVerb.Get; try { await _dapr.InvokeMethodAsync <object, Order>( "orderquery", id.ToString(), null, ext); return(true); } catch (Exception ex) { if (((Grpc.Core.RpcException)ex.InnerException).StatusCode == Grpc.Core.StatusCode.NotFound) { return(false); } //else ==> should handle the other cases or rely on retry policies of a service mesh } return(false); }
internal static async Task InvokeGrpcIncrementLoyaltyPointsAsync(DaprClient client) { Console.WriteLine("Invoking update to loyalty points"); // Initialize the payload for the request var incrementRequest = new IncrementRequest() { Id = 1, Points = 400 }; HTTPExtension httpExtension = new HTTPExtension() { Verb = HTTPVerb.Post }; // Make the service invocation request. // Pass in an increment request and expect back a payload that // represents the loyalty account. var account = await client.InvokeMethodAsync <IncrementRequest, LoyaltyAccount>("grpc-loyalty-service", "increment", incrementRequest, httpExtension); // Display the results Console.WriteLine("Updated points: {0}", account.TotalPoints); }
static internal async void StartValidationLoopAsync(int delayInSeconds) { const string SnapshotAppName = "snapshot"; TimeSpan delay = TimeSpan.FromSeconds(delayInSeconds); DaprClientBuilder daprClientBuilder = new DaprClientBuilder(); DaprClient client = daprClientBuilder.Build(); Dictionary <string, int> prevStats = null; Dictionary <string, int> stats = null; while (true) { Console.WriteLine("Checking stats in {0} seconds", delayInSeconds); await Task.Delay(delay); try { using (ServiceInvocationCallTime.NewTimer()) { HTTPExtension extension = new HTTPExtension() { Verb = HTTPVerb.Get }; stats = await client.InvokeMethodAsync <Dictionary <string, int> >(SnapshotAppName, "hashtagdata", extension); } } catch (Exception e) { Console.WriteLine("Caught {0}", e.ToString()); ServiceInvocationFailureCount.Inc(); continue; } // skip the calculation the first time if (prevStats != null) { int changed = 0; foreach (var kv in stats) { if (prevStats.ContainsKey(kv.Key) == false || prevStats[kv.Key] != kv.Value) { changed++; } } Console.WriteLine("Number changed is {0}", changed); if (changed == 0) { LogStats(prevStats, stats); UnchangedStatsMetric.IncTo(1); } else { UnchangedStatsMetric.IncTo(0); } } prevStats = stats; } }
private (Autogenerated.InvokeServiceRequest, CallOptions) MakeInvokeRequestAsync( string appId, string methodName, Any data, HTTPExtension httpExtension, CancellationToken cancellationToken = default) { var protoHTTPExtension = new Autogenerated.HTTPExtension(); var contentType = ""; Metadata headers = null; if (httpExtension != null) { protoHTTPExtension.Verb = ConvertHTTPVerb(httpExtension.Verb); if (httpExtension.QueryString != null) { foreach (var (key, value) in httpExtension.QueryString) { protoHTTPExtension.Querystring.Add(key, value); } } if (httpExtension.Headers != null) { headers = new Metadata(); foreach (var (key, value) in httpExtension.Headers) { headers.Add(key, value); } } contentType = httpExtension.ContentType ?? Constants.ContentTypeApplicationJson; } else { protoHTTPExtension.Verb = Autogenerated.HTTPExtension.Types.Verb.Post; contentType = Constants.ContentTypeApplicationJson; } var invokeRequest = new Autogenerated.InvokeRequest() { Method = methodName, Data = data, ContentType = contentType, HttpExtension = protoHTTPExtension }; var request = new Autogenerated.InvokeServiceRequest() { Id = appId, Message = invokeRequest, }; var callOptions = new CallOptions(headers: headers ?? new Metadata(), cancellationToken: cancellationToken); // add token for dapr api token based authentication var daprApiToken = Environment.GetEnvironmentVariable("DAPR_API_TOKEN"); if (daprApiToken != null) { callOptions.Headers.Add("dapr-api-token", daprApiToken); } return (request, callOptions); }