diff --git a/Constants/AzureEndpoints.cs b/Constants/AzureEndpoints.cs new file mode 100644 index 0000000..ef52f2e --- /dev/null +++ b/Constants/AzureEndpoints.cs @@ -0,0 +1,13 @@ +namespace xApi.Constants +{ + public struct AzureEndpoints + { + // + public const string ConnectionDataEndpoint = "/_apis/connectionData"; + + // + #region Projects ... + public const string ProjectsEndpoint = "/_apis/projects"; + #endregion + } +} \ No newline at end of file diff --git a/Constants/ConfigurationNodeNames.cs b/Constants/ConfigurationNodeNames.cs index e1bf455..9d60647 100644 --- a/Constants/ConfigurationNodeNames.cs +++ b/Constants/ConfigurationNodeNames.cs @@ -3,5 +3,6 @@ namespace xApi.Constants public partial struct ConfigurationNodeNames { public const string ApiConfigurationNodeName = "ApiConfiguration"; + public const string AzureServiceConfigurationNodeName = "AzureServiceConfiguration"; } } \ No newline at end of file diff --git a/Constants/Params.cs b/Constants/Params.cs index 05b37e8..2a40a07 100644 --- a/Constants/Params.cs +++ b/Constants/Params.cs @@ -4,6 +4,7 @@ namespace xApi.Constants { // // Common Params ... - public const string ApiVersionParam = "version"; + public const string ApiVersionParam = "version"; + public const string AzureHttpClient = "AzureHttpClient"; } } \ No newline at end of file diff --git a/Controllers/AzureController.cs b/Controllers/AzureController.cs new file mode 100644 index 0000000..4931236 --- /dev/null +++ b/Controllers/AzureController.cs @@ -0,0 +1,81 @@ +using xApi.Interfaces; +using Microsoft.AspNetCore.Mvc; + +namespace xApi.Controllers +{ + [ApiController] + [ApiVersion("1.0")] + [Route("api/v{version:apiVersion}/[controller]")] + public class AzureController : ControllerBase + { + // + private readonly IAzureServices azureServices; + private readonly ILogger logger; + + public AzureController( + IAzureServices azureServices, + ILogger logger + ) + { + // + this.logger = logger; + this.azureServices = azureServices; + } + + /// + /// Get connection data from Azure Services ... + /// + /// + /// + [HttpGet("ConnectionData")] + public async Task> GetConnectionData( + CancellationToken cancellationToken = default + ) + { + // + try + { + // + var response = await azureServices + .GetConnectionDataAsync(cancellationToken); + + // + return Ok(response); + } + catch (Exception ex) + { + // + logger.LogError(ex, "Error occurred ..."); + return StatusCode(500, "Internal server error"); + } + } + + /// + /// Get projects from Azure Services ... + /// + /// + /// + [HttpGet("GetProjects")] + public async Task> GetProjects( + CancellationToken cancellationToken = default + ) + { + // + try + { + // + var response = await azureServices + .GetProjectsAsync(cancellationToken); + + // + return Ok(response); + } + catch (Exception ex) + { + // + logger.LogError(ex, "Error occurred ..."); + return StatusCode(500, "Internal server error"); + } + } + } +} \ No newline at end of file diff --git a/Extensions/DIHelperExtensions.cs b/Extensions/DIHelperExtensions.cs index 340aba2..52febc4 100644 --- a/Extensions/DIHelperExtensions.cs +++ b/Extensions/DIHelperExtensions.cs @@ -1,5 +1,9 @@ using xApi.Models; using xApi.Constants; +using xApi.Providers; +using xApi.Interfaces; +using System.Net.Http.Headers; +using System.Text; namespace xApi.Extensions { @@ -34,6 +38,139 @@ namespace xApi.Extensions return result; } + /// + /// Extract Azure Service Configuration based on appSetting file ... + /// + /// + /// + public static AzureServiceConfiguration? GetAzureServiceConfiguration( + this IConfiguration source + ) + { + // + var section = source + .GetSection(ConfigurationNodeNames.AzureServiceConfigurationNodeName); + var result = section.Get(); + + // + return result; + } + + /// + /// Add Application Configuration to Service Collection ... + /// + /// + /// + public static void AddApiConfiguration( + this IServiceCollection source, + IConfiguration configuration + ) + { + // + var config = configuration.GetApiConfiguration(); + source.AddApiConfiguration(config); + } + + /// + /// Add Application Configuration to Service Collection ... + /// + /// + /// + public static void AddApiConfiguration( + this IServiceCollection source, + ApiConfiguration? configuration + ) + { + // + if (configuration is null || + !configuration.IsValid()) + { + throw new InvalidDataException("Api Configuration is not Valid ..."); + } + + // + source.AddSingleton(configuration); + } + + /// + /// Add Azure Service Configuration to Service Collection ... + /// + /// + /// + public static void AddAzureServiceConfiguration( + this IServiceCollection source, + IConfiguration configuration + ) + { + // + var config = configuration.GetAzureServiceConfiguration(); + source.AddAzureServiceConfiguration(config); + } + + /// + /// Add Azure Service Configuration to Service Collection ... + /// + /// + /// + /// / + public static void AddAzureServiceConfiguration( + this IServiceCollection source, + AzureServiceConfiguration? configuration + ) + { + // + if (configuration is null || + !configuration.IsValid()) + { + throw new InvalidDataException("Azure Service Configuration is not Valid ..."); + } + + // + source.AddSingleton(configuration); + } + + /// + /// Add Azure Service Configuration to Service Collection ... + /// and Register Azure Services ... + /// + /// + /// + public static void AddAzureApiServices( + this IServiceCollection source, + IConfiguration configuration + ) + { + // + // Retrieve Configuration and Add to Service Collection ... + var config = configuration.GetAzureServiceConfiguration(); + source.AddAzureServiceConfiguration(config); + + // + // Register Specified HttpClient for Azure DevOps Service ... + source.AddHttpClient(Params.AzureHttpClient, (sp, client) => + { + // + client.BaseAddress = new Uri(config!.BaseUrl!); + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // + client.Timeout = TimeSpan.FromSeconds(20); + + // + var pat = config.Pat; + if (!string.IsNullOrWhiteSpace(pat)) + { + // + var authToken = Convert.ToBase64String(Encoding.ASCII.GetBytes($":{pat}")); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authToken); + } + }); + + // + // Register Azure Service ... + source.AddScoped(); + } + /// /// Inject Specific Registered Service from IServiceCollection /// diff --git a/Extensions/ModelExtensions.cs b/Extensions/ModelExtensions.cs index 30206af..fd9ba93 100644 --- a/Extensions/ModelExtensions.cs +++ b/Extensions/ModelExtensions.cs @@ -1,9 +1,105 @@ using xApi.Models; +using System.Text.Json; +using System.Text.Json.Serialization; namespace xApi.Extensions { public static class ModelExtensions { + // + #region Common ... + /// + /// Parse Json String to Specified Type of Object ... + /// + /// + /// + /// + /// + /// + public static T? ParseJSON( + this string json, + JsonSerializerOptions? options = null + ) + { + // + if (string.IsNullOrWhiteSpace(json)) + { + return default; + } + + // + // Normalize ... + options = GetDefaultJsonSerializerOptions(options); + + // + try + { + // + return JsonSerializer + .Deserialize(json, options); + } + catch (JsonException ex) + { + throw new InvalidOperationException($"Failed to deserialize JSON to {typeof(T).Name}", ex); + } + } + + /// + /// Convert to Json String ... + /// + /// + /// + /// + /// + public static string? ToJSON( + this object? obj, + JsonSerializerOptions? options = null + ) + { + // + if (obj is null) + { + return null; + } + + // + options = GetDefaultJsonSerializerOptions(options); + try + { + // + return JsonSerializer + .Serialize(obj, options); + } + catch (NotSupportedException ex) + { + throw new InvalidOperationException($"Failed to serialize object of type {obj.GetType().Name}", ex); + } + } + + /// + /// Convert to Pretty Json String ... + /// + /// + /// + /// + public static string? ToPrettyJSON( + this object? obj, + JsonSerializerOptions? options = null + ) + { + // + if (obj is null) + { + return null; + } + + // + options = GetDefaultJsonSerializerOptions(options); + options.WriteIndented = true; + return JsonSerializer.Serialize(obj, options); + } + #endregion + /// /// Validate Configuration Model ... /// @@ -20,5 +116,49 @@ namespace xApi.Extensions // return result; } + + /// + /// Validate Configuration Model ... + /// + /// + /// + public static bool IsValid(this AzureServiceConfiguration? configuration) + { + // + var result = configuration != null + && !string.IsNullOrWhiteSpace(configuration.Pat) + && !string.IsNullOrWhiteSpace(configuration.BaseUrl); + + // + return result; + } + + // + #region Private ... + /// + /// Retrieve Default JsonSerializerOptions ... + /// + /// + /// + private static JsonSerializerOptions GetDefaultJsonSerializerOptions( + JsonSerializerOptions? options = null + ) + { + // + if (options is null) + { + options = new() + { + WriteIndented = false, + PropertyNameCaseInsensitive = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + } + + // + return options; + } + #endregion } } \ No newline at end of file diff --git a/Interfaces/IAzureServices.cs b/Interfaces/IAzureServices.cs new file mode 100644 index 0000000..24f5090 --- /dev/null +++ b/Interfaces/IAzureServices.cs @@ -0,0 +1,18 @@ +using xApi.Models; + +namespace xApi.Interfaces +{ + /// + /// Implementing Azure Services Interfaces ... + /// + public interface IAzureServices + { + Task GetConnectionDataAsync( + CancellationToken cancellationToken = default + ); + + Task GetProjectsAsync( + CancellationToken cancellationToken = default + ); + } +} \ No newline at end of file diff --git a/Models/AzureModels.cs b/Models/AzureModels.cs new file mode 100644 index 0000000..0646d57 --- /dev/null +++ b/Models/AzureModels.cs @@ -0,0 +1,76 @@ +using System.Text.Json.Serialization; + +namespace xApi.Models +{ + public class AzureConnectionDataDto + { + [JsonPropertyName("instanceId")] + public string? InstanceId { get; set; } + + [JsonPropertyName("deploymentId")] + public string? DeploymentId { get; set; } + + [JsonPropertyName("deploymentType")] + public string? DeploymentType { get; set; } + + [JsonPropertyName("authorizedUser")] + public AzureUserDetailsDto? AuthorizedUser { get; set; } + + [JsonPropertyName("authenticatedUser")] + public AzureUserDetailsDto? AuthenticatedUser { get; set; } + + [JsonPropertyName("locationServiceData")] + public AzureLocationServiceDto? LocationServiceData { get; set; } + } + + public class AzurePropertyValueDto + { + [JsonPropertyName("$type")] + public string? Type { get; set; } + + [JsonPropertyName("$value")] + public string? Value { get; set; } + } + + public class AzureUserDetailsDto + { + [JsonPropertyName("id")] + public string? Id { get; set; } + + [JsonPropertyName("isActive")] + public bool IsActive { get; set; } + + [JsonPropertyName("metaTypeId")] + public int MetaTypeId { get; set; } + + [JsonPropertyName("descriptor")] + public string? Descriptor { get; set; } + + [JsonPropertyName("resourceVersion")] + public int ResourceVersion { get; set; } + + [JsonPropertyName("subjectDescriptor")] + public string? SubjectDescriptor { get; set; } + + [JsonPropertyName("providerDisplayName")] + public string? ProviderDisplayName { get; set; } + + [JsonPropertyName("properties")] + public Dictionary? Properties { get; set; } + } + + public class AzureLocationServiceDto + { + [JsonPropertyName("lastChangeId")] + public int LastChangeId { get; set; } + + [JsonPropertyName("lastChangeId64")] + public long LastChangeId64 { get; set; } + + [JsonPropertyName("clientCacheTimeToLive")] + public int ClientCacheTimeToLive { get; set; } + + [JsonPropertyName("defaultAccessMappingMoniker")] + public string? DefaultAccessMappingMoniker { get; set; } + } +} \ No newline at end of file diff --git a/Models/AzureServiceConfiguration.cs b/Models/AzureServiceConfiguration.cs new file mode 100644 index 0000000..86c13fe --- /dev/null +++ b/Models/AzureServiceConfiguration.cs @@ -0,0 +1,8 @@ +namespace xApi.Models +{ + public class AzureServiceConfiguration + { + public string? Pat { get; set; } + public string? BaseUrl { get; set; } + } +} \ No newline at end of file diff --git a/Program.cs b/Program.cs index 52d5b7f..c551e6f 100644 --- a/Program.cs +++ b/Program.cs @@ -3,6 +3,7 @@ using xApi.Attributes; using System.Reflection; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; +using Microsoft.AspNetCore.Mvc; // // Access Application Builder ... @@ -18,17 +19,39 @@ var xmlFilePath = Path.Combine(AppContext.BaseDirectory, xmlFilename); builder.Services.AddEndpointsApiExplorer(); // -// Register Swagger Generator ... +// Extract Api Configuration ... var appConfiguration = builder.Configuration - .GetApiConfiguration() ?? + .GetApiConfiguration() ?? throw new InvalidDataException("Api Configuration is not Found ..."); if (!appConfiguration.IsValid()) { throw new InvalidDataException("Api Configuration is not Valid ..."); } +builder.Services.AddApiConfiguration(appConfiguration); // -builder.Services.AddSingleton(appConfiguration); +// Register Azure Service ... +builder.Services.AddAzureApiServices(builder.Configuration); + +// +// Register Api Versioning ... +builder.Services.AddApiVersioning(opt => +{ + // + // Set Default Api Version ... + opt.DefaultApiVersion = new ApiVersion(1, 0); + + // + // Set Routing to Default API Version, if Version unspecified ... + opt.AssumeDefaultVersionWhenUnspecified = true; + + // + // Report All Available Api Versions on Response ... + opt.ReportApiVersions = true; +}); + +// +// Register Swagger Generator ... builder.Services.AddSwaggerGen(delegate (SwaggerGenOptions options) { // diff --git a/Providers/AzureServices.cs b/Providers/AzureServices.cs new file mode 100644 index 0000000..4f8599d --- /dev/null +++ b/Providers/AzureServices.cs @@ -0,0 +1,250 @@ +using xApi.Models; +using xApi.Constants; +using xApi.Interfaces; +using xApi.Extensions; +using System.Text.Json; +using System.Net.Http.Headers; + +namespace xApi.Providers +{ + public class AzureServices : IAzureServices + { + // + private readonly ILogger logger; + private readonly IHttpClientFactory httpClientFactory; + private readonly AzureServiceConfiguration configuration; + + public AzureServices( + ILogger logger, + IHttpClientFactory httpClientFactory, + AzureServiceConfiguration configuration + ) + { + // + this.logger = logger; + this.configuration = configuration; + this.httpClientFactory = httpClientFactory; + } + + /// + /// Retrieve Connection Info ... + /// + /// + /// + /// + public async Task GetConnectionDataAsync( + CancellationToken cancellationToken = default + ) + { + // + var json = await GetFromAzureAsync( + AzureEndpoints.ConnectionDataEndpoint, + cancellationToken: cancellationToken + ); + + // + var result = json.ParseJSON(); + if (result is null) + { + // + var message = "Failed to parse Azure connection data ..."; + + // + logger.LogError(message); + throw new InvalidOperationException(message); + } + + // + return result; + } + + public async Task GetProjectsAsync( + CancellationToken cancellationToken = default + ) + { + // + var json = await GetFromAzureAsync( + AzureEndpoints.ProjectsEndpoint, + cancellationToken: cancellationToken + ); + + // + // var result = json.ParseJSON(); + // if (result is null) + // { + // // + // var message = "Failed to parse Azure connection data ..."; + + // // + // logger.LogError(message); + // throw new InvalidOperationException(message); + // } + + // + return json; + } + + // + #region Private ... + private async Task HandleAzureRequest( + string path, + HttpMethod method, + IDictionary? headers = null, + IDictionary? queryParams = null, + IDictionary? routeParams = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + var pat = configuration.Pat; + if (string.IsNullOrWhiteSpace(pat)) + { + // + var message = "Azure PAT is not configured ..."; + logger.LogError(message); + throw new InvalidOperationException(message); + } + if (string.IsNullOrWhiteSpace(path)) + { + // + var message = "Request Path is not configured ..."; + logger.LogError(message); + throw new InvalidOperationException(message); + } + + // + // Create Http Client ... + using (HttpClient client = new()) + { + // + // Add Accept ... + client.DefaultRequestHeaders.Accept.Add( + new MediaTypeWithQualityHeaderValue("application/json")); + + // + // Add Personal Access Token ... + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", + Convert.ToBase64String( + System.Text.Encoding.ASCII.GetBytes( + string.Format("{0}:{1}", "", pat)))); + + // + // Preparing Request Path ... + var url = configuration.BaseUrl; + if (!url!.EndsWith('/')) + { + url += "/"; + } + if (path.StartsWith('/')) + { + path = path[1..]; + } + + // + // Handle Route Params ... + if (routeParams is not null && + routeParams.Any()) + { + // + var exists = + routeParams.Where(rp => path.Contains(rp.Key)); + foreach (var irp in exists) + { + + } + } + + // + // Finalize Url ... + url = $"{url}{path}"; + + // + // Preparing Request ... + var request = new HttpRequestMessage( + method: method, + requestUri: url + ); + HttpResponseMessage? response = null; + } + } + + private async Task GetFromAzureAsync( + string relativePath, + CancellationToken cancellationToken = default + ) + { + // + // Validate PAT ... + var pat = configuration.Pat; + if (string.IsNullOrWhiteSpace(pat)) + { + // + logger.LogError("Azure PAT is not configured ..."); + throw new InvalidOperationException("Azure PAT is not configured ..."); + } + + // + // Create Specified Http Client ... + var client = httpClientFactory.CreateClient(Params.AzureHttpClient); + + // + // Url ... + var url = $"{client.BaseAddress}{relativePath}"; + logger.LogInformation("Url: {url}", url); + + // + // Handle Request and Response ... + try + { + // + using var cts = CancellationTokenSource + .CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(20)); + + // + var response = await client.GetAsync(relativePath, cts.Token); + if (!response.IsSuccessStatusCode) + { + // + var content = await response.Content.ReadAsStringAsync(cts.Token); + logger.LogError("Azure returned HTTP {StatusCode}. Content: {Content} ...", response.StatusCode, content); + throw new HttpRequestException($"Azure returned HTTP {(int)response.StatusCode} ..."); + } + + // + // Reading Content ... + var json = await response.Content.ReadAsStringAsync(cts.Token); + + // + // Validating JSON ... + try + { + JsonDocument.Parse(json); + } + catch (JsonException ex) + { + // + logger.LogError(ex, "Azure returned non-JSON data. Path: {Path} ...", relativePath); + throw new InvalidDataException("Azure returned non-JSON data ..."); + } + + // + return json; + } + catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException || !cancellationToken.IsCancellationRequested) + { + // + logger.LogError(ex, "Azure request timed out. Path: {Path} ...", relativePath); + throw new TimeoutException("Azure request timed out ..."); + } + catch (Exception ex) + { + // + logger.LogError(ex, "Could not connect to Azure. Path: {Path} ...", relativePath); + throw; + } + } + #endregion + } +} \ No newline at end of file diff --git a/appsettings.Development.json b/appsettings.Development.json index 8a85a1a..d10fcad 100644 --- a/appsettings.Development.json +++ b/appsettings.Development.json @@ -7,10 +7,14 @@ "Email": "hkhazaeeasl@rpk.ir", "Url": "https://rpkavosh.ir" }, + "AzureServiceConfiguration": { + "Pat": "6zvwbdviuswlets7ovugq7nningtx4v6gqll7qkyqhnn75nrxh3q", + "BaseUrl": "http://192.168.10.22:8080/tfs/RPKavoshDevOps" + }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } } -} +} \ No newline at end of file