Search code examples
c#gittfstfvctfs-sdk

How do I create a Git Repository within a TeamProject in Tfs?


I'm trying to move a TfsServer from an old TFVC based Server (2013), to a newer version (2018). I got most of it figured out but I just can't manage to create a lot of repositories programmatically.

I've been trying to use Microsoft.TeamFoundation.ExtendedClient to create the repositories in a specific TeamProject, based on a list of names. I've managed to query all the repositories that already exist:

public void CreateTeamProjectRepositories(IEnumerable<string> input)
{
      using (var newCollection = new TfsTeamProjectCollection(new Uri(_newUrl)))
      {
           var service = newCollection.GetService<GitRepositoryService>();
      }
}

Sadly the documentation is fairly thin on this, in fact the only kind of official documentation I was able to find is this:

https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2013/dn231953(v%3Dvs.120)

I can't even find that class in the Extended Client, the only class I Can find is GitRepositoryService that I used above but there seems to be no documentation whatsoever for that class.

I found some unofficial stuff online describing how to create TeamProjects, but nothing on Repos within a TeamProject (remote url like www.url.com:8080/tfs/TeamProjectCollection/TeamProject/_git/RepoName).

Anyone got some experience with this?


Solution

  • I don't think you can create a Git repository with the old TFS classes but you can do it with the new TFS .Net libraries (available in NuGet):

    VssConnection connection = new VssConnection(new Uri("http://tfs-server:8080/tfs/{collection}"), new VssCredentials());
    GitHttpClient gitClient = connection.GetClient<GitHttpClient>();
    GitRepository newRepo = new GitRepository() { Name = "newRepo" };
    await gitClient.CreateRepositoryAsync(newRepo, "teamProjectName");
    

    The above code work on TFS 2018, if you want to create the repositories in TFS 2013 I'm not sure the code will work, so you can use HttpClient to execute the Rest API and create the repo:

    var tfsUrl = "http://tfstest01:8080/tfs/{collection}";
    var tfsUri = new Uri(tfsInstance + "/{teamProjectGUID}/_apis/git/repositories/?api-version=1.0");
    using (HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
    {
         var data = new { name = "newRepo" };
         var json = JsonConvert.SerializeObject(data);
         var content = new StringContent(json, Encoding.UTF8, "application/json");
         HttpResponseMessage response = null;
         response = client.PostAsync(tfsUri, content).Result;
    }