Example #1
0
        public async Task <List <VSTSChange> > GetChangesetDetails(int changesetId)
        {
            TfvcChangeset changeset = null;

            TfvcHttpClient vsClient = Conn.GetClient <TfvcHttpClient>();

            changeset = await vsClient.GetChangesetAsync(changesetId, null, true, true, null, true, null, null, null, null, null);

            List <TfvcChange> tfvchanges = await vsClient.GetChangesetChangesAsync(changesetId);

            List <VSTSChange> changes = new List <VSTSChange>();

            foreach (var tfvchange in tfvchanges)
            {
                VSTSChange change = new VSTSChange()
                {
                    ChangeType = tfvchange.ChangeType.ToString(),
                    FilePath   = tfvchange.Item.Path
                };

                changes.Add(change);
            }

            return(changes);
        }
Example #2
0
        public Task <SourceRepository> FetchAllFiles(BuildConfig config)
        {
            return(Task.Run(async() =>
            {
                if (this.Conn != null)
                {
                    this.Client = Conn.GetClient <TfvcHttpClient>();
                    List <TfvcItem> files = await Client.GetItemsAsync(config.RootFolder, VersionControlRecursionType.Full);
                    SourceRepository repo = new SourceRepository();

                    repo.Files.AddRange(files.Where(x => x.DeletionId == 0).Select(x => new TFSWebFileItem(x, Conn, config, Client)));

                    repo.LatestVersion = files
                                         .Select(x => x.ChangesetVersion)
                                         .OrderByDescending(x => x)
                                         .FirstOrDefault()
                                         .ToString();
                    return repo;
                }

                SourceRepository result = new SourceRepository();
                result.LatestVersion = Server.GetLatestChangesetId().ToString();
                List <ISourceItem> list = result.Files;
                var items = Server.GetItems(config.RootFolder, VersionSpec.Latest, RecursionType.Full, DeletedState.Any, ItemType.Any);
                foreach (var item in items.Items)
                {
                    if (item.DeletionId == 0)
                    {
                        list.Add(new TFS2015FileItem(item, config));
                    }
                }
                return result;
            }));
        }
        public TfvcChangesetRef CreateChange()
        {
            VssConnection  connection = this.Context.Connection;
            TfvcHttpClient tfvcClient = connection.GetClient <TfvcHttpClient>();

            string   projectName             = ClientSampleHelpers.FindAnyProject(this.Context).Name;
            DateTime time                    = DateTime.UtcNow;
            string   destinationFilePath     = string.Format("$/{0}/example-file-{1}.txt", projectName, time.ToString("yyyy-MM-dd-HH-mm-ss-ff"));
            string   destinationFileContents = string.Format("File contents as of {0}", time);

            TfvcChangeset changeset = new TfvcChangeset()
            {
                Changes = new[]
                {
                    new TfvcChange()
                    {
                        ChangeType = VersionControlChangeType.Add,
                        Item       = new TfvcItem()
                        {
                            Path            = destinationFilePath,
                            ContentMetadata = new FileContentMetadata()
                            {
                                Encoding    = Encoding.UTF8.WindowsCodePage,
                                ContentType = "text/plain",
                            }
                        },
                        NewContent = new ItemContent()
                        {
                            Content     = destinationFileContents,
                            ContentType = ItemContentType.RawText,
                        },
                    },
                },
                Comment = "(sample) Adding a new changeset via API",
            };

            try
            {
                TfvcChangesetRef changesetRef = tfvcClient.CreateChangesetAsync(changeset).Result;
                Console.WriteLine("{0} by {1}: {2}", changesetRef.ChangesetId, changesetRef.Author.DisplayName, changesetRef.Comment ?? "<no comment>");
                return(changesetRef);
            }
            catch (AggregateException e)
            {
                Console.WriteLine("Something went wrong, could not create TFVC changeset.");
                if (e.InnerException.Message.Contains(projectName))
                {
                    Console.WriteLine("This may mean project \"{0}\" isn't configured for TFVC.", projectName);
                    Console.WriteLine("Add a TFVC repo to the project, then try this sample again.");
                }
                else
                {
                    Console.WriteLine(e.InnerException.Message);
                }
            }

            return(null);
        }
Example #4
0
 static void InitClients(VssConnection Connection)
 {
     WitClient            = Connection.GetClient <WorkItemTrackingHttpClient>();
     BuildClient          = Connection.GetClient <BuildHttpClient>();
     ProjectClient        = Connection.GetClient <ProjectHttpClient>();
     GitClient            = Connection.GetClient <GitHttpClient>();
     TfvsClient           = Connection.GetClient <TfvcHttpClient>();
     TestManagementClient = Connection.GetClient <TestManagementHttpClient>();
 }
        public static async Task <List <TfvcItem> > GetFoldersAsync(this TfvcHttpClient source, string projectName, string basePath, bool recursive, CancellationToken cancellationToken)
        {
            Logger.Debug($"Getting folders for '{basePath}', Recursion = {recursive}...");

            var level = recursive ? VersionControlRecursionType.Full : VersionControlRecursionType.None;
            var items = await source.GetItemsAsync(projectName, scopePath : basePath, recursionLevel : level, includeLinks : false, cancellationToken : cancellationToken).ConfigureAwait(false) ?? new List <TfvcItem>();

            return(items.Where(i => i.IsFolder).ToList());
        }
Example #6
0
        public TfsRepository(TfsSettings tfsSettings)
        {
            if (tfsSettings == null)
            {
                throw new ArgumentNullException(nameof(tfsSettings));
            }

            _versionControlClient = new TfvcHttpClient(new Uri(tfsSettings.CollectionUri), new VssCredentials());
        }
        private async Task DownloadFolderAsync(TfvcHttpClient client, string remotePath, string localPath, CancellationToken cancellationToken)
        {
            Logger.Info($"Downloading files from '{remotePath}' to '{localPath}'");

            await client.GetAllAsync(remotePath, localPath, cancellationToken).ConfigureAwait(false);

            //Read only files cause us problems so clear the flag now
            await FileSystem.ClearReadOnlyAttributeAsync(localPath, true, cancellationToken).ConfigureAwait(false);
        }
Example #8
0
        public TfsRepository(Uri tfsUri, string userName, string password)
        {
            if (string.IsNullOrWhiteSpace(userName))
            {
                throw new ArgumentOutOfRangeException(nameof(userName));
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentOutOfRangeException(nameof(password));
            }

            _versionControlClient = new TfvcHttpClient(tfsUri, new VssCredentials(new VssBasicCredential(userName, password)));
        }
Example #9
0
        static void Main(string[] args)
        {
            var url = new Uri("https://jacanotest123.visualstudio.com");

            var connection = new VssConnection(url, new VssClientCredentials());

            //var connection = new VssConnection(url, new VssBasicCredential("pat", "t77dabkbus5eu77bnvya6k4garoy3kxgyqn4jogktlmqslththea"));

            connection.ConnectAsync().SyncResult();

            TfvcHttpClient tfvcClient = connection.GetClient <TfvcHttpClient>();

            IEnumerable <TfvcBranch> branches = tfvcClient.GetBranchesAsync(includeParent: true, includeChildren: true).Result;
        }
        public IEnumerable <TfvcChangesetRef> ListChangesets()
        {
            VssConnection  connection = this.Context.Connection;
            TfvcHttpClient tfvcClient = connection.GetClient <TfvcHttpClient>();

            IEnumerable <TfvcChangesetRef> changesets = tfvcClient.GetChangesetsAsync(top: 10).Result;

            foreach (TfvcChangesetRef changeset in changesets)
            {
                Console.WriteLine("{0} by {1}: {2}", changeset.ChangesetId, changeset.Author.DisplayName, changeset.Comment ?? "<no comment>");
            }

            return(changesets);
        }
Example #11
0
        static public void GetChangesetWorkItemFromLabel(string tfsCollectionUrl, string personalAccessToken)
        {
            Console.WriteLine("Loading Labels Items and associated work items ... ");

            VssBasicCredential credentials = new VssBasicCredential(string.Empty, personalAccessToken);

            using (TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(tfsCollectionUrl), credentials))
            {
                // Can retrieve SOAP service from TfsTeamProjectCollection instance
                //VersionControlServer vcServer = tpc.GetService<VersionControlServer>();
                //ItemSet itemSet = vcServer.GetItems("$/", RecursionType.OneLevel);
                //foreach (Item item in itemSet.Items)
                //{
                //    Console.WriteLine(item.ServerItem);
                //}

                // Can retrieve REST client from same TfsTeamProjectCollection instance
                TfvcHttpClient tfvcClient = tpc.GetClient <TfvcHttpClient>();
                //List<TfvcItem> tfvcItems = tfvcClient.GetItemsAsync("$/", VersionControlRecursionType.OneLevel).Result;
                //foreach (TfvcItem item in tfvcItems)
                //{
                //    Console.WriteLine(item.Path);
                //}

                TfvcLabelRequestData tfvcLabelRequestData = new TfvcLabelRequestData();

                List <TfvcLabelRef> labelRefs = tfvcClient.GetLabelsAsync(tfvcLabelRequestData).Result;

                foreach (TfvcLabelRef item in labelRefs)
                {
                    Console.WriteLine("Label Id: " + item.Id + "\tName: " + item.Name + "\t Modified:" + item.ModifiedDate);
                    TfvcLabel       tfvcLabel  = tfvcClient.GetLabelAsync(item.Id.ToString(), tfvcLabelRequestData).Result;
                    List <TfvcItem> labelItems = tfvcClient.GetLabelItemsAsync(item.Id.ToString()).Result;
                    foreach (TfvcItem vcItem in labelItems)
                    {
                        Console.WriteLine("\tItem:" + vcItem.Path + "\t ChangesetVersion: " + vcItem.ChangesetVersion);

                        List <AssociatedWorkItem> changesetWorkItems = tfvcClient.GetChangesetWorkItemsAsync(vcItem.ChangesetVersion).Result;
                        foreach (AssociatedWorkItem assItem in changesetWorkItems)
                        {
                            Console.WriteLine("\t\t Associated WorkItem Id: " + assItem.Id + "\t Title: " + assItem.Title);
                        }
                    }
                }
            }

            Console.ReadLine();
        }
        public IEnumerable <TfvcBranch> ListBranches()
        {
            VssConnection  connection = this.Context.Connection;
            TfvcHttpClient tfvcClient = connection.GetClient <TfvcHttpClient>();

            IEnumerable <TfvcBranch> branches = tfvcClient.GetBranchesAsync(includeParent: true, includeChildren: true).Result;

            foreach (TfvcBranch branch in branches)
            {
                Console.WriteLine("{0} ({2}): {1}", branch.Path, branch.Description ?? "<no description>", branch.Owner.DisplayName);
            }

            if (branches.Count() == 0)
            {
                Console.WriteLine("No branches found.");
            }

            return(branches);
        }
        public IEnumerable <TfvcChange> GetChangesetChanges()
        {
            VssConnection  connection = this.Context.Connection;
            TfvcHttpClient tfvcClient = connection.GetClient <TfvcHttpClient>();

            TfvcChangesetRef latestChangeset;

            using (new ClientSampleHttpLoggerOutputSuppression())
            {
                latestChangeset = tfvcClient.GetChangesetsAsync(top: 1).Result.First();
            }

            IEnumerable <TfvcChange> changes = tfvcClient.GetChangesetChangesAsync(id: latestChangeset.ChangesetId).Result;

            foreach (TfvcChange change in changes)
            {
                Console.WriteLine("{0}: {1}", change.ChangeType, change.Item.Path);
            }

            return(changes);
        }
Example #14
0
        public async Task <List <VSTSChangeset> > GetLastestChangesetAsync(int skip, int top)
        {
            List <VSTSChangeset> Changesets = new List <VSTSChangeset>();

            TfvcHttpClient          vsClient      = Conn.GetClient <TfvcHttpClient>();
            List <TfvcChangesetRef> ChangesetRefs = await vsClient.GetChangesetsAsync(UserSetting.TFSProjectName, null, true, true, null, true, skip, top);

            //TfvcChangeset Changeset = await vsClient.GetChangesetAsync(ChangesetRefs[0].ChangesetId, null, true, true, null, true);

            foreach (TfvcChangesetRef changesetRef in ChangesetRefs)
            {
                List <AssociatedWorkItem> workItems = await vsClient.GetChangesetWorkItemsAsync(changesetRef.ChangesetId);

                string WorkItemDisplayValue = "";

                foreach (var workitem in workItems)
                {
                    WorkItemDisplayValue += workitem.Id + " - " + workitem.Title + "\n";
                }

                if (WorkItemDisplayValue.Length > 2)
                {
                    WorkItemDisplayValue = WorkItemDisplayValue.Substring(0, WorkItemDisplayValue.Length - 2);
                }

                Changesets.Add(new VSTSChangeset()
                {
                    ChangesetId = changesetRef.ChangesetId,
                    Author      = changesetRef.Author.DisplayName,
                    CheckedInBy = changesetRef.CheckedInBy.DisplayName,
                    Comment     = changesetRef.Comment,
                    CreatedDate = changesetRef.CreatedDate,
                    Url         = changesetRef.Url,
                    WorkItem    = WorkItemDisplayValue,
                    Workitems   = workItems
                });
            }

            return(Changesets);
        }
Example #15
0
        public TfvcItem DownloadItem()
        {
            VssConnection  connection = this.Context.Connection;
            TfvcHttpClient tfvcClient = connection.GetClient <TfvcHttpClient>();

            // get the items in the root of the project
            string          projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;
            string          scopePath   = $"$/{projectName}/";
            List <TfvcItem> items       = tfvcClient.GetItemsAsync(scopePath: scopePath, recursionLevel: VersionControlRecursionType.OneLevel).Result;

            foreach (TfvcItem item in items)
            {
                if (!item.IsFolder)
                {
                    Console.WriteLine("You can download file contents for {0} at {1}", item.Path, item.Url);
                    return(item);
                }
            }

            Console.WriteLine("No files found in the root.");
            return(null);
        }
Example #16
0
        public IEnumerable <TfvcItem> ListItems()
        {
            VssConnection  connection = this.Context.Connection;
            TfvcHttpClient tfvcClient = connection.GetClient <TfvcHttpClient>();

            // get just the items in the root of the project
            string          projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;
            string          scopePath   = $"$/{projectName}/";
            List <TfvcItem> items       = tfvcClient.GetItemsAsync(scopePath: scopePath, recursionLevel: VersionControlRecursionType.OneLevel).Result;

            foreach (TfvcItem item in items)
            {
                Console.WriteLine("{0}    {1}   #{3}   {2}", item.ChangeDate, item.IsFolder ? "<DIR>" : "     ", item.Path, item.ChangesetVersion);
            }

            if (items.Count() == 0)
            {
                Console.WriteLine("No items found.");
            }

            return(items);
        }
        public static async Task <TfvcItem> FindItemAsync(this TfvcHttpClient source, string itemPath, bool throwIfNotFound, CancellationToken cancellationToken)
        {
            TfvcItem item = null;

            try
            {
                item = await source.TryCatchAsync(c => c.GetItemAsync(itemPath, cancellationToken: cancellationToken)).ConfigureAwait(false);
            } catch (VssServiceException e)
            {
                if (!e.IsWarning())
                {
                    throw e;
                }

                /* Ignore because we cannot get the message code from an "item not found" error */
            };

            if (item == null && throwIfNotFound)
            {
                throw new Exception("Item not found.");
            }

            return(item);
        }
        public static async Task GetAllAsync(this TfvcHttpClient source, string itemPath, string targetPath, CancellationToken cancellationToken)
        {
            Logger.Debug($"Downloading '{itemPath}'");

            var request = new TfvcItemRequestData()
            {
                ItemDescriptors = new[]
                {
                    new TfvcItemDescriptor()
                    {
                        Path = itemPath, RecursionLevel = VersionControlRecursionType.Full
                    }
                }
            };

            //Download the items
            using (var stream = await source.GetItemsBatchZipAsync(request))
            {
                Logger.Debug($"Extracting '{itemPath}' to '{targetPath}'");
                var fileCount = await ExtractZipAsync(stream, targetPath, itemPath, cancellationToken).ConfigureAwait(false);

                Logger.Debug($"Extracted {fileCount} files to '{targetPath}'");
            };
        }
Example #19
0
        private static async Task DownloadAsync(string tfsUrl, string destinationFolder, string scope, Func <TfvcItem, bool> filter)
        {
            int maxConcurrency = 8;

            ServicePointManager.DefaultConnectionLimit = maxConcurrency;
            var baseUrl = new Uri(tfsUrl);
            VssClientCredentials vssClientCredentials = new VssClientCredentials();

            vssClientCredentials.Storage = new VssClientCredentialStorage();

            var vssHttpRequestSettings = new VssHttpRequestSettings();

            vssHttpRequestSettings.SendTimeout = TimeSpan.FromMilliseconds(-1);
            var client = new TfvcHttpClient(baseUrl, vssClientCredentials, vssHttpRequestSettings);

            try
            {
                var items = await client.GetItemsAsync(scopePath : scope, recursionLevel : VersionControlRecursionType.Full, includeLinks : false).ConfigureAwait(false);

                var files = items.Where(filter).OrderBy(_ => _.Path).ToList();

                var transformBlock = new TransformBlock <TfvcItem, TfvcItem>(async item =>
                {
                    if (item.IsFolder)
                    {
                        var fullPath = GetFullPath(destinationFolder, item.Path);
                        if (!Directory.Exists(fullPath))
                        {
                            Directory.CreateDirectory(fullPath);
                        }
                    }
                    else
                    {
                        var fullPath   = GetFullPath(destinationFolder, item.Path);
                        var folderPath = Path.GetDirectoryName(fullPath);
                        if (folderPath != null && !Directory.Exists(folderPath))
                        {
                            Directory.CreateDirectory(folderPath);
                        }

                        using (var stream = await client.GetItemContentAsync(item.Path))
                            using (var fs = File.Create(fullPath))
                            {
                                await stream.CopyToAsync(fs).ConfigureAwait(false);
                            }
                    }

                    return(item);
                }, new ExecutionDataflowBlockOptions {
                    MaxDegreeOfParallelism = maxConcurrency
                });

                var writePathBlock = new ActionBlock <TfvcItem>(c =>
                {
                    var index = files.IndexOf(c);
                    Console.WriteLine($"{index}/{files.Count}: {c.Path}");
                });
                transformBlock.LinkTo(writePathBlock, new DataflowLinkOptions {
                    PropagateCompletion = true
                });

                foreach (var item in files)
                {
                    transformBlock.Post(item);
                }

                transformBlock.Complete();
                await transformBlock.Completion.ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #20
0
        static void Main(string[] args)
        {
            OptionSet option_set = new OptionSet()
                                   .Add("?|help|h", "Prints out the options.", option => { help = option != null; })
                                   .Add("su|source-url=", "Set the source VSTS account URL (https://[sourcerepo].visualstudio.com)", option => sourceUrl = option)
                                   .Add("sp|source-project=", "Set the source VSTS project", option => sourceProject = option)
                                   .Add("sr|source-repository=", "Set the source VSTS repository path. (ex: $/SourceRepo)", option => sourceRepo = option)
                                   .Add("du|destination-url=", "Set the destination VSTS account URL (https://[destrepo].visualstudio.com)", option => destinationUrl = option)
                                   .Add("dp|destination-project=", "Set the destination VSTS project", option => destinationProject = option)
                                   .Add("dr|destination-repository=", "Set the destination VSTS repository path. (ex: $/DestinationRepo)", option => destinationRepo = option);

            try
            {
                option_set.Parse(args);
            }
            catch (Exception ex)
            {
                LogGenericException(ex, "Error on commandline parse");
            }
            if (help)
            {
                ShowHelp(usage, option_set);
            }

            if (string.IsNullOrEmpty(sourceUrl))
            {
                Console.Write("Enter the source account url (https://<<account>>.visualstudio.com/): ");
                sourceUrl = Console.ReadLine();
            }
            if (string.IsNullOrEmpty(sourceProject))
            {
                Console.Write("Enter the source project: ");
                sourceProject = Console.ReadLine();
            }
            if (string.IsNullOrEmpty(sourceRepo))
            {
                Console.Write("Enter the source repository ($/MYSOURCEREPO): ");
                sourceRepo = Console.ReadLine();
            }

            if (string.IsNullOrEmpty(destinationUrl))
            {
                Console.Write("Enter the destination account url (https://<<account>>.visualstudio.com/): ");
                destinationUrl = Console.ReadLine();
            }
            if (string.IsNullOrEmpty(destinationProject))
            {
                Console.Write("Enter the destination project: ");
                destinationProject = Console.ReadLine();
            }
            if (string.IsNullOrEmpty(destinationRepo))
            {
                Console.Write("Enter the source repository ($/MYDESTREPO): ");
                destinationRepo = Console.ReadLine();
            }

            string sourceAccount      = $"{sourceUrl}DefaultCollection";
            string destinationAccount = $"{destinationUrl}DefaultCollection";

            // Interactively ask the user for credentials

            VssCredentials sourceCredentials = new VssClientCredentials();

            sourceCredentials.Storage = new VssClientCredentialStorage();

            VssCredentials destinationCredentials = new VssClientCredentials();

            destinationCredentials.Storage = new VssClientCredentialStorage();

            BuildHttpClient     sourceBuildClient          = null;
            BuildHttpClient     destinationBuildClient     = null;
            ProjectHttpClient   destinationProjectClient   = null;
            TaskAgentHttpClient destinationTaskAgentClient = null;
            TfvcHttpClient      destinationTfvcClient      = null;

            try
            {
                Console.WriteLine($"Creating VSTS connections and clients.");
                Console.WriteLine();
                // Connect to VSTS Source and Destination
                VssConnection sourceConnection = new VssConnection(new Uri(sourceAccount), sourceCredentials);
                Console.WriteLine($"Authorized acccount {sourceUrl} as {sourceConnection.AuthorizedIdentity.DisplayName} <{sourceConnection.AuthorizedIdentity.Descriptor.Identifier}>");
                VssConnection destinationConnection = new VssConnection(new Uri(destinationAccount), destinationCredentials);
                Console.WriteLine($"Authorized acccount {destinationUrl} as {destinationConnection.AuthorizedIdentity.DisplayName} <{sourceConnection.AuthorizedIdentity.Descriptor.Identifier}>");
                Console.WriteLine();
                // Get a number of HttpClients to read and write data
                Console.WriteLine("Creating source build client.");
                sourceBuildClient = sourceConnection.GetClient <BuildHttpClient>();
                Console.WriteLine("Creating destination build client.");
                destinationBuildClient = destinationConnection.GetClient <BuildHttpClient>();
                Console.WriteLine("Creating destination project client.");
                destinationProjectClient = destinationConnection.GetClient <ProjectHttpClient>();
                Console.WriteLine("Creating destination task agent client.");
                destinationTaskAgentClient = destinationConnection.GetClient <TaskAgentHttpClient>();
                Console.WriteLine("Creating destination TFVC client.");
                destinationTfvcClient = destinationConnection.GetClient <TfvcHttpClient>();
                Console.WriteLine();
            }
            catch (AggregateException ex)
            {
                string message = "Error creating connections.";
                LogAggregateException(ex, message);
            }
            catch (Exception ex)
            {
                string message = "Error creating connections.";
                LogGenericException(ex, message);
            }

            List <BuildDefinition> sourceBuildDefs              = null;
            TeamProject            destinationProjectObject     = null;
            Dictionary <string, TaskAgentQueue> agentDictionary = null;

            try
            {
                sourceBuildDefs = sourceBuildClient.GetFullDefinitionsAsync(project: sourceProject).Result;
            }
            catch (AggregateException ex)
            {
                string message = "Error retreiving objects from source.";
                LogAggregateException(ex, message);
            }
            catch (Exception ex)
            {
                string message = "Error retreiving objects from source.";
                LogGenericException(ex, message);
            }

            try
            {
                destinationProjectObject = destinationProjectClient.GetProject(destinationProject).Result;
                var projectAgentQueues = destinationTaskAgentClient.GetAgentQueuesAsync(project: destinationProject).Result;
                agentDictionary = projectAgentQueues.ToDictionary(k => k.Name);
            }
            catch (AggregateException ex)
            {
                string message = "Error retreiving objects from destination.";
                LogAggregateException(ex, message);
            }
            catch (Exception ex)
            {
                string message = "Error retreiving objects from destination.";
                LogGenericException(ex, message);
            }

            foreach (var item in sourceBuildDefs)
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    item.Name = item.Name + DateTime.Now.ToUnixEpochTime();
                }

                item.Project    = destinationProjectObject;
                item.AuthoredBy = null; // Remove any author to avoid errors in transfer

                FixTriggerRepositories(item);
                UpdateAgentPool(agentDictionary, item);
                ConvertRepositoryPath(item);

                try
                {
                    Console.WriteLine($"Adding build definition: {item.Name}");
                    var itemOut = destinationBuildClient.CreateDefinitionAsync(item).Result;
                }
                catch (AggregateException ex)
                {
                    LogAggregateException(ex, $"Error creating build {item.Name} on {destinationAccount}");
                }
                catch (Exception ex)
                {
                    LogGenericException(ex, $"Error creating build {item.Name} on {destinationAccount}");
                }
            }
            if (hasErrors)
            {
                ExitWithErrors();
            }
            ExitSuccess();
        }
Example #21
0
            public TFSWebFileItem(TfvcItem x, VssConnection conn, BuildConfig config, TfvcHttpClient client)
            {
                this.Client = client;
                this.x      = x;
                this.conn   = conn;
                string path = x.Path;

                path        = path.Substring(config.RootFolder.Length);
                Name        = System.IO.Path.GetFileName(path);
                Folder      = path;
                IsDirectory = x.IsFolder;
                if (!x.IsFolder)
                {
                    Folder = Folder.Substring(0, Folder.Length - Name.Length);
                }
                Url          = x.Url;
                this.Version = x.ChangesetVersion.ToString();
                this.Url     = config.RootFolder + "/" + Folder + Name;
            }
        public TfvcChangesetRef EditExistingFile()
        {
            VssConnection  connection = this.Context.Connection;
            TfvcHttpClient tfvcClient = connection.GetClient <TfvcHttpClient>();

            // first, create a file we know is safe to edit
            string   projectName          = ClientSampleHelpers.FindAnyProject(this.Context).Name;
            DateTime time                 = DateTime.UtcNow;
            string   destinationFilePath  = string.Format("$/{0}/file-to-edit-{1}.txt", projectName, time.ToString("yyyy-MM-dd-HH-mm-ss-ff"));
            string   originalFileContents = string.Format("Initial contents as of {0}", time);

            TfvcChangeset createFile = new TfvcChangeset()
            {
                Changes = new[]
                {
                    new TfvcChange()
                    {
                        ChangeType = VersionControlChangeType.Add,
                        Item       = new TfvcItem()
                        {
                            Path            = destinationFilePath,
                            ContentMetadata = new FileContentMetadata()
                            {
                                Encoding    = Encoding.UTF8.WindowsCodePage,
                                ContentType = "text/plain",
                            }
                        },
                        NewContent = new ItemContent()
                        {
                            Content     = originalFileContents,
                            ContentType = ItemContentType.RawText,
                        },
                    },
                },
                Comment = "(sample) Adding a file which we'll later edit",
            };

            TfvcChangesetRef createFileRef;

            try
            {
                createFileRef = tfvcClient.CreateChangesetAsync(createFile).Result;
                Console.WriteLine("{0} by {1}: {2}", createFileRef.ChangesetId, createFileRef.Author.DisplayName, createFileRef.Comment ?? "<no comment>");
            }
            catch (AggregateException e)
            {
                Console.WriteLine("Something went wrong, could not create TFVC changeset.");
                if (e.InnerException.Message.Contains(projectName))
                {
                    Console.WriteLine("This may mean project \"{0}\" isn't configured for TFVC.", projectName);
                    Console.WriteLine("Add a TFVC repo to the project, then try this sample again.");
                }
                else
                {
                    Console.WriteLine(e.InnerException.Message);
                }
                return(null);
            }

            // now edit the file contents
            string        editedFileContents = originalFileContents + "\nEdited contents";
            TfvcChangeset changeset          = new TfvcChangeset()
            {
                Changes = new[]
                {
                    new TfvcChange()
                    {
                        ChangeType = VersionControlChangeType.Edit,
                        Item       = new TfvcItem()
                        {
                            Path            = destinationFilePath,
                            ContentMetadata = new FileContentMetadata()
                            {
                                Encoding    = Encoding.UTF8.WindowsCodePage,
                                ContentType = "text/plain",
                            },
                            // must tell the API what version we want to change
                            ChangesetVersion = createFileRef.ChangesetId,
                        },
                        NewContent = new ItemContent()
                        {
                            Content     = editedFileContents,
                            ContentType = ItemContentType.RawText,
                        },
                    },
                },
                Comment = "(sample) Editing the file via API",
            };

            try
            {
                TfvcChangesetRef changesetRef = tfvcClient.CreateChangesetAsync(changeset).Result;
                Console.WriteLine("{0} by {1}: {2}", changesetRef.ChangesetId, changesetRef.Author.DisplayName, changesetRef.Comment ?? "<no comment>");
                return(changesetRef);
            }
            catch (AggregateException e)
            {
                Console.WriteLine("Something went wrong, could not create TFVC changeset.");
                if (e.InnerException.Message.Contains(projectName))
                {
                    Console.WriteLine("This may mean project \"{0}\" isn't configured for TFVC.", projectName);
                    Console.WriteLine("Add a TFVC repo to the project, then try this sample again.");
                }
                else
                {
                    Console.WriteLine(e.InnerException.Message);
                }
            }

            return(null);
        }
        public static async Task <(string itemPath, Version version)> FindLatestVersionAsync(this TfvcHttpClient source, string itemPath, CancellationToken cancellationToken)
        {
            //Find the releases branch
            var releasesBranch = await source.FindItemAsync(itemPath, false, cancellationToken).ConfigureAwait(false);

            if (releasesBranch == null)
            {
                return(null, null);
            }

            //Enumerate the child folders ordered by "version"
            var projectName = ItemPath.GetProject(itemPath);
            var children    = await source.GetFoldersAsync(projectName, releasesBranch.Path, false, cancellationToken).ConfigureAwait(false);

            return((from c in children
                    let v = TryParseVersion(c.GetName())
                            where v != null
                            orderby v descending
                            select(c.Path, v)).FirstOrDefault());
        }