using Adaptation.FileHandlers.ConvertExcelToJson; using Adaptation.FileHandlers.json.WorkItems; using Adaptation.Shared; using Adaptation.Shared.Duplicator; using Adaptation.Shared.Methods; using Microsoft.TeamFoundation.WorkItemTracking.WebApi; using Microsoft.VisualStudio.Services.WebApi.Patch; using Microsoft.VisualStudio.Services.WebApi.Patch.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace Adaptation.FileHandlers.json; public class ProcessData : IProcessData { private readonly List _Details; List Shared.Properties.IProcessData.Details => _Details; public ProcessData(IFileRead fileRead, Logistics logistics, List fileInfoCollection, HttpClient httpClient, string basePage, string api, string query, WorkItemTrackingHttpClient workItemTrackingHttpClient, string project, string json) { fileInfoCollection.Clear(); _Details = new List(); Parse(fileRead, logistics, fileInfoCollection, httpClient, basePage, api, query, workItemTrackingHttpClient, project, json); } string IProcessData.GetCurrentReactor(IFileRead fileRead, Logistics logistics, Dictionary reactors) => throw new Exception(string.Concat("See ", nameof(Parse))); Tuple> IProcessData.GetResults(IFileRead fileRead, Logistics logistics, List fileInfoCollection) => new(logistics.Logistics1[0], Array.Empty(), Array.Empty(), fileInfoCollection); internal static List GetDescriptions(JsonElement[] jsonElements) => throw new NotImplementedException(); #nullable enable private static void AddPatch(JsonPatchDocument document, string path, object value) => document.Add(new JsonPatchOperation { From = null, Operation = Operation.Add, Path = path, Value = value }); private static Dictionary GetFIBacklogMesaCollection(string json, string keySection) { Dictionary results = new(); string key; FIBacklogMesa[]? fiBacklogMesaCollection; fiBacklogMesaCollection = JsonSerializer.Deserialize(json, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); if (fiBacklogMesaCollection is null || !fiBacklogMesaCollection.Any()) throw new NullReferenceException(); foreach (FIBacklogMesa fIBacklogMesa in fiBacklogMesaCollection) { if (string.IsNullOrEmpty(fIBacklogMesa.Requestor)) continue; if (string.IsNullOrEmpty(fIBacklogMesa.Req)) continue; key = $"{fIBacklogMesa.Requestor.Split(' ').First()}{keySection}{fIBacklogMesa.Req}"; if (results.ContainsKey(key)) continue; results.Add(key, fIBacklogMesa); } return results; } private static string GetIds(HttpClient httpClient, string basePage, string api, string query) { StringBuilder result = new(); Task httpResponseMessageTask = httpClient.GetAsync(string.Concat(basePage, api, query)); httpResponseMessageTask.Wait(); if (!httpResponseMessageTask.Result.IsSuccessStatusCode) throw new Exception(httpResponseMessageTask.Result.StatusCode.ToString()); Task streamTask = httpResponseMessageTask.Result.Content.ReadAsStreamAsync(); streamTask.Wait(); if (!streamTask.Result.CanRead) throw new NullReferenceException(nameof(streamTask)); WIQL.Root? root = JsonSerializer.Deserialize(streamTask.Result, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); streamTask.Result.Dispose(); if (root is null || root.WorkItems is null) throw new NullReferenceException(nameof(root)); foreach (WIQL.WorkItem workItem in root.WorkItems) _ = result.Append(workItem.Id).Append(','); if (result.Length > 0) _ = result.Remove(result.Length - 1, 1); return result.ToString(); } private static Value[] GetWorkItems(HttpClient httpClient, string basePage, string api, string ids) { Value[]? results; // List results = new(); // Value? value; Task httpResponseMessageTask = httpClient.GetAsync(string.Concat(basePage, api, $"/workitems?ids={ids}")); httpResponseMessageTask.Wait(); if (!httpResponseMessageTask.Result.IsSuccessStatusCode) throw new Exception(httpResponseMessageTask.Result.StatusCode.ToString()); Task streamTask = httpResponseMessageTask.Result.Content.ReadAsStreamAsync(); streamTask.Wait(); if (!streamTask.Result.CanRead) throw new NullReferenceException(nameof(streamTask)); JsonElement? jsonElement = JsonSerializer.Deserialize(streamTask.Result); if (jsonElement is null || jsonElement.Value.ValueKind != JsonValueKind.Object) throw new NullReferenceException(nameof(jsonElement)); results = JsonSerializer.Deserialize(jsonElement.Value.EnumerateObject().Last().Value); if (results is null || !results.Any()) throw new NullReferenceException(nameof(results)); return results; } private static Value[] GetExtra(string keySection, IReadOnlyList workItems, Dictionary keyToFIBacklogMesa) { List results = new(); foreach (Value value in workItems) { if (!value.Fields.SystemTitle.Contains(keySection)) continue; if (keyToFIBacklogMesa.Remove(value.Fields.SystemTitle)) continue; results.Add(value); } return results.ToArray(); } private static string GetDescription(FIBacklogMesa fiBacklogMesa, DateTime dateTime) => $"Req:{fiBacklogMesa.Req}; Submitted:{(dateTime == DateTime.MinValue ? fiBacklogMesa.Submitted : dateTime.ToString("d-MMM-yy"))}; Requestor:{fiBacklogMesa.Requestor}; AssignedTo:{fiBacklogMesa.AssignedTo}; SecondResource:{fiBacklogMesa.SecondResource}; Systems:{fiBacklogMesa.SystemS}; "; private static void Update(HttpClient httpClient, string basePage, string api, string query, HttpContent httpContent) { #if CORE Task httpResponseMessageTask = httpClient.PatchAsync(string.Concat(basePage, api, query), httpContent); httpResponseMessageTask.Wait(); if (!httpResponseMessageTask.Result.IsSuccessStatusCode) throw new Exception(httpResponseMessageTask.Result.StatusCode.ToString()); Task stringTask = httpResponseMessageTask.Result.Content.ReadAsStringAsync(); stringTask.Wait(); #endif } private static void UpdateIds(HttpClient httpClient, string basePage, string api, string[] checkFiles) { int? idIndex; string[] lines; string[] segments; string stringPayload; HttpContent httpContent; foreach (string checkFile in checkFiles) { idIndex = null; lines = File.ReadAllLines(checkFile); if (lines.Length < 1) continue; segments = lines.First().Split(','); for (int i = 0; i < segments.Length; i++) { if (segments[i] == "ID") { idIndex = i; break; } } if (idIndex is null) continue; for (int i = 1; i < lines.Length; i++) { segments = lines[i].Split(','); if (segments.Length < idIndex.Value) continue; var payload = new { op = "replace", path = "/fields/System.IterationPath", value = "Mesa_FI" }; stringPayload = JsonSerializer.Serialize(payload); httpContent = new StringContent($"[{stringPayload}]", Encoding.UTF8, "application/json-patch+json"); Update(httpClient, basePage, api, $"/workitems/{segments[idIndex.Value].Replace("\"", string.Empty)}?api-version=1.0", httpContent); } } } private void Parse(IFileRead fileRead, Logistics logistics, List fileInfoCollection, HttpClient httpClient, string basePage, string api, string query, WorkItemTrackingHttpClient workItemTrackingHttpClient, string project, string json) { if (fileRead is null) throw new NullReferenceException(); if (logistics is null) throw new NullReferenceException(); if (fileInfoCollection is null) throw new NullReferenceException(); int counter = 0; DateTime dateTime; string description; string keySection = " UAT for "; string? directory = Path.GetDirectoryName(fileRead.ReportFullPath); if (directory is null) throw new Exception(); string[] checkFiles = Directory.GetFiles(directory, "*.csv", SearchOption.TopDirectoryOnly); if (checkFiles.Any()) UpdateIds(httpClient, basePage, api, checkFiles); else { string ids = GetIds(httpClient, basePage, api, query); Value[] workItems = GetWorkItems(httpClient, basePage, api, ids); Task workItemTask; Dictionary keyToFIBacklogMesa = GetFIBacklogMesaCollection(json, keySection); int count = keyToFIBacklogMesa.Count; Value[] extra = GetExtra(keySection, workItems, keyToFIBacklogMesa); if (count != extra.Length) { } if (count != keyToFIBacklogMesa.Count) { } _Details.AddRange(workItems); foreach (KeyValuePair keyValuePair in keyToFIBacklogMesa) { if (counter > 5) break; JsonPatchDocument document = new(); if (!DateTime.TryParse(keyValuePair.Value.Submitted, out dateTime)) dateTime = DateTime.MinValue; AddPatch(document, "/fields/System.AreaPath", project); description = GetDescription(keyValuePair.Value, dateTime); AddPatch(document, "/fields/System.IterationPath", project); AddPatch(document, "/fields/System.Title", keyValuePair.Key); AddPatch(document, "/fields/System.Description", description); // AddPatch(document, "/fields/System.AssignedTo", "Mike.Phares@infineon.com"); if (!fileRead.IsEAFHosted) continue; workItemTask = workItemTrackingHttpClient.CreateWorkItemAsync(document, project, "Task"); workItemTask.Wait(); counter++; if (workItemTask.Result is null) continue; } } } }