public static async Task <VssConnection> GetVssConnectionAsync(Uri uri, string accessToken, DelegatingHandler retryOnTimeoutMessageHandler = null) { VssConnection connection; if (!_vssConnections.TryGetValue(uri, out connection)) { VssClientCredentials cred = GetCredentials(accessToken); VssClientHttpRequestSettings settings = VssClientHttpRequestSettings.Default.Clone(); if (settings.SendTimeout < _minTimeout) { settings.SendTimeout = _minTimeout; } VssHttpMessageHandler innerHandler = new VssHttpMessageHandler(cred, settings); DelegatingHandler[] handlers = new DelegatingHandler[] { retryOnTimeoutMessageHandler }; connection = new VssConnection(uri, innerHandler, handlers); await connection.ConnectAsync().ConfigureAwait(false); if (!_vssConnections.TryAdd(uri, connection)) { // first writer wins. Every caller returned the same instance. connection = _vssConnections[uri]; } } return(connection); }
public VssConnection( Uri baseUrl, VssHttpMessageHandler innerHandler, IEnumerable <DelegatingHandler> delegatingHandlers) : this(baseUrl, innerHandler, delegatingHandlers, true) { }
private void CreateConnection() { VssHttpMessageHandler vssHandler = new VssHttpMessageHandler( Credentials, VssClientHttpRequestSettings.Default.Clone()); connection = new VssConnection( Url, vssHandler, Array.Empty <DelegatingHandler>()); }
static void Main(string[] args) { var credentials = new VssAadCredential(); var messageHandler = new VssHttpMessageHandler(credentials, new VssHttpRequestSettings()); Uri uri = new Uri(@"https://microsoft.visualstudio.com/"); GitHttpClient gitHttpClient = new GitHttpClient(uri, messageHandler.Credentials); var Repositories = gitHttpClient.GetRepositoriesAsync().Result; GitRepository repository = Repositories.FirstOrDefault(r => r.Name.ToLowerInvariant() == "Localization".ToLowerInvariant()); var gitBranchStatuss = gitHttpClient.GetBranchesAsync(repository.Id).Result; GitBranchStats gitBranchStatus = gitBranchStatuss.FirstOrDefault(branch => branch.Name.ToLowerInvariant() == "master"); var descriptor = new GitVersionDescriptor() { Version = gitBranchStatus.Name, VersionOptions = GitVersionOptions.None, VersionType = GitVersionType.Branch }; //GitItem item = gitHttpClient.GetItemAsync(repositoryId: repository.Id, path: "/intl/af-za/loc/windows/lcl/aad/brokerplugin/microsoft.aad.brokerplugin.dll.lcl", scopePath: "/intl/af-za/loc/windows/lcl/aad/brokerplugin/microsoft.aad.brokerplugin.dll.lcl", recursionLevel: VersionControlRecursionType.OneLevel, includeContentMetadata: true, latestProcessedChange: true, download: true, versionDescriptor: descriptor, userState: null, cancellationToken: new CancellationToken()).Result; VersionControlProjectInfo vvvvvv = new VersionControlProjectInfo(); List <GitItem> items = gitHttpClient.GetItemsAsync(repositoryId: repository.Id, scopePath: "/intl/af-za/loc/windows/lcl/aad/brokerplugin/microsoft.aad.brokerplugin.dll.lcl", recursionLevel: VersionControlRecursionType.OneLevel, includeContentMetadata: true, latestProcessedChange: true, download: true, includeLinks: false, versionDescriptor: descriptor, userState: null, cancellationToken: new CancellationToken()).Result; List <GitCommitRef> aaaa = gitHttpClient.GetCommitsAsync(repositoryId: repository.Id, searchCriteria: new GitQueryCommitsCriteria(), skip: null, top: null, userState: null, cancellationToken: new CancellationToken()).Result; GitCommitChanges gitCommitChanges = gitHttpClient.GetChangesAsync(items[0].CommitId, repositoryId: repository.Id, top: null, skip: null, userState: null, cancellationToken: new CancellationToken()).Result; Stream ssss = gitHttpClient.GetItemContentAsync(repositoryId: repository.Id, path: items[0].Path, recursionLevel: VersionControlRecursionType.None, includeContentMetadata: true, latestProcessedChange: true, download: true, versionDescriptor: descriptor, userState: null, cancellationToken: new CancellationToken()).Result; using (MemoryStream memoryStream = new MemoryStream()) { ssss.CopyTo(memoryStream); // Use StreamReader to read MemoryStream created from byte array using (StreamReader streamReader = new StreamReader(new MemoryStream(memoryStream.ToArray()))) { string fileString = streamReader.ReadToEnd(); } } }
private void InternalDownloadReport(string tfsUri, string reportUrl, string reportDestinationPath, ILogger logger) { VssHttpMessageHandler vssHttpMessageHandler = GetHttpHandler(tfsUri, logger); HttpClient httpClient = new HttpClient(vssHttpMessageHandler); logger.LogInfo(Resources.DOWN_DIAG_DownloadCoverageReportFromTo, reportUrl, reportDestinationPath); using (HttpResponseMessage response = httpClient.GetAsync(reportUrl).Result) { if (response.IsSuccessStatusCode) { using (FileStream fileStream = new FileStream(reportDestinationPath, FileMode.Create, FileAccess.Write)) { response.Content.CopyToAsync(fileStream).Wait(); } } } }
private VssConnection( Uri baseUrl, VssHttpMessageHandler innerHandler, IEnumerable <DelegatingHandler> delegatingHandlers, Boolean allowUnattributedClients) { ArgumentUtility.CheckForNull(baseUrl, "baseUrl"); ArgumentUtility.CheckForNull(innerHandler, "innerHandler"); // Permit delegatingHandlers to be null m_delegatingHandlers = delegatingHandlers = delegatingHandlers ?? Enumerable.Empty <DelegatingHandler>(); m_baseUrl = baseUrl; m_innerHandler = innerHandler; m_allowUnattributedClients = allowUnattributedClients; // Do we need to add a retry handler to the pipeline? If so, it needs to come last. if (this.Settings.MaxRetryRequest > 0) { delegatingHandlers = delegatingHandlers.Concat(new DelegatingHandler[] { new VssHttpRetryMessageHandler(this.Settings.MaxRetryRequest) }); } // Create and persist the pipeline. if (delegatingHandlers.Any()) { m_pipeline = HttpClientFactory.CreatePipeline(m_innerHandler, delegatingHandlers); } else { m_pipeline = m_innerHandler; } m_serverDataProvider = new VssServerDataProvider(this, m_pipeline, m_baseUrl.AbsoluteUri); if (innerHandler.Credentials != null) { // store base url on credentials, as it is required when creating a token storage key. if (innerHandler.Credentials.Federated != null) { innerHandler.Credentials.Federated.TokenStorageUrl = baseUrl; } } }
private async Task <VssConnection> ConnectToAzureDevOpsAsync(WorkItemEventContext eventContext, VssCredentials clientCredentials, CancellationToken cancellationToken) { // see https://docs.microsoft.com/en-us/azure/devops/integrate/concepts/rate-limits#api-client-experience var policy = Policy .Handle <HttpRequestException>() // https://github.com/App-vNext/Polly/wiki/Retry#retryafter-when-the-response-specifies-how-long-to-wait .OrResult <HttpResponseMessage>(r => r.StatusCode == (HttpStatusCode)429) .WaitAndRetryAsync( retryCount: MaxRetries, sleepDurationProvider: (retryCount, response, context) => { return(response.Result?.Headers.RetryAfter.Delta.Value ?? TimeSpan.FromSeconds(BaseRetryInterval * retryCount)); }, #pragma warning disable CS1998 onRetryAsync: async(response, timespan, retryCount, context) => { logger.WriteInfo($"{Environment.NewLine}Waiting {timespan} before retrying (attemp #{retryCount}/{MaxRetries})..."); } #pragma warning restore CS1998 ); var handler = new PolicyHttpMessageHandler(policy); var vssHandler = new VssHttpMessageHandler(clientCredentials, VssClientHttpRequestSettings.Default.Clone()); var devops = new VssConnection(eventContext.CollectionUri, vssHandler, new DelegatingHandler[] { handler }); try { await devops.ConnectAsync(cancellationToken); logger.WriteInfo($"Connected to Azure DevOps"); } catch (System.Exception ex) { logger.WriteError(ex.Message); if (ex.InnerException != null) { logger.WriteError(ex.InnerException.Message); } throw; } return(devops); }
private AzureContext Initialise(string defaultProjectName) { if (isInitialsed) { return(this); } AzureHttpLogger loggerHandler = new AzureHttpLogger(); VssHttpMessageHandler vssHandler = new VssHttpMessageHandler( Credentials, VssClientHttpRequestSettings.Default.Clone()); this.Connection = new AzureConnection( this.AzureProjectUrl, vssHandler, new DelegatingHandler[] { loggerHandler }); //* Establishing connection, which may fail also :) this.Connection.ConnectAsync().SyncResult(); #region Configuring for project TeamProjectReference defaultProject = this.FindProject(defaultProjectName); if (defaultProject == null) { throw new Exception(string.Format("Failed to initised - Missing project '{0}'", defaultProjectName)); } SetValue("$defautProject", defaultProject); SetValue("$allAssignToUsers", this.GetAllTeamMembers().Select(item => item.Identity.DisplayName).ToArray()); #endregion isInitialsed = true; return(this); }
private VssHttpMessageHandler GetHttpHandler(string tfsUri) { VssCredentials vssCreds; var tfsCollectionUri = new Uri(tfsUri); using (var collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsCollectionUri)) { // Build agents run non-attended and most often non-interactive so make sure not to create a credential prompt collection.ClientCredentials.AllowInteractive = false; collection.EnsureAuthenticated(); this.logger.LogInfo(Resources.DOWN_DIAG_ConnectedToTFS, tfsUri); // We need VSS credentials that encapsulate all types of credentials (NetworkCredentials for TFS, OAuth for VSO) var connection = collection as TfsConnection; vssCreds = TfsClientCredentialsConverter.ConvertToVssCredentials(connection.ClientCredentials, tfsCollectionUri); } Debug.Assert(vssCreds != null, "Not expecting ConvertToVssCredentials "); var vssHttpMessageHandler = new VssHttpMessageHandler(vssCreds, new VssHttpRequestSettings()); return(vssHttpMessageHandler); }
private static async Task TestRetry(string collectionUrl, string devOpsToken, int worktItemId, CancellationToken cancellationToken) { // see https://docs.microsoft.com/en-us/azure/devops/integrate/concepts/rate-limits#api-client-experience int MaxRetries = 3; var policy = Policy .Handle <HttpRequestException>() // https://github.com/App-vNext/Polly/wiki/Retry#retryafter-when-the-response-specifies-how-long-to-wait .OrResult <HttpResponseMessage>(r => r.StatusCode == (HttpStatusCode)429) .WaitAndRetryAsync( retryCount: MaxRetries, sleepDurationProvider: (retryCount, response, context) => { return(response.Result?.Headers.RetryAfter.Delta.Value ?? TimeSpan.FromSeconds(30 * retryCount)); }, onRetryAsync: async(response, timespan, retryCount, context) => { await Console.Out.WriteLineAsync($"{Environment.NewLine}Waiting {timespan} before retrying (attemp #{retryCount}/{MaxRetries})..."); } ); var handler = new PolicyHttpMessageHandler(policy); var clientCredentials = new VssBasicCredential("", devOpsToken); var vssHandler = new VssHttpMessageHandler(clientCredentials, VssClientHttpRequestSettings.Default.Clone()); using var devops = new VssConnection(new Uri(collectionUrl), vssHandler, new DelegatingHandler[] { handler }); await devops.ConnectAsync(cancellationToken); using var witClient = await devops.GetClientAsync <WorkItemTrackingHttpClient>(cancellationToken); for (int i = 0; i < 10; i++) { _ = await witClient.GetWorkItemAsync(worktItemId); Console.Write('+'); } devops.Disconnect(); }
private VssHttpMessageHandler GetHttpHandler(string tfsUri, ILogger logger) { VssCredentials vssCreds = null; Uri tfsCollectionUri = new Uri(tfsUri); using (TfsTeamProjectCollection collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsCollectionUri)) { // Build agents run non-attended and most often non-interactive so make sure not to create a credential prompt collection.ClientCredentials.AllowInteractive = false; collection.EnsureAuthenticated(); logger.LogInfo(Resources.DOWN_DIAG_ConnectedToTFS, tfsUri); // We need VSS credentials that encapsulate all types of credentials (NetworkCredentials for TFS, OAuth for VSO) TfsConnection connection = collection as TfsConnection; vssCreds = connection.ClientCredentials.ConvertToVssCredentials(tfsCollectionUri); } Debug.Assert(vssCreds != null, "Not expecting ConvertToVssCredentials "); VssHttpMessageHandler vssHttpMessageHandler = new VssHttpMessageHandler(vssCreds, new VssHttpRequestSettings()); return vssHttpMessageHandler; }
public AzureConnection(Uri baseUrl, VssHttpMessageHandler innerHandler, IEnumerable <DelegatingHandler> delegatingHandlers) : base(baseUrl, innerHandler, delegatingHandlers) { }