API: Trying to set name of an appveyor project - api

I am trying to create an appveyor project using powershell and set my own name.
function Invoke-AppveyorCreateProject {
param (
[System.String] $appveyorProjectName,
[System.String] $repositoryName
)
# step 1, create project
$project = #{
repositoryProvider="gitHub"
repositoryName="esskar/$repositoryName"
isPrivate=$true
}
$json = $project | ConvertTo-Json
$project = Invoke-RestMethod -Method Post -Uri "$AppveyorApiUrl/projects" -Headers $AppveyorRestHeaders -Body $json -ContentType "application/json"
# step 2, update project
$project.name = $appveyorProjectName
$json = $project | ConvertTo-Json
$project = Invoke-RestMethod -Method Put -Uri "$AppveyorApiUrl/projects" -Headers $AppveyorRestHeaders -Body $json -ContentType "application/json"
}
# Globals
$AppveyorApiUrl = 'https://ci.appveyor.com/api'
$AppveyorApiToken = $env:AppveyorApiToken
$AppveyorRestHeaders = #{
"Authorization" = "Bearer $AppveyorApiToken"
"Content-type" = "application/json"
}
$AppveyorAccountName = $env:AppveyorAccountName
Invoke-AppveyorCreateProject "foo.bar" "repo1"
Step 1 works, the project is created, but when I try to change the name, i get an exception
Invoke-RestMethod : {"message":"Object reference not set to an instance of an object."}
At appveyortest.ps1:20 char:16
+ ... $project = Invoke-RestMethod -Method Put -Uri "$AppveyorApiUrl/proje ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
when i try to set the name during creation in step 1, then name is not used, and project has the same name as without setting the name.

Use the following code for the Step 2:
$settings = Invoke-RestMethod -Uri "$AppveyorApiUrl/projects/$($project.accountName)/$($project.slug)/settings" -Headers $AppveyorRestHeaders -Method Get
$settings.settings.name = $appveyorProjectName
Invoke-RestMethod -Uri "$AppveyorApiUrl/projects" -Headers $AppveyorRestHeaders -Body ($settings.settings | ConvertTo-Json -Depth 10) -Method Put

Related

Check if current user has permissions to create work items

Is there an endpoint in TFS rest api that i can use to check if the current logged in user has enough permissions to create a new TFS work item ?
Try to use validation with the validateOnly parameter Work Items - Create.
PowerShell sample:
$pat = '<pat>'
$url = 'https://dev.azure.com/<org>/<project>/_apis/wit/workitems/$Task?validateOnly=true&api-version=6.1-preview.3'
$body = '[{"op":"add","path":"/fields/System.Title","from":null,"value":"Sample task"}]'
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "",$pat)))
Invoke-RestMethod -Uri $url -Method Post -ContentType "application/json-patch+json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $body
Result:
Invoke-RestMethod : {"$id":"1","innerException":null,"message":"TF237111: The current user does not have permissions to save work items under the specified area path.","typeName":"Microsoft.Azure.Boards.WebApi.Com
mon.PermissionDeniedException, Microsoft.Azure.Boards.WebApi.Common","typeKey":"PermissionDeniedException","errorCode":0,"eventId":3000}
At line:10 char:1
+ Invoke-RestMethod -Uri $url -Method Post -ContentType "application/js ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Azure pipelines: How to add failed selenium Xunit test case attachment in VS test task

I use the Xunit2 selenium framework for automated test cases. Some case fails in pipeline. I want to see the attachment of the fail test case in the Test tab. How can I do this using VS test task?
The option publishRunAttachments: true, it will update attachments to Test run attachment tab, check the pic below
After the VS test task runs, we can get the run ID through the variable VSTEST_TESTRUNID.
Then we could call the RESST API Create Test Result Attachment to add attachments to the test result attachment tab.
Request API:
POST https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/attachments?api-version=6.0-preview.1
Request Body:
{
"stream": "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAIAAABvFaqvAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABlSURBVDhP7cxBCsAgDERR739pG/CnGJI0FopQ8O2cjNP6R85QbeNQU7wT1dkijaQ3vkZoWElaoTeJojW01cYh0jwfgiFBV/lEjOZtacijN/nLkOBHhIaVDgn+Wdycp6FXzlCl9wt0Y0cAzHo/zgAAAABJRU5ErkJggg==",
"fileName": "imageAsFileAttachment.png",
"comment": "Test attachment upload",
"attachmentType": "GeneralAttachment"
}
You could also check this thread
Update1
We could add task power shell and call the rest api via below script:
$connectionToken="{PAT}"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$URL = "https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/attachments?api-version=6.0-preview.1"
$body =#"
{
"stream": "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAIAAABvFaqvAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABlSURBVDhP7cxBCsAgDERR739pG/CnGJI0FopQ8O2cjNP6R85QbeNQU7wT1dkijaQ3vkZoWElaoTeJojW01cYh0jwfgiFBV/lEjOZtacijN/nLkOBHhIaVDgn+Wdycp6FXzlCl9wt0Y0cAzHo/zgAAAABJRU5ErkJggg==",
"fileName": "imageAsFileAttachment.png",
"comment": "Test attachment upload",
"attachmentType": "GeneralAttachment"
}
"#
$Result = Invoke-RestMethod -Uri $URL -ContentType "application/json" -Body $body -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST
Update2
Check the pic below and notice the URL
According to the screenshot you shared before, it seems that you want to add attachments to the test run instead of test result. So we just need test run ID and we could get the test run ID from variable after the task vs test ends.
If you want to add attachments to test result, we could list all test result via test run ID.
Sample URL:
GET https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{RunID}/results
The add attachments to the test result via test result ID and test run ID.
Sample power shell script to list all test result ID
$connectionToken="{PAT}"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$URL = "https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{RunID}/results"
$Result = Invoke-RestMethod -Uri $URL -Headers #{authorization = "Basic $base64AuthInfo"} -Method Get
foreach($Run in $Result.value){
Write-Host "This test run contain" $Run.id "and the test reuslt name is" $Run.testCase.name
}
Update3
$connectionToken="{PAT}"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$URL = "https://dev.azure.com/{organization}/{project}/_apis/test/Runs/134/results"
$Result = Invoke-RestMethod -Uri $URL -Headers #{authorization = "Basic $base64AuthInfo"} -Method Get
#List all test result get the test result ID via result
foreach($Run in $Result.value){
#Get the test result ID via result
If($Run.outcome -eq "Failed"){
$TestResultID = $Run.id
#Write-Host $TestResultID
#Add attachment via test run ID and test result ID
$TestResultAttachmentURL = "https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/Results/$($TestResultID)/attachments?api-version=6.0-preview.1"
$body =#"
{
"stream": "VXNlciB0ZXh0IGNvbnRlbnQgdG8gdXBsb2FkLg==",
"fileName": "textAsFileAttachment.txt",
"comment": "Test attachment upload",
"attachmentType": "GeneralAttachment"
}
"#
$TestResultAttachmentResult = Invoke-RestMethod -Uri $TestResultAttachmentURL -ContentType "application/json" -Body $body -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST
}
}
Update4
$AzureDevOpsPAT = {PAT}
$AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
$UriOrga = "https://dev.azure.com/{organization}/{project}/"
$uriAccount = $UriOrga + "_apis/test/runs?api-version=6.0"
$response = Invoke-RestMethod -Uri $uriAccount -Headers $AzureDevOpsAuthenicationHeader -Method Get
$testRunsIdSorted = $response.value | sort-object id -Descending
Write-Host "##vso[task.setvariable variable=runId]$($testRunsIdSorted[0].id | ConvertTo-Json -Depth 100)"
$result = Invoke-RestMethod -Uri https://dev.azure.com/{organization}/{project}/_apis/test/runs/$($testRunsIdSorted[0].id)/results?api-version=6.0 -Headers $AzureDevOpsAuthenicationHeader -Method Get
#List all test result get the test result ID via result
foreach($Run in $result.value){
#Get the test result ID via result
If($Run.outcome -eq "Failed"){
$TestResultID = $Run.id
#Write-Host $TestResultID
#Add attachment via test run ID and test result ID
$TestResultAttachmentURL = "https://dev.azure.com/{organization}/{project}/_apis/test/Runs/$($runId)/Results/$($TestResultID)/attachments?api-version=6.0-preview.1"
$body =#"
{
"stream": "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAIAAABvFaqvAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABlSURBVDhP7cxBCsAgDERR739pG/CnGJI0FopQ8O2cjNP6R85QbeNQU7wT1dkijaQ3vkZoWElaoTeJojW01cYh0jwfgiFBV/lEjOZtacijN/nLkOBHhIaVDgn+Wdycp6FXzlCl9wt0Y0cAzHo/zgAAAABJRU5ErkJggg==",
"fileName": "imageAsFileAttachment.png",
"comment": "Test attachment upload",
"attachmentType": "GeneralAttachment"
}
"#
$TestResultAttachmentResult = Invoke-RestMethod -Uri $TestResultAttachmentURL -ContentType "application/json" -Body $body -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST
}
}
If I click on .png file, it shows nothing.

EDIT the Azure databrics cluster's SPARK configuration using PowerShell and REST API

I am trying to EDIT the Azure databrics cluster's SPARK configuration using PowerShell and REST API. However I am getting an error which I am unable to understand/fix. I have provided the 'required' fields as parameters, however, the error states that I haven't passed them
CODE:
$DBAPIRootUrl = "dec" # example: https://uksouth.azuredatabricks.net
$DBAPIKey = "abc" # Example dapi601e67891a9d1f7886e40916479aaa
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
$ClustersAPIListUrl = $DBAPIRootUrl.Trim('/') + "/api/2.0/clusters/list"
$ClustersAPIEditUrl = $DBAPIRootUrl.Trim('/') + "/api/2.0/clusters/edit"
$headers = #{
Authorization = "Bearer $DBAPIKey"
"Content-Type" = "application/json"
}
$response = Invoke-WebRequest -Uri $ClustersAPIListUrl -Method GET -Headers $headers #-Body $parameters
$json_response = ($response.Content | ConvertFrom-Json)
$jsonDoc = [pscustomobject]#{
cluster_id = $json_response.clusters.cluster_id
spark_version = $json_response.clusters.spark_version
node_type_id = $json_response.clusters.node_type_id
spark_conf = "
javax.jdo.option.ConnectionPassword
datanucleus.fixedDatastore false
javax.jdo.option.ConnectionURL jdbc:sqlserver://metadatasrvr.database.windows.net:1433;database=emptydb
datanucleus.schema.autoCreateAll true
spark.hadoop.hive.metastore.schema.verification false
datanucleus.autoCreateSchema true
spark.sql.hive.metastore.jars maven
javax.jdo.option.ConnectionDriverName com.microsoft.sqlserver.jdbc.SQLServerDriver
spark.sql.hive.metastore.version 1.2.0
javax.jdo.option.ConnectionUserName"
}
$jsonDoc | ConvertTo-Json
#$parameters | ConvertTo-Json
$response = Invoke-WebRequest -Uri $ClustersAPIEditUrl -Method POST -Headers $headers -Body $jsonDoc
ERROR:
Invoke-WebRequest : {"error_code":"INVALID_PARAMETER_VALUE","message":"Missing required fields: cluster_id, size"}
At line:21 char:13
+ $response = Invoke-WebRequest -Uri $ClustersAPIEditUrl -Method POST - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
The error message clearly explains ""error_code":"INVALID_PARAMETER_VALUE","message":"Missing required fields: cluster_id, size"}".
Note: While editing Databricks cluster, make sure to pass the "cluster_id" and "node_type_id" as a mandatory expecting fields.
To Edit the configuration of a cluster to match the provided attributes and size.
An example request:
{
"cluster_id": "1202-211320-brick1",
"num_workers": 10,
"spark_version": "5.3.x-scala2.11",
"node_type_id": "Standard_D3_v2"
}
Reference: Databricks - REST API EDIT clusters
Hope this helps.

Passing Credential on Invoke-RestMethod for AzureDevOps API to Retrieve Users

I am trying to create a powershell script that will retrieve a number of users from AzureDevOps organization using REST API. I have encrypted my password and placed it in credentials, however I am getting an error like this:
Invoke-RestMethod : Cannot process argument transformation on parameter
'Credential'.
userName
At D:\Others\Retrieve Users.ps1:11 char:80
+ ... stakeholderUrl -Method Get -Credential $webclient.Credentials).identi
...
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-RestMethod],
ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId :
ParameterArgumentTransformationError,Microsoft.PowerShell.
Commands.InvokeRestMethodCommand
Here is my Powershell Script Code:
$stakeholderUrl =
"https://vsaex.dev.azure.com/[organizationName]/_apis/userentitlements?api-
version=5.0-preview.2"
$password = Get-Content D:\GetUsers\password.txt | ConvertTo-SecureString -
Key (Get-Content D:\GetUsers\aes.key)
$credential = New-Object
System.Net.NetworkCredential("sample#abc.com",$password)
$stakeholder = (Invoke-RestMethod -Uri $stakeholderUrl -Method Get -
Credential $credential).identities
$StakeholderUsers = #()
foreach($user in $stakeholder){
$customObject = new-object PSObject -property #{
"Display Name" = $user.displayName
"Email" = $user.mailAddress
"License" = $user.licenseDisplayName
}
$StakeholderUsers += $customObject
}
$StakeholderUsers | Select `
displayName,
mailAddress,
licenseDisplayName
I would appreciate if you could help me on this.
Thanks!
Store the credentials in this way:
domain\username:password
$Credentials= Get-Content D:\GetUsers\Credentials.txt
Create the Base64-encoded Basic authorization header:
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}" -f $Credentials)))
Invoke the rest:
$result = Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}

Powershell Rest API- Encode PDF to B64

I'm having an issue trying to get this to work. What I'm trying to do is upload a "PDF" to our system using API commands in Powershell. I've been able to upload "documents" from my disk drive, but when I try to view them they are either "Document not found" or "Cannot open this PDF" or ""The input is not a valid Base-64 string as it contains a non-base 64 character". I've tried different methods: encoding/decoding in a variety of ways, I've tried opening it in several different programs- doesn't seem like nothing is working and I'm losing sleep.
Below is my code for just straight upload:
$fileName = "C:\files\Test1.pdf"
$data = ConvertTo-Json #{
encrypted="false";
allowSaveBinaryData="True";
binaryData=$fileName;
divider="Expense Report";
isMultipageImage="true";
extension="pdf";
name="Test1.pdf";
relProjectId="31";
}
$addproject="https://ENDPOINT URL.com/v4/documents/597?guid=$temp&fbsite=https://MYURL.com/"
Invoke-RestMethod -ContentType 'application/json' -Method PUT -Body $data -Uri $addproject
Below is my code I tried using encoding/decoding:
$fileName = "C:\files\Test1.pdf"
$fileContent = get-content $fileName
$fileContentBytes = [System.Text.Encoding]::Unicode.GetBytes($fileContent)
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)
$data = ConvertTo-Json #{
encrypted="false";
allowSaveBinaryData="True";
binaryData=$fileContentEncoded;
divider="Expense Report";
isMultipageImage="true";
extension="pdf";
name="Test1.pdf";
relProjectId="31";
}
$addproject="https://ENDPOINT URL.com/v4/documents/597?guid=$temp&fbsite=https://MYURL.com/"
Invoke-RestMethod -ContentType 'application/json' -Method PUT -Body $data -Uri $addproject
I've figured it out with this::
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept", 'application/pdf')
$fileName="C:\files\$item2"
$fileContent = get-content -Raw $fileName
$fileContentBytes = [System.Text.Encoding]::Default.GetBytes($fileContent)
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)
$data = ConvertTo-Json #{
encrypted="false";
allowSaveBinaryData="true";
binaryData="$fileContentEncoded"
divider="Expense Report";
extension="pdf";
name="$fileContentEncoded";
relProjectId="31";
fileID="597"
}
$var2[$i2]="https://MY ENDPOINT /v4/documents/597?guid=$AUTHtemp&fbsite=https://XXXXXXXXX/"
Invoke-RestMethod -headers $headers -ContentType 'application/json' -Method PUT -body $data -Uri $var2[$i2]}