Create queries across projects in Azure DevOps - azure

I'm trying to create queries across several projects. I've got 7 or 8 queries in total and a dozen or so projects so thought that having some sort of script may make it easier.
I've come up with this (basically copy and paste from somewhere else admittedly) but I have no idea where/how to run it, and whether I've even got everything. I'm assuming that I haven't because I don't have the PAT token but I'm really not sure.
I'm completely out of my comfort zone with this but if I get one right then I'm hoping the rest will be easy because I'm just amending the query. Could anyone offer a bit of help? Should I be using Visual Studio Code or something else to run this? Do I just drop this code in or am I missing something key??
POST https://dev.azure.com/MattR778/ProjectA/_apis/wit/queries/{query}?api-version=5.0
{ "name": "No Status Change", "wiql": "Select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.AreaPath], [System.IterationPath]
From WorkItems Where [System.TeamProject] = #project AND [System.WorkItemType] = 'User Story' AND [System.State] = 'New' AND [Microsoft.VSTS.Common.StateChangeDate]
< #startofday( '-90d') }
I thought I had it, and I got an error message because I hadn't put a " towards the end (rookie mistake). I've re-run it but I still can't get it to work. I feel like it's really close but I tried running the sample request on https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/queries/create?view=azure-devops-rest-6.0 and it had a similar response so I don't think it's the body.
I'm getting back this message:
{
"$id": "1",
"innerException": null,
"message": "TF401243: The query {query} does not exist, or you do not have permission to read it.",
"typeName": "Microsoft.TeamFoundation.WorkItemTracking.Server.QueryItems.QueryItemNotFoundException, Microsoft.TeamFoundation.WorkItemTracking.Server",
"typeKey": "QueryItemNotFoundException",
"errorCode": 600288,
"eventId": 3200
}
I've added the PAT to the authorization tab, so not sure what the issue is. I think it's nearly there, and I've been able to link into my DevOps project before with a simple GET test (so I don't think it's an issue with the connection between Postman and DevOps?), but I'm a little unsure of where to go next with this.
The full screenshot of what I've tried to run in Postman

You can run REST API in PowerShell.
Here is the script.
$token = "{PAT}"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$url="https://dev.azure.com/MattR778/ProjectA/_apis/wit/queries/{query}?api-version=5.0"
$body = #'
{
"name": "No Status Change",
"wiql": "Select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.AreaPath], [System.IterationPath] From WorkItems Where [System.TeamProject] = #project AND [System.WorkItemType] = 'User Story' AND [System.State] = 'New' AND [Microsoft.VSTS.Common.StateChangeDate]< #startofday( '-90d')
}
'#
$head = #{ Authorization =" Basic $token" }
Invoke-RestMethod -Uri $url -Method Post -Headers $head -Body $body -ContentType application/json
You can run the script in PowerShell or the PowerShell task in Azure DevOps pipeline.
In addition, you can also use some softwares designed to run APIs, like Postman.
Update:
In Postman, if you want to authenticate with PAT, you need to select "Basic Auth" in "Authorization" and enter PAT in the "Password".
In "Body", you need to select "raw" and choose "JSON". Then, paste your request body in the testbox.
The scripts above are for command-line tools such as PowerShell or Bash. If you are using Postman, you'd just need to provide the request body.
Update 2:

Related

How Do I Download Test Step Attachments for Test Cases in Azure DevOps

I'm trying to download all the test step attachments for a test case through API Call using GET https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/Results/{testCaseResultId}/attachments/{attachmentId}?api-version=6.0-preview.1.
My call works but where do I find the attachment in my files?
How Do I Download Test Step Attachments for Test Cases in Azure DevOps
That because the REST API Attachments - Get Test Result Attachment Zip
will display the context of the attachments instead of download the attachments directly.
To resolve this issue, we could save the attachment to the file by the scripts like:
$AttachmentsOutfile = "D:\Testcase\AttachmentsOutfile.trx"
$connectionToken="You PAT Here"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::
ASCII.GetBytes(":$($connectionToken)"))
$AuditLogURL = "https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/Results/{testCaseResultId}/attachments/{attachmentId}?api-version=6.0-preview.1"
$AuditInfo = Invoke-RestMethod -Uri $AuditLogURL -Headers #{authorization = "Basic $base64AuthInfo"} -Method Get –OutFile $AttachmentsOutfile
The test result:

Azure Event Hub : Create Logger - 400 Invalid Hostname

I am trying to create a proof of concept with Azure APIM and am stuck at a 400 invalid hostname error.
I have tried following this example
https://learn.microsoft.com/en-gb/azure/api-management/api-management-howto-log-event-hubs
which leads me to this page
https://learn.microsoft.com/en-us/rest/api/apimanagement/2019-12-01/logger/createorupdate
I have in postman the put command with the following url, edited out the personal details
https://management.azure.com/subscriptions/xxxxx-yyyy-zzz-a4ed-b0b5ddddddd/resourceGroups/xx-Trial/providers/Microsoft.ApiManagement/service/xxx-API-Management-Services/loggers/loggerId?api-version=2019-12-01
This is being sent as a PUT command
This is the body that is also being sent
{
"type": "AzureEventHub",
"description": "xx Poc description",
"credentials": {
"name": "apim",
"connectionString": "Endpoint=sb://xx-poc.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=yyyyyyK/ixxxxxxxxxxxxxxc="
}
}
The response that comes back is
<h2>Bad Request - Invalid Hostname</h2>
<hr>
<p>HTTP Error 400. The request hostname is invalid.</p>
I would be grateful if anyone can help me progress this forward as I cannot see what I have missed.
Thanks
After hours of searching I finally stumbled across this url https://www.svenmalvik.com/azure-apim-with-eventhub/ which has resolve my issue.
I had done everything right in terms of setup, but this was the final step that was missing
$apimCtx = New-AzApiManagementContext -ResourceGroupName "xx-Trial" -ServiceName "xx-API-Management-Services"
$ehConnection = (Get-AzEventHubKey -ResourceGroupName "xx-Trial" -NamespaceName "xx-yyy-zzz-eh-ns" -AuthorizationRuleName "xx-yyy-zzz-eh-auth-rule").PrimaryConnectionString
New-AzApiManagementLogger -Context $apimCtx -LoggerId "simon-logger" -Name "simon-logger" -ConnectionString "$ehConnection;EntityPath=xx-yyy-eh"
I believe there'are something wrong with the request body.
{
"type": "AzureEventHub",
"description": "xx Poc description",
"credentials": {
"name": "apim",
"connectionString": "Endpoint=sb://xx-poc.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=yyyyyyK/ixxxxxxxxxxxxxxc="
}
}
Please check the following settings in your request body:
For name, please make sure it's the Event hub instance name, not the Eventhub namespace name. And you can refer to this doc for more details about them.
For connectionString, please make sure it's the Eventhub namespace connectiong string(do not use the Eventhub instance level connection string). For more details, please refer to this doc.
At the end, please also check if the eventhub instance is disabled or not.

Empty "Parsed-HTML" field on using "invoke-webrequest" in Azure Powershell Runbook

I am trying to make a rest API call using "invoke-webrequest" in azure powershell runbook.
At first, I got the error message regarding the Internet Explorer Engine. When I searched about it, I found that using **-UseBasicParsing** would solve the problem. However, after using it, I am not facing the error message anymore but I am getting empty "**Parsed-Html**".
The code is running fine when I am running it locally.
$result = invoke-webrequest -uri $url -Headers $Header -UseBasicParsing
I expect the output of Parsed-Html to be an object, but it is null.
In Automation, when we use cmdlet Invoke-WebRequest we need to use the–UseBasicParsing option as we do not have the Internet Explorer in Azure Automation sandboxes.
In this scenario you should use **HtmlAgilityPack**. Upload the **HtmlAgilityPack.dll** as module and use command "add-type -Path .\HtmlAgilityPack.dll " in runbook to generate the **HtmlDocument**
Code would look something like below:
$URI = "https://www.google.fr/search?q=googe&rlz=1C1CHBF_frFR711FR711&oq=googe&aqs=chrome..69i57j69i60l5.912j0j7&sourceid=chrome&ie=UTF-8#q=google"
$wc = New-Object System.Net.WebClient
$htmlString=$wc.DownloadString($URI)
cd C:\Modules\User\HtmlAgilityPack
add-type -Path .\HtmlAgilityPack.dll
$doc = New-Object HtmlAgilityPack.HtmlDocument
$doc.LoadHtml($htmlString)
$root= $doc.DocumentNode
$root.SelectSingleNode("//head/title").Innertext
You can check this link for further reference.
Hope it helps.

How to enable JSON response for SharePoint 2013 REST APIs onpremise?

I am using SharePoint 2013 onprem and online version for integration purpose. While accessing REST APIs for online SharePoint, I was able to use application/json and application/xml as ACCEPT header with no issues.
However, while accessing SharePoint 2013 onpremise REST APIs I could use application/xml as ACCEPT header and using application/json throwing below error:
GET - http://xxxxxxx:8300/_api/web/
Header -
Accept:application/json
Response:
{
"error": {
"code": "-1, Microsoft.SharePoint.Client.ClientServiceException",
"message": {
"lang": "en-US",
"value": "The HTTP header ACCEPT is missing or its value is invalid."
}
}
}
Could you please suggest How can I get JSON response for LIST, LISTITEM objects?
Try this:
"accept": "application/json; odata=verbose"
I've encountered this type of issue before in on-premise SharePoint 2013. Mike's answer also has merit. You will need to change your Accept header value to "application/json;odata=verbose", though I don't think that is the issue. I think you need to patch the on-premise instance of SharePoint to support OData 3 and JSON Light. Read the instructions carefully from the following blog post. As we deploy solutions in the field, we still find farms that encounter this when we make requests for json from the REST API. However, you are far more likely to find it in a freshly spun up development instance. It's relatively quick and simple to address. Good Luck!
Edit:
It appears the Technet article was recently removed. Here is the download link for WCF Data Services 5.6. Still follow the guidance in original post and I think you'll be up and running pretty quickly. In addition, you should be able to drop off the odata=verbose portion of the Accept header after this update.
PowerShell To Complete the Upgrade (Run after the WCF Data Services Install)
Run this on the SharePoint Server that your upgraded WCF Data Services on.
$configOwnerName = "JSONLightDependentAssembly"
$spWebConfigModClass ="Microsoft.SharePoint.Administration.SPWebConfigModification"
$dependentAssemblyPath ="configuration/runtime/*[local-name()='assemblyBinding' and namespace-uri()='urn:schemas-microsoft-com:asm.v1']"
$dependentAssemblyNameStart ="*[local-name()='dependentAssembly'][*/#name='"
$dependentAssemblyNameEnd = "'][*/#publicKeyToken='31bf3856ad364e35'][*/#culture='neutral']"
$dependentAssemblyValueStart = "<dependentAssembly><assemblyIdentity name='"
$dependentAssemblyValueEnd ="' publicKeyToken='31bf3856ad364e35' culture='neutral' /><bindingRedirect oldVersion='5.0.0.0' newVersion='5.6.0.0' /></dependentAssembly>"
$edmAssemblyName ="Microsoft.Data.Edm"
$odataAssemblyName ="Microsoft.Data.Odata"
$dataServicesAssemblyName ="Microsoft.Data.Services"
$dataServicesClientAssemblyName ="Microsoft.Data.Services.Client"
$spatialAssemblyName ="System.Spatial"
$assemblyNamesArray = $edmAssemblyName,$odataAssemblyName,$dataServicesAssemblyName,$dataServicesClientAssemblyName, $spatialAssemblyName
Add-PSSnapin Microsoft.SharePoint.Powershell
$webService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
################ Adds individual assemblies ####################
For ($i=0; $i -lt 5; $i++)
{
echo "Adding Assembly..."$assemblyNamesArray[$i]
$dependentAssembly = New-Object $spWebConfigModClass
$dependentAssembly.Path=$dependentAssemblyPath
$dependentAssembly.Sequence =0 # First item to be inserted
$dependentAssembly.Owner = $configOwnerName
$dependentAssembly.Name =$dependentAssemblyNameStart + $assemblyNamesArray[$i] + $dependentAssemblyNameEnd
$dependentAssembly.Type = 0 #Ensure Child Node
$dependentAssembly.Value = $dependentAssemblyValueStart + $assemblyNamesArray[$i] + $dependentAssemblyValueEnd
$webService.WebConfigModifications.Add($dependentAssembly)
}
###############################################################
echo "Saving Web Config Modification"
$webService.Update()
$webService.ApplyWebConfigModifications()
echo "Update Complete"
Change this
headers:
{
"accept": "application/json",
},
Try This
headers:
{
"accept": "application/json;odata=verbose",
},

Does ms graph API support outlook on office 365 on Germany endpoint?

I found that graph API in Germany endpoint seems not to support
GET /users/<id>/mailFolders/delta
it returns
**400**
{
"error": {
"code": "ErrorInvalidIdMalformed",
"message": "Id is malformed.",
"innerError": {
"request-id": "cf713386-f050-40b4-b987-43cc2384eade",
"date": "2017-12-12T07:13:10"
}
}
}
However it works fine at
GET /users/<id>/mailFolders
Thanks for help
I had been in the same trouble, but I resolved.
Your request to:
GET /users/<id>/mailFolders/delta
is not correct, I think.
I guess that this mail folder delta was made by you, doesn't it?
To specify a mail folder, you need to use folder id, not display name.
Though you might already get the folder id, you can get the folder id by sending a request
GET /users/<id>/mailFolders
Note: Actually, we can get folder_ids via powershell:
Get-MailboxFolderStatistics
cmdlet on Exchange. However, these folder_id are malformed in ms-graph request. So you need to use the id which you can get as described above.

Resources