LeonardoX LeonardoX - 10 months ago 113
C# Question

export/import build definition from/to JSon file (TFS 2013)

I'm trying to export and import build definitions from tfs2013, following this link and this, but none of them are working for me. I know there are some plugins for tfs which do this, but I can't use any of them due to company policies restrictions.

GetDefinitionAsync and GetFullDefinitionsAsync methods are fine, but they don't retrieve ProcessParameters property, so I can't export a full build definition which includes this important information. I've tried to get this property calling IBuildServer.QueryBuildDefinitions, but when I try to create new build definition I can't because the data type is Microsoft.TeamFoundation.Build.Client.IBuildDefinition and I can't create new instance of Microsoft.TeamFoundation.Build.Client.BuildDefinition due to it's a sealed class. how can I copy ProcessParameters and the other info to import the full build definition?

Thanks

Answer Source

Ok, finally after a deep research I found the way to export/import

Export to JSon:

    public static void ExportBuildDef(Microsoft.TeamFoundation.Build.Client.IBuildDefinition buildDefinition, string project, string filePath)
    {
        Console.WriteLine($"Exporting build definition '{buildDefinition.Name}' from '{project}' project.");

        var json = JsonConvert.SerializeObject(
            buildDefinition, 
            Newtonsoft.Json.Formatting.Indented, 
            new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

        json = removePasswords(json);

        File.WriteAllText(filePath, json);
        Console.WriteLine($"Build definition '{buildDefinition.Name}' succesfully exported to '{filePath}'.");
    }

    private static string removePasswords(string json)
    {
        string res = json;

        var searchFor = "\"Password\":";
        var startIndex = json.IndexOf(searchFor);
        if (startIndex >= 0)
        {
            var endIndex = json.IndexOf(",", startIndex);
            var pwd = json.Substring(startIndex, endIndex - startIndex);
            if (pwd.IndexOf(":") > 0)
            {
                pwd = json.Substring(startIndex, endIndex - startIndex).Split(':')[1].Trim();
                res = json.Replace(pwd, "\"{hidden}\"");
            }

        }

        return res;
    }

Import from JSon

Note: BuildDefinitionModel class is a set of "POCO" classes (not included long file) which can be obtained converting to C# classes from the exported JSon file from here

public static void ImportBuildDefinition(IBuildServer buildServer, string projectName, string filePath, string newBuildName, string sourceProvider)
    {
        if (!File.Exists(filePath))
            throw new FileNotFoundException("File does not exist!", filePath);

        Console.WriteLine($"Importing build definition from file '{filePath}' to '{projectName}' project.");
        var json = File.ReadAllText(filePath);
        var buildDef = JsonConvert.DeserializeObject<BuildDefinitionModel>(json);

        var newBuildDefinition = CloneBuildDefinition(buildServer, buildDef, newBuildName, projectName, sourceProvider);

        Console.WriteLine($"Build definition '{buildDef.Name}' succesfully imported to '{projectName}' project.");
    }

    static IBuildDefinition CloneBuildDefinition(IBuildServer buildServer, BuildDefinitionModel buildDefinitionSource, string newBuildName, string projectName, string sourceProvider)
    {
        var buildDefinitionClone = buildServer.CreateBuildDefinition(projectName);

        buildDefinitionClone.BuildController = GetBuildController(buildServer, "");
        buildDefinitionClone.Process = buildServer.QueryProcessTemplates(buildDefinitionSource.TeamProject).FirstOrDefault(c=> c.Id == buildDefinitionSource.Process.Id);
        buildDefinitionClone.ProcessParameters = buildDefinitionSource.ProcessParameters;
        buildDefinitionClone.TriggerType = buildDefinitionSource.TriggerType;
        buildDefinitionClone.ContinuousIntegrationQuietPeriod = buildDefinitionSource.ContinuousIntegrationQuietPeriod;
        buildDefinitionClone.DefaultDropLocation = buildDefinitionSource.DefaultDropLocation;
        buildDefinitionClone.Description = buildDefinitionSource.Description;
        buildDefinitionClone.QueueStatus = Microsoft.TeamFoundation.Build.Client.DefinitionQueueStatus.Enabled;
        buildDefinitionClone.BatchSize = buildDefinitionSource.BatchSize;
        buildDefinitionClone.Name = newBuildName;

        foreach (var schedule in buildDefinitionSource.Schedules)
        {
            var newSchedule = buildDefinitionClone.AddSchedule();
            newSchedule.DaysToBuild = schedule.DaysToBuild;
            newSchedule.StartTime = schedule.StartTime;
            newSchedule.TimeZone = schedule.TimeZone;
        }

        foreach (var mapping in buildDefinitionSource.Workspace.Mappings)
        {
            buildDefinitionClone.Workspace.AddMapping(
                mapping.ServerItem, mapping.LocalItem, mapping.MappingType, mapping.Depth);
        }

        buildDefinitionClone.RetentionPolicyList.Clear();

        foreach (var policy in buildDefinitionSource.RetentionPolicyList)
        {
            buildDefinitionClone.AddRetentionPolicy(
                policy.BuildReason, policy.BuildStatus, policy.NumberToKeep, policy.DeleteOptions);
        }

        //Source Provider
        IBuildDefinitionSourceProvider provider = buildDefinitionClone.CreateInitialSourceProvider(sourceProvider);
        if (sourceProvider == VersionControlType.TFGIT.ToString())
        {
            provider.Fields["RepositoryName"] = "Git";
        }
        buildDefinitionClone.SetSourceProvider(provider);


        buildDefinitionClone.Save();
        return buildDefinitionClone;
    }

    private static IBuildController GetBuildController(IBuildServer buildServer, string buildController)
    {
        if (string.IsNullOrEmpty(buildController))
            return buildServer.QueryBuildControllers(false).Where(c=> c.Status == ControllerStatus.Available).First();

        return buildServer.GetBuildController(buildController);
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download