private void UploadAttachmentAsync(int workItemId, string destinationResultsLocation, string fitnesseDataTableName)
{
string fi = System.IO.Directory.GetFiles(destinationResultsLocation).FirstOrDefault();
var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fi));
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
// Extract just the file name
var fileName = Path.GetFileName(fi);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = fileName,
Name = "file"
};
// Upload the file to Azure DevOps
string requestUrl = $"{OrganizationUrl}{ProjectName}/_apis/wit/attachments?api-version=7.0";
HttpResponseMessage response = client.PostAsync(requestUrl, fileContent).Result;
if (response.IsSuccessStatusCode)
{
var jsonResponse = response.Content.ReadAsStringAsync().Result;
// Extract attachment URL from the response
var jsonObject = JObject.Parse(jsonResponse);
// Extract the URL from the response, which contains the attachment URL
var attachmentUrl = jsonObject["url"].ToString();
// Now, link the attachment to the work item
LinkAttachmentToWorkItemAsync(workItemId, attachmentUrl, fileName);
}
else
{
Console.WriteLine("Error uploading attachment: " + response.StatusCode);
}
}
private void LinkAttachmentToWorkItemAsync(int workItemId, string attachmenturl, string fileName)
{
var jsonContent = new List
{
new JsonPatchOperation
{
op = "add",
path = "/relations/-", // Add a new relation (attachment)
value = new Relation
{
rel = "AttachedFile", // Define the type of relation (attachment)
url = attachmenturl, // URL where the attachment is stored
displayName = fileName, // Display name of the attachment
attributes = new attributes
{
comment = $"Uploaded attachment: {fileName}" // Optional comment or description
}
}
}
};
var content = new StringContent(_serializer.Serialize(jsonContent), Encoding.UTF8, "application/json-patch+json");
var response = client.PatchAsync($"{OrganizationUrl}{ProjectName}/_apis/wit/workitems/{workItemId}?api-version=7.1", content).Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Attachment linked to work item successfully.");
}
else
{
Console.WriteLine("Error linking attachment to work item: " + response.StatusCode);
}
}
Я могу успешно получить вложения, связанные с рабочим элементом, и если я загрузю вложение, я смогу увидеть данные. Но проблема в том, что во вложении не отображается имя файла. Когда я загружаю файл, имя будет идентификатором вложения. Как мне заставить это работать или это не поддерживается?
Я написал код для прикрепления файла к созданному рабочему элементу на C# с использованием REST API Azure Devops, как показано здесь: [code]private void UploadAttachmentAsync(int workItemId, string destinationResultsLocation, string fitnesseDataTableName) { string fi = System.IO.Directory.GetFiles(destinationResultsLocation).FirstOrDefault();
var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fi)); fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
// Extract just the file name var fileName = Path.GetFileName(fi); fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = fileName, Name = "file" };
// Upload the file to Azure DevOps string requestUrl = $"{OrganizationUrl}{ProjectName}/_apis/wit/attachments?api-version=7.0"; HttpResponseMessage response = client.PostAsync(requestUrl, fileContent).Result;
if (response.IsSuccessStatusCode) { var jsonResponse = response.Content.ReadAsStringAsync().Result; // Extract attachment URL from the response var jsonObject = JObject.Parse(jsonResponse); // Extract the URL from the response, which contains the attachment URL var attachmentUrl = jsonObject["url"].ToString();
// Now, link the attachment to the work item LinkAttachmentToWorkItemAsync(workItemId, attachmentUrl, fileName); } else { Console.WriteLine("Error uploading attachment: " + response.StatusCode); } }
private void LinkAttachmentToWorkItemAsync(int workItemId, string attachmenturl, string fileName) { var jsonContent = new List { new JsonPatchOperation { op = "add", path = "/relations/-", // Add a new relation (attachment) value = new Relation { rel = "AttachedFile", // Define the type of relation (attachment) url = attachmenturl, // URL where the attachment is stored displayName = fileName, // Display name of the attachment attributes = new attributes { comment = $"Uploaded attachment: {fileName}" // Optional comment or description } } } };
var content = new StringContent(_serializer.Serialize(jsonContent), Encoding.UTF8, "application/json-patch+json"); var response = client.PatchAsync($"{OrganizationUrl}{ProjectName}/_apis/wit/workitems/{workItemId}?api-version=7.1", content).Result;
if (response.IsSuccessStatusCode) { Console.WriteLine("Attachment linked to work item successfully."); } else { Console.WriteLine("Error linking attachment to work item: " + response.StatusCode); } } [/code] Я могу успешно получить вложения, связанные с рабочим элементом, и если я загрузю вложение, я смогу увидеть данные. Но проблема в том, что во вложении не отображается имя файла. Когда я загружаю файл, имя будет идентификатором вложения. Как мне заставить это работать или это не поддерживается?
Аналогично UnnotificationAttachment, не подходящему для прикрепления изображения, но Expo. Так что я сделал. const = useAssets(localAttachments ?? []);
const = useState([]);
useEffect(() => {
let mounted = true;
(async () => {
if (!localAssets) {...
Я пытаюсь автоматизировать активацию панели подключения к удаленному рабочему столу Azure, имитируя сочетание клавиш Ctrl + Alt + Home с помощью кода PowerShell и C#. Для этого я использую функцию keybd_event из библиотеки user32.dll для имитации...
I have a Winforms app written in c#, which needs to save a file on the desktop. I'm using Environment.GetFolderPath(Environment.SpecialFolder.Desktop) to get the path to the Desktop, and it runs fine. I need the app to also run on Linux (using...