public IEnumerable <ReleaseApproval> ListPendingApprovalsForASpecificUser() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; string assignedToFilter = ClientSampleHelpers.GetCurrentUserDisplayName(this.Context); // Get a release client instance VssConnection connection = Context.Connection; ReleaseHttpClient2 releaseClient = connection.GetClient <ReleaseHttpClient2>(); List <ReleaseApproval> releaseApprovals = new List <ReleaseApproval>(); // Iterate (as needed) to get the full set of approvals int continuationToken = 0; bool parseResult; do { IPagedCollection <ReleaseApproval> releaseApprovalsPage = releaseClient.GetApprovalsAsync2(project: projectName, assignedToFilter: assignedToFilter, continuationToken: continuationToken).Result; releaseApprovals.AddRange(releaseApprovalsPage); int parsedContinuationToken = 0; parseResult = int.TryParse(releaseApprovalsPage.ContinuationToken, out parsedContinuationToken); if (parseResult) { continuationToken = parsedContinuationToken; } } while ((continuationToken != 0) && parseResult); // Show the approvals foreach (ReleaseApproval releaseApproval in releaseApprovals) { Console.WriteLine("{0} {1}", releaseApproval.Id.ToString().PadLeft(6), releaseApproval.Status); } return(releaseApprovals); }
public TestSuite UpdateTestSuiteProperties() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; // Get a testplan client instance VssConnection connection = Context.Connection; TestPlanHttpClient testPlanClient = connection.GetClient <TestPlanHttpClient>(); TestSuiteUpdateParams testSuiteUpdateParams = new TestSuiteUpdateParams() { DefaultTesters = new List <IdentityRef>() { new IdentityRef() { Id = "9b6bee0e-28b2-42b6-ab5b-5122b63d473c" } } }; TestSuite updtaetdTestSuite = testPlanClient.UpdateTestSuiteAsync(testSuiteUpdateParams, projectName, 79, 83).Result; Console.WriteLine("{0} {1}", updtaetdTestSuite.Id.ToString().PadLeft(6), updtaetdTestSuite.Name); return(updtaetdTestSuite); }
public ReleaseEnvironment StartDeployment() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; // Get a release client instance VssConnection connection = Context.Connection; ReleaseHttpClient releaseClient = connection.GetClient <ReleaseHttpClient>(); WebApiRelease release = CreateRelease(releaseClient, newlyCreatedReleaseDefinitionId, projectName); ReleaseEnvironmentUpdateMetadata releaseEnvironmentUpdateMetadata = new ReleaseEnvironmentUpdateMetadata() { Status = EnvironmentStatus.InProgress }; int releaseEnvironmentId = release.Environments.FirstOrDefault().Id; // Start deployment to an environment ReleaseEnvironment releaseEnvironment = releaseClient.UpdateReleaseEnvironmentAsync(releaseEnvironmentUpdateMetadata, projectName, release.Id, releaseEnvironmentId).Result; Context.Log("{0} {1}", releaseEnvironment.Id.ToString().PadLeft(6), releaseEnvironment.Name); return(releaseEnvironment); }
public TestSuite CreateTestSuite() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; // Get a testplan client instance VssConnection connection = Context.Connection; TestPlanHttpClient testPlanClient = connection.GetClient <TestPlanHttpClient>(); TestSuiteCreateParams testSuiteCreateParams = new TestSuiteCreateParams() { Name = "SubSuite 1.1.1", SuiteType = TestSuiteType.StaticTestSuite, ParentSuite = new TestSuiteReference() { Id = 85 }, InheritDefaultConfigurations = false, DefaultConfigurations = new List <TestConfigurationReference>() { new TestConfigurationReference() { Id = 1 }, new TestConfigurationReference() { Id = 2 } } }; // Create Test Variable TestSuite suite = testPlanClient.CreateTestSuiteAsync(testSuiteCreateParams, projectName, 79).Result; Console.WriteLine("{0} {1}", suite.Id.ToString().PadLeft(6), suite.Name); return(suite); }
public TestPlanWebApi.TestPlan GetTestPlanById() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; // Get a testplan client instance VssConnection connection = Context.Connection; TestPlanHttpClient testPlanClient = connection.GetClient <TestPlanHttpClient>(); TestPlanWebApi.TestPlan newplan1; Context.TryGetValue <TestPlanWebApi.TestPlan>("$newPlan1", out newplan1); if (newplan1 != null) { int id = newplan1.Id; // get a test plan TestPlanWebApi.TestPlan plan = testPlanClient.GetTestPlanByIdAsync(projectName, id).Result; Context.Log("{0} {1}", plan.Id, plan.Name); return(plan); } return(null); }
public TestPlanWebApi.TestPlan CreateTestPlanWithAreaPathAndIteration() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; // Get a testplan client instance VssConnection connection = Context.Connection; TestPlanHttpClient testPlanClient = connection.GetClient <TestPlanHttpClient>(); TestPlanWebApi.TestPlanCreateParams testPlanCreateParams = new TestPlanWebApi.TestPlanCreateParams() { Name = "newCreatedPlan1", AreaPath = this._getArea(), Iteration = this._getIteration() }; // create a test plan TestPlanWebApi.TestPlan plan = testPlanClient.CreateTestPlanAsync(testPlanCreateParams, projectName).Result; Context.SetValue <TestPlanWebApi.TestPlan>("$newPlan1", plan); Context.Log("{0} {1}", plan.Id, plan.Name); return(plan); }
public TestConfiguration GetTestConfigurationById() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; // Get a testplan client instance VssConnection connection = Context.Connection; TestPlanHttpClient testPlanClient = connection.GetClient <TestPlanHttpClient>(); TestConfiguration newConfiguration; Context.TryGetValue <TestConfiguration>("$newConfiguration", out newConfiguration); if (newConfiguration != null) { int id = newConfiguration.Id; // Get Test configurations TestConfiguration configuration = testPlanClient.GetTestConfigurationByIdAsync(projectName, id).Result; Context.Log("{0} {1}", configuration.Id.ToString().PadLeft(6), configuration.Name); return(configuration); } return(null); }
public ReleaseDefinition UpdateReleaseDefinition() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; // Get a release client instance VssConnection connection = Context.Connection; ReleaseHttpClient releaseClient = connection.GetClient <ReleaseHttpClient>(); ReleaseDefinition releaseDefinition = releaseClient.GetReleaseDefinitionAsync(project: projectName, definitionId: newlyCreatedReleaseDefinitionId).Result; // add a non secret variable to definition ConfigurationVariableValue variable = new ConfigurationVariableValue(); variable.Value = "NonSecretValue"; variable.IsSecret = false; releaseDefinition.Variables.Add("NonSecretVariable", variable); // update release definition ReleaseDefinition updatedReleaseDefinition = releaseClient.UpdateReleaseDefinitionAsync(project: projectName, releaseDefinition: releaseDefinition).Result; Context.Log("{0} {1} {2}", updatedReleaseDefinition.Id.ToString().PadLeft(6), updatedReleaseDefinition.Revision, updatedReleaseDefinition.ModifiedOn); return(releaseDefinition); }
public ReleaseDefinition CreateReleaseDefinition() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; ReleaseDefinition definition = new ReleaseDefinition() { Name = releaseDefinitionName, Revision = 1, Environments = new List <ReleaseDefinitionEnvironment>() { new ReleaseDefinitionEnvironment() { Name = "PROD", DeployPhases = new List <DeployPhase>() { new AgentBasedDeployPhase() { Name = "Run on agent", Rank = 1 } }, PreDeployApprovals = new ReleaseDefinitionApprovals() { Approvals = new List <ReleaseDefinitionApprovalStep>() { new ReleaseDefinitionApprovalStep() { IsAutomated = true, Rank = 1 } } }, PostDeployApprovals = new ReleaseDefinitionApprovals() { Approvals = new List <ReleaseDefinitionApprovalStep>() { new ReleaseDefinitionApprovalStep() { IsAutomated = true, Rank = 1 } } }, RetentionPolicy = new EnvironmentRetentionPolicy() { DaysToKeep = 30, ReleasesToKeep = 3, RetainBuild = true } } } }; // Get a release client instance VssConnection connection = Context.Connection; ReleaseHttpClient releaseClient = connection.GetClient <ReleaseHttpClient>(); // create a release definition ReleaseDefinition releaseDefinition = releaseClient.CreateReleaseDefinitionAsync(project: projectName, releaseDefinition: definition).Result; newlyCreatedReleaseDefinitionId = releaseDefinition.Id; Console.WriteLine("{0} {1}", releaseDefinition.Id.ToString().PadLeft(6), releaseDefinition.Name); return(releaseDefinition); }
public GitPullRequest CreatePullRequestInner(bool cleanUp) { VssConnection connection = this.Context.Connection; GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); GitRepository repo = GitSampleHelpers.FindAnyRepository(this.Context, project.Id); // we need a new branch with changes in order to create a PR // first, find the default branch string defaultBranchName = GitSampleHelpers.WithoutRefsPrefix(repo.DefaultBranch); GitRef defaultBranch = gitClient.GetRefsAsync(repo.Id, filter: defaultBranchName).Result.First(); // next, craft the branch and commit that we'll push GitRefUpdate newBranch = new GitRefUpdate() { Name = $"refs/heads/vsts-api-sample/{GitSampleHelpers.ChooseRefsafeName()}", OldObjectId = defaultBranch.ObjectId, }; string newFileName = $"{GitSampleHelpers.ChooseItemsafeName()}.md"; GitCommitRef newCommit = new GitCommitRef() { Comment = "Add a sample file", Changes = new GitChange[] { new GitChange() { ChangeType = VersionControlChangeType.Add, Item = new GitItem() { Path = $"/vsts-api-sample/{newFileName}" }, NewContent = new ItemContent() { Content = "# Thank you for using VSTS!", ContentType = ItemContentType.RawText, }, } }, }; // create the push with the new branch and commit GitPush push = gitClient.CreatePushAsync(new GitPush() { RefUpdates = new GitRefUpdate[] { newBranch }, Commits = new GitCommitRef[] { newCommit }, }, repo.Id).Result; // finally, create a PR var pr = gitClient.CreatePullRequestAsync(new GitPullRequest() { SourceRefName = newBranch.Name, TargetRefName = repo.DefaultBranch, Title = $"Add {newFileName} (from VSTS REST samples)", Description = "Adding this file from the pull request samples", }, repo.Id).Result; Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name); Console.WriteLine("{0} (#{1}) {2} -> {3}", pr.Title.Substring(0, Math.Min(40, pr.Title.Length)), pr.PullRequestId, pr.SourceRefName, pr.TargetRefName); if (cleanUp) { // clean up after ourselves (and in case logging is on, don't log these calls) ClientSampleHttpLogger.SetSuppressOutput(this.Context, true); // abandon the PR GitPullRequest updatedPr = new GitPullRequest() { Status = PullRequestStatus.Abandoned, }; pr = gitClient.UpdatePullRequestAsync(updatedPr, repo.Id, pr.PullRequestId).Result; // delete the branch GitRefUpdateResult refDeleteResult = gitClient.UpdateRefsAsync( new GitRefUpdate[] { new GitRefUpdate() { OldObjectId = push.RefUpdates.First().NewObjectId, NewObjectId = new string('0', 40), Name = push.RefUpdates.First().Name, } }, repositoryId: repo.Id).Result.First(); } return(pr); }
public ReleaseDefinition CreateReleaseDefinition() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; string currentUserId = ClientSampleHelpers.GetCurrentUserId(this.Context).ToString(); // If you want to override varaibles at release create time you should set 'AllowOverride'. ConfigurationVariableValue nonSceretVariable = new ConfigurationVariableValue(); nonSceretVariable.Value = "NonSecretValue"; nonSceretVariable.IsSecret = false; nonSceretVariable.AllowOverride = true; ConfigurationVariableValue sceretVariable = new ConfigurationVariableValue(); sceretVariable.Value = "SecretValue"; sceretVariable.IsSecret = true; ConfigurationVariableValue nonOverrideVariable = new ConfigurationVariableValue(); nonOverrideVariable.Value = "NonOverridevariable"; nonOverrideVariable.IsSecret = false; nonOverrideVariable.AllowOverride = false; Dictionary <string, ConfigurationVariableValue> releaseLevelVariables = new Dictionary <string, ConfigurationVariableValue>(); releaseLevelVariables.Add(NonSecretReleaseLevelVaraible, nonSceretVariable); releaseLevelVariables.Add("SecretReleaseLevelVaraible", sceretVariable); releaseLevelVariables.Add("NonOverridevariable", nonOverrideVariable); ReleaseDefinition definition = new ReleaseDefinition() { Name = releaseDefinitionName, Revision = 1, Variables = releaseLevelVariables, // You can add varaibles at environment level also. Environments = new List <ReleaseDefinitionEnvironment>() { new ReleaseDefinitionEnvironment() { Name = "PROD", DeployPhases = new List <DeployPhase>() { new AgentBasedDeployPhase() { Name = "Run on agent", Rank = 1, DeploymentInput = new AgentDeploymentInput() { QueueId = 1 } } }, PreDeployApprovals = new ReleaseDefinitionApprovals() { Approvals = new List <ReleaseDefinitionApprovalStep>() { new ReleaseDefinitionApprovalStep() { IsAutomated = false, Rank = 1, Approver = new IdentityRef() { Id = currentUserId } }, } }, PostDeployApprovals = new ReleaseDefinitionApprovals() { Approvals = new List <ReleaseDefinitionApprovalStep>() { new ReleaseDefinitionApprovalStep() { IsAutomated = true, Rank = 1 } } }, RetentionPolicy = new EnvironmentRetentionPolicy() { DaysToKeep = 30, ReleasesToKeep = 3, RetainBuild = true } } } }; // Get a release client instance VssConnection connection = Context.Connection; ReleaseHttpClient releaseClient = connection.GetClient <ReleaseHttpClient>(); // create a release definition ReleaseDefinition releaseDefinition = releaseClient.CreateReleaseDefinitionAsync(project: projectName, releaseDefinition: definition).Result; newlyCreatedReleaseDefinitionId = releaseDefinition.Id; Context.Log("{0} {1}", releaseDefinition.Id.ToString().PadLeft(6), releaseDefinition.Name); return(releaseDefinition); }
public void CreateReleaseWithManualIntervention() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; ReleaseDefinition definition = new ReleaseDefinition() { Name = releaseDefinitionName, Revision = 1, Environments = new List <ReleaseDefinitionEnvironment>() { new ReleaseDefinitionEnvironment() { Name = "PROD", Conditions = new List <Condition>() { new Condition() { ConditionType = ConditionType.Event, Name = "ReleaseStarted" } }, DeployPhases = new List <DeployPhase>() { new RunOnServerDeployPhase() { Name = "Agentless phase", Rank = 1, WorkflowTasks = new List <WorkflowTask>() { new WorkflowTask() { Name = "Manual Intervention", TaskId = new Guid("bcb64569-d51a-4af0-9c01-ea5d05b3b622"), Version = "8.*", Enabled = true } } } }, PreDeployApprovals = new ReleaseDefinitionApprovals() { Approvals = new List <ReleaseDefinitionApprovalStep>() { new ReleaseDefinitionApprovalStep() { IsAutomated = true, Rank = 1, } } }, PostDeployApprovals = new ReleaseDefinitionApprovals() { Approvals = new List <ReleaseDefinitionApprovalStep>() { new ReleaseDefinitionApprovalStep() { IsAutomated = true, Rank = 1 } } }, RetentionPolicy = new EnvironmentRetentionPolicy() { DaysToKeep = 30, ReleasesToKeep = 3, RetainBuild = true } } } }; // Get a release client instance VssConnection connection = Context.Connection; ReleaseHttpClient releaseClient = connection.GetClient <ReleaseHttpClient>(); // create a release definition ReleaseDefinition releaseDefinition = releaseClient.CreateReleaseDefinitionAsync(project: projectName, releaseDefinition: definition).Result; this._newlyCreatedReleaseDefinitionId = releaseDefinition.Id; this._newlyCreatedRelease1 = ReleasesSample.CreateRelease(releaseClient, _newlyCreatedReleaseDefinitionId, projectName); this._newlyCreatedRelease2 = ReleasesSample.CreateRelease(releaseClient, _newlyCreatedReleaseDefinitionId, projectName); Context.Log("{0} {1}", _newlyCreatedRelease1.Id.ToString().PadLeft(6), _newlyCreatedRelease1.Name); Context.Log("{0} {1}", _newlyCreatedRelease2.Id.ToString().PadLeft(6), _newlyCreatedRelease2.Name); }
public static GitRepository FindAnyRepositoryOnAnyProject(ClientSampleContext context) { Guid projectId = ClientSampleHelpers.FindAnyProject(context).Id; return(FindAnyRepository(context, projectId)); }
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 ReleaseGates IgnoreGate() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; string gateName = "Query Work Items"; ReleaseDefinitionGatesStep releaseDefinitionGatesStep = new ReleaseDefinitionGatesStep { Gates = new List <ReleaseDefinitionGate> { new ReleaseDefinitionGate { Tasks = new List <WorkflowTask> { new WorkflowTask { Enabled = true, Name = gateName, TaskId = new Guid("f1e4b0e6-017e-4819-8a48-ef19ae96e289"), Version = "0.*", Inputs = new Dictionary <string, string> { { "queryId", "c871ca91-e30c-43a0-9306-97a2be93861e" }, { "maxThreshold", "6" }, { "minThreshold", "2" } } } } } }, GatesOptions = new ReleaseDefinitionGatesOptions { IsEnabled = true, MinimumSuccessDuration = 2, SamplingInterval = 5, StabilizationTime = 10, Timeout = 60 }, Id = 0 }; ReleaseDefinition definition = new ReleaseDefinition() { Name = releaseDefinitionName, Revision = 1, Environments = new List <ReleaseDefinitionEnvironment>() { new ReleaseDefinitionEnvironment() { Name = "PROD", Conditions = new List <Condition>() { new Condition() { ConditionType = ConditionType.Event, Name = "ReleaseStarted" } }, DeployPhases = new List <DeployPhase>() { new RunOnServerDeployPhase() { Name = "Agentless phase", Rank = 1, WorkflowTasks = new List <WorkflowTask>() { new WorkflowTask() { Name = "Manual Intervention", TaskId = new Guid("bcb64569-d51a-4af0-9c01-ea5d05b3b622"), Version = "8.*", Enabled = true } } } }, PreDeployApprovals = new ReleaseDefinitionApprovals() { Approvals = new List <ReleaseDefinitionApprovalStep>() { new ReleaseDefinitionApprovalStep() { IsAutomated = true, Rank = 1, } } }, PostDeployApprovals = new ReleaseDefinitionApprovals() { Approvals = new List <ReleaseDefinitionApprovalStep>() { new ReleaseDefinitionApprovalStep() { IsAutomated = true, Rank = 1 } } }, RetentionPolicy = new EnvironmentRetentionPolicy() { DaysToKeep = 30, ReleasesToKeep = 3, RetainBuild = true }, PreDeploymentGates = releaseDefinitionGatesStep } } }; // Get a release client instance VssConnection connection = Context.Connection; ReleaseHttpClient releaseClient = connection.GetClient <ReleaseHttpClient>(); // create a release definition ReleaseDefinition releaseDefinition = releaseClient.CreateReleaseDefinitionAsync(project: projectName, releaseDefinition: definition).Result; this._newlyCreatedReleaseDefinitionId = releaseDefinition.Id; // create a release WebApiRelease release = ReleasesSample.CreateRelease(releaseClient, _newlyCreatedReleaseDefinitionId, projectName); Context.Log("{0} {1}", release.Id.ToString().PadLeft(6), release.Name); // Wait till deployment moves to evaluation gates state ClientSampleHelpers.Retry( TimeSpan.FromMinutes(2), TimeSpan.FromSeconds(5), () => { release = releaseClient.GetReleaseAsync(project: projectName, releaseId: release.Id).Result; return(release != null && release.Environments.First().DeploySteps.FirstOrDefault().OperationStatus == DeploymentOperationStatus.EvaluatingGates); }); // Ignore the gate GateUpdateMetadata gateUpdateMetadata = new GateUpdateMetadata { Comment = "Ignore gate", GatesToIgnore = new List <string> { gateName } }; int gateStepId = release.Environments.FirstOrDefault().DeploySteps.FirstOrDefault().PreDeploymentGates.Id; ReleaseGates releaseGates = releaseClient.UpdateGatesAsync(gateUpdateMetadata: gateUpdateMetadata, project: projectName, gateStepId: gateStepId).Result; Context.Log("{0} {1}", releaseGates.Id.ToString().PadLeft(6), releaseGates.Id); return(releaseGates); }
public TfvcChangesetRef CreateChangeMultiFile() { VssConnection connection = this.Context.Connection; TfvcHttpClient tfvcClient = connection.GetClient <TfvcHttpClient>(); string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; DateTime time = DateTime.UtcNow; string destinationFilePath1 = string.Format("$/{0}/example-file-{1}.1.txt", projectName, time.ToString("yyyy-MM-dd-HH-mm-ss-ff")); string destinationFileContents1 = string.Format("File 1 contents as of {0}", time); string destinationFilePath2 = string.Format("$/{0}/example-file-{1}.2.txt", projectName, time.ToString("yyyy-MM-dd-HH-mm-ss-ff")); string destinationFileContents2 = string.Format("File 2 contents as of {0}", time); TfvcChangeset changeset = new TfvcChangeset() { Changes = new[] { new TfvcChange() { ChangeType = VersionControlChangeType.Add, Item = new TfvcItem() { Path = destinationFilePath1, ContentMetadata = new FileContentMetadata() { Encoding = Encoding.UTF8.WindowsCodePage, ContentType = "text/plain", } }, NewContent = new ItemContent() { Content = destinationFileContents1, ContentType = ItemContentType.RawText, }, }, new TfvcChange() { ChangeType = VersionControlChangeType.Add, Item = new TfvcItem() { Path = destinationFilePath2, ContentMetadata = new FileContentMetadata() { Encoding = Encoding.UTF8.WindowsCodePage, ContentType = "text/plain", } }, NewContent = new ItemContent() { Content = destinationFileContents2, ContentType = ItemContentType.RawText, }, }, }, Comment = "(sample) Adding multiple files via API", }; try { Console.WriteLine("Writing files {0} and {1}", destinationFilePath1, destinationFilePath2); 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 GitPush CreatePush() { VssConnection connection = this.Context.Connection; GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); GitRepository repo = GitSampleHelpers.FindAnyRepository(this.Context, project.Id); // we will create a new push by making a small change to the default branch // first, find the default branch string defaultBranchName = GitSampleHelpers.WithoutRefsPrefix(repo.DefaultBranch); GitRef defaultBranch = gitClient.GetRefsAsync(repo.Id, filter: defaultBranchName).Result.First(); // next, craft the branch and commit that we'll push GitRefUpdate newBranch = new GitRefUpdate() { Name = $"refs/heads/vsts-api-sample/{GitSampleHelpers.ChooseRefsafeName()}", OldObjectId = defaultBranch.ObjectId, }; string newFileName = $"{GitSampleHelpers.ChooseItemsafeName()}.md"; GitCommitRef newCommit = new GitCommitRef() { Comment = "Add a sample file", Changes = new GitChange[] { new GitChange() { ChangeType = VersionControlChangeType.Add, Item = new GitItem() { Path = $"/vsts-api-sample/{newFileName}" }, NewContent = new ItemContent() { Content = "# Thank you for using VSTS!", ContentType = ItemContentType.RawText, }, } }, }; // create the push with the new branch and commit GitPush push = gitClient.CreatePushAsync(new GitPush() { RefUpdates = new GitRefUpdate[] { newBranch }, Commits = new GitCommitRef[] { newCommit }, }, repo.Id).Result; Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name); Console.WriteLine("push {0} updated {1} to {2}", push.PushId, push.RefUpdates.First().Name, push.Commits.First().CommitId); // now clean up after ourselves (and in case logging is on, don't log these calls) ClientSampleHttpLogger.SetSuppressOutput(this.Context, true); // delete the branch GitRefUpdateResult refDeleteResult = gitClient.UpdateRefsAsync( new GitRefUpdate[] { new GitRefUpdate() { OldObjectId = push.RefUpdates.First().NewObjectId, NewObjectId = new string('0', 40), Name = push.RefUpdates.First().Name, } }, repositoryId: repo.Id).Result.First(); // pushes and commits are immutable, so no way to clean them up // but the commit will be unreachable after this return(push); }
public WorkItem CreateAndLinkToWorkItem() { string title = "My new work item with links"; string description = "This is a new work item that has a link also created on it."; string linkUrl = Context.GetValue <WorkItem>("$newWorkItem1").Url; //get the url of a previously added work item JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Title", Value = title } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Description", Value = description } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.History", Value = "Jim has the most context around this." } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/relations/-", Value = new { rel = "System.LinkTypes.Hierarchy-Reverse", url = linkUrl, attributes = new { comment = "decomposition of work" } } } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); // Get the project to create the sample work item in TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); WorkItem result = workItemTrackingClient.CreateWorkItemAsync(patchDocument, project.Name, "Task").Result; return(result); }
public List <ReleaseTaskAttachment> GetReleaseAttachment() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; ReleaseDefinition definition = new ReleaseDefinition() { Name = releaseDefinitionName, Revision = 1, Environments = new List <ReleaseDefinitionEnvironment>() { new ReleaseDefinitionEnvironment() { Name = "PROD", Conditions = new List <Condition>() { new Condition() { ConditionType = ConditionType.Event, Name = "ReleaseStarted" } }, DeployPhases = new List <DeployPhase>() { new AgentBasedDeployPhase() { Name = "Run on agent", Rank = 1, DeploymentInput = new AgentDeploymentInput() { QueueId = 1 }, WorkflowTasks = new List <WorkflowTask> { new WorkflowTask { Name = taskName, Enabled = true, TimeoutInMinutes = 0, Inputs = new Dictionary <string, string> { { "targetType", "inline" }, { "script", "New-Item -Path 'newfile.txt' -ItemType File\n\nWrite-Host \"##vso[task.addattachment type=myattachmenttype;name=myattachmentname;]$(SYSTEM.DEFAULTWORKINGDIRECTORY)\\newfile.txt\"" } }, TaskId = new Guid("e213ff0f-5d5c-4791-802d-52ea3e7be1f1"), Version = "2.*", DefinitionType = "task", Condition = "succeeded()", } } } }, PreDeployApprovals = new ReleaseDefinitionApprovals() { Approvals = new List <ReleaseDefinitionApprovalStep>() { new ReleaseDefinitionApprovalStep() { IsAutomated = true, Rank = 1 } } }, PostDeployApprovals = new ReleaseDefinitionApprovals() { Approvals = new List <ReleaseDefinitionApprovalStep>() { new ReleaseDefinitionApprovalStep() { IsAutomated = true, Rank = 1 } } }, RetentionPolicy = new EnvironmentRetentionPolicy() { DaysToKeep = 30, ReleasesToKeep = 3, RetainBuild = true } } } }; // Get a release client instance VssConnection connection = Context.Connection; ReleaseHttpClient releaseClient = connection.GetClient <ReleaseHttpClient>(); // create a release definition ReleaseDefinition releaseDefinition = releaseClient.CreateReleaseDefinitionAsync(project: projectName, releaseDefinition: definition).Result; this._newlyCreatedReleaseDefinitionId = releaseDefinition.Id; Context.Log("{0} {1} {2}", releaseDefinition.Id.ToString().PadLeft(6), releaseDefinition.Name, projectName); // create a release WebApiRelease release = ReleasesSample.CreateRelease(releaseClient, _newlyCreatedReleaseDefinitionId, projectName); Context.Log("{0} {1}", release.Id.ToString().PadLeft(6), release.Name); _newlyCreatedRelease = release.Id; // Wait till deployment completed ClientSampleHelpers.Retry( TimeSpan.FromMinutes(2), TimeSpan.FromSeconds(5), () => { release = releaseClient.GetReleaseAsync(project: projectName, releaseId: release.Id).Result; return(release != null && release.Environments.First().Status == EnvironmentStatus.Succeeded); }); // Get release task attachments ReleaseEnvironment environment = release.Environments.FirstOrDefault(); DeploymentAttempt deployStep = environment.DeploySteps.First(); Guid planId = deployStep.ReleaseDeployPhases.First().RunPlanId.Value; List <ReleaseTaskAttachment> releaseTaskAttachment = releaseClient.GetReleaseTaskAttachmentsAsync(project: projectName, releaseId: release.Id, environmentId: environment.Id, attemptId: deployStep.Attempt, planId: planId, type: "myattachmenttype").Result; Context.Log("{0} {1}", releaseTaskAttachment.First().Name.PadLeft(6), releaseTaskAttachment.First().Type); return(releaseTaskAttachment); }