public async Task <ActionResult> TestPostAsync([FromServices] DaprClient daprClient) { this.logger.LogInformation("POST!!"); var r = await daprClient.GetStateEntryAsync <int>(StoreName, "key"); r.Value++; await r.SaveAsync(); return(Ok()); }
internal static async Task PublishEventAsync(DaprClient client) { var eventData = new Widget() { Size = "small", Color = "yellow", }; await client.PublishEventAsync("TopicA", eventData); Console.WriteLine("Published Event!"); }
public DaprStoresGateway(ILogger <DaprStoresGateway> logger, DaprClient daprClient, IConfiguration configuration) { _logger = logger; _daprClient = daprClient; _configuration = configuration; StoreAppId = configuration.GetValue <string>("IDENTITY_AUDIENCE"); logger.LogInformation($"Begin to log dapr :{StoreAppId} "); }
internal static async Task SaveStateAsync(DaprClient client) { var state = new Widget() { Size = "small", Color = "yellow", }; await client.SaveStateAsync(storeName, stateKeyName, state); Console.WriteLine("Saved State!"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton <IFineCalculator, HardCodedFineCalculator>(); services.AddSingleton <VehicleRegistrationService>( _ => new VehicleRegistrationService( DaprClient.CreateInvokeHttpClient("vehicleregistrationservice"))); services.AddControllers().AddDapr(); }
public async Task <ActionResult <OrderResponse> > Order(List <Item> items, [FromServices] DaprClient daprClient) { _logger.LogDebug("Enter Order"); // TODO: Process Order _logger.LogInformation($"Received an order with {items.Count} items."); await SendEmail(items, daprClient); return(new OrderResponse()); }
public async Task <IActionResult> App2Get([FromServices] DaprClient daprClient) { var ext = new Dapr.Client.Http.HTTPExtension() { Verb = Dapr.Client.Http.HTTPVerb.Get, }; var status = await daprClient.InvokeMethodAsync <object>("app2", "health", ext); return(Ok(status)); }
public async Task <IActionResult> Remove(string id, [FromServices] DaprClient daprClient) { var state = await daprClient.GetStateEntryAsync <List <Item> >(StoreName, _userId); int index = state.Value.FindIndex(i => i.Product.Id == id); state.Value.RemoveAt(index); await state.SaveAsync(); return(RedirectToAction("Index")); }
public async Task <ActionResult> PubPostAsync([FromServices] DaprClient daprClient) { this.logger.LogInformation("PUB Start"); foreach (var e in Enumerable.Range(0, 20)) { await daprClient.PublishEventAsync("sample", e); } this.logger.LogInformation("PUB End"); return(Ok()); }
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)); }
/// <summary> /// Creates a new instance of <see cref="DaprSecretStoreConfigurationProvider"/>. /// </summary> /// <param name="store">Dapr Secre Store name.</param> /// <param name="normalizeKey">Indicates whether any key delimiters should be replaced with the delimiter ":".</param> /// <param name="keyDelimiters">A collection of delimiters that will be replaced by ':' in the key of every secret.</param> /// <param name="metadata">A collection of metadata key-value pairs that will be provided to the secret store. The valid metadata keys and values are determined by the type of secret store used.</param> /// <param name="client">Dapr client used to retrieve Secrets</param> public DaprSecretStoreConfigurationProvider(string store, bool normalizeKey, IList <string> keyDelimiters, IReadOnlyDictionary <string, string> metadata, DaprClient client) { ArgumentVerifier.ThrowIfNullOrEmpty(store, nameof(store)); ArgumentVerifier.ThrowIfNull(client, nameof(client)); this.store = store; this.normalizeKey = normalizeKey; this.keyDelimiters = keyDelimiters; this.metadata = metadata; this.client = client; }
public AuthenticationManager(UserManager <IdentityUser> userManager, SignInManager <IdentityUser> signInManager, DaprClient daprClient, IConfiguration configuration, TokenValidationParameters validationParameters, FarmerzonAuthenticationContext context) { UserManager = userManager; SignInManager = signInManager; DaprClient = daprClient; Configuration = configuration; ValidationParameters = validationParameters; Context = context; }
public TenantStore( ILogger <TenantStore> logger, IStringLocalizer <TenantFrameworkResource> sl, DaprClient daprClient, TenantCacheService tenantCacheService) { _logger = logger; _sl = sl; _daprClient = daprClient; _tenantCacheService = tenantCacheService; }
public async Task <ActionResult <Customer> > Create(Customer customer, [FromServices] DaprClient daprClient) { logger.LogDebug("Enter new Customer"); var state = await daprClient.GetStateEntryAsync <Customer>(StoreName, customer.Id); state.Value ??= customer; state.Value.Name = customer.Name; await state.SaveAsync(); return(state.Value); }
public async Task TestGrpcProxyMessageSendAndReceive() { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(20)); var invoker = DaprClient.CreateInvocationInvoker(appId: this.AppId, daprEndpoint: this.GrpcEndpoint); var client = new Messager.MessagerClient(invoker); await client.SendMessageAsync(new SendMessageRequest { Recipient = "Client", Message = "Hello" }, cancellationToken : cts.Token); var response = await client.GetMessageAsync(new GetMessageRequest { Recipient = "Client" }, cancellationToken : cts.Token); Assert.Equal("Hello", response.Message); }
/// <summary> /// This example shows how to invoke a method on a service listening on gRPC. /// </summary> /// <param name="client"></param> /// <returns></returns> internal static async Task InvokeMethodOnGrpcServiceAsync(DaprClient client) { MyData data = new MyData() { Message = "mydata" }; // invokes a method named "hello" that takes input of type "MyData" and returns a string. string s = await client.InvokeMethodAsync <MyData, string>("nodeapp", "hello", data); Console.WriteLine("received {0}", s); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WeatherForecastProxyService", Version = "v1" }); }); services.AddSingleton <IWeatherForecastClient, WeatherForecastClient>( _ => new WeatherForecastClient(DaprClient.CreateInvokeHttpClient("backend"))); }
///<inheritdoc/> public override async Task PublishAsync <TIntegrationEvent>( TIntegrationEvent @event, string topic = null, string prefix = null) { if (@event is null) { throw new ArgumentNullException(nameof(@event)); } var topicName = GetTopicName(@event.GetType(), topic, prefix); await DaprClient.PublishEventAsync(DaprEventBusOptions.Value.PubSubName, topicName, @event); }
public static DaprClient MakeDaprProxy() { if (m_DaprProxy == null) { DaprClient daprProxy = new DaprClientBuilder() .UseJsonSerializationOptions(JsonConfig.MakeJsonSerializerOptions()) .Build(); m_DaprProxy = daprProxy; } return(m_DaprProxy); }
public static async Task StateTransactionSliceAsync(this DaprClient client, string storeName, string streamHeadKey, StreamHead head, string headetag, Dictionary <string, string> meta, EventData[] versionedEvents, string sliceKey, string sliceetag) { var sliceReq = new StateTransactionRequest(sliceKey, JsonSerializer.SerializeToUtf8Bytes(versionedEvents), Client.StateOperationType.Upsert, string.IsNullOrWhiteSpace(sliceetag) ? null : sliceetag, metadata: meta); var headReq = new StateTransactionRequest(streamHeadKey, JsonSerializer.SerializeToUtf8Bytes(head), Client.StateOperationType.Upsert, etag: string.IsNullOrWhiteSpace(headetag) ? null : headetag, metadata: meta); var reqs = new List <StateTransactionRequest> { sliceReq, headReq }; await client.ExecuteStateTransactionAsync(storeName, reqs, meta); }
public VideoIndexerController(IBackgroundTaskQueue queue, [FromServices] DaprClient daprClient, ILogger <VideoIndexerController> logger, IConfiguration configuration) { _queue = queue; _daprClient = daprClient; _logger = logger; _configuration = configuration; apiUrl = _configuration["VIDEO_API_URL"]; }
/// <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) { // Add the verb to metadata if the method is other than a POST var metaData = new Dictionary <string, string>(); metaData.Add("http.verb", "GET"); // Invokes a GET method named "hello" that takes input of type "MyData" and returns a string. var res = await client.InvokeMethodAsync <object>("routing", "17", metaData); Console.WriteLine($"Received balance {res}"); }
public virtual async Task <T?> GetCacheAsync(DaprClient daprClient, string cacheKey) { var state = await daprClient.GetStateEntryAsync <StateData <T>?>(ConfigConstant.CodexStoreName, cacheKey); if (state.Value == null || IsExpiredCache(state.Value)) { if (state.Value != null) { await daprClient.DeleteStateAsync(ConfigConstant.CodexStoreName, cacheKey); } return(default);
public static async Task <Tenant> SearchTenantByIdAsync( ILogger logger, IStringLocalizer <TenantFrameworkResource> sl, TenantCacheService tenantCacheService, DaprClient daprClient, string tenantId) { try { string cacheKey = $"{CacheConstant.Tenant_}{tenantId}"; var tenant = await tenantCacheService.GetCacheAsync(daprClient, cacheKey); if (tenant == null) { var secretValues = await daprClient.GetSecretAsync(ConfigConstant.CodexKey, ConfigConstant.MicroserviceApiKey); var microserviceApiKey = secretValues[ConfigConstant.MicroserviceApiKey]; tenant = await daprClient.InvokeMethodAsync <Tenant>(ApiNameConstant.TenantApi, $"Tenant/{tenantId}", new HTTPExtension() { Verb = HTTPVerb.Get, Headers = { { HttpHeaderConstant.TenantId, tenantId }, { HttpHeaderConstant.ApiKey, $"{tenantId}.{microserviceApiKey}" } } } ); await tenantCacheService.UpdateCacheAsync(daprClient, cacheKey, tenant); return(tenant); } else { return(tenant); } } catch (Exception exception) { if (exception is Grpc.Core.RpcException rpcException && rpcException.Status.StatusCode == Grpc.Core.StatusCode.NotFound) { logger.LogInformation(rpcException, $"Tenant not found : '{tenantId}'"); throw new InvalidTenantIdException($"{sl[TenantFrameworkResource.TENANT_NOT_FOUND]!} : '{tenantId}'", "TENANT_NOT_FOUND"); } logger.LogError(exception, $"Unable to find Tenant {tenantId}"); throw new TechnicalException($"{sl[TenantFrameworkResource.TENANT_NOT_FOUND]!} : '{tenantId}'", "TENANT_NOT_FOUND"); } }
/// <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}"); }
internal static async Task GetStateAsync(DaprClient client) { var state = await client.GetStateAsync <Widget>(storeName, stateKeyName); if (state == null) { Console.WriteLine("State not found in store"); } else { Console.WriteLine($"Got State: {state.Size} {state.Color}"); } }
public async Task <ActionResult> GetSecret(string secretName, [FromServices] DaprClient daprClient) { var secretValues = await daprClient.GetSecretAsync( "azurekeyvault", "daprsecret"); //, new Dictionary<string, string>() { { "namespace", "default" } }); // Namespace where Kubernetes secret is deployed // Get secret value. In Azure KeyVault secret only has one value with same key var secretValue = secretValues["daprsecret"]; return(new JsonResult(secretValue)); }
/// <summary> /// Initializes a new instance of the <see cref="StateEntry{TValue}"/> class. /// </summary> /// <param name="client">The <see cref="DaprClient" /> instance used to retrieve the value.</param> /// <param name="storeName">The name of the state store.</param> /// <param name="key">The state key.</param> /// <param name="value">The value.</param> /// <param name="etag">The ETag.</param> /// <remarks> /// Application code should not need to create instances of <see cref="StateEntry{T}" />. Use /// <see cref="DaprClient.GetStateEntryAsync{TValue}(string, string, ConsistencyMode?, CancellationToken)" /> to access /// state entries. /// </remarks> public StateEntry(DaprClient client, string storeName, string key, TValue value, string etag) { ArgumentVerifier.ThrowIfNull(client, nameof(client)); ArgumentVerifier.ThrowIfNullOrEmpty(storeName, nameof(storeName)); ArgumentVerifier.ThrowIfNullOrEmpty(key, nameof(key)); this.StoreName = storeName; this.Key = key; this.Value = value; this.client = client; this.ETag = etag; }
public async Task <ActionResult <Account> > Deposit(Transaction transaction, [FromServices] DaprClient daprClient) { var state = await daprClient.GetStateEntryAsync <Account>(StoreName, transaction.Id); state.Value ??= new Account() { Id = transaction.Id, }; state.Value.Balance += transaction.Amount; await state.SaveAsync(); return(state.Value); }
internal static async Task InvokeGrpcDepositServiceOperationAsync(DaprClient client) { Console.WriteLine("Invoking grpc deposit"); var data = new { id = "17", amount = (decimal)99 }; Console.WriteLine("invoking"); var a = await client.InvokeMethodAsync <object, Account>("grpcsample", "deposit", data, new HttpInvocationOptions()); Console.WriteLine("Returned: id:{0} | Balance:{1}", a.Id, a.Balance); Console.WriteLine("Completed grpc deposit"); }