Compare commits

...
1 Commits
Author SHA1 Message Date
saherelm bc66d86ed2 endpoint implementation ... 2026-11-19 18:08:53 +03:30
7 changed files with 408 additions and 86 deletions
+15 -2
View File
@@ -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
}
}
+62 -5
View File
@@ -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
}
/// <summary>
/// Get connection data from Azure Services ...
/// Get Connection data from Azure Services ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("ConnectionData")]
public async Task<ActionResult<string>> GetConnectionData(
public async Task<ActionResult<AzureConnectionDataDto>> GetConnectionData(
CancellationToken cancellationToken = default
)
{
@@ -51,12 +52,12 @@ namespace xApi.Controllers
}
/// <summary>
/// Get projects from Azure Services ...
/// Get Projects from Azure Services ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("GetProjects")]
public async Task<ActionResult<string>> GetProjects(
public async Task<ActionResult<AzureListDto<AzureProjectDto>>> GetProjects(
CancellationToken cancellationToken = default
)
{
@@ -77,5 +78,61 @@ namespace xApi.Controllers
return StatusCode(500, "Internal server error");
}
}
/// <summary>
/// Get Repositories from Azure Services ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("GetRepositories")]
public async Task<ActionResult<AzureListDto<AzureRepositoryDto>>> 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");
}
}
/// <summary>
/// Get WorkItem Types from Azure Services ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("GetWorkItemTypes")]
public async Task<ActionResult<string>> 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");
}
}
}
}
+56
View File
@@ -0,0 +1,56 @@
using System.Text;
namespace xApi.Extensions
{
public static class HttpExtensions
{
/// <summary>
/// Apply Query String to Specified Url ...
/// </summary>
/// <param name="url"></param>
/// <param name="queries"></param>
/// <returns></returns>
public static string ApplyQueryString(
this string url,
IDictionary<string, string>? 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;
}
}
}
+32 -1
View File
@@ -7,12 +7,43 @@ namespace xApi.Interfaces
/// </summary>
public interface IAzureServices
{
/// <summary>
/// Retrieve Connection Info ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
Task<AzureConnectionDataDto> GetConnectionDataAsync(
CancellationToken cancellationToken = default
);
Task<string> GetProjectsAsync(
/// <summary>
/// Retrieve Connection Info ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
Task<AzureListDto<AzureProjectDto>> GetProjectsAsync(
CancellationToken cancellationToken = default
);
/// <summary>
/// Retrieve a List of Azure Repositories ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
Task<AzureListDto<AzureRepositoryDto>> GetRepositoriesAsync(
CancellationToken cancellationToken = default
);
Task<string> GetWorkItemTypesAsync(
CancellationToken cancellationToken = default
);
// AzureListDto<AzureRepositoryDto>
// Task<string> GetWorkItemsAsync(
// CancellationToken cancellationToken = default
// );
}
}
+72 -2
View File
@@ -57,7 +57,7 @@ namespace xApi.Models
[JsonPropertyName("properties")]
public Dictionary<string, AzurePropertyValueDto>? 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<T>
where T : class
{
[JsonPropertyName("count")]
public int Count { get; set; }
[JsonPropertyName("value")]
public List<T> Value { get; set; } = [];
}
}
+170 -75
View File
@@ -11,19 +11,16 @@ namespace xApi.Providers
{
//
private readonly ILogger<AzureServices> logger;
private readonly IHttpClientFactory httpClientFactory;
private readonly AzureServiceConfiguration configuration;
public AzureServices(
ILogger<AzureServices> logger,
IHttpClientFactory httpClientFactory,
AzureServiceConfiguration configuration
)
{
//
this.logger = logger;
this.configuration = configuration;
this.httpClientFactory = httpClientFactory;
}
/// <summary>
@@ -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<string> GetProjectsAsync(
/// <summary>
/// Retrieve a List of Azure Projects ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<AzureListDto<AzureProjectDto>> 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<AzureConnectionDataDto>();
var result = json.ParseJSON<AzureListDto<AzureProjectDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
/// <summary>
/// Retrieve a List of Azure Repositories ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<AzureListDto<AzureRepositoryDto>> GetRepositoriesAsync(
CancellationToken cancellationToken = default
)
{
//
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.RepositoriesEndpoint
);
//
var result = json.ParseJSON<AzureListDto<AzureRepositoryDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
public async Task<string> GetWorkItemTypesAsync(
CancellationToken cancellationToken = default
)
{
//
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.WorkItemsODataEndpoint
);
//
return json;
//
// var result = json.ParseJSON<AzureListDto<AzureRepositoryDto>>();
// 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 ...
/// <summary>
/// Handle Running Http Requests ...
/// </summary>
/// <param name="path"></param>
/// <param name="method"></param>
/// <param name="forceJsonValidation"></param>
/// <param name="headers"></param>
/// <param name="queryParams"></param>
/// <param name="routeParams"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<string> HandleAzureRequest(
string path,
HttpMethod method,
bool forceJsonValidation = true,
IDictionary<string, string>? headers = null,
IDictionary<string, string>? queryParams = null,
IDictionary<string, string>? 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<string> 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
}
+1 -1
View File
@@ -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": {