How to integrate UFT 12.25 with VSTS - azure-devops

We are automating Windows based Application using UFT and Client requires us to integrate UFT with VSTS since Functional testing Team is using VSTS Dashboard for all Testing Life Cycle.
Please help me in this regard if anyone has implemented this stuff earlier or currently working on same.
Regards
Raman Kumar

Refer to these steps:
Run UFT scripts through Jenkins build
Call VSTS REST API to create new test run and update test result with a specified bug.
Create new test run
Update test results for a test run
You can call REST API by using Microsoft Team Foundation Server Extended Client.
Simple code:
var u = new Uri("https://[account].visualstudio.com");
VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.VssBasicCredential(string.Empty, "[personal access token]"));
var connection = new VssConnection(u, c);
var testClient = connection.GetClient<TestManagementHttpClient>();
int testpointid = 158;
string teamProject = "scrum2015";
RunCreateModel run = new RunCreateModel(name:"APIRun7",plan:new Microsoft.TeamFoundation.TestManagement.WebApi.ShallowReference("232"),pointIds:new int[] { testpointid });
TestRun testrun = testClient.CreateTestRunAsync(teamProject, run).Result;
TestCaseResultUpdateModel testCaseUpdate = new TestCaseResultUpdateModel() { State="Completed", Outcome="Passed", TestResult=new Microsoft.TeamFoundation.TestManagement.WebApi.ShallowReference("100000") };
var testResults = testClient.UpdateTestResultsAsync(new TestCaseResultUpdateModel[] { testCaseUpdate }, teamProject, testrun.Id).Result;
RunUpdateModel runmodel = new RunUpdateModel(state: "Completed");
TestRun testRunResult= testClient.UpdateTestRunAsync(teamProject, testrun.Id, runmodel).Result;

Related

Service Now REST API script for listening from DevOps web hooks

I am wondering how connect between DevOps Boards Incidents and Tasks (web hooks used) to ServiceNow. The requirement is Service Now will need to listen every time there is an update to Azure DevOps boards incidents or Tasks.
I have created a Scripted REST API at Service Now with the following Example script:
`(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var body = request.body.data;
var eventType = request.headers['auth_token'];
var workItem = body.resource;
var title = workItem.fields['System.Title'];
var description = workItem.fields['System.Description'];
var state = workItem.fields['System.State'];
var priority = workItem.fields['System.priority'];
if(eventType == 'workitem.created') {
title = workItem.fields['System.Title'];
description = workItem.fields['System.Description'];
state = workItem.fields['System.State'];
} else if(eventType == 'workitem.updated') {
title = workItem.fields['System.Title'];
description = workItem.fields['System.Description'];
state = workItem.fields['System.State'];
}
response.setStatus(200);
})(request, response);`
Now, Just wondering how to invoke this API end point when there is an update.
If you are on the Scripted REST Resource form in ServiceNow, then you should see a "Explore REST API" link at the bottom of the page. If you click that link it will take you page that you can use to test your API. Right below the "Send" button there should be links to generate code samples to call your API.

Need help for Checkmarx.Api cake plugin

I am trying to incorporate "Checkmarx" Static code scans as a stage into my devops pipeline. Currently our code uses "cake" files to excute the stages (invoked by PowerShell).
I was checking the cake support for Checkmarx.Api but could not find any neither in the Checkmarx site or in the Cake website. The NuGet gallery has a tab for the cake addin - https://www.nuget.org/packages/Checkmarx.API/
but does not share any information on the contracts exposed.
So reaching out to the community to see if anyone has done any work on this or has any references. Any other way you have incorporated "Checkmarx" into your build pipeline (without directly using the plugin rather using the CxCLi) would also be helpful as well.
As answered in the GitHub discussion where you asked the same question:
Cake scripts based on "normal" C#, so whatever the usage of Checkmarx.API, you can simply incorporate that in your cake scripts. Probably something like:
Task("Scan")
.Does(() =>
{
// place your code here..
});
As for using Checkmarx.API, I would suggest asking in the Checkmarx.API repo.
Alternatively, it seems that there is a CLI available. You can use that using the one of the process aliases.
Probably something like:
Task("Scan")
.Does(() =>
{
StartProcess("runCxConsole.cmd", new ProcessSettings
{
Arguments = #"Scan -v -ProjectName ""CxServer/bookname j2"" -CxServer http://localhost -CxUser username -CxPassword admin -LocationType folder -LocationPath ""C:\Data\Projects\Java\bs java"" -preset ""Checkmarx Default"""
});
});
(Note: I took the Arguments to runCxConsole.cmd from the documentation - I did not test that.)
I will mark this as closed as I have been able to get around this using .net HttpClient but unfortunately could not implement using Checkmarx cake addin.
I will paste the sample code, i was getting some ssl eerror until i added the "ServerCertificateCustomValidationCallback" to return true
string accessToken = string.Empty;
try
{
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
using (var client = new HttpClient(httpClientHandler))
{
client.BaseAddress = new Uri(CXUrl+"/auth/identity/connect/token");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Accept", "*/*");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("scope", "access_control_api sast_api"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", pwd),
new KeyValuePair<string, string>("client_id", "resource_owner_sast_client"),
new KeyValuePair<string, string>("client_secret", "****************************"),
});
var response = client.PostAsync("", content);
var result = JsonConvert.DeserializeObject<CXAccessToken>(response.Result.Content.ReadAsStringAsync().Result);
accessToken = result.access_token;
}
}
}

"ResourceContainerAccessDenied" returned as value of CloudTask.ExecutionInformation.FailureInformation.Code but not in TaskFailureInformationCodes

I have a .net core 3.0 application using the Microsoft.Azure.Batch 12.0.0 C# nuget package.
I create a job containing one task with a resource file like this (pseudo codeish):
var source = ResourceFile.FromStorageContainerUrl(settings.Input.Container.GetAccessUrl());
var cloudTask = new CloudTask(_taskId, commandline)
{
...
ResourceFiles = new[] { source, },
...
}
await _batchClient.JobOperations.AddTaskAsync("jobid", cloudTask,
cancellationToken: cancellationToken);
when i now request the status of the task
var cloudJob = await _batchClient.JobOperations.GetJobAsync("jobId", cancellationToken:
cancellationToken);
var cloudTask = cloudJob.ListTasks().SingleOrDefault();
var code = cloudTask.ExecutionInformation.FailureInformation,Code
code can be of value "ResourceContainerAccessDenied" if indeed we do not have access to the ResourceCondainer - "ResourceContainerAccessDenied" is not
a member of Microsoft.Azure.Batch.Common.TaskFailureInformationCodes and not documented anywhere as far as i can see.
Is this a bug in the Azure Batch C# SDK? Am i overlooking something? Where can i get a list of all possible code values?
The fact that this error code is not included in the C# SDK is indeed a bug.
I will be fixing this bug as part of an upcoming SDK release (ETA ~1 week).

How do you get a list of all project iterations using the Azure DevOps Services .NET SDK?

I'd like to get a list of all the iterations for a given project in a Azure DevOps repository, using the .NET API.
Is there any example of how to do this? The current documentation (https://learn.microsoft.com/en-us/dotnet/api/microsoft.teamfoundation.work.webapi.workhttpclientbase.getteamiterationsasync?view=azure-devops-dotnet) is pretty thin.
Below is a working example of how to achieve this.
You need to reference Microsoft.TeamFoundation.Work.WebApi.
public async Task<List<TeamSettingsIteration>> GetProjectIterations(string serverUrl, string projectName)
{
var uri = new Uri(serverUrl);
var creds = new VssClientCredentials(new WindowsCredential(true), new VssFederatedCredential(true), CredentialPromptType.PromptIfNeeded);
var azureDevopsConnection = new VssConnection(uri, creds);
await azureDevopsConnection.ConnectAsync();
WorkHttpClient azureDevOpsWorkHttpClient = azureDevopsConnection.GetClient<WorkHttpClient>();
TeamContext teamContext = new TeamContext(projectName);
List<TeamSettingsIteration> results= await azureDevOpsWorkHttpClient.GetTeamIterationsAsync(teamContext);
return results;
}

Sharepoint authentication without using sharepoint development environment or service references?

I am trying to access a local SharePoint site using a .net program and am having difficulties.
I don't want to use the SharePoint development environment (may have many developers work on this, and that is just one more thing to install).
I would also like to make this configurable so that I can change the site and list name without recompiling. I don't think I can do that with the Service References. If I can, how?
I also don't want the user to enter sharepoint validation information, I am ok with storing sharepoint login information in a .config file.
I believe I could do this with REST, but can't figure out how to create an AccessToken without using the Sharepoint development environment.
Any help would be appreciated.
The main problem I was having was not understanding that you could put other types of credentials in the request.Credentials property. Here is the code I created:
public bool CopyFileToSharePoint(string fileName, Stream fileStream)
{
var data = new byte[fileStream.Length];
fileStream.Read(data, 0, (int) fileStream.Length);
fileStream.Close();
var sharePointPath =
SharePointWebSiteUrl + "/_api/web/lists/getByTitle('" + SharePointListName + "')" +
"/RootFolder/Files/add(url='" + fileName + "',overwrite='true')";
var request = (HttpWebRequest) WebRequest.Create(sharePointPath);
request.Credentials = new NetworkCredential(SharePointUserName, SharePointPassword, SharePointLoginDomain);
request.Method = "POST";
request.Accept = "application/atom+xml";
request.Headers["X-RequestDigest"] = GetFormDigest(SharePointWebSiteUrl);
request.ContentType = "application/txt";
request.ContentLength = data.Length;
request.GetRequestStream().Write(data, 0, data.Length);
var response = (HttpWebResponse) request.GetResponse();
return response.StatusCode == HttpStatusCode.OK;
}
I'm sure it's not perfect, but it works.