Functionality of Attachments and their use in Work Item Tracking API - azure

I stumbled across the documentation for creating attachments, listed under work item tracking, and I'm curious about the functionality. According to this stack overflow post, the functionality seems to be that it uploads a file to the "backend" without any association to a work item. I am having some trouble understanding what the use case for this endpoint is... Is it just a glorified storage space? What is its intended use if there is no UI to view the item and no relations to any existing entities other than a project? Is there any available end point that I am missing that would allow me to add an attachment to an existing work item?

You also need to use Work Items - Update rest api to add the attachments to a work item. See below:
1, First use Attachments - Create rest api to update the attachment to azure devops server.
When the attachment is successfully uploaded, The attachment id and url will be returned to you. And you will need to use the attachment url in the Work Items - Update rest api. See examples
2, Use Work Items - Update to add the attachment to the work item. Put the attachment url in the request body like below example:
[{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
# attachment url
"url": "https://dev.azure.com/fabrikam/_apis/wit/attachments/098a279a-60b9-40a8-868b-b7fd00c0a439?fileName=Spec.txt",
"attributes": {
"comment": "Spec for the work"
}
}
}]
See below full example in powershell scipts:
# Attachments - Create REST API
$url = "https://dev.azure.com/{org}/{proj}/_apis/wit/attachments?fileName=textAsFileAttachment.txt&api-version=6.0"
$PAT="Personal access token"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)"))
$body= 'this a attached text file'
# update attachment to azure devops server. attachment id and url will be returned
$attachment= Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic {0}" -f $base64AuthInfo} -ContentType "application/octet-stream" -Method post -Body $body
# Work Items - Update REST API
$wurl ="https://dev.azure.com/{org}/{proj}/_apis/wit/workitems/{workitem Id}?api-version=6.0"
$wbody=#(
#{
"op"= "add";
"path"= "/relations/-";
"value"= #{
"rel"= "AttachedFile";
"url"= $attachment.url; #Attachment url
"attributes"= #{
"comment"= "attachment Test"
}
}
})
# add attachment to workitem.
Invoke-RestMethod -Uri $wurl -Headers #{Authorization = "Basic {0}" -f $base64AuthInfo} -ContentType "application/json-patch+json" -Method patch -Body (convertto-json $wbody -Depth 10)
Then the attachment you uploaded to azure devops will be attached to a workitem. See below result of above example:

Related

connecting to azure rest api using powershell resulting in StatusCode : 203 StatusDescription : Non-Authoritative Information

I am able to connect fine to azure API's using a PAT token in postman, however am not able to authenticate using powershell.
After playing around with different authorization passing I am still stuck with getting the html page for the sign in returned. Here is a sample request I am making
Invoke-RestMethod https://feeds.dev.azure.com/xx/x/_apis/packaging/Feeds/x/Packages -Headers #{Authorization="Token :xxx"}
After much searching I came across https://www.opentechguides.com/how-to/article/azure/201/devops-rest-powershell.html. Here is a simplified snippet that allowed my request to go through successfully.
#enter your token in pat token
$pat = "xxx"
# Create header with PAT
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$header = #{authorization = "Basic $token"}
#enter your url in projects url
$projectsUrl = "https://feeds.dev.azure.com/xx/x/_apis/packaging/Feeds/x/Packages -Headers"
$projects = Invoke-RestMethod -Uri $projectsUrl -Method Get -ContentType "application/json" -Headers $header

How to manage the Azure APIM developer portal delegation with Azure PowerShell

I want to enable the Azure APIM developer portal sign-in & sign-up delegation and to generate a "Delegation Validation Key". This is straightforward with the Azure portal:
I want to achieve the same thing but with Azure PowerShell as part of a bigger deployment pipeline.
I cannot find any documentation on how to do that.
Thanks
AFAIK, We can not achieve the above requirement using powershell , Here are the details (MICROSOFT DOCUMENTATION) for what we can configure through powershell for APIM .
Instead of that we can configure the above requirement using git , Please refer this MICRSOFT DOCUMENTATION for more details & the list of cmdlets for APIM .
An additional option is to use an HTTP call against the resource. The call can be made with the PowerShell script as well.
This can be done as follows:
Get an Azure access token - you should have a Service Principal with sufficient permissions for the resource we are going to deal with.
$tokenUri = "https://login.microsoftonline.com/${tenantId}/oauth2/token"
$form = #{
grant_type = 'client_credentials'
resource = 'https://management.core.windows.net/'
client_id = $spClientId
client_secret = $spClientSecret
}
$response = Invoke-RestMethod -Uri $tokenUri -Method Post -Body $form
$azureToken = $response.access_token
Send an HTTP request against the APIM service
$url = "https://management.azure.com/subscriptions/${subscriptionId}/resourceGroups/${apiManagementRg}/providers/Microsoft.ApiManagement/service/${apiManagementName}/portalsettings/delegation?api-version=2020-12-01"
$headers = #{ 'Authorization' = "Bearer ${azureToken}" }
$body = #"
{
"properties": {
"url": "$delegationUrl",
"validationKey": "$validationKey",
"subscriptions": {
"enabled": false
},
"userRegistration": {
"enabled": true
}
}
}
"#
$delegationResponse = Invoke-RestMethod -Method 'Put' -Body $body -Uri $url -Headers $headers

How to get the values of pull request Created by and Approved by in Azure DevOps CI pipeline

I have the pull-request build in Azure DevOps in that I have used inline PowerShell script to get the Pull Request ID by following System variables (DevOps Services) documentation.
But I want to get the values of Pull Request Created by and Approved by using predefined variables.
So, can anyone suggest how to do it.
There are no predefined variables of Created by or Approved by for a Pull Request. Instead, you could use Pull Requests - Get Pull Request By Id api to get these information, as you have had Pull Request ID:
GET https://dev.azure.com/{organization}/{project}/_apis/git/pullrequests/{pullRequestId}?api-version=6.0
In the response, you could get createdBy value:
Regarding Approved by value, you could get vote in reviewers. The vote with value 10 are the approvers.
Vote on a pull request:
10 - approved 5 - approved with suggestions 0 - no vote -5 - waiting for author -10 - rejected
You could use the powershell to run the api:
Param(
[string]$org = "orgname",
[string]$projectName = "projectname",
[string]$keepForever = "true",
[string]$user = " ",
[string]$token = "YourPAT"
)
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$uri = "https://dev.azure.com/$org/$projectName/_apis/git/pullrequests/$pullrequestid?api-version=6.0"
$result = Invoke-RestMethod -Uri $uri -Method Get -Body $json -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
Write-Host "$($result | ConvertTo-Json -Depth 100)"

Current Iteration Query Script Devops Looping Through Projects

I'm trying to put a script together that will let me loop through projects and create queries relevant to the current iteration.
I can loop through and create queries until it comes to looking at the iteration path and then it doesn't seem to like it.
When I run my script all of the other queries are created, and this one is as well, but it brings up an error when I go to look at it because it's posting that it's not in the right form. How can I get this query to loop through like the others and bring back the appropriate team in the process?
I'm assuming that somehow I've got to put project and team as variables? I tried $project as well but that just presented a similar error. Although I'm also confused about about the "" since the code doesn't like that either, and it won't even create the query when I've tried that.
$JSON27 = #'
{
"name": "Current Sprint Query", "wiql": "SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State],[System.Tags],[Microsoft.VSTS.Scheduling.OriginalEstimate],[Microsoft.VSTS.Scheduling.CompletedWork],[System.IterationPath] FROM workitems WHERE [System.TeamProject] = #project AND [System.WorkItemType] <> '' AND [System.State] = 'Closed' AND [System.IterationPath] = #CurrentIteration('[Project]/Team') ORDER BY [System.WorkItemType]"
}
'#
$response27 = Invoke-RestMethod -Uri $url1 -Headers #{Authorization = "Basic $token"} -Method Post -Body $JSON27 -ContentType application/json
Please refer to the following script to get the project name first, and then create a query by looping through the obtained project name.
Please use #CurrentIteration('[Project]\\Team') instead of #CurrentIteration('[Project]/Team') or #CurrentIteration('[Project]\Team')
$token = "your PAT"
$url="https://dev.azure.com/org name/_apis/projects?api-version=6.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
echo $url
foreach ($project in $response.value.name){
$url3="https://dev.azure.com/org name/$($project)/_apis/wit/queries/My Queries?api-version=6.1-preview.2"
echo $url1
$body = "{
`"name`": `"query name`",
`"wiql`": `"Select [System.Id], [System.State] From WorkItems where [System.IterationPath] = #CurrentIteration('[$project]\\$project Team') `"
}"
echo $body
$response3 = Invoke-RestMethod -Uri $url3 -Headers #{Authorization = "Basic $token"} -Method Post -Body $body -ContentType application/json
echo $response3
}
Summarizing the discussion in comments as an answer below:
So, as the error message calls out, I think the issue is that you have #CurrentIteration('[Project]/Team') in your query instead of #CurrentIteration('[Project]\Team').
Your query should be this instead:
$JSON27 = #'
{
"name": "Current Sprint Query", "wiql": "SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State],[System.Tags],[Microsoft.VSTS.Scheduling.OriginalEstimate],[Microsoft.VSTS.Scheduling.CompletedWork],[System.IterationPath] FROM workitems WHERE [System.TeamProject] = #project AND [System.WorkItemType] <> '' AND [System.State] = 'Closed' AND [System.IterationPath] = #CurrentIteration('[Project]\Team') ORDER BY [System.WorkItemType]"
}
'#
EDIT:
By default, shared queries and new queries are scoped to the current project. For querying across multiple projects, you can add the TeamProject field to filter to a select number of projects as:
..
AND [System.TeamProject] IN ('Project 1', 'Project 2', 'Project 3')
However, using the #CurrentIteration macro would need you to select a Team and may not work across Projects and Teams. Check this idea on Developer Community for more details.

Create several queries across multiple projects in Azure DevOps

I'm trying to create the same queries across several projects. I feel like I'm almost there, but can't come up with the right 'thing' to create more than one query. I've tried "," ";" "AND" - and have managed to get it to create one but never both.
Could someone assist?? I've put down a quick example snippet of the type of thing I'm trying (which is why the fields are the same). If I can get that right, I'll use it for real with all the different queries I have (there's quite a few!)
{ $url1="https://dev.azure.com/[ORGANISATION]/$($project)/_apis/wit/queries/Shared Queries?api-version=6.0"
$JSON = #'
{
"name": "All User Stories JW6", "wiql": "SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State],[System.Tags],[Microsoft.VSTS.Scheduling.OriginalEstimate],[Microsoft.VSTS.Scheduling.CompletedWork] FROM workitems WHERE [System.WorkItemType] = 'User Story' AND [System.State] = 'Active' ORDER BY [System.WorkItemType]",
"name": "All User Stories JW7", "wiql": "SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State],[System.Tags],[Microsoft.VSTS.Scheduling.OriginalEstimate],[Microsoft.VSTS.Scheduling.CompletedWork] FROM workitems WHERE [System.WorkItemType] = 'User Story' AND [System.State] = 'Active' ORDER BY [System.WorkItemType]"
}
'#
Create several queries across multiple projects in Azure DevOps
I am afraid we could not set duplicate Keys in JSON body.
That because the names in json object SHOULD be unique, check the state in RFC-7159:
The current standard for JSON published by the Internet Engineering
Task Force (IETF), states "The names within an object SHOULD be
unique".
I use the body in the postman, I got the same warning:
If we use the duplicate Keys in JSON body, most popular parsers may take only the last value present in the object for a particular key and ignore the previous ones.
In your sample, only query All User Stories JW7 will be created.
To resolve this issue, we have to create a another body $JSON2, and send another request:
$JSON2 = #'
{
"name": "All User Stories JW7", "wiql": "SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State],[System.Tags],[Microsoft.VSTS.Scheduling.OriginalEstimate],[Microsoft.VSTS.Scheduling.CompletedWork] FROM workitems WHERE [System.WorkItemType] = 'User Story' AND [System.State] = 'Active' ORDER BY [System.WorkItemType]"
}
'#
$CreateQuery1= Invoke-RestMethod -Uri $url -headers $headers -Method Post -ContentType "application/json" -Body $Json1
$CreateQuery2= Invoke-RestMethod -Uri $url -headers $headers -Method Post -ContentType "application/json" -Body $Json2

Resources