I have the following code to retrieve all projects in TFS using the .net SDK for VSTS and using TFS2018. But I only get the top most project folders. How can I retrieve the subfolders of a certain project?
var uri = new Uri("https://devserver/tfs/DefaultCollection");
using (var projectHttpClient = new ProjectHttpClient(uri, cred)) {
var projects = projectHttpClient.GetProjects().Result;
}
I also tried changing the uri to
var uri = new Uri("https://devserver/tfs/DefaultCollection/MyProject");
But I get a Page not found error.
Here is a snapshot of the TFS structure. I would like to retrieve the projects on the sublevel. However I am only receiving the second level projects. The level with the user icons.
Try the code below to get folders:
using Microsoft.TeamFoundation.Client;
using System;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace TestCaseProject
{
class Program
{
static void Main(string[] args)
{
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("http://tfsserver:8080/tfs/DefaultCollection"));
var versioncontrols = tfs.GetService<VersionControlServer>();
var workspace = versioncontrols.CreateWorkspace("workspaceName","workspaceOwner");
String ServerFolder = #"$/TeamProject/Folder";
String LocalFolder = #"C:\Folder";
WorkingFolder workfolder = new WorkingFolder(ServerFolder, LocalFolder);
workspace.CreateMapping(workfolder);
workspace.Get();
}
}
}
Related
I am trying the following to get list of projects from "on prem" TFS
private static async void Method()
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "Username", "Password"))));
using (HttpResponseMessage response = client.GetAsync(
"http://test-test-app1:8080/tfs/boc_projects/_apis/projects?api-version=2").Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
I am using a user name and password which has admin permissions on TFS i am trying to connect.But i get unauthorized access error when i try the above.
The REST API of getting a list of team projects is:
>
http://tfsserver:8080/tfs/CollectionName/_apis/projects?api-version=1.0
Make sure you have enabled Basic Auth for your TFS:
check your IIS to see whether the Basic authentication service role is installed.
go to IIS Manager, select Team Foundation Server -- Authentication
and disable everything other than Basic Authentication. Then do the
same for the tfs node under Team Foundation Server.
restart your IIS.
Here's a simple app using the Catalog Service. It looks for a file by cycling through all Project Collections and Projects, and finds instances of the file by name. It wouldn't take much to change it for your needs.
using System;
using System.Linq;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace EpsiFinder
{
internal class Program
{
// Server URL. Yes, it's hardcoded.
public static string Url = #"http://tfs.someserver.com:8080/tfs";
private static void Main()
{
// Use this pattern search for the file that you want to find
var filePatterns = new[] { "somefile.cs" };
var configurationServerUri = new Uri(Url);
var configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(configurationServerUri);
var configurationServerNode = configurationServer.CatalogNode;
// Query the children of the configuration server node for all of the team project collection nodes
var tpcNodes = configurationServerNode.QueryChildren(
new[] { CatalogResourceTypes.ProjectCollection },
false,
CatalogQueryOptions.None);
// Changed to use the Catalog Service, which doesn't require admin access. Yay.
foreach (var tpcNode in tpcNodes)
{
Console.WriteLine("Collection: " + tpcNode.Resource.DisplayName + " - " + tpcNode.Resource.Description);
// Get the ServiceDefinition for the team project collection from the resource.
var tpcServiceDefinition = tpcNode.Resource.ServiceReferences["Location"];
var configLocationService = configurationServer.GetService<ILocationService>();
var newUrl = new Uri(configLocationService.LocationForCurrentConnection(tpcServiceDefinition));
// Connect to the team project collection
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(newUrl);
// This is where we can do stuff with the team project collection object
// Get the Version Control instance
var versionControl = tfs.GetService<VersionControlServer>();
// Select the branches that match our criteria
var teamBranches = versionControl.QueryRootBranchObjects(RecursionType.Full)
.Where(s => !s.Properties.RootItem.IsDeleted)
.Select(s => s.Properties.RootItem.Item)
.ToList();
// Match the file in the branches, spit out the ones that match
foreach (var item in from teamBranch in teamBranches
from filePattern in filePatterns
from item in
versionControl.GetItems(teamBranch + "/" + filePattern, RecursionType.Full)
.Items
select item)
Console.WriteLine(item.ServerItem);
}
}
}
}
We have many projects with several files inside each. Files can be checked in from the main solution root, from the project level and from the individual level.
Is there a way to find all files checked in by a particular user during the past few days, for all the levels?
If you have the TFS power tools installed you can use the command "tfpt searchcs" from a visual studio command prompt. This will allow you to search for all change sets checked in by a particular user and also set a start and end date along side some other filters. This might meet your needs
I think it's not possible to drill down to the files of each changeset of a user within a given timeframe by using the standard reporting facilities of TFS.The following uses the TFS-SDK & should accomplish the task:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace GetCheckedInFiles
{
class Program
{
static void Main()
{
TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://tfsURI"));
var versionControl = teamProjectCollection.GetService<VersionControlServer>();
//enforcing 3 days as "past few days":
var deltaInDays = new TimeSpan(3, 0, 0, 0);
DateTime date = DateTime.Now - deltaInDays;
VersionSpec versionFrom = GetDateVSpec(date);
VersionSpec versionTo = GetDateVSpec(DateTime.Now);
IEnumerable results = versionControl.QueryHistory("$/", VersionSpec.Latest, 0, RecursionType.Full, "User" , versionFrom, versionTo, int.MaxValue, true, true);
List<Changeset> changesets = results.Cast<Changeset>().ToList();
if (0 < changesets.Count)
{
foreach (Changeset changeset in changesets)
{
Change[] changes = changeset.Changes;
Console.WriteLine("Files contained in "+changeset.ChangesetId+" at "+changeset.CreationDate+" with comment "+changeset.Comment);
foreach (Change change in changes)
{
string serverItem = change.Item.ServerItem;
Console.WriteLine(serverItem + " "+change.ChangeType);
}
Console.WriteLine();
}
}
}
private static VersionSpec GetDateVSpec(DateTime date)
{
string dateSpec = string.Format("D{0:yyy}-{0:MM}-{0:dd}T{0:HH}:{0:mm}", date);
return VersionSpec.ParseSingleSpec(dateSpec, "");
}
}
}
The GetDateVSpec was copied from this post by Robaticus
Is there a way to get tfs 2010 teambuild's controller (and agent) status from the command line? my controllers (have got about 20) keep on having to be restarted (we know why this is) and I'd like a way to run a script (psexec?) to check what's stayed up.
It's possible to have a small console app that does this for you as follows:
using System;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
namespace GetAgentsStatus
{
class Program
{
static void Main()
{
TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("CollectionUri"));
IBuildServer buildService = (IBuildServer)teamProjectCollection.GetService(typeof(IBuildServer));
IBuildController buildController = buildService.GetBuildController("BuildControllerName");
foreach (var agent in buildController.Agents)
{
if(agent.Status == AgentStatus.Offline || agent.Status == AgentStatus.Unavailable)
{
Console.WriteLine(string.Format("{0} needs restarting",agent.Name));
}
}
}
}
}
If you open any build definition for editing, navigate to "Build Defaults" to retrieve the value of BuildControllerName
I am working on TFS API. I am trying to get the entire list of projects, subprojects, files from TFS.
Could someone guide me regarding it.
TfsTeamProjectCollection teamProjectCollection = teamFoundationserver.TfsTeamProjectCollection;
ProjectCollection projCollect = (ProjectCollection) teamProjectCollection.GetService(typeof(ProjectCollection));
The above code just shows the first level from TFS. How Can I go further deep into TFS tree.
I want the entire list of projects, and solutions under each project.
Thanks,
SV
There's no such thing as a "subproject." What it sounds like you want to do is get a listing of all subfolders / files under each project.
To do that, iterate through each of your projects, and do a GetItems on each. Here's some code:
TfsTeamProjectCollection teamProjectCollection = new TfsTeamProjectCollection(new Uri("http://sw100429:8080"));
ProjectCollection projCollect = (ProjectCollection)teamProjectCollection.GetService(typeof(ProjectCollection));
VersionControlServer vcs = teamProjectCollection.GetService<VersionControlServer>();
// This approach lets you get the list of files for each team project individually.
foreach (TeamProject tp in projCollect)
{
string path = string.Format("$/{0}", tp.Name);
var filesAndFolders = vcs.GetItems(path, RecursionType.Full);
}
// However, this approach is a bit more succinct - instead
// of getting them for each team project, just start at "$/" and work your way down
var allFilesAndFolders = vcs.GetItems("$/", RecursionType.Full);
Using your q&a (thanks) I was able to put this sample together after a lot of trial and error. It goes a step further to show how to map the local paths too. I hope this saves some readers some head aches.
This example was put together in a form in VS 2015 and uses the following assembly references (that were also tricky to track down)
All located in C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\vl45o2it.tph on my machine.
Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.VisualStudio.TeamFoundation.dll
Apologies if my terminology is out in places. I don't mind if you edit any of this.
using System;
using System.Linq;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Framework.Client;
using System.Diagnostics;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace Tfs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Uri tfsUri = new Uri("http://server:8080/tfs");
string repositoryName = "yourrepository";
string projectPath = "$/project/path/path/path";
Uri repositoryUri = new Uri(string.Format("{0}/{1}", tfsUri.AbsoluteUri, repositoryName));
TfsConfigurationServer tfscs = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
//get the repository
CatalogNode repository = tfscs.CatalogNode.QueryChildren(new Guid[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None)
.FirstOrDefault(a => string.Compare(a.Resource.DisplayName, repositoryName, true) == 0);
//open in the project collection
TfsTeamProjectCollection pc = tfscs.GetTeamProjectCollection(new Guid(repository.Resource.Properties["InstanceId"]));
//tfs project file structure access
VersionControlServer vcs = pc.GetService<VersionControlServer>();
WorkspaceInfo wsi = Workstation.Current.GetAllLocalWorkspaceInfo().FirstOrDefault(a => a.ServerUri == repositoryUri);
//user functionality (checkin, localpaths etc)
Workspace ws = wsi.GetWorkspace(pc);
//get the file structure
ItemSet items = vcs.GetItems(projectPath, RecursionType.Full);
foreach (Item i in items.Items)
{
Debug.WriteLine(string.Format("{0} ({1}) - {2} - {3}", i.ServerItem,
i.ContentLength.ToString(),
i.ItemType.ToString(),
ws.GetLocalItemForServerItem(i.ServerItem)));
}
}
}
}
How do I install custom SharePoint Timer job on MOSS
Hello I created,
custom SharePoint Timer job,
Below in this document is my code.
I wrote and installed a lot of
webparts.
But this is the first time I write
SharePoint Timer job on MOSS.
i try to deploy it wite wspBuilder,
try to copy it to gac,
But the JOB not appear on the list JOB on
Central Administration site ,
Central Administration > Operations > Timer Job Definitions ,
how can i add it and see it on the ,
Central Administration > Operations > Timer Job Definitions
the code.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.IO;
using Microsoft.SharePoint;
namespace WSPBuilderProject1.FeatureCode
{
public class MyTimerJob : SPJobDefinition
{
public MyTimerJob()
: base()
{
this.Title = "My Timer Job";
}
public MyTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
: base(jobName, service, server, targetType)
{
this.Title = "My Timer Job";
}
public MyTimerJob(string jobName, SPWebApplication webApplication)
: base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
{
this.Title = "My Timer Job";
}
public override void Execute(Guid contentDbId)
{
using (SPWeb oWeb = SPContext.Current.Site.OpenWeb("/"))
{
SPWeb mySite = SPContext.Current.Web;
mySite.AllowUnsafeUpdates = true;
SPListItemCollection listItems = mySite.Lists["AuditLogCalculatedData"].Items;
int itemCount = listItems.Count;
for (int k = 0; k < itemCount; k++)
{
try
{
listItems.Delete(k);
}
catch { }
}
SPListItem item = listItems.Add();
item["FileName"] = "roi";
item["NumOfEntries"] = 10102;
item.Update();
mySite.AllowUnsafeUpdates = false;
}
}
}
}
This is the sample code which can be executed on FeatureActivated event
public override void FeatureActivated (SPFeatureReceiverProperties props) {
SPWebApplication webApp = props.Feature.Parent as SPWebApplication;
if (webApp == null)
throw new SPException("Error obtaining reference to Web application.");
// Ensure the job is not already registered.
foreach (SPJobDefinition job in webApp.JobDefinitions)
if (job.Name == JOB_NAME) job.Delete();
// Install job.
SharePointWarmupJob warmupJob = new SharePointWarmupJob(webApplication);
// Schedule the job to run every minute all the time.
SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
schedule.Interval = 1;
warmupJob.Schedule = schedule;
// Save changes.
warmupJob.Update();
}
The solution
If you read down the article, there is a zipped solution file (TaskLogger_CustomTimerJob.zip) which you can use and compile yourself.
VS2008 will prompt you to convert project to 2008, just do it and compile.
Building the project
The problem you can't build lies within file BuildSharePointPackage.Targets. MakeCabPath is not valid for your environment. My makecab.exe lies in C:\Windows\system32 path. I tried to change path and rebuild, but it didn't work, it somehow tried to use the old location. So i just copied makecab.exe to C:\Program Files\Microsoft Cabinet SDK\bin and it builds sucessfully.
WSPBuilder
Also, you may want to use WSPBuilder to alleviate the pain on creating SharePoint solutions. It installs visual studio extension which you can use to make wsp file and deploy from visual studio. Download WSPBuilder here, and use Walkthrough of the Visual Studio Add-in