diff --git a/Constants/AzureEndpoints.cs b/Constants/AzureEndpoints.cs
index ef52f2e..7c5aa8d 100644
--- a/Constants/AzureEndpoints.cs
+++ b/Constants/AzureEndpoints.cs
@@ -3,11 +3,24 @@ namespace xApi.Constants
public struct AzureEndpoints
{
//
- public const string ConnectionDataEndpoint = "/_apis/connectionData";
+ public const string ConnectionDataEndpoint = "/connectionData";
//
#region Projects ...
- public const string ProjectsEndpoint = "/_apis/projects";
+ public const string ProjectsEndpoint = "/projects";
+ #endregion
+
+ //
+ #region Repositories(Git) ...
+ public const string RepositoriesEndpoint = "/git/repositories";
+ #endregion
+
+ //
+ #region WorkItems(s)/Issues ...
+ public const string WorkItemsQueryEndpoint = "/wit/wiql";
+ public const string WorkItemsBaseEndpoint = "/wit/workitems";
+ public const string WorkItemTypesEndpoint = "/wit/workitemtype";
+ public const string WorkItemsODataEndpoint = "Issue%20Tracker/_odata/v4.0-preview/WorkItems?$top=1&$select=WorkItemId,Title";
#endregion
}
}
\ No newline at end of file
diff --git a/Controllers/AzureController.cs b/Controllers/AzureController.cs
index 4931236..e309cfd 100644
--- a/Controllers/AzureController.cs
+++ b/Controllers/AzureController.cs
@@ -1,11 +1,12 @@
using xApi.Interfaces;
using Microsoft.AspNetCore.Mvc;
+using xApi.Models;
namespace xApi.Controllers
{
[ApiController]
[ApiVersion("1.0")]
- [Route("api/v{version:apiVersion}/[controller]")]
+ [Route("api/v{version:apiVersion}/[controller]")]
public class AzureController : ControllerBase
{
//
@@ -23,12 +24,12 @@ namespace xApi.Controllers
}
///
- /// Get connection data from Azure Services ...
+ /// Get Connection data from Azure Services ...
///
///
///
[HttpGet("ConnectionData")]
- public async Task> GetConnectionData(
+ public async Task> GetConnectionData(
CancellationToken cancellationToken = default
)
{
@@ -51,12 +52,12 @@ namespace xApi.Controllers
}
///
- /// Get projects from Azure Services ...
+ /// Get Projects from Azure Services ...
///
///
///
[HttpGet("GetProjects")]
- public async Task> GetProjects(
+ public async Task>> GetProjects(
CancellationToken cancellationToken = default
)
{
@@ -77,5 +78,61 @@ namespace xApi.Controllers
return StatusCode(500, "Internal server error");
}
}
+
+ ///
+ /// Get Repositories from Azure Services ...
+ ///
+ ///
+ ///
+ [HttpGet("GetRepositories")]
+ public async Task>> GetRepositories(
+ CancellationToken cancellationToken = default
+ )
+ {
+ //
+ try
+ {
+ //
+ var response = await azureServices
+ .GetRepositoriesAsync(cancellationToken);
+
+ //
+ return Ok(response);
+ }
+ catch (Exception ex)
+ {
+ //
+ logger.LogError(ex, "Error occurred ...");
+ return StatusCode(500, "Internal server error");
+ }
+ }
+
+ ///
+ /// Get WorkItem Types from Azure Services ...
+ ///
+ ///
+ ///
+ [HttpGet("GetWorkItemTypes")]
+ public async Task> GetWorkItemTypes(
+ CancellationToken cancellationToken = default
+ )
+ {
+ //
+ try
+ {
+ //
+ var response = await azureServices
+ .GetWorkItemTypesAsync(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/HttpExtensions.cs b/Extensions/HttpExtensions.cs
new file mode 100644
index 0000000..794d09b
--- /dev/null
+++ b/Extensions/HttpExtensions.cs
@@ -0,0 +1,56 @@
+using System.Text;
+
+namespace xApi.Extensions
+{
+ public static class HttpExtensions
+ {
+ ///
+ /// Apply Query String to Specified Url ...
+ ///
+ ///
+ ///
+ ///
+ public static string ApplyQueryString(
+ this string url,
+ IDictionary? queries = null
+ )
+ {
+ //
+ var result = url;
+ if (queries is null ||
+ string.IsNullOrWhiteSpace(result))
+ {
+ return result;
+ }
+
+ //
+ // Handling ...
+ bool isMarkupAdded = false;
+ var sb = new StringBuilder();
+ sb.Append(result);
+ foreach (var param in queries)
+ {
+ //
+ if (string.IsNullOrWhiteSpace(param.Value))
+ {
+ continue;
+ }
+
+ //
+ sb.Append(isMarkupAdded ? '&' : '?');
+ sb.Append(param.Key);
+ sb.Append('=');
+ sb.Append(param.Value);
+
+ //
+ isMarkupAdded = true;
+ }
+
+ //
+ result = sb.ToString();
+
+ //
+ return result;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Interfaces/IAzureServices.cs b/Interfaces/IAzureServices.cs
index 24f5090..6cc0ed2 100644
--- a/Interfaces/IAzureServices.cs
+++ b/Interfaces/IAzureServices.cs
@@ -7,12 +7,43 @@ namespace xApi.Interfaces
///
public interface IAzureServices
{
+ ///
+ /// Retrieve Connection Info ...
+ ///
+ ///
+ ///
+ ///
Task GetConnectionDataAsync(
CancellationToken cancellationToken = default
);
- Task GetProjectsAsync(
+ ///
+ /// Retrieve Connection Info ...
+ ///
+ ///
+ ///
+ ///
+ Task> GetProjectsAsync(
CancellationToken cancellationToken = default
);
+
+ ///
+ /// Retrieve a List of Azure Repositories ...
+ ///
+ ///
+ ///
+ ///
+ Task> GetRepositoriesAsync(
+ CancellationToken cancellationToken = default
+ );
+
+ Task GetWorkItemTypesAsync(
+ CancellationToken cancellationToken = default
+ );
+
+ // AzureListDto
+ // Task GetWorkItemsAsync(
+ // CancellationToken cancellationToken = default
+ // );
}
}
\ No newline at end of file
diff --git a/Models/AzureModels.cs b/Models/AzureModels.cs
index 0646d57..e9c6255 100644
--- a/Models/AzureModels.cs
+++ b/Models/AzureModels.cs
@@ -57,7 +57,7 @@ namespace xApi.Models
[JsonPropertyName("properties")]
public Dictionary? Properties { get; set; }
- }
+ }
public class AzureLocationServiceDto
{
@@ -72,5 +72,75 @@ namespace xApi.Models
[JsonPropertyName("defaultAccessMappingMoniker")]
public string? DefaultAccessMappingMoniker { get; set; }
- }
+ }
+
+ public class AzureProjectDto
+ {
+ [JsonPropertyName("id")]
+ public Guid Id { get; set; }
+
+ [JsonPropertyName("name")]
+ public string? Name { get; set; }
+
+ [JsonPropertyName("description")]
+ public string? Description { get; set; }
+
+ [JsonPropertyName("url")]
+ public string? Url { get; set; }
+
+ [JsonPropertyName("state")]
+ public string? State { get; set; }
+
+ [JsonPropertyName("revision")]
+ public int? Revision { get; set; }
+
+ [JsonPropertyName("visibility")]
+ public string? Visibility { get; set; }
+
+ [JsonPropertyName("lastUpdateTime")]
+ public DateTime LastUpdateTime { get; set; }
+ }
+
+ public class AzureRepositoryDto
+ {
+ [JsonPropertyName("id")]
+ public Guid Id { get; set; }
+
+ [JsonPropertyName("size")]
+ public long Size { get; set; }
+
+ [JsonPropertyName("name")]
+ public string? Name { get; set; }
+
+ [JsonPropertyName("url")]
+ public string? Url { get; set; }
+
+ [JsonPropertyName("webUrl")]
+ public string? WebUrl { get; set; }
+
+ [JsonPropertyName("sshUrl")]
+ public string? SshUrl { get; set; }
+
+ [JsonPropertyName("isDisabled")]
+ public bool IsDisabled { get; set; }
+
+ [JsonPropertyName("remoteUrl")]
+ public string? RemoteUrl { get; set; }
+
+ [JsonPropertyName("defaultBranch")]
+ public string? DefaultBranch { get; set; }
+
+ [JsonPropertyName("project")]
+ public AzureProjectDto? Project { get; set; }
+ }
+
+ public class AzureListDto
+ where T : class
+ {
+ [JsonPropertyName("count")]
+ public int Count { get; set; }
+
+ [JsonPropertyName("value")]
+ public List Value { get; set; } = [];
+ }
}
\ No newline at end of file
diff --git a/Providers/AzureServices.cs b/Providers/AzureServices.cs
index 4f8599d..c895777 100644
--- a/Providers/AzureServices.cs
+++ b/Providers/AzureServices.cs
@@ -11,19 +11,16 @@ namespace xApi.Providers
{
//
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;
}
///
@@ -37,9 +34,10 @@ namespace xApi.Providers
)
{
//
- var json = await GetFromAzureAsync(
- AzureEndpoints.ConnectionDataEndpoint,
- cancellationToken: cancellationToken
+ var json = await HandleAzureRequest(
+ method: HttpMethod.Get,
+ cancellationToken: cancellationToken,
+ path: AzureEndpoints.ConnectionDataEndpoint
);
//
@@ -47,7 +45,7 @@ namespace xApi.Providers
if (result is null)
{
//
- var message = "Failed to parse Azure connection data ...";
+ var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
@@ -58,37 +56,119 @@ namespace xApi.Providers
return result;
}
- public async Task GetProjectsAsync(
+ ///
+ /// Retrieve a List of Azure Projects ...
+ ///
+ ///
+ ///
+ ///
+ public async Task> GetProjectsAsync(
CancellationToken cancellationToken = default
)
{
//
- var json = await GetFromAzureAsync(
- AzureEndpoints.ProjectsEndpoint,
- cancellationToken: cancellationToken
+ var json = await HandleAzureRequest(
+ method: HttpMethod.Get,
+ cancellationToken: cancellationToken,
+ path: AzureEndpoints.ProjectsEndpoint
);
//
- // var result = json.ParseJSON();
+ var result = json.ParseJSON>();
+ if (result is null)
+ {
+ //
+ var message = "Failed to parse Azure data ...";
+
+ //
+ logger.LogError(message);
+ throw new InvalidOperationException(message);
+ }
+
+ //
+ return result;
+ }
+
+ ///
+ /// Retrieve a List of Azure Repositories ...
+ ///
+ ///
+ ///
+ ///
+ public async Task> GetRepositoriesAsync(
+ CancellationToken cancellationToken = default
+ )
+ {
+ //
+ var json = await HandleAzureRequest(
+ method: HttpMethod.Get,
+ cancellationToken: cancellationToken,
+ path: AzureEndpoints.RepositoriesEndpoint
+ );
+
+ //
+ var result = json.ParseJSON>();
+ if (result is null)
+ {
+ //
+ var message = "Failed to parse Azure data ...";
+
+ //
+ logger.LogError(message);
+ throw new InvalidOperationException(message);
+ }
+
+ //
+ return result;
+ }
+
+ public async Task GetWorkItemTypesAsync(
+ CancellationToken cancellationToken = default
+ )
+ {
+ //
+ var json = await HandleAzureRequest(
+ method: HttpMethod.Get,
+ cancellationToken: cancellationToken,
+ path: AzureEndpoints.WorkItemsODataEndpoint
+ );
+
+ //
+ return json;
+
+ //
+ // var result = json.ParseJSON>();
// if (result is null)
// {
// //
- // var message = "Failed to parse Azure connection data ...";
+ // var message = "Failed to parse Azure data ...";
// //
// logger.LogError(message);
// throw new InvalidOperationException(message);
// }
- //
- return json;
+ // //
+ // return result;
}
//
#region Private ...
+ ///
+ /// Handle Running Http Requests ...
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
private async Task HandleAzureRequest(
string path,
HttpMethod method,
+ bool forceJsonValidation = true,
IDictionary? headers = null,
IDictionary? queryParams = null,
IDictionary? routeParams = null,
@@ -115,6 +195,7 @@ namespace xApi.Providers
//
// Create Http Client ...
+ var result = string.Empty;
using (HttpClient client = new())
{
//
@@ -159,91 +240,105 @@ namespace xApi.Providers
// Finalize Url ...
url = $"{url}{path}";
+ //
+ // Applying Query String ...
+ url = url
+ .ApplyQueryString(queries: queryParams);
+
//
// 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)
+ // Applying Headers ...
+ if (headers is not null &&
+ headers.Any())
{
//
- 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} ...");
+ foreach (var header in headers)
+ {
+ //
+ if (string.IsNullOrWhiteSpace(header.Value))
+ {
+ continue;
+ }
+
+ //
+ request.Headers.Add(
+ name: header.Key,
+ value: header.Value
+ );
+ }
}
//
- // Reading Content ...
- var json = await response.Content.ReadAsStringAsync(cts.Token);
+ try
+ {
+ //
+ using var cts = CancellationTokenSource
+ .CreateLinkedTokenSource(cancellationToken);
+ cts.CancelAfter(TimeSpan.FromSeconds(20));
+ //
+ // Execute Request ...
+ var response = await client.SendAsync(
+ request: request,
+ cancellationToken: cts.Token
+ );
+
+ //
+ // Validate Request ...
+ 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 ...
+ result = await response.Content.ReadAsStringAsync(cts.Token);
+ }
+ catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException || !cancellationToken.IsCancellationRequested)
+ {
+ //
+ logger.LogError(ex, "Azure request timed out. Path: {Path} ...", path);
+ throw new TimeoutException("Azure request timed out ...");
+ }
+ catch (Exception ex)
+ {
+ //
+ logger.LogError(ex, "Could not connect to Azure. Path: {Path} ...", path);
+ throw;
+ }
+ }
+
+ //
+ // Force Json Validation ...
+ if (forceJsonValidation)
+ {
//
// Validating JSON ...
try
{
- JsonDocument.Parse(json);
+ JsonDocument.Parse(result);
}
catch (JsonException ex)
{
//
- logger.LogError(ex, "Azure returned non-JSON data. Path: {Path} ...", relativePath);
+ logger.LogError(ex, "Azure returned non-JSON data. Path: {Path} ...", path);
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;
- }
+ //
+ return result;
}
#endregion
}
diff --git a/appsettings.Development.json b/appsettings.Development.json
index d10fcad..b7c20ea 100644
--- a/appsettings.Development.json
+++ b/appsettings.Development.json
@@ -9,7 +9,7 @@
},
"AzureServiceConfiguration": {
"Pat": "6zvwbdviuswlets7ovugq7nningtx4v6gqll7qkyqhnn75nrxh3q",
- "BaseUrl": "http://192.168.10.22:8080/tfs/RPKavoshDevOps"
+ "BaseUrl": "http://192.168.10.22:8080/tfs/RPKavoshDevOps/_apis"
},
"Logging": {
"LogLevel": {