Compare commits

..
2 Commits
Author SHA1 Message Date
saherelm 102e95c59d last ... 2026-11-21 17:47:56 +03:30
saherelm bc66d86ed2 endpoint implementation ... 2026-11-19 18:08:53 +03:30
10 changed files with 1385 additions and 93 deletions
+16 -2
View File
@@ -3,11 +3,25 @@ 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 WorkItemFieldsEndpoint = "/wit/fields";
public const string WorkItemsQueryEndpoint = "/wit/wiql";
public const string WorkItemsBaseEndpoint = "/wit/workitems";
public const string WorkItemTypesEndpoint = "/wit/workitemtypes";
public const string WorkItemsODataEndpoint = "Issue%20Tracker/_odata/v4.0-preview/WorkItems?$top=1&$select=WorkItemId,Title";
#endregion
}
}
+163 -5
View File
@@ -1,3 +1,4 @@
using xApi.Models;
using xApi.Interfaces;
using Microsoft.AspNetCore.Mvc;
@@ -5,7 +6,7 @@ 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,162 @@ 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="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("WorkItem/{id}")]
public async Task<ActionResult<AzureWorkItemDto>> GetWorkItem(
[FromRoute] long id,
CancellationToken cancellationToken = default
)
{
//
try
{
//
var response = await azureServices
.GetWorkItemAsync(
workItemId: id,
cancellationToken: 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="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("WorkItem/{id}/Revisions")]
public async Task<ActionResult<AzureWorkItemDto>> GetWorkItemRevisions(
[FromRoute] long id,
CancellationToken cancellationToken = default
)
{
//
try
{
//
var response = await azureServices
.GetWorkItemRevisionsAsync(
workItemId: id,
cancellationToken: cancellationToken
);
//
return Ok(response);
}
catch (Exception ex)
{
//
logger.LogError(ex, "Error occurred ...");
return StatusCode(500, "Internal server error");
}
}
/// <summary>
/// Retrieve Work Item Fields ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("WorkItems/Fields")]
public async Task<ActionResult<AzureListDto<AzureWorkItemFieldDto>>> GetWorkItemFields(
CancellationToken cancellationToken = default
)
{
//
try
{
//
var response = await azureServices
.GetWorkItemFieldsAsync(
cancellationToken: cancellationToken
);
//
return Ok(response);
}
catch (Exception ex)
{
//
logger.LogError(ex, "Error occurred ...");
return StatusCode(500, "Internal server error");
}
}
/// <summary>
/// Get Specified Project's WorkItem Types ...
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("projects/{id}/WorkItemTypes")]
public async Task<ActionResult<AzureListDto<AzureWorkItemTypeDto>>> GetProjectWorkItemTypes(
[FromRoute] Guid id,
CancellationToken cancellationToken
)
{
//
try
{
//
var response = await azureServices
.GetProjectWorkItemTypesAsync(
id: id,
cancellationToken: cancellationToken
);
//
return Ok(response);
}
catch (Exception ex)
{
//
logger.LogError(ex, "Error occurred ...");
return StatusCode(500, "Internal server error");
}
}
}
}
+77
View File
@@ -0,0 +1,77 @@
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;
}
/// <summary>
/// Normalize a URL Segment ...
/// </summary>
/// <param name="segment"></param>
/// <returns></returns>
public static string NormalizeUrlSegent(
this string segment
)
{
//
if (!string.IsNullOrWhiteSpace(segment) &&
segment.StartsWith("/")
)
{
segment = segment[1..];
}
//
return segment;
}
}
}
+333
View File
@@ -0,0 +1,333 @@
using xApi.Models;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace xApi.Helpers
{
public struct AzureWorkItemJsonProperties
{
public const string State = "System.State";
public const string Title = "System.Title";
public const string Reason = "System.Reason";
public const string AreaPath = "System.AreaPath";
public const string CreatedBy = "System.CreatedBy";
public const string ChangedBy = "System.ChangedBy";
public const string AssignedTo = "System.AssignedTo";
public const string ChangedDate = "System.ChangedDate";
public const string BoardColumn = "System.BoardColumn";
public const string Description = "System.Description";
public const string CreatedDate = "System.CreatedDate";
public const string TeamProject = "System.TeamProject";
public const string CommentCount = "System.CommentCount";
public const string WorkItemType = "System.WorkItemType";
public const string IterationPath = "System.IterationPath";
public const string BoardColumnDone = "System.BoardColumnDone";
}
public class AzureWorkItemFieldsDtoConverter : JsonConverter<AzureWorkItemFieldsDto>
{
public override AzureWorkItemFieldsDto Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options
)
{
//
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException("WorkItem fields must be a JSON object.");
}
//
var dto = new AzureWorkItemFieldsDto();
while (reader.Read())
{
//
if (reader.TokenType == JsonTokenType.EndObject)
{
return dto;
}
//
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new JsonException();
}
//
var propertyName = reader.GetString()!;
reader.Read();
switch (propertyName)
{
//
case AzureWorkItemJsonProperties.AreaPath:
dto.AreaPath = ReadString(ref reader);
break;
//
case AzureWorkItemJsonProperties.TeamProject:
dto.TeamProject = ReadString(ref reader);
break;
//
case AzureWorkItemJsonProperties.IterationPath:
dto.IterationPath = ReadString(ref reader);
break;
//
case AzureWorkItemJsonProperties.WorkItemType:
dto.WorkItemType = ReadString(ref reader);
break;
//
case AzureWorkItemJsonProperties.State:
dto.State = ReadString(ref reader);
break;
//
case AzureWorkItemJsonProperties.Reason:
dto.Reason = ReadString(ref reader);
break;
//
case AzureWorkItemJsonProperties.AssignedTo:
dto.AssignedTo = ReadAssignee(ref reader, options);
break;
//
case AzureWorkItemJsonProperties.CreatedDate:
dto.CreatedDate = ReadDateTimeOffset(ref reader);
break;
//
case AzureWorkItemJsonProperties.CreatedBy:
dto.CreatedBy = ReadAssignee(ref reader, options);
break;
//
case AzureWorkItemJsonProperties.ChangedDate:
dto.ChangedDate = ReadDateTimeOffset(ref reader);
break;
//
case AzureWorkItemJsonProperties.ChangedBy:
dto.ChangedBy = ReadAssignee(ref reader, options);
break;
//
case AzureWorkItemJsonProperties.CommentCount:
dto.CommentCount = ReadInt32(ref reader);
break;
//
case AzureWorkItemJsonProperties.Title:
dto.Title = ReadString(ref reader);
break;
//
case AzureWorkItemJsonProperties.BoardColumn:
dto.BoardColumn = ReadString(ref reader);
break;
//
case AzureWorkItemJsonProperties.BoardColumnDone:
dto.BoardColumnDone = ReadBoolean(ref reader);
break;
//
case AzureWorkItemJsonProperties.Description:
dto.Description = ReadString(ref reader);
break;
//
default:
dto.OtherFields[propertyName] = ReadValueAsString(ref reader);
break;
}
}
//
throw new JsonException("Unexpected end of JSON.");
}
public override void Write(
Utf8JsonWriter writer,
AzureWorkItemFieldsDto value,
JsonSerializerOptions options
)
{
//
writer.WriteStartObject();
//
WriteString(writer, AzureWorkItemJsonProperties.AreaPath, value.AreaPath);
WriteString(writer, AzureWorkItemJsonProperties.TeamProject, value.TeamProject);
WriteString(writer, AzureWorkItemJsonProperties.IterationPath, value.IterationPath);
WriteString(writer, AzureWorkItemJsonProperties.WorkItemType, value.WorkItemType);
WriteString(writer, AzureWorkItemJsonProperties.State, value.State);
WriteString(writer, AzureWorkItemJsonProperties.Reason, value.Reason);
//
WriteAssignee(writer, AzureWorkItemJsonProperties.AssignedTo, value.AssignedTo, options);
WriteDateTimeOffset(writer, AzureWorkItemJsonProperties.CreatedDate, value.CreatedDate);
WriteAssignee(writer, AzureWorkItemJsonProperties.CreatedBy, value.CreatedBy, options);
WriteDateTimeOffset(writer, AzureWorkItemJsonProperties.ChangedDate, value.ChangedDate);
WriteAssignee(writer, AzureWorkItemJsonProperties.ChangedBy, value.ChangedBy, options);
//
writer.WriteNumber(AzureWorkItemJsonProperties.CommentCount, value.CommentCount);
WriteString(writer, AzureWorkItemJsonProperties.Title, value.Title);
WriteString(writer, AzureWorkItemJsonProperties.BoardColumn, value.BoardColumn);
//
writer.WriteBoolean(AzureWorkItemJsonProperties.BoardColumnDone, value.BoardColumnDone);
WriteString(writer, AzureWorkItemJsonProperties.Description, value.Description);
//
foreach (var item in value.OtherFields)
{
writer.WriteString(item.Key, item.Value);
}
//
writer.WriteEndObject();
}
private static string? ReadString(ref Utf8JsonReader reader)
=> reader.TokenType == JsonTokenType.Null
? null
: reader.GetString();
private static AzureAssigneeDto? ReadAssignee(
ref Utf8JsonReader reader,
JsonSerializerOptions options
)
{
//
if (reader.TokenType == JsonTokenType.Null)
{
return null;
}
using var doc = JsonDocument.ParseValue(ref reader);
var result = doc.RootElement.Deserialize<AzureAssigneeDto>(options);
//
return result;
}
private static DateTimeOffset? ReadDateTimeOffset(ref Utf8JsonReader reader)
=> reader.TokenType == JsonTokenType.Null
? null
: reader.GetDateTimeOffset();
private static int ReadInt32(ref Utf8JsonReader reader)
=> reader.TokenType == JsonTokenType.Null
? 0
: reader.GetInt32();
private static bool ReadBoolean(ref Utf8JsonReader reader)
=> reader.TokenType != JsonTokenType.Null && reader.GetBoolean();
private static string ReadValueAsString(ref Utf8JsonReader reader)
{
//
switch (reader.TokenType)
{
//
case JsonTokenType.String:
return reader.GetString() ?? "null";
//
case JsonTokenType.Null:
return "null";
//
case JsonTokenType.True:
return "true";
//
case JsonTokenType.False:
return "false";
//
case JsonTokenType.Number:
{
//
using var doc = JsonDocument.ParseValue(ref reader);
return doc.RootElement.GetRawText();
}
//
case JsonTokenType.StartObject:
case JsonTokenType.StartArray:
{
//
using var doc = JsonDocument.ParseValue(ref reader);
return doc.RootElement.GetRawText();
}
//
default:
{
//
using var doc = JsonDocument.ParseValue(ref reader);
return doc.RootElement.GetRawText();
}
}
}
private static void WriteString(
Utf8JsonWriter writer,
string name,
string? value
)
{
//
if (value is null)
{
writer.WriteNull(name);
}
else
{
writer.WriteString(name, value);
}
}
private static void WriteDateTimeOffset(
Utf8JsonWriter writer,
string name,
DateTimeOffset? value
)
{
//
if (value.HasValue)
{
writer.WriteString(name, value.Value);
}
else
{
writer.WriteNull(name);
}
}
private static void WriteAssignee(
Utf8JsonWriter writer,
string name,
AzureAssigneeDto? value,
JsonSerializerOptions options
)
{
//
writer.WritePropertyName(name);
if (value is null)
{
writer.WriteNullValue();
}
else
{
JsonSerializer.Serialize(writer, value, options);
}
}
}
}
+70 -1
View File
@@ -7,12 +7,81 @@ 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
);
/// <summary>
/// Retrieve Specified Work Item ...
/// </summary>
/// <param name="workItemId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<AzureWorkItemDto> GetWorkItemAsync(
long workItemId,
CancellationToken cancellationToken = default
);
/// <summary>
/// Get Specified Project's WorkItem Types ...
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<AzureListDto<AzureWorkItemTypeDto>> GetProjectWorkItemTypesAsync(
Guid id,
CancellationToken cancellationToken = default
);
/// <summary>
/// Get Specified WorkItem Revisions (History) ...
/// </summary>
/// <param name="workItemId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<AzureListDto<WorkItemRevisionDto>> GetWorkItemRevisionsAsync(
long workItemId,
CancellationToken cancellationToken = default
);
/// <summary>
/// Retrieve Work Item Fields ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<AzureListDto<AzureWorkItemFieldDto>> GetWorkItemFieldsAsync(
CancellationToken cancellationToken = default
);
// AzureListDto<AzureRepositoryDto>
// Task<string> GetWorkItemsAsync(
// CancellationToken cancellationToken = default
// );
}
}
+369 -2
View File
@@ -1,4 +1,6 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using xApi.Helpers;
namespace xApi.Models
{
@@ -57,7 +59,7 @@ namespace xApi.Models
[JsonPropertyName("properties")]
public Dictionary<string, AzurePropertyValueDto>? Properties { get; set; }
}
}
public class AzureLocationServiceDto
{
@@ -72,5 +74,370 @@ 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 AzureWorkItemDto
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("rev")]
public int Rev { get; set; }
[JsonPropertyName("fields")]
public AzureWorkItemFieldsDto? Fields { get; set; }
[JsonPropertyName("_links")]
public AzureWorkItemLinksDto? Links { get; set; }
[JsonPropertyName("url")]
public string? Url { get; set; }
}
[JsonConverter(typeof(AzureWorkItemFieldsDtoConverter))]
public class AzureWorkItemFieldsDto
{
[JsonPropertyName("System.AreaPath")]
public string? AreaPath { get; set; }
[JsonPropertyName("System.TeamProject")]
public string? TeamProject { get; set; }
[JsonPropertyName("System.IterationPath")]
public string? IterationPath { get; set; }
[JsonPropertyName("System.WorkItemType")]
public string? WorkItemType { get; set; }
[JsonPropertyName("System.State")]
public string? State { get; set; }
[JsonPropertyName("System.Reason")]
public string? Reason { get; set; }
[JsonPropertyName("System.AssignedTo")]
public AzureAssigneeDto? AssignedTo { get; set; }
[JsonPropertyName("System.CreatedDate")]
public DateTimeOffset? CreatedDate { get; set; }
[JsonPropertyName("System.CreatedBy")]
public AzureAssigneeDto? CreatedBy { get; set; }
[JsonPropertyName("System.ChangedDate")]
public DateTimeOffset? ChangedDate { get; set; }
[JsonPropertyName("System.ChangedBy")]
public AzureAssigneeDto? ChangedBy { get; set; }
[JsonPropertyName("System.CommentCount")]
public int CommentCount { get; set; }
[JsonPropertyName("System.Title")]
public string? Title { get; set; }
[JsonPropertyName("System.BoardColumn")]
public string? BoardColumn { get; set; }
[JsonPropertyName("System.BoardColumnDone")]
public bool BoardColumnDone { get; set; }
[JsonPropertyName("System.Description")]
public string? Description { get; set; }
public Dictionary<string, string> OtherFields { get; set; }
= new(StringComparer.OrdinalIgnoreCase);
}
public class WorkItemRevisionDto
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("rev")]
public int Rev { get; set; }
[JsonPropertyName("fields")]
public AzureWorkItemFieldsDto? Fields { get; set; }
[JsonPropertyName("url")]
public string? Url { get; set; }
}
public class AzureWorkItemTypeDto
{
[JsonPropertyName("name")]
public string? Name { get; set; }
[JsonPropertyName("referenceName")]
public string? ReferenceName { get; set; }
[JsonPropertyName("description")]
public string? Description { get; set; }
[JsonPropertyName("color")]
public string? Color { get; set; }
[JsonPropertyName("icon")]
public AzureWorkItemTypeIconDto? Icon { get; set; }
[JsonPropertyName("isDisabled")]
public bool IsDisabled { get; set; }
[JsonPropertyName("xmlForm")]
public string? XmlForm { get; set; }
[JsonPropertyName("fields")]
public List<AzureWorkItemFieldDefinitionDto> Fields { get; set; } = [];
[JsonPropertyName("fieldInstances")]
public List<AzureWorkItemFieldDefinitionDto> FieldInstances { get; set; } = [];
[JsonPropertyName("transitions")]
public Dictionary<string, List<AzureWorkItemTransitionDto>> Transitions { get; set; } = [];
[JsonPropertyName("states")]
public List<AzureWorkItemStateDto> States { get; set; } = [];
[JsonPropertyName("url")]
public string? Url { get; set; }
}
public class AzureWorkItemFieldDto
{
[JsonPropertyName("name")]
public string? Name { get; set; }
[JsonPropertyName("referenceName")]
public string? ReferenceName { get; set; }
[JsonPropertyName("description")]
public string? Description { get; set; }
[JsonPropertyName("type")]
public string? Type { get; set; }
[JsonPropertyName("usage")]
public string? Usage { get; set; }
[JsonPropertyName("readOnly")]
public bool ReadOnly { get; set; }
[JsonPropertyName("canSortBy")]
public bool CanSortBy { get; set; }
[JsonPropertyName("isQueryable")]
public bool IsQueryable { get; set; }
[JsonPropertyName("supportedOperations")]
public List<AzureFieldSupportedOperationDto> SupportedOperations { get; set; } = new();
[JsonPropertyName("isIdentity")]
public bool IsIdentity { get; set; }
[JsonPropertyName("isPicklist")]
public bool IsPicklist { get; set; }
[JsonPropertyName("isPicklistSuggested")]
public bool IsPicklistSuggested { get; set; }
[JsonPropertyName("url")]
public string? Url { get; set; }
[JsonExtensionData]
public Dictionary<string, JsonElement>? AdditionalProperties { get; set; }
}
public class AzureFieldSupportedOperationDto
{
[JsonPropertyName("referenceName")]
public string? ReferenceName { get; set; }
[JsonPropertyName("name")]
public string? Name { get; set; }
}
public class AzureWorkItemFieldDefinitionDto
{
[JsonPropertyName("defaultValue")]
public JsonElement? DefaultValue { get; set; }
[JsonPropertyName("helpText")]
public string? HelpText { get; set; }
[JsonPropertyName("alwaysRequired")]
public bool AlwaysRequired { get; set; }
[JsonPropertyName("referenceName")]
public string? ReferenceName { get; set; }
[JsonPropertyName("name")]
public string? Name { get; set; }
[JsonPropertyName("url")]
public string? Url { get; set; }
[JsonExtensionData]
public Dictionary<string, JsonElement>? AdditionalProperties { get; set; }
}
public class AzureWorkItemTransitionDto
{
[JsonPropertyName("to")]
public string? To { get; set; }
[JsonPropertyName("actions")]
public List<string>? Actions { get; set; }
}
public class AzureWorkItemStateDto
{
[JsonPropertyName("name")]
public string? Name { get; set; }
[JsonPropertyName("color")]
public string? Color { get; set; }
[JsonPropertyName("category")]
public string? Category { get; set; }
}
public class AzureWorkItemTypeIconDto
{
[JsonPropertyName("id")]
public string? Id { get; set; }
[JsonPropertyName("url")]
public string? Url { get; set; }
}
public class AzureAssigneeDto
{
[JsonPropertyName("displayName")]
public string? DisplayName { get; set; }
[JsonPropertyName("url")]
public string? Url { get; set; }
[JsonPropertyName("_links")]
public AzureAssigneeLinksDto? Links { get; set; }
[JsonPropertyName("id")]
public string? Id { get; set; }
[JsonPropertyName("uniqueName")]
public string? UniqueName { get; set; }
[JsonPropertyName("imageUrl")]
public string? ImageUrl { get; set; }
[JsonPropertyName("descriptor")]
public string? Descriptor { get; set; }
}
public class AzureAssigneeLinksDto
{
[JsonPropertyName("avatar")]
public AzureItemLinkDto? Avatar { get; set; }
}
public class AzureWorkItemLinksDto
{
[JsonPropertyName("self")]
public AzureItemLinkDto? Self { get; set; }
[JsonPropertyName("workItemUpdates")]
public AzureItemLinkDto? WorkItemUpdates { get; set; }
[JsonPropertyName("workItemRevisions")]
public AzureItemLinkDto? WorkItemRevisions { get; set; }
[JsonPropertyName("workItemComments")]
public AzureItemLinkDto? WorkItemComments { get; set; }
[JsonPropertyName("html")]
public AzureItemLinkDto? Html { get; set; }
[JsonPropertyName("workItemType")]
public AzureItemLinkDto? WorkItemType { get; set; }
[JsonPropertyName("fields")]
public AzureItemLinkDto? Fields { get; set; }
}
public class AzureItemLinkDto
{
[JsonPropertyName("href")]
public string? Href { get; set; }
}
public class AzureListDto<T>
where T : class
{
[JsonPropertyName("count")]
public int Count { get; set; }
[JsonPropertyName("value")]
public List<T> Value { get; set; } = [];
}
}
+1
View File
@@ -4,5 +4,6 @@ namespace xApi.Models
{
public string? Pat { get; set; }
public string? BaseUrl { get; set; }
public string? ApiSuffix { get; set; }
}
}
+1 -1
View File
@@ -2,8 +2,8 @@ using xApi.Extensions;
using xApi.Attributes;
using System.Reflection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.SwaggerGen;
//
// Access Application Builder ...
+352 -80
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,259 @@ 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,
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.ProjectsEndpoint
);
//
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;
}
/// <summary>
/// Retrieve Specified Work Item ...
/// </summary>
/// <param name="workItemId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<AzureWorkItemDto> GetWorkItemAsync(
long workItemId,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (workItemId <= 0)
{
//
var message = "Invalid Args ...";
//
logger.LogError(message);
throw new ArgumentException(message);
}
//
// Prepare WorkItem Path ...
var path = $"{AzureEndpoints.WorkItemsBaseEndpoint}/{workItemId}";
var json = await HandleAzureRequest(
path: path,
method: HttpMethod.Get,
cancellationToken: cancellationToken
);
//
// var result = json.ParseJSON<AzureConnectionDataDto>();
// if (result is null)
// {
// //
// var message = "Failed to parse Azure connection data ...";
var result = json.ParseJSON<AzureWorkItemDto>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
// //
// logger.LogError(message);
// throw new InvalidOperationException(message);
// }
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return json;
return result;
}
/// <summary>
/// Retrieve Work Item Fields ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<AzureListDto<AzureWorkItemFieldDto>> GetWorkItemFieldsAsync(
CancellationToken cancellationToken = default
)
{
//
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.WorkItemFieldsEndpoint
);
//
var result = json.ParseJSON<AzureListDto<AzureWorkItemFieldDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
/// <summary>
/// Get Specified Project's WorkItem Types ...
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<AzureListDto<AzureWorkItemTypeDto>> GetProjectWorkItemTypesAsync(
Guid id,
CancellationToken cancellationToken = default
)
{
//
// Prepare Custom Path for WorkItem ...
var path = $"{PrepareProjectBaseUrl(id)}/{AzureEndpoints.WorkItemTypesEndpoint.NormalizeUrlSegent()}";
//
var json = await HandleAzureRequest(
path: path,
forceApiSuffix: false,
method: HttpMethod.Get,
forceJsonValidation: true,
cancellationToken: cancellationToken
);
//
var result = json.ParseJSON<AzureListDto<AzureWorkItemTypeDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
/// <summary>
/// Get Specified WorkItem Revisions (History) ...
/// </summary>
/// <param name="workItemId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<AzureListDto<WorkItemRevisionDto>> GetWorkItemRevisionsAsync(
long workItemId,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (workItemId <= 0)
{
//
var message = "Invalid Args ...";
//
logger.LogError(message);
throw new ArgumentException(message);
}
//
// Prepare WorkItem Path ...
var path = $"{AzureEndpoints.WorkItemsBaseEndpoint}/{workItemId}/revisions";
var json = await HandleAzureRequest(
path: path,
method: HttpMethod.Get,
cancellationToken: cancellationToken
);
//
var result = json.ParseJSON<AzureListDto<WorkItemRevisionDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
//
#region Private ...
/// <summary>
/// Handle Running Http Requests ...
/// </summary>
/// <param name="path"></param>
/// <param name="method"></param>
/// <param name="forceApiSuffix"></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 forceApiSuffix = true,
bool forceJsonValidation = true,
IDictionary<string, string>? headers = null,
IDictionary<string, string>? queryParams = null,
IDictionary<string, string>? routeParams = null,
@@ -115,6 +335,7 @@ namespace xApi.Providers
//
// Create Http Client ...
var result = string.Empty;
using (HttpClient client = new())
{
//
@@ -136,6 +357,26 @@ namespace xApi.Providers
{
url += "/";
}
//
// Handle Suffix ...
if (forceApiSuffix &&
!string.IsNullOrWhiteSpace(configuration.ApiSuffix)
)
{
//
var suffix = configuration.ApiSuffix;
if (suffix.StartsWith('/'))
{
suffix = suffix[1..];
}
//
url += $"{suffix}/";
}
//
// Normalize Path ...
if (path.StartsWith('/'))
{
path = path[1..];
@@ -144,7 +385,8 @@ namespace xApi.Providers
//
// Handle Route Params ...
if (routeParams is not null &&
routeParams.Any())
routeParams.Any()
)
{
//
var exists =
@@ -159,91 +401,121 @@ 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);
// Handle Request ...
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;
}
private string PrepareProjectBaseUrl(
Guid id
)
{
//
var result = $"{id}/{configuration.ApiSuffix?.NormalizeUrlSegent()}";
if (result.EndsWith('/')) {
result = result[..^1];
}
//
return result;
}
#endregion
}
+3 -2
View File
@@ -8,8 +8,9 @@
"Url": "https://rpkavosh.ir"
},
"AzureServiceConfiguration": {
"Pat": "6zvwbdviuswlets7ovugq7nningtx4v6gqll7qkyqhnn75nrxh3q",
"BaseUrl": "http://192.168.10.22:8080/tfs/RPKavoshDevOps"
"ApiSuffix": "/_apis",
"BaseUrl": "http://192.168.10.22:8080/tfs/RPKavoshDevOps",
"Pat": "6zvwbdviuswlets7ovugq7nningtx4v6gqll7qkyqhnn75nrxh3q"
},
"Logging": {
"LogLevel": {