tfs command line 'merge' equivalent in .NET - c#

EDIT: poor wording of my question. What I am trying to achieve is to 'discard' the merge history of the changeset
EDIT 2
I worked out how I can remove the changeset from the merge candidate queue. I don't particularly think it is a good idea but I am including the code simply for 'completeness' sake.
SCENARIO: developer fixes bug on branch and checks in. Developer then fixes bug on trunk instead of merging (trunk has changed dramatically therefore not merging). However the changeset appears in the list when merging from the branch to the trunk. I am trying to mark this changeset to remove it from this list. This can be done using the commandline utility by passing the 'discard' switch...I am tryinh to achive the same using the TFS API..
I think I am pretty close by use of the Merge method but am not sure of the options to pass in. I do NOT want to perform a merge just want to mark the changeset as merged without merging
have got a list of changesets from TFS using a Winforms app and would like be able to merge a changeset by calling discard on it using C#
the merge command is here
can this be done using the TFS .NET libraries or do I have to call the commandline editor from the winforms app?
//get the merge candidates
IEnumerable<MergeCandidate> mergeCandidates =
_vcs.GetMergeCandidates(cboSource.Text, cboTarget.Text, RecursionType.Full)
.OrderByDescending(x => x.Changeset.ChangesetId)
.AsEnumerable();
//user select a changeset from a grid and then I want to discard this changeset from the //'merge list'
string _changeset = grdChangeSets.CurrentRow.Cells[0].Value.ToString();
VersionSpec vfrom = VersionSpec.ParseSingleSpec(_changeset, null);
VersionSpec vto = VersionSpec.ParseSingleSpec(_changeset,null);
_workspaces[0].Merge(cboSource.Text, cboTarget.Text, vfrom, vto, LockLevel.None, RecursionType.Full,
MergeOptions.AlwaysAcceptMine);
EDIT 2 CODE
string _changeSetId = grdChangeSets.CurrentRow.Cells[0].Value.ToString();
VersionSpec vfrom = VersionSpec.ParseSingleSpec(_changeSetId, null);
VersionSpec vto = VersionSpec.ParseSingleSpec(_changeSetId, null);
UsiWorkspace wksp = new UsiWorkspace();
wksp.ResolveConflicts(_workspaces[0]);
GetStatus getStatus = _workspaces[0].Merge(cboSource.Text,
cboTarget.Text,
vfrom,
vto,
LockLevel.None,
RecursionType.Full,
MergeOptions.AlwaysAcceptMine);
var _conflicts = workspaces[0].QueryConflicts(null, true);
foreach (Conflict conflict in _conflicts)
{
conflict.Resolution = Resolution.DeleteConflict;
workspace.ResolveConflict(conflict);
}
var wip = new WorkspaceCheckInParameters(_workspaces[0].GetPendingChanges(),string.Format("CHECKED IN FROM TFS TOOL - {0} {1}", DateTimeOffset.Now.ToString(), Environment.UserName))
{
OverrideGatedCheckIn = ((CheckInOptions2) _vcs.SupportedFeatures & CheckInOptions2.OverrideGatedCheckIn) ==
CheckInOptions2.OverrideGatedCheckIn,
PolicyOverride = new PolicyOverrideInfo("CHECKED IN FROM TFS TOOL - POLICY", null)
};
_workspaces[0].CheckIn(wip);

There is a merge method in the TFS api : http://msdn.microsoft.com/en-us/library/ff731634.aspx
Perhaps something like this :
var status = _workspace.Merge(sourceTfsPath, targetTfsPath, null, null, LockLevel.None, RecursionType.Full,
MergeOptions.AlwaysAcceptMine);
Trace.WriteLine(status.NumOperations);
var conflicts = _workspace.QueryConflicts(null, true);
foreach (var conflict in conflicts)
{
conflict.Resolution = Resolution.AcceptYours;
_workspace.ResolveConflict(conflict);
}

Related

Finding changesets associated with the work item or having specific comment TFS Api

I'm trying to find all changesets associated with the work item using Microsoft.TeamFoundation.WorkItemTracking.Client. Using query I was able to get the information about the work items in question, however I cannot find any changeset information on the object I'm getting back. In addition to that there are some changesets that are not linked to specific work item but easy identifiable by the comment. Is there a quick way to find these using tfs api?
Edit: this is not a duplicate of How to get work items associated with a changeset id using tfs api? b/c in that question person has a changeset and would like to find associated work items. In my case I have a work items and I would like to find all changesets associated with the specific work items. In addition to that I need to find all changesets that have specific string in the comment.
After more googling on the subject and exploring tfs API here is what I ended up with:
If all you changesets are linked to the work items (not really my case but this is what I originally was asking about):
// based on https://etoptanci.wordpress.com/2011/05/04/seeing-all-code-changes-for-a-work-item/
private static void GetChangesForWorkItem()
{
var configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(#"http://myserver:8080/tfs"));
var tpcService = configurationServer.GetService<ITeamProjectCollectionService>();
var collectionNodes = configurationServer.CatalogNode.QueryChildren(
new[] { CatalogResourceTypes.ProjectCollection },
false, CatalogQueryOptions.None);
var collectionNode = collectionNodes.First(x => x.Resource.DisplayName == "<collection name>");
// Use the InstanceId property to get the team project collection
Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
TfsTeamProjectCollection collection = configurationServer.GetTeamProjectCollection(collectionId);
var vcs = collection.GetService<VersionControlServer>();
var store = new WorkItemStore(collection);
var workItems = new List<WorkItem>()
{
store.GetWorkItem(1123),
store.GetWorkItem(1145),
};
var associatedChangesets = new List<Changeset>();
foreach (var workItem in workItems)
{
foreach (var link in workItem.Links)
{
if((link==null) || !(link is ExternalLink))
continue;
string externalLink = ((ExternalLink)link).LinkedArtifactUri;
var artifact =LinkingUtilities.DecodeUri(externalLink);
if (artifact.ArtifactType == "Changeset")
associatedChangesets.Add(vcs.ArtifactProvider.GetChangeset(new Uri(externalLink)));
}
}
Console.WriteLine(associatedChangesets.Select(x=>x.ChangesetId).OrderBy(x => x));
}
If you need to get by comment as well then you gate all changesets for the daterange and then filter out by Changeset.Comment which is a string.
Check the REST API:
GET https://{instance}/defaultcollection/_apis/tfvc/changesets/{id}?api-version={version}[&includedetails={boolean}&includeworkitems={boolean}&includesourcerenames={boolean}&maxchangecount={int}&maxcommentlength={int}]
You can also use RestAPI (as stated in the first answer)
https://www.visualstudio.com/en-us/docs/integrate/api/wit/work-items#with-links-and-attachments
You need to filter out "relations" array with rel == "ArtifactLink"

Neo4jclient where is this class - Neo4jDataRepository?

I am trying to batch insert relationships into neo4j database using the Neo4jclient for c#. I found this code by user dcinzona. I am looking through the latest source code and can't find this class Neo4jDataRespository anywhere. Is this a custom class created by this user or am I missing something?
string merge1 = string.Format("c:{0} {{{1}:row.{2}}}", IDFieldLeft.Replace("Id", ""), IDFieldLeft, IDFieldLeft);
string merge2 = string.Format("a:{0} {{{1}:row.{2}}}", IDFieldRight.Replace("Id", ""), IDFieldRight, IDFieldRight);
string merge3 = string.Format("(c)-[r:{0} {{row}}]->(a)", entityName);
foreach (var list in Neo4jDataRepository.Batch(relationshipMatrix, 1000))
{
var query = client
.Cypher
.WithParam("coll", list.ToList())
.ForEach("(row in {coll})")//manually create json array of list objects
.Merge(merge1)
.Merge(merge2)
.Merge(merge3);
query.ExecuteWithoutResults();
}
This is a custom class created by that user, it's not part of Neo4jClient.
I'm not sure what they've done, and I've not seen it referenced anywhere else but by them I'm afraid :/

How to get history of checkins/changsets for specific Team Project?

I'm using the TFS Client API to try and query a TFS 2010 instance.
I need to be able to do the following
For a specified team project, say 'Project A'
Get a list of the history of recent check-ins made to this project (say the last 50, or the list for the last day)
Then be able to iterate through this list and get some metadata for the items (file and folder names ideally)
I think I need to use the QueryXXX methods on the VersionControlServer class, but cannot find any helpful or clear examples on how to use this.
I have seen there is GetLastestChangesetId method, but this doesn't look like it can be scoped to a specific project or directory.
This is pretty straightforward:
var tfsUrl = "http://myTfsServer:8080/tfs/defaultcollection";
var sourceControlRootPath = "$/MyTeamProject";
var tfsConnection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsUrl));
var vcs = tfsConnection.GetService<VersionControlServer>();
var changeSets = vcs.QueryHistory(sourceControlRootPath, RecursionType.Full);
foreach (var c in changeSets)
{
var changeSet = vcs.GetChangeset(c.ChangesetId);
foreach (var change in changeSet.Changes)
{
// All sorts of juicy data in here
}
}
In 2021, using azure devOps Tfs Client Api
As per the documentation, the Api is meant for following Tfs servers.
Azure DevOps Services | Azure DevOps Server 2020 | Azure DevOps Server 2019 | TFS 2018 - TFS 2013
Namespaces used here:
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.VisualStudio.Services.WebApi;
Create VssConnection as follows,
string myTfsProjectUri = "url path to your tfs project";
VssConnection myConnection = new VssConnection( new Uri( collectionUri ), new VssClientCredentials() );
Create TfvcHttpClient client as follows,
TfvcHttpClient myVersionControlHttpClient = myConnection.GetClient<TfvcHttpClient>();
Get Changesets using search criteria as follows (given snippet finds all the check-ins between given fromCheckInId & toCheckInId),
List<TfvcChangesetRef> changeSets = VersionControlHttpClient
.GetChangesetsAsync(
projectName, /* Tfs Project name */
null, /* Max Comment length, can be null */
null, /* Number of results to Skip, can be null */
null, /* Maximum Number of results to return, can be null */
null, /* Results are sorted by ID in descending order by default. Use id asc to sort by ID in ascending order */
new TfvcChangesetSearchCriteria()
{
ItemPath = branchName, /* Path to Branch under given project */
FromId = fromCheckinId, /* From check-in id to start search */
ToId = toCheckinId /* To check-in id to end search */
} ).Result;
This API can be used with FromDate and ToDate search criteria as well.
For more information, read official documentation

CRM2011 - Why are existing values being deleted when I add a new option set value using InsertOptionValueRequest

I'm trying to add new values to a MS Dynamics CRM option set in C# with InsertOptionValueRequest, and when I do, some of the existing option set values get deleted.
The code I am using is as follows:
ovRequest = new InsertOptionValueRequest
{
AttributeLogicalName = strOptionsetName,
EntityLogicalName = strEntityName,
Label = new Label(strLabel, LanguageCode)
};
_service.Execute(ovRequest);
I then publish entity with:
pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><entities><entity>{0}</entity></entities></importexportxml>", strEntityName) };
ospService.Execute(pxReq1);
I am finding this is happening both with Local Option Sets and Global Option Sets and can't see any pattern in the value being deleted. Am I doing something wrong or is this a bug in the SDK?
PS, can someone add a insertoptionvaluerequest tag to this, because I think that tag would be most relevant to this post.
I have found an answer to my question. MS Dynamics is not deleting existing values, it is overwriting the label on existing option set values. This is definitely a bug as the command being run is InsertOptionValueRequest and there is a separate UpdateOptionValueReqequest for updating values.
To work around it, manually set the Value when inserting the record instead of relying on the system to generate one for you:
ovRequest = new InsertOptionValueRequest
{
AttributeLogicalName = strOptionsetName,
EntityLogicalName = strEntityName,
Label = new Label(strLabel, LanguageCode),
Value = MyNewValue
};
_service.Execute(ovRequest);

How to get a list of revision using sharpsvn

How do I get a list of revisions from sharpsvn
If you look at the metadata for SvnLogEventArgs (which is returned as a collection from GetLog) it derives from SvnLoggingEventArgs, which has properties of Author, Revision, Time and LogMessage (amongst others)
Each SvnLogEventArgs item has a collection of ChangedPaths, which have properties for SvnChangeAction, and Path.
You can get a list of all the log info by this method:
var client = new SvnClient();
System.Collections.ObjectModel.Collection<SvnLogEventArgs> logEventArgs;
client.GetLog("targetPath", out logEventArgs);
Iterating through all the logEventArgs will give you some useful information - LogMessage, Author, etc.
I don't know what you're doing, but I am checking the latest version of the working copy using SvnWorkingCopyClient:
var workingCopyClient = new SvnWorkingCopyClient();
SvnWorkingCopyVersion version;
workingCopyClient.GetVersion(workingFolder, out version);
The latest version of the local working repository is then available through
long localRev = version.End;
For a remote repository, use
var client = new SvnClient();
SvnInfoEventArgs info;
client.GetInfo(targetUri, out info);
long remoteRev = info.Revision;
instead.
This is similar to using the svnversion tool from the command line. Hope this helps.
Guessing at what your question really is about the answer is most likely SvnClient.Log(), to get you a list of changes of a path.
Another anwer would be:
for (int i = 1; i < 101; i++)
yield return i;
to get you the first 100 revisisions of a repository ;-)
See Using SharpSvn to retrieve log entries within a date range for some examples on how to use SvnClient.Log()
This is the code form which you can get all the revisions no in list revisions numbers. UriSCpath will be uri for svn path.
SvnTarget tr = SvnTarget.FromUri(UriSCPath);
Collection<SvnLogEventArgs> logEventArgs;
List<Int64> revisionNumbers = new List<Int64>();
SvnLogArgs logArgs = new SvnLogArgs();
DPISVN_Clnt.GetLog(UriSCPath, logArgs, out logEventArgs);
Int64 latestReision = logEventArgs[0].Revision;
foreach (var item in logEventArgs)
{
revisionNumbers.Add(item.Revision);
}

Categories

Resources