I need to find out how many labels are there inside each module of a collection in Team Foundation repository.
I am using TFS 2013.
I know we can get it from Visual Studio. But we need a script which gets us the number of labels as output.
Can anyone help me out in getting a C# or a Powershell code to obtain the same?
TIA
You can use .NET Client Libraries to get this: .NET client libraries for Visual Studio Team Services (and TFS)
Code sample:
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace GetLabels
{
class Program
{
static void Main(string[] args)
{
string tfscollection = "http://xxx:8080/tfs/defaultcollection";
TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(tfscollection));
VersionControlServer vcs = ttpc.GetService<VersionControlServer>();
string labelname = null;
string labelscope = "$/";
string owner = null;
bool includeitem = false;
int labelnumber;
VersionControlLabel[] labels = vcs.QueryLabels(labelname,labelscope,owner,includeitem);
labelnumber = labels.Length;
Console.WriteLine(labelnumber);
Console.ReadLine();
}
}
}
Related
Our company recently updated TFS to 2015 update 1. After that context menu item named Drop folder disappeared from completed builds. I found nothing about it and how to bring it back. When I click Open on completed build, VS opens web version of TFS where I forced to click through the menus and copy drop folder path manually. So I decided to write a simple extension that will add this item to the menu.
Some googling brought me to this page. But it seems that the example code is quite old and not working in VS2015:
IVsTeamFoundationBuild vsTfBuild = (IVsTeamFoundationBuild)GetService(typeof(IVsTeamFoundationBuild));
IBuildDetail[] builds = vsTfBuild.BuildExplorer.CompletedView.SelectedBuilds;
Property SelectedBuilds is always empty. I suppose that it relates to old window from VS2010. It returns items that are instance of IBuildDetail interface.
So I found this piece of code here:
var teamExplorer = (ITeamExplorer)ServiceProvider.GetService(typeof(ITeamExplorer));
var page = teamExplorer.CurrentPage;
var buildsPageExt = (IBuildsPageExt)page.GetExtensibilityService(typeof(IBuildsPageExt));
var build = buildsPageExt.SelectedBuilds[0];
Here build is the instance of IBuildModel interface. It lacks DropLocation property.
Is there any way to found drop location of selected build? Or maybe latest build?
You can use IBuildDedetail.DropLocation in .NET client libraries for Visual Studio Team Services (and TFS). Basic code for your reference:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
namespace BuildAPI
{
class Program
{
static void Main(string[] args)
{
string project = "http://xxx.xxx.xxx.xxx";
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(project));
IBuildServer ibs = tpc.GetService<IBuildServer>();
var builds = ibs.QueryBuilds("TeamProjectName");
foreach (IBuildDetail ibd in builds)
{
Console.WriteLine(ibd.DropLocation);
Console.ReadLine();
}
}
}
}
So, after digging through TFS API, I ended up with this workaround.
private void MenuItemCallback(object sender, EventArgs e)
{
var context = (ITeamFoundationContextManager)ServiceProvider.GetService(typeof(ITeamFoundationContextManager));
IBuildServer buildServer = context.CurrentContext.TeamProjectCollection.GetService<IBuildServer>();
var teamExplorer = (ITeamExplorer)ServiceProvider.GetService(typeof(ITeamExplorer));
var buildsPageExt = (IBuildsPageExt)teamExplorer.CurrentPage.GetExtensibilityService(typeof(IBuildsPageExt));
var menuCommand = (MenuCommand)sender;
if (menuCommand.CommandID.Guid == CommandSetCompleted)
{
foreach (var buildDetail in buildsPageExt.SelectedBuilds)
Process.Start("explorer.exe", GetBuild(buildServer, buildDetail).DropLocation);
}
if (menuCommand.CommandID.Guid == CommandSetFavorite)
{
var definitions = buildsPageExt.SelectedFavoriteDefinitions.Concat(buildsPageExt.SelectedXamlDefinitions).ToArray();
foreach (var build in GetLatestSuccessfulBuild(buildServer, definitions))
Process.Start("explorer.exe", build.DropLocation);
}
}
private IBuildDetail GetBuild(IBuildServer buildServer, IBuildModel buildModel)
{
Uri buildUri = new Uri(buildModel.GetType().GetProperty("UriToOpen").GetValue(buildModel).ToString());
return buildServer.GetBuild(buildUri);
}
private IBuildDetail[] GetLatestSuccessfulBuild(IBuildServer buildServer, IDefinitionModel[] buildDefinitions)
{
var spec = buildServer.CreateBuildDetailSpec(buildDefinitions.Select(bd => bd.Uri));
spec.MaxBuildsPerDefinition = 1;
spec.QueryOrder = BuildQueryOrder.FinishTimeDescending;
spec.Status = BuildStatus.Succeeded;
var builds = buildServer.QueryBuilds(spec);
return builds.Builds;
}
I have been trying to figure out how is possible to create a query folder via VSO api, but I always the "Method not allowed" message.
I'm using Microsoft.TeamFoundationServer.Client package to connect VSO. This page says that this library is needed for me. I can query data, but it seems something is missing to create data. This library is fit for me because I have a WebApi whihch manages the communication to VSO API.
Here is my code:
public QueryHierarchyItem CreateFolderAsync(string folderName)
{
QueryHierarchyItem newFolder = new QueryHierarchyItem()
{
Name = folderName,
IsFolder = true,
//Path = "Queries/Shared Queries/" + folderName,
IsPublic = true
};
QueryHierarchyItem item = witClient.CreateQueryAsync(newFolder, _projectName, null).Result;
return item;
}
I have tried to play with the Path property but it did not help.
I have checked the user rights. My user is member of "Project Administrators", and
rights are also set up to manage query folders (Click the chevron next to the "Shared Queries" folder -> select "Security") as group and as single user. It did not help.
I use a free account. The strange is that I have logged in with the same user from Visual Studio and I can manage the folders. Is this functionality available for free accounts?
You can refer to this blog from MSDN for details: http://blogs.msdn.com/b/team_foundation/archive/2010/06/16/work-item-tracking-queries-object-model-in-2010.aspx
Quote the code here:
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
namespace QueryAPI
{
class Program
{
private static Project myproject = null;
public static QueryFolder GetMyQueriesFolder()
{
foreach (QueryFolder folder in myproject.QueryHierarchy)
{
if (folder.IsPersonal == true)
return folder;
}
throw new Exception("Cannot find the My Queries folder");
}
public static QueryFolder AddNewFolder(string folderName)
{
QueryFolder folder = new QueryFolder(folderName, GetMyQueriesFolder());
myproject.QueryHierarchy.Save();
return folder;
}
static void Main(string[] args)
{
TfsTeamProjectCollection coll = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("Your TFS Server URI"));
WorkItemStore store = new WorkItemStore(coll);
myproject = store.Projects["Your project name"];
QueryFolder myNewfolder = AddNewFolder("Your folder name");
}
}
}
I want to automate testing of newly created build agents in TFS.
Now, I have written code to queue builds of particular build definition on TFS.
Problem I am facing is to queue build definition on agents of given controller.
Previously there was one method which I've commented in my code
for doing this, i.e. IbuildRequest.buildagent, but now it has been deprecated in newer tfs api.
Edit:
I have already tested IbuildRequest.BuildController property which tends to randomly pick agent, which is currently free.
What I want to know is can I force build definition to use one build Agent using tfs api.
using System;
using System.Linq;
using System.Security.Principal;
using System.Collections.Generic;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
namespace BuildAgentsTestApp
{
class Program
{
static void Main(string[] args)
{
Uri collectionURI = new Uri("https://tfs-uri");
var tfsCreds = new TfsClientCredentials(new WindowsCredential(), true);
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(collectionURI,tfsCreds);
WindowsIdentity user = WindowsIdentity.GetCurrent();
tfs.EnsureAuthenticated();
if (tfs.HasAuthenticated)
{
WorkItemStore workItemStore = tfs.GetService<WorkItemStore>();
Project teamProject = workItemStore.Projects["myProjectName"];
IBuildServer buildServer = (IBuildServer)tfs.GetService(typeof(IBuildServer));
IBuildDefinition buildDef = buildServer.GetBuildDefinition(teamProject.Name, "myBuildDefinitionName");
var controller = GetRequestedController(buildServer, "myControllerName");
var AgentsList = GetAgentCollection(controller);
//Queue each build definition
IBuildRequest buildRequest = buildDef.CreateBuildRequest();
buildRequest.GetOption = GetOption.Custom;
//buildRequest.BuildAgent = AgentsList.First();
buildServer.QueueBuild(buildRequest);
}
Console.WriteLine("Build Queued!");
Console.ReadKey();
}
static IBuildController GetRequestedController(IBuildServer reqBuildServer, string reqControllerName)
{
var requiredController = reqBuildServer.QueryBuildControllers()
.Where(ctrl =>
ctrl.Name == reqControllerName
).FirstOrDefault();
return requiredController;
}
static List<IBuildAgent> GetAgentCollection(IBuildController controller)
{
var ListOfAgents = from agent in controller.Agents
select agent;
return ListOfAgents.ToList();
}
}
}
I want to be able to read the VS build configurations programmatically. That is because I want to create my own builder.
How do I do that? Does anyone have code example?
What i mean is that if I have Debug, Development, Release I want them to be listed in a list box in a Form application. I have tried using the "EnvDTE.dll" class but I am not sure it is what I am looking for. If anyone has a concrete example or link to an example I would be more than grateful.
You can use the msbuild API. In Visual Studio 2015, there is a class called Microsoft.Build.Construction.SolutionFile in the Microsoft.Build.dll that ships with VS2015 that you can use to load a solution.
In VS2013 there is no such thing, but you can do the following:
(reference Microsoft.Build.dll, Microsoft.Build.Engine.dll, Microsoft.Build.Framework.dll)
class Program
{
static void Main(string[] args)
{
string nameOfSolutionForThisProject = #"MySolutionFile.sln";
string wrapperContent = SolutionWrapperProject.Generate(nameOfSolutionForThisProject, toolsVersionOverride: null, projectBuildEventContext: null);
byte[] rawWrapperContent = Encoding.Unicode.GetBytes(wrapperContent.ToCharArray());
using (MemoryStream memStream = new MemoryStream(rawWrapperContent))
using (XmlTextReader xmlReader = new XmlTextReader(memStream))
{
Project proj = ProjectCollection.GlobalProjectCollection.LoadProject(xmlReader);
foreach (var p in proj.ConditionedProperties)
{
Console.WriteLine(p.Key);
Console.WriteLine(string.Join(", ", p.Value));
}
}
Console.ReadLine();
}
}
ConditionedProperties contains a list of platforms and configurations contained in the solution. You can use this to populate your forms.
Is it possible to connect Visual Studio to TFS Team Project from code? I found article how to connect to TFS: http://msdn.microsoft.com/en-us/library/vstudio/bb286958.aspx however this allows me to perform basic actions on TFS from code but not connecting Visual Studio.
As I understand your question, you can't... you have 3 options:
1-Making an extension for VS Team Explore and this extension will depend on you are already connected using VS.
Extending Team Explorer in Visual Studio 2012
2- Making a separate exe so you will use the the TeamProjectPicker so
you can choose which TFS and which Team Project you want to connect to.
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Application.EnableVisualStyles(); // Makes it look nicer from a console app.
//"using" pattern is recommended as the picker needs to be disposed of
using (TeamProjectPicker tpp = new TeamProjectPicker(TeamProjectPickerMode.MultiProject, false))
{
DialogResult result = tpp.ShowDialog();
if (result == DialogResult.OK)
{
System.Console.WriteLine("Selected Team Project Collection Uri: " + tpp.SelectedTeamProjectCollection.Uri);
System.Console.WriteLine("Selected Projects:");
foreach (ProjectInfo projectInfo in tpp.SelectedProjects)
{
System.Console.WriteLine(projectInfo.Name);
}
}
}
}
}
}
3- Use API for TFS and hardcode path or put it in a config file like the following:
using System;
using System.Collections.ObjectModel;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Framework.Client;
namespace TfsApplication
{
class Program
{
static void Main(String[] args)
{
// Connect to Team Foundation Server
// Server is the name of the server that is running the application tier for Team Foundation.
// Port is the port that Team Foundation uses. The default port is 8080.
// VDir is the virtual path to the Team Foundation application. The default path is tfs.
Uri tfsUri = (args.Length < 1) ?
new Uri("http://Server:Port/VDir") : new Uri(args[0]);
TfsConfigurationServer configurationServer =
TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
// Get the catalog of team project collections
ReadOnlyCollection<CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(
new[] { CatalogResourceTypes.ProjectCollection },
false, CatalogQueryOptions.None);
// List the team project collections
foreach (CatalogNode collectionNode in collectionNodes)
{
// Use the InstanceId property to get the team project collection
Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
// Print the name of the team project collection
Console.WriteLine("Collection: " + teamProjectCollection.Name);
// Get a catalog of team projects for the collection
ReadOnlyCollection<CatalogNode> projectNodes = collectionNode.QueryChildren(
new[] { CatalogResourceTypes.TeamProject },
false, CatalogQueryOptions.None);
// List the team projects in the collection
foreach (CatalogNode projectNode in projectNodes)
{
Console.WriteLine(" Team Project: " + projectNode.Resource.DisplayName);
}
}
}
}
}
Here you can find step by step guide to Connect Visual Studio to TFS
http://tfs.visualstudio.com/en-us/learn/code/connect-vs/