private void SetupManagementClients(MockContext context) { ResourceManagementClient = GetResourceManagementClient(context); LogicManagementClient = GetLogicManagementClient(context); OldResourceManagementClient = GetOldResourceManagementClient(context); _helper.SetupManagementClients(OldResourceManagementClient, ResourceManagementClient, LogicManagementClient); }
/// <summary> /// Creates a mock LogicManagementClient /// </summary> /// <param name="handler">delegating handler for http requests</param> /// <returns>LogicManagementClient Client</returns> protected ILogicManagementClient CreateWorkflowClient(RecordedDelegatingHandler handler) { var client = new LogicManagementClient(new TokenCredentials("token"), handler); client.SubscriptionId = "66666666-6666-6666-6666-666666666666"; return(client); }
/// <summary> /// Initializes the LogicManagementClient and assigns it to a static variable. This will be used the test framework to retrieve data using Azure Logic Apps SDK /// </summary> public static void Start() { ServiceClientCredentials credentials = GetAzureCredentials(); _client = new LogicManagementClient(credentials); _client.SubscriptionId = Config.SubscriptionId; }
/// <summary> /// Initializes a new instance of the <see cref="LogicAppClient"/> class. /// </summary> /// <param name="resourceGroup">The resource group where the logic app is located.</param> /// <param name="logicAppName">The name of the logic app resource running in Azure.</param> /// <param name="client">The logic management client to run REST operations during client operations.</param> /// <param name="logger">The instance to write diagnostic trace messages while interacting with the logic app.</param> public LogicAppClient(string resourceGroup, string logicAppName, LogicManagementClient client, ILogger logger) { Guard.NotNullOrEmpty(resourceGroup, nameof(resourceGroup)); Guard.NotNullOrEmpty(logicAppName, nameof(logicAppName)); Guard.NotNull(client, nameof(client)); _resourceGroup = resourceGroup; _logicAppName = logicAppName; _logicManagementClient = client; _logger = logger ?? NullLogger.Instance; }
/// <summary> /// Uses a accessToken to authenticate with Azure. /// </summary> /// <param name="subscriptionId">The ID that identifies the subscription on Azure.</param> /// <param name="accessToken">The token to use to call the Azure management API.</param> /// <exception cref="ArgumentException">Thrown when the <paramref name="subscriptionId"/> or <paramref name="accessToken"/> is blank.</exception> public static LogicAppAuthentication UsingAccessToken(string subscriptionId, string accessToken) { Guard.NotNullOrWhitespace(subscriptionId, nameof(subscriptionId), "Requires an ID that identifies the Azure subscription that has access to the Azure resources"); Guard.NotNullOrWhitespace(accessToken, nameof(accessToken), "Requires an access token to authenticate a client or application with Azure that is authorized to interact with the Logic Apps running on Azure"); return(new LogicAppAuthentication(() => { LogicManagementClient client = AuthenticateLogicAppsManagement(subscriptionId, accessToken); return Task.FromResult(client); })); }
public async Task SchemaBadRequest_Missing_RequiredFields_SimplerCode() { var tenantId = Environment.GetEnvironmentVariable("ACSUG_TENANT_ID"); var clientId = Environment.GetEnvironmentVariable("ACSUG_CLIENT_ID"); var clientSecret = Environment.GetEnvironmentVariable("ACSUG_CLIENT_SECRET"); var subscriptionId = Environment.GetEnvironmentVariable("ACSUG_SUBSCRIPTION_ID"); // Get credentials var context = new AuthenticationContext($"https://login.windows.net/{tenantId}"); var credentials = new ClientCredential(clientId, clientSecret); var result = await context.AcquireTokenAsync("https://management.core.windows.net/", credentials); string token = result.CreateAuthorizationHeader().Substring("Bearer ".Length); var tokenCredentials = new TokenCredentials(token); // Use Logic Apps Management var logicAppsClient = new LogicManagementClient(tokenCredentials); logicAppsClient.SubscriptionId = subscriptionId; // Retrieve Logic Apps Uri var url = await logicAppsClient.WorkflowTriggers.ListCallbackUrlWithHttpMessagesAsync("ACSUG-LogicApps-Testing", "lapp-buyticketcorinthians-dev", "manual"); // Create mock data to be tested var request = new Models.APIRequest { price = 0 }; // Serialize payload var serializerOptions = new JsonSerializerOptions { IgnoreNullValues = true }; var requestContent = new StringContent(JsonSerializer.Serialize <Models.APIRequest>( request, serializerOptions), Encoding.UTF8, "application/json"); var httpClient = new HttpClient(); var response = await httpClient.PostAsync(new Uri(url.Body.Value), requestContent); var responseContent = await response.Content.ReadAsStreamAsync(); var logicAppsResponse = await JsonSerializer.DeserializeAsync <Models.LogicAppsErrorResponse>(responseContent, serializerOptions); // Verify that the Http code returned is 400 (BadRequest) Assert.IsTrue(response.StatusCode == System.Net.HttpStatusCode.BadRequest, $"Expected '{System.Net.HttpStatusCode.BadRequest}' but received '{response.StatusCode}. Details: {logicAppsResponse.error.message}'"); Assert.AreEqual(logicAppsResponse.error.code, "TriggerInputSchemaMismatch", $"Expected 'TriggerInputSchemaMismatch' but received '{logicAppsResponse.error.code}. Details: {logicAppsResponse.error.message}'"); Assert.IsTrue(logicAppsResponse.error.message.Contains("Required properties are missing from object") && logicAppsResponse.error.message.Contains("customerName") && logicAppsResponse.error.message.Contains("date") && logicAppsResponse.error.message.Contains("homeTeam") && logicAppsResponse.error.message.Contains("awayTeam"), $"Error message received not matching the expected: '{logicAppsResponse.error.message}'"); }
/// <summary> /// Uses an access token to authenticate with Azure. /// </summary> /// <param name="subscriptionId">The ID that identifies the subscription on Azure.</param> /// <param name="accessTokenSecretName">The secret key to use to fetch access token from the secret provider. This will be used to call the Azure management API.</param> /// <param name="secretProvider">The provider to get the client secret; using the <paramref name="accessTokenSecretName"/>.</param> /// <exception cref="ArgumentException">Thrown when the <paramref name="subscriptionId"/> or <paramref name="accessTokenSecretName"/> is blank.</exception> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="secretProvider"/> is blank.</exception> public static LogicAppAuthentication UsingAccessToken(string subscriptionId, string accessTokenSecretName, ISecretProvider secretProvider) { Guard.NotNullOrWhitespace(subscriptionId, nameof(subscriptionId), "Requires an ID that identifies the Azure subscription that has access to the Azure resources"); Guard.NotNullOrWhitespace(accessTokenSecretName, nameof(accessTokenSecretName), "Requires an access token secret key that points to the access token of the client or application that is authorized to interact with the Logic Apps running on Azure"); Guard.NotNull(secretProvider, nameof(secretProvider), "Requires an secret provider instance to retrieve the access token of the client or application that is authorized to interact with the Logic Apps running on Azure"); return(new LogicAppAuthentication(async() => { string accessToken = await secretProvider.GetRawSecretAsync(accessTokenSecretName); LogicManagementClient managementClient = AuthenticateLogicAppsManagement(subscriptionId, accessToken); return managementClient; })); }
/// <summary> /// Creates a new authenticated instance of the <see cref="LogicAppClient"/>. /// </summary> /// <param name="resourceGroup">The resource group where the logic app is located.</param> /// <param name="logicAppName">The name of the logic app resource running in Azure.</param> /// <param name="authentication">The authentication mechanism to authenticate this client.</param> /// <param name="logger">The instance to write diagnostic trace messages while interacting with the logic app.</param> /// <returns> /// An authenticated client capable of interacting with the logic app resource running in Azure. /// </returns> public static async Task<LogicAppClient> CreateAsync( string resourceGroup, string logicAppName, LogicAppAuthentication authentication, ILogger logger) { Guard.NotNullOrEmpty(resourceGroup, nameof(resourceGroup)); Guard.NotNullOrEmpty(logicAppName, nameof(logicAppName)); Guard.NotNull(authentication, nameof(authentication)); LogicManagementClient managementClient = await authentication.AuthenticateAsync(); logger = logger ?? NullLogger.Instance; return new LogicAppClient(resourceGroup, logicAppName, managementClient, logger); }
/// <summary> /// Uses an access token to authenticate with Azure. /// </summary> /// <param name="subscriptionId">The ID that identifies the subscription on Azure.</param> /// <param name="accessTokenKey">The secret key to use to fetch access token from the secret provider. This will be used to call the Azure management API.</param> /// <param name="secretProvider">The provider to get the client secret; using the <paramref name="accessTokenKey"/>.</param> public static LogicAppAuthentication UsingAccessToken(string subscriptionId, string accessTokenKey, ISecretProvider secretProvider) { Guard.NotNullOrWhitespace(subscriptionId, nameof(subscriptionId)); Guard.NotNullOrWhitespace(accessTokenKey, nameof(accessTokenKey)); Guard.NotNull(secretProvider, nameof(secretProvider)); return(new LogicAppAuthentication(async() => { string accessToken = await secretProvider.GetRawSecretAsync(accessTokenKey); LogicManagementClient managementClient = await AuthenticateLogicAppsManagementAsync(subscriptionId, accessToken); return managementClient; })); }
public async Task AuthenticateLogicAppManagement_UsingAccessToken_Succeeds() { // Arrange string subscriptionId = Configuration.GetAzureSubscriptionId(); string accessToken = Configuration.GetAzureAccessToken(); var authentication = LogicAppAuthentication.UsingAccessToken(subscriptionId, accessToken); // Act using (LogicManagementClient managementClient = await authentication.AuthenticateAsync()) { // Assert Assert.NotNull(managementClient); } }
protected void CleanResourceGroup(LogicManagementClient client, string resourceGroup = Constants.DefaultResourceGroup) { var integrationAccounts = client.IntegrationAccounts.ListByResourceGroup(resourceGroup); foreach (var integrationAccount in integrationAccounts) { client.IntegrationAccounts.Delete(resourceGroup, integrationAccount.Name); } var workflows = client.Workflows.ListByResourceGroup(resourceGroup); foreach (var workflow in workflows) { client.Workflows.Delete(resourceGroup, workflow.Name); } }
/// <summary> /// Uses the service principal to authenticate with Azure. /// </summary> /// <param name="tenantId">The ID where the resources are located on Azure.</param> /// <param name="subscriptionId">The ID that identifies the subscription on Azure.</param> /// <param name="clientId">The ID of the client or application that has access to the logic apps running on Azure.</param> /// <param name="clientSecretKey">The secret of the client or application that has access to the logic apps running on Azure.</param> /// <param name="secretProvider">The provider to get the client secret; using the <paramref name="clientSecretKey"/>.</param> public static LogicAppAuthentication UsingServicePrincipal(string tenantId, string subscriptionId, string clientId, string clientSecretKey, ISecretProvider secretProvider) { Guard.NotNullOrWhitespace(tenantId, nameof(tenantId)); Guard.NotNullOrWhitespace(subscriptionId, nameof(subscriptionId)); Guard.NotNullOrWhitespace(clientId, nameof(clientId)); Guard.NotNullOrWhitespace(clientSecretKey, nameof(clientSecretKey)); Guard.NotNull(secretProvider, nameof(secretProvider)); return(new LogicAppAuthentication(async() => { string clientSecret = await secretProvider.GetRawSecretAsync(clientSecretKey); LogicManagementClient managementClient = await AuthenticateLogicAppsManagementAsync(subscriptionId, tenantId, clientId, clientSecret); return managementClient; })); }
public async Task AuthenticateLogicAppManagement_UsingSecretProvider_Succeeds() { // Arrange string subscriptionId = Configuration.GetAzureSubscriptionId(); string tenantId = Configuration.GetAzureTenantId(); string clientId = Configuration.GetAzureClientId(); var authentication = LogicAppAuthentication.UsingServicePrincipal(tenantId, subscriptionId, clientId, ClientSecretKey, this); // Act using (LogicManagementClient managementClient = await authentication.AuthenticateAsync()) { // Assert Assert.NotNull(managementClient); } Assert.True(_isClientSecretRequested); }
/// <summary> /// Uses the service principal to authenticate with Azure. /// </summary> /// <param name="tenantId">The ID where the resources are located on Azure.</param> /// <param name="subscriptionId">The ID that identifies the subscription on Azure.</param> /// <param name="clientId">The ID of the client or application that has access to the logic apps running on Azure.</param> /// <param name="clientSecretName">The secret of the client or application that has access to the logic apps running on Azure.</param> /// <param name="secretProvider">The provider to get the client secret; using the <paramref name="clientSecretName"/>.</param> /// <param name="cloud">The Azure cloud environment to use during authenticating and interacting with the Azure Logic Apps resources.</param> /// <exception cref="ArgumentException">Thrown when the <paramref name="tenantId"/>, <paramref name="subscriptionId"/>, <paramref name="clientId"/>, or <paramref name="clientSecretName"/> is blank.</exception> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="secretProvider"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="cloud"/> is outside the bounds of the enumeration.</exception> public static LogicAppAuthentication UsingServicePrincipal(string tenantId, string subscriptionId, string clientId, string clientSecretName, ISecretProvider secretProvider, AzureCloud cloud = AzureCloud.Global) { Guard.NotNullOrWhitespace(tenantId, nameof(tenantId), "Requires an tenant ID where the Azure resources are located"); Guard.NotNullOrWhitespace(subscriptionId, nameof(subscriptionId), "Requires an ID that identifies the Azure subscription that has access to the Azure resources"); Guard.NotNullOrWhitespace(clientId, nameof(clientId), "Requires an client or application ID that is authorized to interact with the Logic Apps running on Azure"); Guard.NotNullOrWhitespace(clientSecretName, nameof(clientSecretName), "Requires an client or application secret key that points to the secret of the client or application that is authorized to interact with the Logic Apps running on Azure"); Guard.NotNull(secretProvider, nameof(secretProvider), "Requires an secret provider instance to retrieve the secret of the client or application that is authorized to interact with the Logic Apps running on Azure"); Guard.For(() => !Enum.IsDefined(typeof(AzureCloud), cloud), new ArgumentOutOfRangeException(nameof(cloud), cloud, "Requires the Azure cloud environment to be within the bounds of the enumeration")); return(new LogicAppAuthentication(async() => { string clientSecret = await secretProvider.GetRawSecretAsync(clientSecretName); LogicManagementClient managementClient = await AuthenticateLogicAppsManagementAsync(subscriptionId, tenantId, clientId, clientSecret, cloud); return managementClient; })); }
private static async Task <LogicManagementClient> AuthenticateLogicAppsManagementAsync( string subscriptionId, string tenantId, string clientId, string clientSecret, AzureCloud cloud) { AzureEnvironment azureEnvironment = cloud.GetAzureEnvironment(); string authority = azureEnvironment.AuthenticationEndpoint + tenantId; var authContext = new AuthenticationContext(authority); var credential = new ClientCredential(clientId, clientSecret); AuthenticationResult token = await authContext.AcquireTokenAsync(azureEnvironment.ManagementEndpoint, credential); LogicManagementClient client = AuthenticateLogicAppsManagement(subscriptionId, token.AccessToken); return(client); }
public async Task NonHttpTrigger() { var tenantId = Environment.GetEnvironmentVariable("ACSUG_TENANT_ID"); var clientId = Environment.GetEnvironmentVariable("ACSUG_CLIENT_ID"); var clientSecret = Environment.GetEnvironmentVariable("ACSUG_CLIENT_SECRET"); var subscriptionId = Environment.GetEnvironmentVariable("ACSUG_SUBSCRIPTION_ID"); // Get credentials var context = new AuthenticationContext($"https://login.windows.net/{tenantId}"); var credentials = new ClientCredential(clientId, clientSecret); var result = await context.AcquireTokenAsync("https://management.core.windows.net/", credentials); string token = result.CreateAuthorizationHeader().Substring("Bearer ".Length); var tokenCredentials = new TokenCredentials(token); // Use Logic Apps Management var logicAppsClient = new LogicManagementClient(tokenCredentials); logicAppsClient.SubscriptionId = subscriptionId; // Retrieve Logic Apps Uri var xxx = logicAppsClient.WorkflowTriggers.Run("ACSUG-LogicApps-Testing", "lapp-nonhttptrigger-dev", "When_a_blob_is_added_or_modified_(properties_only)"); // Create mock data to be tested var request = new Models.APIRequest { price = 0 }; // Serialize payload var serializerOptions = new JsonSerializerOptions { IgnoreNullValues = true }; var requestContent = new StringContent(JsonSerializer.Serialize <Models.APIRequest>( request, serializerOptions), Encoding.UTF8, "application/json"); /*var httpClient = new HttpClient(); * var response = await httpClient.PostAsync(new Uri(url.Body.Value), requestContent); * * var responseContent = await response.Content.ReadAsStreamAsync(); * var logicAppsResponse = await JsonSerializer.DeserializeAsync<Models.LogicAppsErrorResponse>(responseContent, serializerOptions);*/ }
public async Task Initialize() { _serializerOptions = new JsonSerializerOptions { IgnoreNullValues = true }; // Read these settings from an environment variable for local test or from Key Vault for Azure DevOps /* Get local environment variables using powershell: * Get-ChildItem -Path Env:AZURE* * * Set system or user environment variables using Powershell: * [System.Environment]::SetEnvironmentVariable('AZURE_TENANT_ID','XXX',[System.EnvironmentVariableTarget]::Machine|User) * [System.Environment]::SetEnvironmentVariable('AZURE_CLIENT_ID','YYY',[System.EnvironmentVariableTarget]::Machine) * [System.Environment]::SetEnvironmentVariable('AZURE_CLIENT_SECRET','ZZZ',[System.EnvironmentVariableTarget]::Machine) * [System.Environment]::SetEnvironmentVariable('AZURE_SUBSCRIPTION_ID','XYZ',[System.EnvironmentVariableTarget]::Machine) */ _tenantId = Environment.GetEnvironmentVariable("ACSUG_TENANT_ID"); _clientId = Environment.GetEnvironmentVariable("ACSUG_CLIENT_ID"); _clientSecret = Environment.GetEnvironmentVariable("ACSUG_CLIENT_SECRET"); _subscriptionId = Environment.GetEnvironmentVariable("ACSUG_SUBSCRIPTION_ID"); if (string.IsNullOrEmpty(_tenantId) || string.IsNullOrEmpty(_clientId) || string.IsNullOrEmpty(_clientSecret) || string.IsNullOrEmpty(_subscriptionId)) { throw new Exception($"authentication credentials are invalid! TenantId: {_tenantId}, SubscriptionId: {_subscriptionId}, ClientId: {_clientId}, ClientSecret: {_clientSecret}"); } _resourceGroupName = $"ACSUG-LogicApps-Testing"; _logicAppName = $"lapp-buyticketcorinthians-dev"; ServiceClientCredentials credentials = await GetCredentials(_tenantId, _clientId, _clientSecret); _client = new LogicManagementClient(credentials); _client.SubscriptionId = _subscriptionId; _httpClient = new HttpClient(); }
private async Task <IEnumerable <LogicAppRun> > GetLogicAppRunsAsync() { using (LogicManagementClient managementClient = await _authentication.AuthenticateAsync()) { var odataQuery = new ODataQuery <WorkflowRunFilter> { Filter = $"StartTime ge {_startTime.UtcDateTime:O} and Status ne 'Running'" }; if (_hasCorrelationId) { odataQuery.Filter += $" and ClientTrackingId eq '{_correlationId}'"; } _logger.LogTrace( "Query logic app runs for '{LogicAppName}' in resource group '{ResourceGroup}': {Query}", _logicAppName, _resourceGroup, odataQuery.Filter); IPage <WorkflowRun> workFlowRuns = await managementClient.WorkflowRuns.ListAsync(_resourceGroup, _logicAppName, odataQuery); _logger.LogTrace("Query returned {WorkFlowRunCount} workflow runs", workFlowRuns.Count()); var logicAppRuns = new Collection <LogicAppRun>(); foreach (WorkflowRun workFlowRun in workFlowRuns) { IEnumerable <LogicAppAction> actions = await FindLogicAppRunActionsAsync(managementClient, workFlowRun.Name); if (_trackingProperties.Count > 0 && actions.Any(action => HasTrackedProperty(action.TrackedProperties)) || _trackingProperties.Count <= 0) { var logicAppRun = LogicAppConverter.ToLogicAppRun(workFlowRun, actions); logicAppRuns.Add(logicAppRun); } } _logger.LogTrace("Query resulted in {LogicAppRunCount} logic app runs", logicAppRuns.Count); return(logicAppRuns.AsEnumerable()); } }
/// <summary> /// Initializes a new instance of the <see cref="LogicAppClient"/> class. /// </summary> /// <param name="resourceGroup">The resource group where the logic app is located.</param> /// <param name="logicAppName">The name of the logic app resource running in Azure.</param> /// <param name="client">The logic management client to run REST operations during client operations.</param> public LogicAppClient(string resourceGroup, string logicAppName, LogicManagementClient client) : this(resourceGroup, logicAppName, client, NullLogger.Instance) { }
public async Task Run( [ServiceBusTrigger("%x12inboundqueuename%", Connection = "InboundServiceBusConnectionString", IsSessionsEnabled = true)] Message inboundMsg, [ServiceBus("%x12204inboundqueuename%", Connection = "InboundServiceBusConnectionString")] IAsyncCollector <Message> outMessages, ILogger log, CancellationToken cancellationToken) { log.LogInformation("C# Service Bus trigger function processed a request."); if (string.IsNullOrEmpty(inboundMsg.SessionId)) { throw new Exception($"No Session ID in this message."); } //Read EDI message List <IEdiItem> ediItems; using (Stream stream = new MemoryStream(inboundMsg.Body)) { using (var reader = new X12Reader(stream, "EdiFabric.Templates.X12")) { ediItems = (await reader.ReadToEndAsync()).ToList(); } } //Get Logic App Management Client using Azure Token if (client == null) { var provider = new AzureServiceTokenProvider(); var token = await provider.GetAccessTokenAsync("https://management.azure.com/"); client = new LogicManagementClient(new TokenCredentials(token)) { SubscriptionId = subscriptionId }; } //Get Agreements from Integration Account if (agreements == null) { agreements = new List <IntegrationAccountAgreement>(); IPage <IntegrationAccountAgreement> pages = await client.IntegrationAccountAgreements.ListAsync(rgName, iaName, null, cancellationToken); agreements.AddRange(pages); while (pages.NextPageLink != null) { pages = await client.IntegrationAccountAgreements.ListNextAsync(pages.NextPageLink); agreements.AddRange(pages); } } //Look for a matching agreement based on ISA header var isa = ediItems.OfType <ISA>().FirstOrDefault(); if (isa == null) { throw new Exception($"No ISA element found."); } var agreementName = from a in agreements where a.GuestIdentity.Qualifier == isa.SenderIDQualifier_5.Trim() && a.GuestIdentity.Value == isa.InterchangeSenderID_6.Trim() && a.HostIdentity.Value == isa.ReceiverIDQualifier_7.Trim() && a.HostIdentity.Value == isa.InterchangeReceiverID_8.Trim() select a.Name.FirstOrDefault(); if (agreementName == null) { throw new Exception($"Agreement between sender partner with qualifier {isa.SenderIDQualifier_5} and ID {isa.InterchangeSenderID_6} and receiver partner with qualifier {isa.ReceiverIDQualifier_7} and ID {isa.InterchangeReceiverID_8} not found"); } //Loop through each shipment and send to subsequent session enabled queue but this time using shipmentID in the session to fan out per order var shipmentItems = ediItems.OfType <TS204>().ToList(); foreach (var shipmentItem in shipmentItems) { //Todo: table lookup of where each customer puts their Shipment ID number as they might be different var shipmentID = shipmentItem.B2.ShipmentIdentificationNumber_04; var xml = Serialize(shipmentItem); Message outMessage = new Message(Encoding.UTF8.GetBytes(xml.ToString())); outMessage.SessionId = $"{inboundMsg.SessionId}+{shipmentID}"; await outMessages.AddAsync(outMessage); } }
public void Connect(string subscriptionId) { _client = new LogicManagementClient(Credentials); _client.SubscriptionId = subscriptionId; }