Tanmay
Tanmay

Reputation: 351

Can I import repository from VSTS to VSTS

I have been exploring the VSTS APIs and trying to copy a repository from one project to another. I get an error this remote has never connected. I tried this via the website too and I get the same error so I am guessing my code is correct.

I wanted to know if anyone has done this before or if someone would be kind enough to try this out on one of their VSTS instances. If you need the code sample let me know. It isn't much other than the one present here.

Update: Here is the code. (Boiled down to a console app)

Models.cs

public class ImportProjectRequest
{
    public Parameters parameters { get; set; }
}

public class Parameters
{
    public Gitsource gitSource { get; set; }
    public string serviceEndpointId { get; set; }
    public bool deleteServiceEndpointAfterImportIsDone { get; set; }
}

public class Gitsource
{
    public string url { get; set; }
}

public class ImportProjectCommand
{
    public Uri baseUri { get; set; }
    public string accessToken { get; set; }
    public string TeamProjectName { get; set; }
    public string CollectionName { get; set; }
    public string RepositoryId { get; set; }
    public ImportProjectRequest RequestObject { get; set; }
}

Program.cs

class Program
{
    static void Main(string[] args)
    {
        HttpClient client = new HttpClient();

        ImportProjectCommand command = new ImportProjectCommand()
        {
            baseUri = new Uri("https://instance-name.visualstudio.com"),
            accessToken = "<permanent-access-token>",
            CollectionName = "DefaultCollection",
            TeamProjectName = "Test Project 3",
            RepositoryId = "Test Project 3",
            RequestObject = new ImportProjectRequest()
            {
                parameters = new Parameters()
                {
                    gitSource = new Gitsource()
                    {
                        url = "https://instance-name.visualstudio.com/_git/Test%20Project"//Server URL from Extrenal Git configured in the serivces tab of Test Project 3
                    },
                    serviceEndpointId = "0f3c8fd4-38bb-4f0f-95fc-8942dd8f53a3", //Retrieved ID from https://instance-name.visualstudio.com/Test%20Project%203/_apis/distributedtask/serviceendpoints?api-version=3.0-preview.1
                    deleteServiceEndpointAfterImportIsDone = false

                }

            }

        };

        string version = "?api-version=3.0-preview";
        var parameters = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", string.Empty, command.accessToken)));
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", parameters);
        var url = string.Format("{0}{1}/{2}/_apis/git/repositories/{3}/importRequests",
            command.baseUri,
            string.IsNullOrEmpty(command.CollectionName) ? "DefaultCollection" : command.CollectionName,
            command.TeamProjectName,
            command.RepositoryId);
        HttpContent result;
        using (HttpResponseMessage response = client.PostAsJsonAsync(url + version, command.RequestObject).Result)
        {
            response.EnsureSuccessStatusCode();
            result = response.Content;
        }
    }
}

Update 2: Thanks to @starain i was able to resolve the error partially. The error was caused because there were spaces in my project and repository name. The code still doesn't work but I am now able to import repositories via the web portal.

I am now stuck at the error where VSTS gives me a message saying

Service Endpoint not accessible to user defd6044-4747-4926-9726-4d19fa5d2d26

Note : GUID above is the GUID of the service enpoint and not the user.

My authentication is correct because I succeeded in creating a new service endpoint via the REST API.

Upvotes: 1

Views: 1304

Answers (2)

Alkampfer
Alkampfer

Reputation: 1337

I can confirm that I was able to import a repository with the very same steps described by starain, the only difference is that I've created the endpoint with API and used PAT token to create endpoint instead of relying on alternate credentials (but this should not change anything)

Everything went good, and the only way to replicate your error

Service Endpoint not accessible to user defd6044-4747-4926-9726-4d19fa5d2d26

is to specify a wrong id of the endpoint (endpoint that does not exists) or use a wrong token in endpoint definition. This suggests me that there are problems with the endpoint you have created.

The simplest option is to create the endpoint with api with a POST call to https://xxxxx.VisualStudio.com/TEAMPROJECT_WITH_TARGET_GIT_REPO/_apis/distributedtask/serviceendpoints?api-version=3.0-preview.1

specifying the Source Repository with url,

{
  "name": "TestImport",
  "type": "git",
  "url": "https://yyyyyyyy.visualstudio.com/DefaultCollection/TargetGitProject/_git/ElasticSearchExamples",
  "authorization": {
    "scheme": "UsernamePassword",
    "parameters": {
      "username": PAT_TOKEN,
      "password": ""
    }
  }
}

This will create the endpoint and immediately gives you the ID

{
  "data": {},
  "id": "**df12f2e3-7c40-4885-8dbd-310f1781369a**",
  "name": "TestImport",
  "type": "git",

This should assure you that you use an id of a valid endpoint.

Upvotes: 1

starian chen-MSFT
starian chen-MSFT

Reputation: 33708

Based on my test, I succeed importing a repository from a VSTS to another VSTS. You can refer to these steps to import repository.

  1. Click your name=>Security=>Select Alternate authentication credentials=>Create an alternate authentication credentials
  2. Go to target VSTS, click services tab in team project admin page, then click New Service Endpoint=>External Git=>Type Connection Name, Server URL (a git repository in source VSTS), User name and Password (alternate account, step 1)
  3. Get a list of service endpoint through REST API (XXX) (e.g. https://[target VSTS name].visualstudio.com/[team project]/_apis/distributedtask/serviceendpoints?api-version=3.0-preview.1], after that you could get service endpoint id of that service endpoint (step 2)
  4. Create a request to import a repository, for example: Address(post request): https://[target vsts name].visualstudio.com/[team project]/_apis/git/repositories/[repository name]/importRequests?api-version=3.0-preview

Json:

{
  "parameters":
    {
      "gitSource":
        {
          "url": "[git repository address in source VSTS]"
        },
      "serviceEndpointId": "[service endpoint id, step 3]",
      "deleteServiceEndpointAfterImportIsDone": false
    }
  } 

Note: the repository name and team project name can't contain whitespace.

Upvotes: 4

Related Questions