Azure DevOps通过Web Extension共享文件 [英] Azure DevOps share Files with Web Extension

查看:89
本文介绍了Azure DevOps通过Web Extension共享文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Buidlpipeline中有一个自定义的PowerShell任务.该任务将有关Buildprocess的信息存储在本地json文件中. (D:\AzureDevOpsData\Skripte\CoverageHistory.json)

I have a custom PowerShell Task inside a Buidlpipeline. That Task stores Informations about the Buildprocess in a local json file. (D:\AzureDevOpsData\Skripte\CoverageHistory.json)

另一个Web扩展应在自定义Web中心中显示json文件的内容.

Another web extension should display the content of the json-file in custom web-hub.

如何在这两个扩展之间共享信息?

我尝试过的事情:

//GET COVERAGE HISTORY JSON
console.log("Error 1:" + historyPath)
var request = new XMLHttpRequest();
console.log("Error 2");
request.open("GET", historyPath, false); //FALSE FOR SYNCHRONOUS REQUEST
console.log("Error 3");
request.send(null);
console.log("Error 4")

打开网络集线器后,我的输出是:

My output after open the web-hub is:

您可能会看到缺少的Error 3输出,因此失败的行必须为request.open("GET", historyPath, false);

You could see the missing Error 3 output so the failed line must be request.open("GET", historyPath, false);

我想了很多关于如何共享这些信息的想法,但是我不知道这样做的通用方法.

I thought a lot about how to share these information but I don't know a common way to do that.

推荐答案

经过一段时间的研究,我发现有机会使用

After a while of research, I found the opportunity to use Extension Documents from Data Storage for that.

我在Buildpipeline中添加了一个PowerShell任务,该任务将json文件转换为Document对象.

I add a PowerShell Task to my Buildpipeline that convert a json file to a Document Object.

param([string]$Uri, [string]$Collection = "DefaultCollection", [string]$Publisher, [string]$Extension, [string]$PAT, [string]$JsonPath)

#VARIABLES
$api = "api-version=3.1-preview.1"
$timeout = 30

#JSON TO EXTENSION SCRIPT
#-----------------------------------------------------------------------------------------------------#
##The script should upload a json file to a azure devops extension as a collection scoped document (data storage)[https://docs.microsoft.com/en-us/azure/devops/extend/develop/data-storage?view=azure-devops]
##Uri = is the uri of the azure devops server (`"{ip}:{port}"`)
##Collection = is the collection name where the extension is installed
##Publisher = is the publisher name of the extension
##Extension = is the the name of the istalled extension, which should get access to the document
##PAT = is a valid personal access token
##JsonPath = is the path of the json file
#-----------------------------------------------------------------------------------------------------#

Write-Host "Uri:`t`t`t$Uri`nCollection:`t$Collection`nPublisher:`t`t$Publisher`nExtension:`t`t$Extension`nPAT:`t`t`t$PAT`nJson Path:`t$JsonPath"

#CHECK ARGUMENTS
if ($Uri -eq "" -or $Collection -eq "" -or $PAT -eq "" -or $JsonPath -eq "") {
    Write-Host "##vso[task.logissue type=error;][ps1] missing uri ({ip}:{port}), collection name, publisher name, extension name, personal access token (PAT) or json file path" -ForegroundColor Red
    exit(-1)
}

#CHECK JSON FILE EXIST
if (-not [System.IO.File]::Exists($JsonPath)) { Write-Host "##vso[task.logissue type=error;][ps1] '$JsonPath' not found" -ForegroundColor Red; exit(-1) }

#READ JSON FILE
$jsonFile = Get-Content $JsonPath -Raw

#CHECK JSON VALID
try { ConvertFrom-Json $jsonFile -ErrorAction Stop; }
catch { Write-Host "##vso[task.logissue type=error;][ps1] '$JsonPath' is invalid:`n$jsonFile" -ForegroundColor Red; exit(-1) }

#AUTHORIZATION HEADERS
$headers = @{
    "Authorization" = ('Basic {0}' -f [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)")))
    "If-Match"      = ""
}

#GET ALL DOCUMENTS
$url = "$Uri/$Collection/_apis/ExtensionManagement/InstalledExtensions/$Publisher/$Extension/Data/Scopes/Default/Current/Collections/$Collection/Documents?"
$result = Invoke-RestMethod -Uri $url -Method GET -ContentType "application/json" -Headers $headers -TimeoutSec $timeout -Verbose
Write-Host "[ps1] get all documents: $result" -ForegroundColor Yellow

#REMOVE ALL DOCUMENTS
Write-Host "[ps1] documents to remove: $($result.count)" -ForegroundColor Yellow
for ($i = 0; $i -lt $result.count; $i++) {

    $id = $result.value[$i].id
    $url = "$Uri/$Collection/_apis/ExtensionManagement/InstalledExtensions/$Publisher/$Extension/Data/Scopes/Default/Current/Collections/$Collection/Documents/$($result.value[$i].id)?$api"
    try { Invoke-RestMethod -Uri $url -Method DELETE -ContentType "application/json" -Headers $headers -TimeoutSec $timeout -Verbose }
    catch { Write-Host "##vso[task.logissue type=error;][ps1] fail to remove document: $id" -ForegroundColor Red; exit(-1) }
    Write-Host "[ps1] delete document: $id" -ForegroundColor Yellow
}

#CREATE DOCUMENT
$body = $jsonFile
$url = "$Uri/$Collection/_apis/ExtensionManagement/InstalledExtensions/$Publisher/$Extension/Data/Scopes/Default/Current/Collections/$Collection/Documents?$api"
try { $result = Invoke-RestMethod -Uri $url -Method POST -ContentType "application/json" -Headers $headers -Body $body -TimeoutSec $timeout -Verbose }
catch { Write-Host "##vso[task.logissue type=error;][ps1] fail to create a document ('$url')" -ForegroundColor Red; exit(-1) }
Write-Host "[ps1] create document: $result" -ForegroundColor Green

#EXIT CODE
Write-Host "[ps1] exit code: 0" -ForegroundColor Green
exit(0)

Web扩展可以在JavaScript中的以下行中读取文档:

The Document can read out by the Web Extension with the following lines in JavaScript:

//GET AZURE DEVOPS COLLECTION
var collection = VSS.getWebContext().collection.name

//GET ALL DOCUMENTS OF EXTENSION
VSS.getService(VSS.ServiceIds.ExtensionData).then(function (dataService) {

    //GET DOCUMENT BY ID
    dataService.getDocuments(collection).then(function (docs) {
        try {
            var value = docs[0]
            console.log("[js] loading chart data:");
            console.log(value);

            //REMOVE ID
            if (value.hasOwnProperty("id")) delete value.id;

            //REMOVE ETAG
            if (value.hasOwnProperty("__etag")) delete value.__etag;
        }
        catch (e) {
            //CATCH MISSING VARIABLE GROUP
            console.log("[js] error while loading chart data:");
            console.log(e);
        }
    });
});

在浏览器控制台中,您可以检出json对象:

In the Browser Console you can check out the json object:

id__etag会自动添加,这就是我从json对象中删除它的方式.

id and __etag get added automatically, thats way I remove it from the json-object.

可能有更好的解决方案,但对我而言,它可以正常工作.如果您决定采用这种方式,请记住, Web扩展取决于PowerShell任务'JsonToExtension'.

There are may better solutions, but for me it works fine. If you decide to go this way, keep in mind, the web extensions depends to the PowerShell Task 'JsonToExtension'.

这篇关于Azure DevOps通过Web Extension共享文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆