public async Task DownloadAsync(IExecutionContext executionContext, ArtifactDefinition artifactDefinition, string localFolderPath) { ArgUtil.NotNull(artifactDefinition, nameof(artifactDefinition)); ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNullOrEmpty(localFolderPath, nameof(localFolderPath)); int buildId = Convert.ToInt32(artifactDefinition.Version, CultureInfo.InvariantCulture); if (buildId <= 0) { throw new ArgumentException("artifactDefinition.Version"); } var buildArtifactDetails = artifactDefinition.Details as BuildArtifactDetails; if (buildArtifactDetails == null) { throw new ArgumentException("artifactDefinition.Details"); } // Get the list of available artifacts from build. executionContext.Output(StringUtil.Loc("RMPreparingToGetBuildArtifactList")); var vssConnection = new VssConnection(buildArtifactDetails.TfsUrl, buildArtifactDetails.Credentials); var buildClient = vssConnection.GetClient<BuildHttpClient>(); var xamlBuildClient = vssConnection.GetClient<XamlBuildHttpClient>(); List<ServerBuildArtifact> buildArtifacts = null; DefinitionType buildDefinitionType = DefinitionType.Build; try { buildArtifacts = await buildClient.GetArtifactsAsync(buildArtifactDetails.Project, buildId); } catch (BuildNotFoundException) { buildArtifacts = await xamlBuildClient.GetArtifactsAsync(buildArtifactDetails.Project, buildId); buildDefinitionType = DefinitionType.Xaml; } // No artifacts found in the build => Fail it. if (buildArtifacts == null || !buildArtifacts.Any()) { throw new ArtifactDownloadException(StringUtil.Loc("RMNoBuildArtifactsFound", buildId)); } // DownloadFromStream each of the artifact sequentially. // TODO: Should we download them parallely? foreach (ServerBuildArtifact buildArtifact in buildArtifacts) { if (Match(buildArtifact, artifactDefinition)) { executionContext.Output(StringUtil.Loc("RMPreparingToDownload", buildArtifact.Name)); await this.DownloadArtifactAsync(executionContext, buildArtifact, artifactDefinition, localFolderPath, buildClient, xamlBuildClient, buildDefinitionType, buildId); } else { executionContext.Warning(StringUtil.Loc("RMArtifactMatchNotFound", buildArtifact.Name)); } } }
static void Main(string[] args) { if (args.Length != 3) { ShowUsage(); return; } string accountUrl = args[0]; var minFinishTime = DateTime.Parse(args[1]); var maxFinishTime = GetMaxFinishTime(DateTime.Parse(args[2])); Console.WriteLine("Getting projects in the account:"); VssConnection connection = new VssConnection(new Uri(accountUrl), new VssAadCredential()); var projectClient = connection.GetClient<ProjectHttpClient>(); var projects = projectClient.GetProjects().Result; var buildClient = connection.GetClient<BuildHttpClient>(); foreach (var project in projects) { var builds = buildClient.GetBuildsAsync(project.Id, minFinishTime: minFinishTime, maxFinishTime: maxFinishTime).Result; if (builds.Count > 0) { Console.WriteLine($"{project.Name} project had {builds.Count} builds run between {minFinishTime} and {maxFinishTime}"); foreach (var build in builds) { ReportBuildInformation(build); } } else { Console.WriteLine($"Project {project.Name} did not having any builds during that time."); } } Console.WriteLine("Press a key."); Console.ReadKey(); }
public async Task PublishCoverageSummaryAsync(VssConnection connection, string project, int buildId, IEnumerable<CodeCoverageStatistics> coverageData, CancellationToken cancellationToken) { var testHttpClient = connection.GetClient<TestManagementHttpClient>(); // <todo: Bug 402783> We are currently passing BuildFlavor and BuildPlatform = "" There value are required be passed to command CodeCoverageData data = new CodeCoverageData() { BuildFlavor = "", BuildPlatform = "", CoverageStats = coverageData.ToList() }; await testHttpClient.UpdateCodeCoverageSummaryAsync(data, project, buildId, cancellationToken: cancellationToken); }
/// <summary> /// Asynchronously initializes the sink. /// </summary> /// <param name="name">The configuration name of the sink.</param> /// <param name="cancellationToken">A token to monitor for cancellation requests. The default value is <see cref="System.Threading.CancellationToken.None" />.</param> /// <returns> /// A <see cref="Task" /> that represents the asynchronous initialize operation. /// </returns> public async Task InitializeAsync(string name, CancellationToken cancellationToken = default(CancellationToken)) { await Task.Delay(0); var element = Configuration.TfsConfigurationSection.Current.Sinks[name]; // todo: support other auth methods, see the auth samples in https://www.visualstudio.com/en-us/integrate/get-started/client-libraries/samples // * OAuth // * ADD //var vssCredentials = new VssCredentials(); // Active directory auth - NTLM against a Team Foundation Server //var vssCredentials = new VssClientCredentials(); // Visual Studio sign-in prompt. Would need work to make this not prompt at every startup var vssCredentials = new VssBasicCredential("", element.AccessToken); var connection = new VssConnection(new Uri(element.ProjectCollection), vssCredentials); _witClient = connection.GetClient<WorkItemTrackingHttpClient>(); }
public async Task ConnectAsync(VssConnection jobConnection) { ArgUtil.NotNull(jobConnection, nameof(jobConnection)); _connection = jobConnection; try { await _connection.ConnectAsync(); } catch (SocketException ex) { ExceptionsUtil.HandleSocketException(ex, _connection.Uri.ToString(), Trace.Error); throw; } catch (Exception ex) { Trace.Info($"Unable to connect to {_connection.Uri}."); Trace.Error(ex); throw; } _locationClient = _connection.GetClient <LocationHttpClient>(); _hasConnection = true; }
internal async Task <ProjectTemplate> UpdateProjectTemplateAsync(ProjectTemplate projectTemplate) { if (projectTemplate is null) { throw new ArgumentNullException(nameof(projectTemplate)); } var repository = projectTemplate.Repository; var creds = new VssBasicCredential(string.Empty, repository.Token); using var connection = new VssConnection(new Uri(repository.BaselUrl), creds); using var client = connection.GetClient <GitHttpClient>(); var commit = await client .GetCommitAsync(project : repository.Project, repository.Ref, repository.Repository) .ConfigureAwait(false); var result = await client .GetTreeAsync(project : repository.Project, repository.Repository, commit.TreeId, recursive : true) .ConfigureAwait(false); var projectYamlFile = await client .GetItemAsync(project : repository.Project, repository.Repository, Constants.ProjectYaml, download : true, versionDescriptor : repository.VersionDescriptor()) .ConfigureAwait(false); var projectYaml = projectYamlFile.Content; var projectJson = new Deserializer().ToJson(projectYaml); TeamCloudSerialize.PopulateObject(projectJson, projectTemplate, new ProjectTemplateConverter(projectTemplate, projectYamlFile.Path)); projectTemplate.Description = await CheckAndPopulateFileContentAsync(client, repository, result.TreeEntries, projectTemplate.Description) .ConfigureAwait(false); return(projectTemplate); }
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 WorkItem AddTags() { int id = Convert.ToInt32(Context.GetValue <WorkItem>("$newWorkItem2").Id); string[] tags = { "teamservices", "client", "sample" }; JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Tags", Value = string.Join(";", tags) } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return(result); }
public TestSuite GetTestSuiteById() { string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name; // Get a testplan client instance VssConnection connection = Context.Connection; TestPlanHttpClient testPlanClient = connection.GetClient <TestPlanHttpClient>(); int testPlanId = this._getTestPlanId(); TestSuite newSuite; Context.TryGetValue <TestSuite>("$newSuite", out newSuite); int id = newSuite.Id; if (id != 0) { // Get Test Suite TestSuite suite = testPlanClient.GetTestSuiteByIdAsync(projectName, testPlanId, id, SuiteExpand.Children).Result; Context.Log("{0} {1}", suite.Id.ToString().PadLeft(6), suite.Name); return(suite); } return(null); }
public WorkItem GetWorkItemRevision() { int id = 1; VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); // give me revision #2 WorkItem revision = workItemTrackingClient.GetRevisionAsync(id, 2).Result; Console.WriteLine("Work Item Revision..."); Console.WriteLine("Id: {0}", revision.Id); Console.WriteLine("Revision: {0}", revision.Rev); Console.WriteLine("Fields"); foreach (var field in revision.Fields) { Console.WriteLine("{0} : {1}", field.Key, field.Value); } Console.WriteLine(); return(revision); }
public async Task ConnectAsync(VssConnection jobConnection) { _connection = jobConnection; int totalAttempts = 5; int attemptCount = totalAttempts; var configurationStore = HostContext.GetService <IConfigurationStore>(); var runnerSettings = configurationStore.GetSettings(); while (!_connection.HasAuthenticated && attemptCount-- > 0) { try { await _connection.ConnectAsync(); break; } catch (Exception ex) when(attemptCount > 0) { Trace.Info($"Catch exception during connect. {attemptCount} attempts left."); Trace.Error(ex); if (runnerSettings.IsHostedServer) { await CheckNetworkEndpointsAsync(attemptCount); } } int attempt = totalAttempts - attemptCount; TimeSpan backoff = BackoffTimerHelper.GetExponentialBackoff(attempt, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(3.2), TimeSpan.FromMilliseconds(100)); await Task.Delay(backoff); } _taskClient = _connection.GetClient <TaskHttpClient>(); _hasConnection = true; }
/// <summary> /// Attempts to authenticate with given access token, returns bool indicating success /// </summary> public static bool VSTSConnect(string accessToken) { VssBasicCredential vssCreds = new VssBasicCredential(string.Empty, accessToken); Task connectTask = null; try { VssConnection = new VssConnection(new Uri(@"https://adamfeher.visualstudio.com"), vssCreds); connectTask = VssConnection.ConnectAsync(); Session.ProjectCollection = new TfsTeamProjectCollection(new Uri(@"https://adamfeher.visualstudio.com/DefaultCollection"), vssCreds); Session.ProjectCollection.Authenticate(); } catch (Exception e) { return(false); } if (!connectTask.IsCompleted) { connectTask.SyncResult(); } Wit = VssConnection.GetClient <WorkItemTrackingHttpClient>(); TestService = ProjectCollection.GetService <ITestManagementService>(); return(true); }
public static async Task ExecWithClientLibrary() { var BaseURL = Configuration["BaseURL"]; var PAT = Configuration["AzureDevOpsPAT"]; var RepositoryId = Configuration["RepositoryId"]; var uri = new Uri(BaseURL); var organizationURL = BaseURL.Substring(0, BaseURL.LastIndexOf('/')); VssConnection connection = new VssConnection(new Uri(organizationURL), new VssBasicCredential(string.Empty, PAT)); // List PR thread. GitHttpClient client = connection.GetClient <GitHttpClient>(); var result = await client.GetPullRequestAsync(RepositoryId, 53); var thtreads = await client.GetThreadsAsync(RepositoryId, 53); var clientMock = new Mock <GitHttpClientBase>(MockBehavior.Strict, new Uri("https://foo.bar"), new VssCredentials()); clientMock.Setup(p => p.GetThreadsAsync(RepositoryId, 53, It.IsAny <int?>(), It.IsAny <int?>(), It.IsAny <object>(), It.IsAny <CancellationToken>())).ReturnsAsync(new List <GitPullRequestCommentThread>()).Verifiable(); var r = clientMock.Object.GetThreadsAsync(RepositoryId, 53); clientMock.Verify(); }
public string AddLinkToBug() { var _id = _configuration.WorkItemId; var _linkToId = _configuration.WorkItemIds.Split(',')[0]; JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add(new JsonPatchOperation() { Operation = Operation.Add, Path = "/relations/-", Value = new { rel = "System.LinkTypes.Dependency-forward", url = _configuration.UriString + "/_apis/wit/workItems/" + _linkToId.ToString(), attributes = new { comment = "Making a new link for the dependency" } } }); VssConnection connection = new VssConnection(_uri, _credentials); WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>(); try { WorkItem result = workItemTrackingHttpClient.UpdateWorkItemAsync(patchDocument, _id).Result; return("success"); } catch (Microsoft.VisualStudio.Services.Common.VssServiceException ex) { return(ex.Message); } catch (Exception ex) { return(ex.InnerException.Message); } }
public WorkItemComment GetSingleWorkItemComment() { WorkItem newWorkItem; using (new ClientSampleHttpLoggerOutputSuppression()) { WorkItemsSample witSample = new WorkItemsSample(); witSample.Context = this.Context; newWorkItem = witSample.CreateWorkItem("Sample work item for comments"); Context.SetValue <WorkItem>("$newWorkItem", newWorkItem); } int id = Convert.ToInt32(newWorkItem.Id); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); WorkItemComment result = workItemTrackingClient.GetCommentAsync(id, 1).Result; Console.WriteLine("Revision: {0}", result.Revision); Console.WriteLine("Text: {0}", result.Text); return(result); }
static void ConnectionThread() { try { //thread to solve the connection problem: https://developercommunity.visualstudio.com/content/problem/142230/tf400813-tf30063-errors-when-connecting-to-vsts-us.html if (UserName == "" && Password == "") { VSConnection = new VssConnection(new Uri(CollectionUrl), new VssCredentials()); } else if (UserName != "" && Password != "" && UserDomain == "") { VSConnection = new VssConnection(new Uri(CollectionUrl), new WindowsCredential(new NetworkCredential(UserName, Password))); } else if (UserName != "" && Password != "" && UserDomain != "") { VSConnection = new VssConnection(new Uri(CollectionUrl), new WindowsCredential(new NetworkCredential(UserName, Password, UserDomain))); } else if (UserName == "" && Password != "") { VSConnection = new VssConnection(new Uri(CollectionUrl), new VssBasicCredential(string.Empty, Password)); //PAT } if (VSConnection != null) { VSConnection.ConnectAsync().SyncResult(); WitClient = VSConnection.GetClient <WorkItemTrackingHttpClient>(); Connected = true; } } catch (Exception ex) { Connected = false; string message = ex.Message + ((ex.InnerException != null) ? "\n" + ex.InnerException.Message : ""); Exceptions += message; } }
private WorkItem UpdateField(string fieldName, string fieldValue) { var cred = new VssBasicCredential(string.Empty, "uq74dz3l5upjjnv6fzuy2tl4kv44afjyx3kz7elp3nb3im2vipxa"); using (var conn = new VssConnection(new Uri("https://dev.azure.com/marketingops"), cred)) using (var client = conn.GetClient<WorkItemTrackingHttpClient>()) { WorkItem workItemResult = null; try { // stay synchronous for now. workItemResult = client.UpdateWorkItemAsync(GetDoc(fieldName, fieldValue), 226552, bypassRules: true).Result; } catch (Exception ex) { Console.Error.WriteLine($"Error:{ex.Message}"); } if (workItemResult != null) Console.WriteLine("update succeeded"); return workItemResult; } }
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 override void Generate(VssConnection connection) { var witClient = connection.GetClient <WorkItemTrackingProcessHttpClient>(); var states = witClient.GetStateDefinitionsAsync(_process.TypeId, WorkItemTypeName).SyncResult(); //workItemType expand states if (!System.IO.Directory.Exists(BaseFolder)) { System.IO.Directory.CreateDirectory(BaseFolder); } var statesDefinition = new List <Models.WorkItemTypeState>(); foreach (var state in states) { var definition = ConvertObject <Models.WorkItemTypeState>(state); statesDefinition.Add(definition); } var definitionString = JsonConvert.SerializeObject(statesDefinition, Formatting.Indented); var fileName = string.Concat("workitemtypestates.", WorkItemTypeName.Replace('\\', '_').Replace('/', '_'), ".json"); System.IO.File.WriteAllText(System.IO.Path.Combine(BaseFolder, fileName), definitionString); }
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 IEnumerable <GitPush> ListPushesIntoMaster(string projectName, string repoName) { VssConnection connection = this.Connection; GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); var repo = gitClient.GetRepositoryAsync(projectName, repoName).Result; List <GitPush> pushes = gitClient.GetPushesAsync( repo.Id, searchCriteria: new GitPushSearchCriteria() { IncludeRefUpdates = true, RefName = "refs/heads/master", }).Result; Console.WriteLine("project {0}, repo {1}", projectName, repo.Name); foreach (GitPush push in pushes) { Console.WriteLine("push {0} by {1} on {2}", push.PushId, push.PushedBy.DisplayName, push.Date); } return(pushes); }
/// <summary> /// Creates a TFS Work Item /// </summary> /// <param name="item">TFS Item with fields filled out.</param> /// <returns>The created Work Item</returns> public TFS_API.WorkItem CreateWorkItem(TFS_Item item) { JsonPatchDocument patchDocument = GeneratePatchDocument(item); VssConnection connection = new VssConnection(_uri, _credentials); WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>(); try { string workItemType = item.WorkItemType == Enums.WorkItemType.UserStory ? "User Story" : item.WorkItemType.ToString(); TFS_API.WorkItem result = workItemTrackingHttpClient.CreateWorkItemAsync(patchDocument, _project, workItemType).Result; Console.WriteLine($"{item.WorkItemType} Successfully Created: {item.WorkItemType} #{0}", result.Id); return(result); } catch (AggregateException ex) { Console.WriteLine($"Error creating {item.WorkItemType}: {ex.InnerException.Message}"); return(null); } catch (Exception) { throw; } }
public async Task ConnectAsync(VssConnection jobConnection) { _connection = jobConnection; int attemptCount = 5; while (!_connection.HasAuthenticated && attemptCount-- > 0) { try { await _connection.ConnectAsync(); break; } catch (Exception ex) when(attemptCount > 0) { Trace.Info($"Catch exception during connect. {attemptCount} attemp left."); Trace.Error(ex); } await Task.Delay(100); } _buildHttpClient = _connection.GetClient <Build2.BuildHttpClient>(); }
public async Task ConnectAsync(Uri serverUrl, VssCredentials credentials) { // Establish the first connection before doing the rest in parallel to eliminate the redundant 401s. // issue: https://github.com/microsoft/azure-pipelines-agent/issues/3149 Task <VssConnection> task1 = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(100)); _genericConnection = await task1; Task <VssConnection> task2 = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60)); Task <VssConnection> task3 = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60)); await Task.WhenAll(task2, task3); _messageConnection = task2.Result; _requestConnection = task3.Result; _genericTaskAgentClient = _genericConnection.GetClient <TaskAgentHttpClient>(); _messageTaskAgentClient = _messageConnection.GetClient <TaskAgentHttpClient>(); _requestTaskAgentClient = _requestConnection.GetClient <TaskAgentHttpClient>(); _hasGenericConnection = true; _hasMessageConnection = true; _hasRequestConnection = true; }
public WebApiRelease 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; Console.WriteLine("{0} {1}", releaseEnvironment.Id.ToString().PadLeft(6), releaseEnvironment.Name); return(release); }
public AttachmentReference UploadTextFile() { // Full path to the text file to upload as an attachment string filePath = ClientSampleHelpers.GetSampleTextFile(); // Get a client VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); Console.WriteLine("Attempting upload of: {0}", filePath); // Upload the attachment AttachmentReference attachment = workItemTrackingClient.CreateAttachmentAsync(@filePath).Result; Console.WriteLine("Attachment created"); Console.WriteLine(" ID : {0}", attachment.Id); Console.WriteLine(" URL : {0}", attachment.Url); // Save the attachment ID for the "download" sample call later Context.SetValue <Guid>("$attachmentId", attachment.Id); Context.SetValue <string>("$attachmentFileName", Path.GetFileName(filePath)); return(attachment); }
public WorkItemQueryResult QueryWorkItems() { string pat = _options.Value.ADO_Pat; string org = _options.Value.ADO_Org; string project = _options.Value.ADO_Project; Uri baseUri = new Uri("https://dev.azure.com/" + org); VssCredentials clientCredentials = new VssCredentials(new VssBasicCredential("username", pat)); VssConnection connection = new VssConnection(baseUri, clientCredentials); WorkItemTrackingHttpClient client = connection.GetClient <WorkItemTrackingHttpClient>(); WorkItemQueryResult result = null; Wiql wiql = new Wiql() { Query = "SELECT [System.Id], [System.Title], [System.State] FROM workitems WHERE [System.TeamProject] = @project AND [System.WorkItemType] = 'Issue' AND [System.State] <> 'Done' AND [System.Tags] CONTAINS 'GitHub Issue' AND [System.BoardColumn] = 'To Do'" }; try { result = client.QueryByWiqlAsync(wiql, project).Result; } catch (Exception) { result = null; } finally { clientCredentials = null; connection = null; client = null; } return(result); }
public FileContainerServer( VssConnection connection, Guid projectId, long containerId, string containerPath) { ArgUtil.NotNull(connection, nameof(connection)); _projectId = projectId; _containerId = containerId; _containerPath = containerPath; // default file upload request timeout to 600 seconds var fileContainerClientConnectionSetting = connection.Settings.Clone(); if (fileContainerClientConnectionSetting.SendTimeout < TimeSpan.FromSeconds(600)) { fileContainerClientConnectionSetting.SendTimeout = TimeSpan.FromSeconds(600); } var fileContainerClientConnection = new VssConnection(connection.Uri, connection.Credentials, fileContainerClientConnectionSetting); _fileContainerHttpClient = fileContainerClientConnection.GetClient <FileContainerHttpClient>(); }
public IEnumerable <ServiceEndpointType> ListEndpointTypes() { // Get a service endpoint client instance VssConnection connection = Context.Connection; ServiceEndpointHttpClient endpointClient = connection.GetClient <ServiceEndpointHttpClient>(); // Get a list of all available service endpoint types List <ServiceEndpointType> types = endpointClient.GetServiceEndpointTypesAsync().Result; // Show details about each type in the console foreach (ServiceEndpointType t in types) { Context.Log(t.Name); Context.Log("Inputs:"); foreach (InputDescriptor input in t.InputDescriptors) { Context.Log("- {0}", input.Id); } Context.Log("Schemes:"); foreach (ServiceEndpointAuthenticationScheme scheme in t.AuthenticationSchemes) { Context.Log("- {0}", scheme.Scheme); Context.Log(" Inputs:"); foreach (InputDescriptor input in scheme.InputDescriptors) { Context.Log(" - {0}", input.Id); } } Context.Log("================================"); } return(types); }
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; Console.WriteLine("{0} {1} {2}", updatedReleaseDefinition.Id.ToString().PadLeft(6), updatedReleaseDefinition.Revision, updatedReleaseDefinition.ModifiedOn); return(releaseDefinition); }
public WorkItem GetWorkItemFullyExpanded() { int id = 5; VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); WorkItem workitem = workItemTrackingClient.GetWorkItemAsync(id, expand: WorkItemExpand.All).Result; Console.WriteLine(workitem.Id); Console.WriteLine("Fields: "); foreach (var field in workitem.Fields) { Console.WriteLine(" {0}: {1}", field.Key, field.Value); } Console.WriteLine("Relations: "); foreach (var relation in workitem.Relations) { Console.WriteLine(" {0} {1}", relation.Rel, relation.Url); } return(workitem); }
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 static void CreateAreaPath(string areaPath, string uri, Guid projectGUID, string PAT) { try { var node = new Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItemClassificationNode(); node.StructureType = Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.TreeNodeStructureType.Area; string areaName = areaPath.Substring(areaPath.LastIndexOf('\\') + 1); string pathToParentNode = areaPath.Substring(areaPath.IndexOf('\\') + 1, areaPath.LastIndexOf('\\') - areaPath.IndexOf('\\')); node.Name = areaName; VssConnection connection = new VssConnection(new Uri(uri), new VssBasicCredential(string.Empty, PAT)); var client = connection.GetClient <WorkItemTrackingHttpClient>(); var result = client.CreateOrUpdateClassificationNodeAsync(node, projectGUID, Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.TreeStructureGroup.Areas, pathToParentNode).Result; } catch (AggregateException ex) { } catch (Exception ex) { MyLogger.Log("Error in AreaPath Creation : " + areaPath); throw; } }
public string Authenticate(string project = "Sda.Afs") { //string project = VSTSContext.Instance.Project; // create a query to get your list of work items needed Wiql wiql = new Wiql() { Query = "Select [State], [Title] " + "From WorkItems " + "Where [Work Item Type] = 'Bug' " + "And [System.TeamProject] = '" + project + "' " + "And [System.State] = 'New' " + "Order By [State] Asc, [Changed Date] Desc" }; //VssConnection connection = new VssConnection(new Uri(VSTSContext.Instance.UriString), // new VssBasicCredential(VSTSContext.Instance.UserName, // VSTSContext.Instance.Password)); VssConnection connection = new VssConnection(new Uri(VSTSContext.Instance.UriString), new VssBasicCredential(VSTSContext.Instance.UserName, VSTSContext.Instance.Password)); WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>(); WorkItemQueryResult workItemQueryResult; try { // execute the query workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result; } catch (Exception e) { return(e.Message); } return("Success"); }
public async Task ConnectAsync(VssConnection jobConnection) { _connection = jobConnection; if (!_connection.HasAuthenticated) { await _connection.ConnectAsync(); } _taskClient = _connection.GetClient<TaskHttpClient>(); _taskAgentClient = _connection.GetClient<TaskAgentHttpClient>(); _hasConnection = true; }