Fetch latest checked in information using TfvcHttpClient Class - tfs

Trying to fetch latest checked in information using TfvcHttpClient class from a specific folder in Team Foundation Server using its client API from a console application.
Please help how can I achieve it? I have personal access token and below mentioned is able to connect by using it:
Code:
string uri = _uri;
string personalAccessToken = _personalAccessToken;
string project = _project;
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken)));
//create wiql object
var wiql = new
{
query = "Select [State], [Title] " +
"From WorkItems " +
"Where [Work Item Type] = 'Bug' " +
"And [System.TeamProject] = '" + project + "' " +
"And [System.State] <> 'Closed' " +
"Order By [State] Asc, [Changed Date] Desc"
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(uri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
//serialize the wiql object into a json string
var postValue = new StringContent(JsonConvert.SerializeObject(wiql), Encoding.UTF8, "application/json"); //mediaType needs to be application/json for a post call
//send query to REST endpoint to return list of id's from query
var method = new HttpMethod("POST");
var httpRequestMessage = new HttpRequestMessage(method, uri + "/_apis/wit/wiql?api-version=2.2") { Content = postValue };
var httpResponseMessage = client.SendAsync(httpRequestMessage).Result;
}
I have tried below mentioned code for achieving:
VssConnection connection = new VssConnection(serverUrl, new
VssBasicCredential(string.Empty, _personalAccessToken));
var buildServer = connection.GetClient<BuildHttpClient>(); // connect to the build server subpart
var sourceControlServer = connection.GetClient<Microsoft.TeamFoundation.SourceControl.WebApi.TfvcHttpClient>(); // connect to the TFS source control subpart
var changesets = buildServer.GetChangesBetweenBuildsAsync("client-rsa", 1, 5).Result;
foreach (var changeset in changesets)
{
var csDetail = sourceControlServer.GetChangesetAsync("client-rsa", Convert.ToInt32(changeset.Id.Replace("C", string.Empty).Trim()), includeDetails: true).Result;
var checkinNote = csDetail.CheckinNotes?.FirstOrDefault(_ => _.Name == "My check-in note");
if (checkinNote != null)
{
Console.WriteLine("{0}: {1}", changeset.Id, changeset.Message);
Console.WriteLine("Check-in note: {0}", checkinNote.Value);
}
else
Console.WriteLine("Warning: {0} has no check-in note", changeset.Id);
}

Here is the simple sample code which use TfvcHttpClient to get the latest changeset information:
string purl = "https://xxx.visualstudio.com";
string projectname = "projectname";
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
VssConnection vc = new VssConnection(new Uri(purl),creds);
TfvcHttpClient thc = vc.GetClient<TfvcHttpClient>();
TfvcChangesetSearchCriteria tcsc = new TfvcChangesetSearchCriteria();
//Specify the server path of the folder
tcsc.ItemPath = "$/XXXX/XXXX";
//Get the entire history of the specified path
List<TfvcChangesetRef> changerefs = thc.GetChangesetsAsync(projectname,null,null,null,null,tcsc).Result;
//Get the latest changeset ref
TfvcChangesetRef changeref = changerefs.First();
//Get the changeset
TfvcChangeset changeset = thc.GetChangesetAsync(projectname,changeref.ChangesetId).Result;
//Get the detailed changes
List<TfvcChange> changes = thc.GetChangesetChangesAsync(changeref.ChangesetId).Result;
foreach (TfvcChange cg in changes)
{
//Code to read detail information
}

Related

No response received to multipart/mixed HTTP request

I am trying to use the Dynamics 365 Web API to GET records. The fetch query generated is too long to use a normal GET query so a workaround is to POST the request instead.
I have simplifed the fetch statement here for ease.
Ignore the lack of async/await and use of .Result, that can easily be sorted afterwards.
Code:
var clientcred = new ClientCredential(Config.ClientId, Config.ClientSecret);
var authenticationContext = new AuthenticationContext($"{Config.AadInstance}{Config.TenantId}");
var authenticationResult = authenticationContext.AcquireTokenAsync(Config.DynamicsUrl, clientcred).Result;
var token = authenticationResult.AccessToken;
var client = new HttpClient();
client.BaseAddress = new Uri("https://foobar.crm4.dynamics.com");
client.Timeout = new TimeSpan(0, 2, 0);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"*\"");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"/api/data/v9.1/$batch");
var content = "--batch_rob--\n" +
"Content-Type: application/http\n" +
"Content-Transfer-Encoding: binary\n" +
$"GET {Config.BaseUrl}contacts?fetchXml=<fetch count=\"10\" ><entity name=\"contact\" ><attribute name=\"fullname\" /></entity></fetch> HTTP/1.1\n" +
"OData-Version: 4.0\n" +
"OData-MaxVersion: 4.0\n" +
"--batch_rob--";
using (var content2 = new MultipartContent())
{
content2.Add(new StringContent(content));
content2.Headers.Remove("Content-Type");
content2.Headers.TryAddWithoutValidation("Content-Type", "multipart/mixed;boundary=batch_rob");
var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"/api/data/v9.1/$batch")
{
Content = content2
};
var response = client.SendAsync(request).Result;
var outcome2 = response.Content.ReadAsStringAsync().Result;
}
This all compiles and appears to run fine. The response however does not contain the JSON I expect (the result of the GET query) but rather is just:
--batchresponse_20851dc6-4ff6-4914-a749-66f451985f67--
Any idea what I have missed?
This is based on the example demonstrated here:
https://dreamingincrm.com/2017/01/15/executing-large-fetchxml-with-webapi/

Create team in GraphAPI returns always null

I am using GraphAPI SDK to create a new Team in Microsoft Teams:
var newTeam = new Team()
{
DisplayName = teamName,
Description = teamName,
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
},
Members = new TeamMembersCollectionPage()
{
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", $"https://graph.microsoft.com/v1.0/users/{userId}"}
}
}
}
};
var team = await this.graphStableClient.Teams
.Request()
.AddAsync(newTeam);
The problem is that I get always null. According documentation this method returns a 202 response (teamsAsyncOperation), but the AddAsync method from SDK returns a Team object. Is there any way to get the tracking url to check if the team creation has been finished with the SDK?
Documentation and working SDK works different... As they wrote in microsoft-graph-docs/issues/10840, we can only get the teamsAsyncOperation header values if we use HttpRequestMessage as in contoso-airlines-teams-sample. They wrote to the people who asks this problem, look to the joined teams :)) :)
var newTeam = new Team()
{
DisplayName = model.DisplayName,
Description = model.Description,
AdditionalData = new Dictionary<string, object>
{
["template#odata.bind"] = $"{graph.BaseUrl}/teamsTemplates('standard')",
["members"] = owners.ToArray()
}
};
// we cannot use 'await client.Teams.Request().AddAsync(newTeam)'
// as we do NOT get the team ID back (object is always null) :(
BaseRequest request = (BaseRequest)graph.Teams.Request();
request.ContentType = "application/json";
request.Method = "POST";
string location;
using (HttpResponseMessage response = await request.SendRequestAsync(newTeam, CancellationToken.None))
location = response.Headers.Location.ToString();
// looks like: /teams('7070b1fd-1f14-4a06-8617-254724d63cde')/operations('c7c34e52-7ebf-4038-b306-f5af2d9891ac')
// but is documented as: /teams/7070b1fd-1f14-4a06-8617-254724d63cde/operations/c7c34e52-7ebf-4038-b306-f5af2d9891ac
// -> this split supports both of them
string[] locationParts = location.Split(new[] { '\'', '/', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
string teamId = locationParts[1];
string operationId = locationParts[3];
// before querying the first time we must wait some secs, else we get a 404
int delayInMilliseconds = 5_000;
while (true)
{
await Task.Delay(delayInMilliseconds);
// lets see how far the teams creation process is
TeamsAsyncOperation operation = await graph.Teams[teamId].Operations[operationId].Request().GetAsync();
if (operation.Status == TeamsAsyncOperationStatus.Succeeded)
break;
if (operation.Status == TeamsAsyncOperationStatus.Failed)
throw new Exception($"Failed to create team '{newTeam.DisplayName}': {operation.Error.Message} ({operation.Error.Code})");
// according to the docs, we should wait > 30 secs between calls
// https://learn.microsoft.com/en-us/graph/api/resources/teamsasyncoperation?view=graph-rest-1.0
delayInMilliseconds = 30_000;
}
// finally, do something with your team...
I found a solution from another question... Tried and saw that it's working...

TFS workItem.Validate() issue

Here is the case. I wrote a tool to create a task WorkItem (version 12.0.0.0), it can run normally and create TFS task last month. But Today, when I rerun it, it doesn't create TFS task and show error message: The field "Assigned To" contains the value "email address" that is not in the list of supported values.
NetworkCredential credential = new NetworkCredential("user", "password");
TfsConfigurationServer configurationServer = new TfsConfigurationServer(tfsUri, credential);
ReadOnlyCollection<CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);
foreach (CatalogNode collectionNode in collectionNodes)
{
Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
ReadOnlyCollection<CatalogNode> projectNodes = collectionNode.QueryChildren(new[] { CatalogResourceTypes.TeamProject }, false, CatalogQueryOptions.None);
foreach (CatalogNode projectNode in projectNodes)
{
Console.WriteLine("Team Project: " + projectNode.Resource.DisplayName);
}
WorkItemStore workstore = teamProjectCollection.GetService<WorkItemStore>();
Project project = workstore.Projects["SpecifiedProject"];
WorkItemType itemtype = project.WorkItemTypes["Task"];
WorkItem workItem = new WorkItem(itemtype);
string assignedTo;
assignedTo = String.Format("{0}#***.com", task.User);
workItem.Fields["Assigned to"].Value = assignedTo;
workItem.Fields["Priority"].Value = task.Priority;
workItem.Fields["Area Path"].Value = AREAPATH;
workItem.Fields["Iteration path"].Value = task.IterationPath;
workItem.Title = task.Title;
workItem.Fields["DESCRIPTION"].Value = task.Description;
workItem.Fields["Original Estimate"].Value = task.EstimatedTime.ToString();
workItem.Fields["Completed Work"].Value = task.ActualTime.ToString();
workItem.Fields["Remaining Work"].Value = task.RemainTime.ToString();
// get the link type for hierarchical relationships
var linkType = workstore.WorkItemLinkTypes[CoreLinkTypeReferenceNames.Hierarchy];
//var linkType = workstore.WorkItemLinkTypes[CoreLinkTypeReferenceNames.Dependency];
RelatedLink rl = new RelatedLink(linkType.ReverseEnd, task.UserStoryID);
workItem.Links.Add(rl);
ArrayList ValidationResult = workItem.Validate();
I think this code block "ArrayList ValidationResult = workItem.Validate();" has some issues, for detail error: enter image description here

ask for version control server (client) from VssConnection

Dears
Please help me to work with VssConnection from Microsoft.VisualStudio.Services.Client.15.134.0-preview package
I need to get pending changes for workspace, query it for conflict and commit
This is how i do it with TfsTeamProjectCollection and
var vssCred = new VssClientCredentials();
using (TfsTeamProjectCollection collection = new TfsTeamProjectCollection(uri, vssCred))
{
collection.Authenticate();
var scs = collection.GetService<VersionControlServer>();
var scsProject = scs.GetTeamProject(teamProjectName);
var workspace = scsProject.VersionControlServer.GetWorkspace(localPath);
var pending = scs.QueryPendingSets(new string[] { "$/" }, RecursionType.Full, workspace.Name, loginName);
if (pending.Any())
{
var pendingChanges = new[] { pending.First().PendingChanges.First() };
var validation = workspace.EvaluateCheckin2(CheckinEvaluationOptions.Conflicts, pendingChanges, "", null, null);
var conflicts = validation.Conflicts;
if (conflicts != null && conflicts.Any())
{
var message = string.Join("\r\n", conflicts.Select(_ => string.Format("{0} {1}", _.Message, _.ServerItem)));
throw new ArgumentException(string.Format("conflict was found\r\n{0}", message));
}
var res = workspace.CheckIn(pendingChanges, "test checkin");
TestContext.WriteLine("checked in {0}", res);
}
}
However there are vsts integration samples that uses VssConnection object
How can I get the same VersionControlServer from VssConnection instance?
I've tried to find Microsoft.TeamFoundation.VersionControl.Client.WebAPi (like Microsoft.TeamFoundation.WorkItemTracking.WebApi) but failed.
var vssCred = new VssClientCredentials();
using (VssConnection connection = new VssConnection(uri, vssCred))
{
var prj = connection.GetClient<ProjectHttpClient>();
var p = prj.GetProject(teamProjectName).Result;
//i'd like to get prj.VersionControl here
//or something like var scs = connection.GetService<VersionControlServer>();
}
Is it possible to get versionControlServer from VssConnection? Should I continue to use TfsTeamProjectCollection to do this task?
You could use TfsTeamProjectCollection as before, as there is no workspace method in VssConnection:
TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>();
List <TfvcItem> tfvcItems = tfvcClient.GetItemsAsync("$/", VersionControlRecursionType.OneLevel).Result;
More examples, you can refer to the link below:
https://learn.microsoft.com/en-us/vsts/integrate/get-started/client-libraries/samples?view=vsts

How to query VSTS Work Items with Wiql

I need to query VSTS work items using Wiql from vsp-node-api package, Please provide any examples if possible.
Refer to following code for details:
import * as vm from 'vso-node-api/WebApi';
import * as wa from 'vso-node-api/WorkItemTrackingApi';
import * as wi from 'vso-node-api/interfaces/WorkItemTrackingInterfaces';
import * as vss from 'vso-node-api/interfaces/Common/VSSInterfaces';
import * as core from 'vso-node-api/interfaces/CoreInterfaces';
var collectionUrl = "https://xxxxxx.visualstudio.com";
let token: string = "PersonalAccessToekn";
let creds = vm.getPersonalAccessTokenHandler(token);
var connection = new vm.WebApi(collectionUrl, creds);
let vstsWI: wa.IWorkItemTrackingApi = connection.getWorkItemTrackingApi();
async function WIQLquery() {
let teamC: core.TeamContext = {project: "", projectId: "", team: "", teamId: "" };
let wiqls: wi.Wiql = { query: "Select [System.Id] From WorkItems Where [System.WorkItemType] = 'Task' And [System.TeamProject] = 'Project'"};
let queryResult: wi.WorkItemQueryResult = await vstsWI.queryByWiql(wiqls, teamC);
queryResult.workItems.forEach(s=>console.log(s.url));
}
WIQLquery();
Here is how I did it, using Javascript instead of Typescript.
Shout out to Eddie Chen for leading me in the right direction.
// file - models/witModel.js
var azdev = require("azure-devops-node-api");
var Model = function(){};
Model.prototype.getWiqlQuery = function(wiqlQuery, teamName){
return new Promise(function(resolve, reject){
const orgUrl = process.env.ADOURI; // ex. https://dev.azure.com/<your org>
const token = process.env.ADOPAT; // Your personal access token
const teamProject = process.env.ADOPROJ;// Team Project
let authHandler = azdev.getPersonalAccessTokenHandler(token);
let connection = new azdev.WebApi(orgUrl, authHandler);
connection.getWorkItemTrackingApi().then(function(witAPI){
var teamContext = {project: teamProject, team: teamName };
witAPI.queryByWiql(wiqlQuery, teamContext).then(function(queryResult){
resolve(queryResult);
}).catch(function(err){reject(err)});
}).catch(function(err){
reject(err);
});
});
};
module.exports = new Model();
And this was how I used it.
// usage - the above code was saved in a module called witModel.js
// feel free to put the module where you need to.
var witModel = require("./models/witModel.js");
// form query and set the value of the teame to query
var query = {query: "your wiql query"};
var team = "team name in Azure DEvops";
// call the promise and handle resolve/reject - then/catch
witModel.getWiqlQueryResuults(query,team).then(function(data){
console.log(data);
}).catch(function(err){
console.log(err)
});

Resources