public static async Task <ICommandResult> RunActivity( [ActivityTrigger] IDurableActivityContext functionContext, [DurableClient] IDurableClient durableClient) { if (functionContext is null) { throw new ArgumentNullException(nameof(functionContext)); } if (durableClient is null) { throw new ArgumentNullException(nameof(durableClient)); } var(commandResult, instanceId) = functionContext.GetInput <(ICommandResult, string)>(); try { var commandStatus = await durableClient .GetStatusAsync(instanceId) .ConfigureAwait(false); return(commandResult .ApplyStatus(commandStatus)); } catch (Exception exc) when(!exc.IsSerializable(out var serializableExc)) { throw serializableExc; } } }
public async Task <IEnumerable <IEnumerable <ProviderDocument> > > RunActivity( [ActivityTrigger] IDurableActivityContext functionContext) { if (functionContext is null) { throw new ArgumentNullException(nameof(functionContext)); } var project = functionContext.GetInput <ProjectDocument>(); if (project is null) { var providers = await providersRepository .ListAsync() .ToListAsync() .ConfigureAwait(false); return(Enumerable.Repeat(providers, 1)); } else { var providers = await providersRepository .ListAsync(project.Type.Providers.Select(p => p.Id)) .ToListAsync() .ConfigureAwait(false); return(project.Type.Providers.Resolve(providers)); } }
public static async Task <string> RunActivity( [ActivityTrigger] IDurableActivityContext functionContext) { if (functionContext is null) { throw new ArgumentNullException(nameof(functionContext)); } var(instanceId, command) = functionContext.GetInput <(string, ICommand)>(); try { var callbackUrl = await CallbackTrigger .AcquireCallbackUrlAsync(instanceId, command) .ConfigureAwait(false); return(callbackUrl); } catch (Exception exc) when(!exc.IsSerializable(out var serializableExc)) { throw serializableExc; } } }
public static long GetFileSize([ActivityTrigger] IDurableActivityContext ctx) { string fileName = ctx.GetInput <string>(); var info = new FileInfo(fileName); return(info.Length); }
public async Task RunActivity( [ActivityTrigger] IDurableActivityContext activityContext, ILogger log) { if (activityContext == null) { throw new ArgumentNullException(nameof(activityContext)); } var project = activityContext.GetInput <ProjectDocument>(); if (!string.IsNullOrEmpty(project.ResourceGroup?.Id)) { var resourceGroup = await azureResourceService .GetResourceGroupAsync(project.ResourceGroup.SubscriptionId, project.ResourceGroup.Name) .ConfigureAwait(false); if (resourceGroup is null) { log.LogWarning($"Could not find resource group '{project.ResourceGroup.Name}' in subscription '{project.ResourceGroup.SubscriptionId}' for tagging."); } else { await resourceGroup .SetTagsAsync(project.Tags) .ConfigureAwait(false); } } }
public static string SayHello([ActivityTrigger] IDurableActivityContext context, ILogger log) { var name = context.GetInput <string>(); log.LogInformation($"Saying hello to {name}."); return($"Hello {name}!"); }
public async Task <IEnumerable <string> > RunActivity( [ActivityTrigger] IDurableActivityContext activityContext, ILogger log) { if (activityContext is null) { throw new ArgumentNullException(nameof(activityContext)); } var resourceId = activityContext.GetInput <string>(); try { var deployment = await azureDeploymentService .GetAzureDeploymentAsync(resourceId) .ConfigureAwait(false); if (deployment is null) { throw new NullReferenceException($"Could not find deployment by resource id '{resourceId}'"); } return(await deployment .GetErrorsAsync() .ConfigureAwait(false)); } catch (Exception exc) { log?.LogError(exc, $"Activity {nameof(AzureDeploymentErrorsActivity)} failed: {exc.Message}"); throw exc.AsSerializable(); } }
public static async Task <ICommandResult> RunActivity( [ActivityTrigger] IDurableActivityContext activityContext, [DurableClient] IDurableClient durableClient, ILogger log) { if (activityContext is null) { throw new ArgumentNullException(nameof(activityContext)); } if (durableClient is null) { throw new ArgumentNullException(nameof(durableClient)); } var commandResult = activityContext.GetInput <ICommandResult>(); try { var commandStatus = await durableClient .GetStatusAsync(commandResult.CommandId.ToString()) .ConfigureAwait(false); if (commandStatus != null) { commandResult.ApplyStatus(commandStatus); } } catch (Exception exc) { log?.LogWarning(exc, $"Failed to augment command result with orchestration status {commandResult.CommandId}: {exc.Message}"); } return(commandResult); }
public static async Task <List <int> > GetUsersForBatchUseCase( [ActivityTrigger] IDurableActivityContext context) { var activity = context.GetInput <CustomerCommunicationUseCase>(); string queryFilename = activity.Parameters.First(p => p.Key == "SQL").Value; string query; var storageConnectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage"); // Connect to the storage account's blob endpoint CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient client = account.CreateCloudBlobClient(); // Create the blob storage container CloudBlobContainer container = client.GetContainerReference("queries"); // Create the blob in the container var blob = container.GetBlockBlobReference(queryFilename); query = await blob.DownloadTextAsync(); var connectionString = Environment.GetEnvironmentVariable("HUB_CONNECTION_STRING"); using (var connection = new SqlConnection(connectionString)) { return((List <int>) await connection.QueryAsync <int>(query)); } }
public static async Task <List <string> > Run( [ActivityTrigger] IDurableActivityContext context, [Inject] IGitHubApiService gitHubApiService, ILogger log) { return(await gitHubApiService.GetUserRepositoryList()); }
public async Task <IEnumerable <SecurityBot.Model.Issue> > GetIssuesAsync( [ActivityTrigger] IDurableActivityContext context, ILogger logger) { var decorationContext = context.GetInput <DecoratorContext>(); var searchIssue = await _repository.GetIssues(decorationContext.PullRequestId, decorationContext.Tag.GetValueOrDefault(SonarCloudConfiguration.ProjectKey)); var issues = new List <Issue>(); foreach (var issue in searchIssue.issues) { var projectKey = decorationContext.Tag.GetValueOrDefault(SonarCloudConfiguration.ProjectKey); var path = issue.component.Replace($"{projectKey}:", ""); var newIssue = new Issue() { Id = issue.key, Type = issue.type, Message = issue.message, Url = $"https://sonarcloud.io/project/issues?id={projectKey}&open={issue.key}&pullRequest={decorationContext.PullRequestId}&resolved=false", Provider = SonarCloudConfiguration.ProviderName }; newIssue.Path = path != projectKey ? path : null; issues.Add(newIssue); } return(issues); }
public async Task <JObject> CreatePRReviewCommentAsync( [ActivityTrigger] IDurableActivityContext context) { var issueContext = context.GetInput <Tuple <CIContext, PullRequestLibrary.Generated.SonarCloud.SearchIssue.Issue> >(); var cIContext = issueContext.Item1; var issue = issueContext.Item2; var path = issue.component.Replace($"{cIContext.ProjectKey}:", ""); if (path != cIContext.ProjectKey) { PullRequestReviewComment result = await _gitHubRepository.CreatePullRequestReviewComment( new PullRequestLibrary.Model.Comment { Body = $"**{issue.type}**\n> {issue.message}\n See [details](https://sonarcloud.io/project/issues?id={cIContext.ProjectKey}&open={issue.key}&pullRequest={cIContext.PullRequestId}&resolved=false)", RepositoryOnwer = _repositoryContext.Owner, RepositoryName = _repositoryContext.Name, CommitId = cIContext.CommitId, Path = path, Position = 5, PullRequestId = cIContext.PullRequestId }); var json = JsonConvert.SerializeObject(result); return(JObject.Parse(json)); } return(null); }
public static async Task <string> RunActivity( [ActivityTrigger] IDurableActivityContext functionContext, ILogger log) { if (functionContext is null) { throw new ArgumentNullException(nameof(functionContext)); } var(instanceId, command) = functionContext.GetInput <(string, ICommand)>(); using (log.BeginCommandScope(command)) { try { log.LogInformation($"Acquire callback url for instance '{instanceId}' of command {command.GetType().Name} ({command.CommandId})"); var callbackUrl = await CallbackTrigger .GetUrlAsync(instanceId, command) .ConfigureAwait(false); return(callbackUrl); } catch (Exception exc) { log.LogError(exc, $"Failed to acquire callback url for instance '{instanceId}' of command {command.GetType().Name} ({command.CommandId}): {exc.Message}"); throw exc.AsSerializable(); } } }
public string MyActivityOne([ActivityTrigger] IDurableActivityContext context, ILogger log) { BeginRequestData beginRequestData = context.GetInput <BeginRequestData>(); log.LogInformation($"Activity {Constants.MyActivityOne} {beginRequestData.Id} {_myConfiguration.Name} {_myConfigurationSecrets.MySecretOne} amount of retries: {_myConfiguration.AmountOfRetries}."); return($"{Constants.MyActivityOne} {beginRequestData.Id} {_myConfiguration.Name} {_myConfigurationSecrets.MySecretOne} amount of retries: {_myConfiguration.AmountOfRetries}."); }
public async Task <AzureDeploymentState> RunActivity( [ActivityTrigger] IDurableActivityContext functionContext, ILogger log) { if (functionContext is null) { throw new ArgumentNullException(nameof(functionContext)); } var resourceId = functionContext.GetInput <string>(); try { var deployment = await azureDeploymentService .GetAzureDeploymentAsync(resourceId) .ConfigureAwait(false); if (deployment is null) { throw new NullReferenceException($"Could not find deployment by resource id '{resourceId}'"); } return(await deployment .GetStateAsync() .ConfigureAwait(false)); } catch (Exception exc) when(!exc.IsSerializable(out var serializableException)) { log.LogError(exc, $"Activity {nameof(AzureDeploymentStateActivity)} failed: {exc.Message}"); throw serializableException; } } }
public async Task <bool> Run( [ActivityTrigger] IDurableActivityContext context, ILogger log) { if (context is null) { throw new ArgumentNullException(nameof(context)); } var component = context.GetInput <Input>().Component; try { var results = await Task.WhenAll( GuardOrganizationAsync(component), GuardProjectAsync(component) ).ConfigureAwait(false); return(results.All(r => r)); } catch (Exception exc) { log.LogError(exc, $"Guard evaluation for component {component.Id} ({component.Slug}) in project {component.ProjectId} failed: {exc.Message}"); throw exc.AsSerializable(); } }
public async Task RunActivity( [ActivityTrigger] IDurableActivityContext functionContext, ILogger log) { if (functionContext is null) { throw new ArgumentNullException(nameof(functionContext)); } var(project, resourceId) = functionContext.GetInput <(Project, string)>(); using (log.BeginProjectScope(project)) { try { var resource = await azureResourceService .GetResourceAsync(resourceId, throwIfNotExists : true) .ConfigureAwait(false); await resource .SetTagsAsync(project.Tags) .ConfigureAwait(false); } catch (Exception exc) { log.LogError(exc, $"{nameof(ProjectResourceTagsActivity)} failed: {exc.Message}"); throw exc.AsSerializable(); } } }
public async Task RunActivity( [ActivityTrigger] IDurableActivityContext functionContext) { if (functionContext is null) { throw new ArgumentNullException(nameof(functionContext)); } var project = functionContext.GetInput <Project>(); var keyVault = await azureResourceService .GetResourceAsync <AzureKeyVaultResource>(project.KeyVault.VaultId, throwIfNotExists : true) .ConfigureAwait(false); var projectIdentityJson = await keyVault .GetSecretAsync(nameof(ProjectIdentity)) .ConfigureAwait(false); if (!string.IsNullOrEmpty(projectIdentityJson)) { await azureDirectoryService .DeleteServicePrincipalAsync(project.Id.ToString()) .ConfigureAwait(false); } await keyVault .SetSecretAsync(nameof(ProjectIdentity), null) .ConfigureAwait(false); }
public static async Task NotifyParticipants( [ActivityTrigger] IDurableActivityContext context, [SignalR(HubName = SignalRHubName)] IAsyncCollector <SignalRMessage> signalRMessages, ILogger log) { string appointmentId = context.InstanceId; var appointment = context.GetInput <Appointment>(); var nickNames = appointment.Participants.ToArray(); foreach (string nickName in nickNames) { var signalRMessage = new SignalRMessage { UserId = nickName, Target = "appointment-state-changed", Arguments = new[] { new { id = appointmentId, participants = nickNames, status = appointment.Status } } }; await signalRMessages.AddAsync(signalRMessage); } }
public static Task <Invoice[]> Run( [ActivityTrigger] IDurableActivityContext context, ILogger logger) { logger.LogInformation("Gathering invoices..."); // Random Belgian companies from Forbes 2019 return(Task.FromResult(new[] { new Invoice { Id = 1, ClientName = "Dexia" }, new Invoice { Id = 2, ClientName = "Umicore" }, new Invoice { Id = 3, ClientName = "Colruyt Group" }, new Invoice { Id = 4, ClientName = "Proximus Group" }, new Invoice { Id = 5, ClientName = "Aveve" }, new Invoice { Id = 6, ClientName = "Kinepolis" } })); }
public static string[] GetFileList([ActivityTrigger] IDurableActivityContext ctx) { string directory = ctx.GetInput <string>(); string[] files = Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly); return(files); }
public string MyActivityOne([ActivityTrigger] IDurableActivityContext context, ILogger log) { string name = context.GetInput <string>(); log.LogInformation($"Activity {Constants.MyActivityOne} {name} {_myConfiguration.Name} {_myConfigurationSecrets.MySecretOne} amount of retries: {_myConfiguration.AmountOfRetries}."); return($"{Constants.MyActivityOne} {name} {_myConfiguration.Name} {_myConfigurationSecrets.MySecretOne} amount of retries: {_myConfiguration.AmountOfRetries}."); }
public async Task RunActivity( [ActivityTrigger] IDurableActivityContext functionContext, ILogger log) { if (functionContext is null) { throw new ArgumentNullException(nameof(functionContext)); } var resourceId = functionContext.GetInput <string>(); try { var deployment = await azureDeploymentService .GetAzureDeploymentAsync(resourceId) .ConfigureAwait(false); await(deployment?.DeleteAsync() ?? Task.CompletedTask) .ConfigureAwait(false); } catch (Exception exc) { log?.LogError(exc, $"Activity {nameof(AzureDeploymentDeleteActivity)} failed: {exc.Message}"); throw exc.AsSerializable(); } }
public string MyActivityTwo([ActivityTrigger] IDurableActivityContext context, ILogger log) { string name = context.GetInput <string>(); log.LogInformation($"Activity {Constants.MyActivityTwo} {name} {_myConfiguration.Name}."); return($"{Constants.MyActivityTwo} {name} {_myConfiguration.Name}!"); }
public async Task RunActivity( [ActivityTrigger] IDurableActivityContext activityContext, ILogger log) { if (activityContext is null) { throw new ArgumentNullException(nameof(activityContext)); } var resourceId = activityContext.GetInput <string>(); try { var resource = await azureResourceService .GetResourceAsync(resourceId) .ConfigureAwait(false); await(resource?.DeleteAsync(true) ?? Task.CompletedTask) .ConfigureAwait(false); } catch (Exception exc) { log.LogError(exc, $"Activity '{nameof(ResourceDeleteActivity)} failed: {exc.Message}"); throw exc.AsSerializable(); } }
public static async Task <DateTime> GetDateFromMessage([ActivityTrigger] IDurableActivityContext context, ILogger log) { var message = context.GetInput <string>(); var client = HttpClientFactory.Create(); var response = await client.GetAsync(string.Concat(Environment.GetEnvironmentVariable("LUISEndpoint"), message)); if (!response.IsSuccessStatusCode) { throw new Exception(await response.Content.ReadAsStringAsync()); } var luisResponse = await response.Content.ReadAsAsync <LuisResponse>(); var dateEntity = luisResponse.Entities.FirstOrDefault(x => x.Type == "builtin.datetimeV2.date" || x.Type == "builtin.datetimeV2.datetime"); if (dateEntity != null && DateTime.TryParse(dateEntity.Resolution.Values?.First()?.Value, out DateTime date)) { return(new DateTime(date.Ticks, DateTimeKind.Utc));; } dateEntity = luisResponse.Entities.FirstOrDefault(x => x.Type == "builtin.datetimeV2.duration"); if (dateEntity != null && Int32.TryParse(dateEntity.Resolution.Values?.First()?.Value, out int seconds)) { return(DateTime.UtcNow.AddSeconds(seconds)); } dateEntity = luisResponse.Entities.FirstOrDefault(x => x.Type == "builtin.datetimeV2.datetimerange"); if (dateEntity != null && DateTime.TryParse(dateEntity.Resolution.Values?.First()?.Start, out DateTime start) && DateTime.TryParse(dateEntity.Resolution.Values?.First()?.End, out DateTime end)) { return(new DateTime(start.AddSeconds(((end - start).TotalSeconds / 2)).Ticks, DateTimeKind.Utc)); } return(DateTime.UtcNow); }
public static async Task RunActivity( [ActivityTrigger] IDurableActivityContext functionContext) { if (functionContext is null) { throw new ArgumentNullException(nameof(functionContext)); } var(key, value) = functionContext.GetInput <(string, string)>(); var appSettings = await FunctionsEnvironment .GetAppSettingsAsync() .ConfigureAwait(false); if (value is null) { appSettings.Remove(key); } else if (!appSettings.TryGetValue(key, out var existingValue) || existingValue != value) { appSettings[key] = value; } else { return; // app settings unmodified - no need to send an update } _ = await FunctionsEnvironment .SetAppSettingsAsync(appSettings) .ConfigureAwait(false); }
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 async Task RunActivity( [ActivityTrigger] IDurableActivityContext functionContext) { if (functionContext is null) { throw new ArgumentNullException(nameof(functionContext)); } var(projectId, principalId) = functionContext.GetInput <(string, Guid)>(); var project = await projectsRepository .GetAsync(projectId) .ConfigureAwait(false); if (project is null) { throw new RetryCanceledException($"Could not find project '{projectId}'"); } if (!string.IsNullOrEmpty(project.ResourceGroup?.Id)) { await EnsureResourceGroupAccessAsync(project, principalId).ConfigureAwait(false); } if (!string.IsNullOrEmpty(project.KeyVault?.VaultId)) { await EnsureKeyVaultAccessAsync(project, principalId).ConfigureAwait(false); } }
public async Task <bool> SendSignalRMessage( [ActivityTrigger] IDurableActivityContext context, [SignalR(HubName = HUB_NAME)] IAsyncCollector <SignalRMessage> signalRMessages) { var(claims, content, messageType) = context.GetInput <(Dictionary <string, string>, string, string)>(); claims.TryGetValue("userID", out var userID); if (string.IsNullOrEmpty(userID)) { _logger.LogError($"There was an error getting the user identifier"); return(false); } var signalRMessage = new SendSignalRMessageActivityResponse() { MessageType = messageType, Content = content }; await signalRMessages.AddAsync(new SignalRMessage { UserId = userID, Target = "sendUpdate", // client method name Arguments = new[] { signalRMessage } }); return(true); }