public static async Task Run( [ServiceBusTrigger("%TripRiderQueue%", Connection = "scooter.servicebusqueue.connection")] Message message, [DurableClient] IDurableEntityClient client, ILogger log) { log.LogInformation($"C# ServiceBus queue trigger function processed message: {message.MessageId}"); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, [DurableClient] IDurableEntityClient durableClient, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); using (StreamReader reader = new StreamReader(req.Body)) { var content = await reader.ReadToEndAsync(); var data = JObject.Parse(content); if (int.TryParse(data["value"].ToString(), out int value)) { if (!this.simpleValueValidator.Validate(value)) { return(new BadRequestObjectResult(new { msg = "value must be smaller than 1000" })); } var subscriptionName = data["subscriptionName"].ToString(); var entityId = new EntityId(Consts.ConsumptionActorName, subscriptionName); await durableClient.SignalEntityAsync(entityId, Consts.AddOperation, value); return(new OkResult()); } } return(new BadRequestResult()); }
public async Task <IActionResult> PostLocation( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "Locations/{id}")] HttpRequestMessage req, string id, [DurableClient] IDurableEntityClient entityClient ) { var command = await req.Content.ReadAsAsync <BeHostQuery>(); var entityId = new EntityId(nameof(PosadasAggregator), id); var locationEntityId = new EntityId(nameof(LocationAggregator), command.LocationName); var hostEntityId = new EntityId(nameof(HostAggregator), command.NameId); var posades = await entityClient.ReadEntityStateAsync <PosadasAggregator>(entityId); if (posades.EntityExists) { return(new ConflictResult()); } var host = await entityClient.ReadEntityStateAsync <HostAggregator>(hostEntityId); if (host.EntityExists is false) { await entityClient.SignalEntityAsync <IHostAggregator>(hostEntityId, proxy => proxy.Create(new CreateHostCommand("Pawel", "Haracz"))); } await entityClient.SignalEntityAsync <ILocationAggregator>(locationEntityId, proxy => proxy.Add(new AddLocationCommand(command.LocationName, 1.4, 16))); await entityClient.SignalEntityAsync <IPasadasAggregator>(entityId, proxy => proxy.Create(new CreatePasadasCommand(command.NameId, command.LocationName))); return(new CreatedResult("Locations", id)); }
public async Task <HttpResponseMessage> Get( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Service/{entityKey}")] HttpRequestMessage req, [DurableClient] IDurableEntityClient entityClient, string entityKey, ILogger log) { var entityId = new EntityId(nameof(ServiceAggregator), entityKey); var state = await entityClient.ReadEntityStateAsync <ServiceQuery>(entityId); if (state.EntityExists) { var json = JsonConvert.SerializeObject(state.EntityState, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }); return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, JsonMediaTypeFormatter.DefaultMediaType.ToString()) }); } return(req.CreateResponse(HttpStatusCode.NotFound)); }
public async Task <VoucherAuditStatus> ProcessAuditorApproval( [ActivityTrigger] IDurableActivityContext context, [DurableClient] IDurableEntityClient entityClient, ILogger log) { var data = context.GetInput <ProcessAuditorApprovalData>(); if (data.ApprovalEventData.Result) { await entityClient.SignalEntityAsync <IVoucherAudit>(data.EntityId, m => m.Approve(data.ApprovalEventData.Auditor)); } else { await entityClient.SignalEntityAsync <IVoucherAudit>(data.EntityId, m => m.Deny(data.ApprovalEventData.Auditor)); } var result = await entityClient.ReadEntityStateAsync <VoucherAudit>(data.EntityId); if (result.EntityState.Approvals.Count == result.EntityState.Auditors.Count()) { await entityClient.SignalEntityAsync <IVoucherAudit>(data.EntityId, m => m.SetStatus(VoucherAuditStatus.ApprovalCompleted)); } return(result.EntityState.Status); }
public static async Task <IActionResult> Create( [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "host/{ip}")] HttpRequest req, string ip, [DurableClient] IDurableEntityClient client, ILogger log) { try { IPAddress.Parse(ip); } catch { return(new BadRequestObjectResult(new { error = "Invalid ip address" })); } log.LogInformation("Adding {ipAddress} to bucket", ip); await client.SignalEntityAsync <IHostEntity>(HostEntity.Id(ip), entity => entity.SetIp(ip)); await client.SignalEntityAsync <IHostEntity>(HostEntity.Id(ip), entity => entity.CheckUp()); return(new OkResult()); }
public static async Task Run([CosmosDBTrigger( databaseName: "changefeedlabdatabase", collectionName: "changefeedlabcollection", ConnectionStringSetting = "DBconnection", LeaseCollectionName = "cartlease", CreateLeaseCollectionIfNotExists = true //,StartFromBeginning = true //For demo of reading event store )] IReadOnlyList <Document> input, [DurableClient] IDurableEntityClient entityClient, ILogger log) { // Iterate through modified documents from change feed. foreach (var doc in input) { var action = doc.GetPropertyValue <string>("Action"); log.LogInformation($"Cart action to process: {action}"); switch (action) { case "Purchased": await entityClient.SignalEntityAsync(createEntityId(doc), "purchased", null); break; case "Added": await entityClient.SignalEntityAsync(createEntityId(doc), "add", getItem(doc)); break; case "Removed": await entityClient.SignalEntityAsync(createEntityId(doc), "remove", getItem(doc)); break; } } }
public async Task ClearEntity( [ActivityTrigger] EntityId voucherAuditEntityId, [DurableClient] IDurableEntityClient entityClient, ILogger log) { await entityClient.SignalEntityAsync <IVoucherAudit>(voucherAuditEntityId, m => m.Clear()); }
public static async Task <HttpResponseMessage> OpenGiftRegistry( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "giftregistry/open")] HttpRequestMessage req, [DurableClient] IDurableEntityClient client, ILogger log) { log.LogInformation("C# HTTP trigger function - Open a gift registry"); var giftRegistryEntityId = new EntityId(nameof(GiftRegistryEntity), Guid.NewGuid().ToString()); var giftRegistryEntityAggregatorId = new EntityId(nameof(GiftRegistryEntityAggregator), "GiftRegistryAggregate"); await client.SignalEntityAsync(giftRegistryEntityId, "Open"); await client.SignalEntityAsync(giftRegistryEntityAggregatorId, "Open"); await client.SignalEntityAsync(giftRegistryEntityId, DateTime.UtcNow.AddMinutes(5), "Close"); await client.SignalEntityAsync(giftRegistryEntityAggregatorId, DateTime.UtcNow.AddMinutes(5), "Close"); // string name = req.Query["name"]; // string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); // dynamic data = JsonConvert.DeserializeObject(requestBody); // name = name ?? data?.name; return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(giftRegistryEntityId), Encoding.UTF8, "application/json") }); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, [DurableClient] IDurableEntityClient entityClient, ILogger log) { //Get cartid from http request string cartid = req.Query["CartId"]; var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); cartid = cartid ?? data?.CartId; if (cartid == null) { return(new BadRequestObjectResult("Please pass a cartid in the query string or in the request body (CartId:xxx)")); } //Read state of Cart Entity. State will give a Cart with a list of Items and a total amount EntityStateResponse <Cart> entityresult = await entityClient.ReadEntityStateAsync <Cart>(new EntityId("Cart", cartid)); if (entityresult.EntityExists) { //Create cart JSON Cart cart = entityresult.EntityState; dynamic cartAsJson = JsonConvert.SerializeObject(cart); return(new OkObjectResult(cartAsJson)); } return(new BadRequestObjectResult($"Someting went wrong reading cart: {cartid}")); }
public async Task <EntityId> CreateVoucherAudit( [ActivityTrigger] IDurableActivityContext context, [DurableClient] IDurableEntityClient entityClient, ILogger log) { var request = context.GetInput <StartVAWorkflowRequest>(); var voucherAuditEntityId = new EntityId(nameof(VoucherAudit), request.VoucherAuditId.ToString()); var result = await entityClient.ReadEntityStateAsync <VoucherAudit>(voucherAuditEntityId); if (result.EntityExists) { throw new ApplicationException($"Workflow for VoucherAudit '{request.VoucherAuditId}' already started."); } var workflowBaseData = new WorkflowBaseData() { InstanceId = context.InstanceId, Auditors = request.Auditors, VoucherAuditId = request.VoucherAuditId }; await entityClient.SignalEntityAsync <IVoucherAudit>(voucherAuditEntityId, m => m.Start(workflowBaseData)); await entityClient.SignalEntityAsync <IVoucherAudit>(voucherAuditEntityId, m => m.SetStatus(VoucherAuditStatus.Started)); return(voucherAuditEntityId); }
public async Task <IActionResult> RunPeek( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "peek")] HttpRequest req, [DurableClient] IDurableEntityClient client) { try { dynamic _data = await req.DeserializeRequest(); string _id = _data?.id ?? String.Empty; if (String.IsNullOrEmpty(_id)) { return(new BadRequestResult()); } var _registry = await client.ReadEntityStateAsync <GiftRegistry>(new EntityId(nameof(GiftRegistry), _id)); return(new OkObjectResult(_registry.EntityState)); } catch (Exception) { return(new StatusCodeResult(500)); } }
public async Task <IActionResult> RunAdd( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "add")] HttpRequest req, [DurableClient] IDurableEntityClient client) { try { dynamic _data = await req.DeserializeRequest(); string _item = _data?.item ?? String.Empty; string _id = _data?.id ?? String.Empty; if (String.IsNullOrEmpty(_item) || String.IsNullOrEmpty(_id)) { return(new BadRequestResult()); } var _registry = await client.ReadEntityStateAsync <GiftRegistry>(new EntityId(nameof(GiftRegistry), _id)); if (!_registry.EntityState.IsOpen) { return(new BadRequestObjectResult("Cannot add itms to a closed gift registry")); } await client.SignalEntityAsync <IGiftRegistry>(_id.ToString(), gr => gr.Add(_item)); return(new OkResult()); } catch (Exception) { return(new StatusCodeResult(500)); } }
public async Task <IActionResult> RunStats( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "stats")] HttpRequest req, [DurableClient] IDurableEntityClient client) { try { var _query = new EntityQuery { EntityName = nameof(GiftRegistry), FetchState = true }; var _result = await client.ListEntitiesAsync(_query, CancellationToken.None); var _statistics = new GiftRegistryStatistics { TotalRegistries = _result.Entities.Count(), TotalItems = _result.Entities.Sum(e => e.State["Items"].Count()) }; return(new OkObjectResult(_statistics)); } catch (Exception) { return(new StatusCodeResult(500)); } }
public async Task <AccessTokenWrapper> GetAuthTokenAsync(IDurableEntityClient client) { _logger.LogInformation($"Auth URL: {_options.PetfinderAPIAuthUrl}"); var entityId = new EntityId(nameof(AuthStateEntity), "petfinderauth"); var response = await client.ReadEntityStateAsync <AuthStateEntity>(entityId); AccessTokenWrapper accessToken; if (response.EntityExists) { _logger.LogInformation("Reading existing entity"); accessToken = await response.EntityState.Get(); } else { _logger.LogInformation("New authentication"); accessToken = await Authenticate(); } _logger.LogInformation($"Access Token Expiration - Expiration Time: {accessToken.ExpiresAtTime} - Expiration Duration: {accessToken.ExpiresInSeconds}"); if (AccessTokenIsInvalidOrExpired(accessToken)) { accessToken = await Authenticate(); } await client.SignalEntityAsync <IAuthStateEntity>(entityId, proxy => proxy.Set(accessToken)); return(accessToken); }
public static async Task <IActionResult> AddToGiftRegistry( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "giftregistry/add/{id}")] HttpRequest req, [DurableClient] IDurableEntityClient client, string id, ILogger log) { log.LogInformation("C# HTTP trigger function - Add entry to gift registry"); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); var text = data?.entry; var giftRegistryEntityId = new EntityId(nameof(GiftRegistryEntity), id); var giftRegistryEntityAggregatorId = new EntityId(nameof(GiftRegistryEntityAggregator), "GiftRegistryAggregate"); var state = await client.ReadEntityStateAsync <GiftRegistryEntity>(giftRegistryEntityId); if (state.EntityExists) { if (state.EntityState.State != GiftRegistryState.Open) { return(new BadRequestResult()); } await client.SignalEntityAsync(giftRegistryEntityId, "Add", text); await client.SignalEntityAsync(giftRegistryEntityAggregatorId, "Add"); return(new OkObjectResult("Entry added")); } return(new NotFoundObjectResult(giftRegistryEntityId)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "CatalogueScanState/Update")] CatalogueScanStateDto dto, [DurableClient] IDurableEntityClient durableEntityClient ) { #region null checks if (dto is null) { throw new ArgumentNullException(nameof(dto)); } if (durableEntityClient is null) { throw new ArgumentNullException(nameof(durableEntityClient)); } #endregion var entityId = ICatalogueScanState.CreateId(new CatalogueScanStateKey(dto.CatalogueType, dto.Store, dto.CatalogueId)); await durableEntityClient.SignalEntityAsync <ICatalogueScanState>( entityId, (scanState) => scanState.UpdateState(dto.ScanState) ).ConfigureAwait(false); return(new OkResult()); }
public static async Task <IActionResult> GetCarts( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "carts")] HttpRequest req, [DurableClient] IDurableEntityClient client) { var result = new List <ShoppingCartModel>(); var query = new EntityQuery() { PageSize = 100, FetchState = true }; do { var cartQuery = await client.ListEntitiesAsync(query, default); foreach (var cart in cartQuery.Entities) { var cartModel = cart.State.ToObject <ShoppingCartModel>(); cartModel.Id = cart.EntityId.EntityKey; result.Add(cartModel); } query.ContinuationToken = cartQuery.ContinuationToken; } while (query.ContinuationToken != null && query.ContinuationToken != "bnVsbA=="); return(new OkObjectResult(result)); }
public static async Task <IActionResult> Read( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "host/{ip}")] HttpRequest req, string ip, [DurableClient] IDurableEntityClient client, ILogger logger) { try { IPAddress.Parse(ip); } catch { return(new BadRequestResult()); } var entity = await client.ReadEntityStateAsync <HostEntity>(HostEntity.Id(ip)); if (!entity.EntityExists) { return(new NotFoundResult()); } return(new OkObjectResult(new { uptime = entity.EntityState.DnsUptime * 100m + "%", ipAddress = entity.EntityState.IpAddress, monitoringSince = entity.EntityState.MonitoringSince, ARecords = entity.EntityState.ipv4Support, isRecursive = true, isHandshake = (bool?)null })); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, [DurableClient] IDurableEntityClient client, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string runId = req.Query["runId"]; string operation = req.Query["operation"]; var entityId = new EntityId(nameof(AMLRun), runId); if (operation == "get") { log.LogInformation("operation get"); var theAMLRun = client.ReadEntityStateAsync <AMLRun>(entityId).Result; log.LogInformation("Status: {0}", theAMLRun.EntityState); return(new OkObjectResult(theAMLRun.EntityState is null ? false : theAMLRun.EntityState.Status)); } if (operation == "done") { log.LogInformation("operation done"); var result = client.SignalEntityAsync(entityId, "Done"); return(new OkObjectResult(true)); } return(new OkObjectResult(false)); }
public async Task <HttpResponseMessage> AddService( [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "Service/{entityKey}")] HttpRequestMessage req, [DurableClient] IDurableEntityClient entityClient, string entityKey, ILogger log) { var command = await req.Content.ReadAsAsync <CreateServiceCommand>(); if (command == null) { throw new ArgumentNullException(nameof(command)); } var entityId = new EntityId(nameof(ServiceAggregator), entityKey); var state = await entityClient.ReadEntityStateAsync <ServiceQuery>(entityId); if (state.EntityExists) { return(req.CreateResponse(HttpStatusCode.Conflict)); } await entityClient.SignalEntityAsync <IServiceAggregator>(entityId, proxy => proxy.Create(command)); await entityClient.SignalEntityAsync <IEntitiesAggregator>(new EntityId(nameof(EntitiesAggregator), EntitiesAggregator.EntityId), proxy => proxy.Add(entityKey)); return(req.CreateResponse(HttpStatusCode.Created)); }
public static async Task <IActionResult> GetLoanBalance( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "LoanBalance/{account}")] HttpRequest req, [DurableClient] IDurableEntityClient client, string account) { var entityId = new EntityId(nameof(Loan), account); var stateResponse = await client.ReadEntityStateAsync <Loan>(entityId); if (!stateResponse.EntityExists) { return(new NotFoundObjectResult($"There is no loan associated with {account}")); } ; var loan = stateResponse.EntityState as Loan; IActionResult result = new OkObjectResult( new { account = account, balance = loan.GetBalance().Result, transactions = loan.GetTransactionHistory().Result } ); return(result); }
public async Task CreateVoucherAudit( [ActivityTrigger] EntityId voucherAuditEntityId, [DurableClient] IDurableEntityClient entityClient, ILogger log) { await entityClient.SignalEntityAsync <IVoucherAudit>(voucherAuditEntityId, m => m.SetStatus(VoucherAuditStatus.InApproval)); }
public static Task <EntityStateResponse <HostEntity> > GetHostState( [ActivityTrigger] IDurableActivityContext context, [DurableClient] IDurableEntityClient client) { var hostId = context.GetInput <EntityId>(); return(client.ReadEntityStateAsync <HostEntity>(hostId)); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, [DurableClient] IDurableEntityClient durableEntityClient) { logger = log; LogInfo("Function Started.", string.Empty); // http client json string url = "https://mocki.io/v1/d569cadb-8f0b-4271-af06-84368787252d"; MyClass?response = await httpClient.GetFromJsonAsync <MyClass>(url); // durable entity var entityId = new EntityId(nameof(EntityExample), "myEntity1"); EntityStateResponse <EntityExample> stateResponse = await durableEntityClient.ReadEntityStateAsync <EntityExample>(entityId); if (!stateResponse.EntityExists) { LogInfo("Doesn't exist.", entityId.EntityKey); await durableEntityClient.SignalEntityAsync <IEntityExample>(entityId, e => e.SetName(response.Name)); // ... } else { LogInfo("Existing entry found.", entityId.EntityKey); EntityExample?myEntity = stateResponse.EntityState; string entityNameProperty = myEntity.Name; } return(new OkObjectResult($"Hello")); // or BadRequestObjectResult() }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "canoehealthcheck")] HttpRequestMessage req, [DurableClient] IDurableEntityClient client, ILogger log) { log.LogInformation("C# HTTP trigger function to return canoe health."); var entityId = new EntityId(nameof(CanoeHealth), "CanoeHealth"); await client.SignalEntityAsync(entityId, "SetStatus"); var state = await client.ReadEntityStateAsync <CanoeHealth>(entityId); if (state.EntityState.Health == CanoeHealthEnum.Ok) { log.LogInformation("Canoe health is Ok."); return(new OkObjectResult(state)); } else { log.LogError("A worker has cursed!"); // Track the Event var evt = new EventTelemetry("A worker has cursed!"); telemetryClient.TrackEvent(evt); return(new BadRequestResult()); } }
public async Task <IActionResult> GetLocations( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Locations")] HttpRequestMessage req, [DurableClient] IDurableEntityClient entityClient, ILogger log ) { var entityId = new EntityId(nameof(PosadasAllAggregatorAggregator), PosadasAllAggregatorAggregator.EntityId); var aggregator = await entityClient.ReadEntityStateAsync <PosadasAllAggregatorAggregator>(entityId); if (aggregator.EntityExists is false) { return(new NotFoundResult()); } var @return = new List <LocationDetailQuery>(); foreach (var id in aggregator.EntityState.EntityIds) { var query = await GetLocationDetailQuery(entityClient, id); if (query == default) { continue; } @return.Add(query); } return(new OkObjectResult(@return)); }
public TestEntityClient( IDurableEntityClient innerClient, EntityId entityId) { this.InnerClient = innerClient ?? throw new ArgumentNullException(nameof(innerClient)); this.entityId = entityId; }
private async ValueTask <LocationDetailQuery> GetLocationDetailQuery(IDurableEntityClient entityClient, string id) { var pasada = await entityClient.ReadEntityStateAsync <PosadasAggregator>(new EntityId(nameof(PosadasAggregator), id)); if (pasada.EntityExists is false) { return(default);
public async Task <HttpResponseMessage> HttpStart( [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestMessage req, [DurableClient] IDurableOrchestrationClient starter, [DurableClient] IDurableEntityClient entityClient) { string requestBody = await req.Content.ReadAsStringAsync(); var person = JsonConvert.DeserializeObject <Person>(requestBody); var storageEntityId = StorageEntity.BuildId(nameof(Person), person.Id); // can read the entity state var entity = await entityClient.ReadEntityStateAsync <StorageEntity>(storageEntityId); if (entity.EntityExists) { _log.Trace(LogEventLevel.Information, message: $"Person was last updated {entity.EntityState.LastUpdated}"); } // can signal entities, but can't wait for response - only in Orchestrations await entityClient.SignalEntityAsync(storageEntityId, nameof(StorageEntity.NotifyUpdated), DateTime.UtcNow); // can use DateTime.UtcNow here, we're not in an orchestration string instanceId = await starter.StartNewAsync(nameof(EntityOrchestrator), person); _log.Exit(LogEventLevel.Information, returnValue: instanceId, message: $"Starting {instanceId}"); return(starter.CreateCheckStatusResponse(req, instanceId)); }