static void Main(string[] args)
        {
            const String c_collectionUri = "https://dev.azure.com/microsoft";
            const String c_projectName   = "Edge";
            const String c_repoName      = "chromium.src";

            // Interactively ask the user for credentials, caching them so the user isn't constantly prompted
            VssCredentials creds = new VssClientCredentials();

            creds.Storage = new VssClientCredentialStorage();

            // Connect to Azure DevOps Services
            VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);

            // Get a GitHttpClient to talk to the Git endpoints
            GitHttpClient gitClient = connection.GetClient <GitHttpClient>();

            // Get data about a specific repository
            var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).Result;

            // Create instance of WorkItemTrackingHttpClient using VssConnection
            WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>();

            // Get 2 levels of query hierarchy items
            List <QueryHierarchyItem> queryHierarchyItems = witClient.GetQueriesAsync(c_projectName, depth: 2).Result;

            // Search for 'My Queries' folder
            QueryHierarchyItem myQueriesFolder = queryHierarchyItems.FirstOrDefault(qhi => qhi.Name.Equals("My Queries"));

            if (myQueriesFolder != null)
            {
                var foo = "Skippy";
            }
        }
Esempio n. 2
0
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            ArgUtil.NotNull(context, nameof(context));
            Tracing trace = context.GetTrace(nameof(AlternateCredential));

            trace.Info(nameof(GetVssCredentials));

            string username;

            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.UserName, out username))
            {
                username = null;
            }

            string password;

            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Password, out password))
            {
                password = null;
            }

            ArgUtil.NotNull(username, nameof(username));
            ArgUtil.NotNull(password, nameof(password));

            trace.Info("username retrieved: {0} chars", username.Length);
            trace.Info("password retrieved: {0} chars", password.Length);

            VssBasicCredential loginCred = new VssBasicCredential(username, password);
            VssCredentials     creds     = new VssClientCredentials(loginCred);

            trace.Verbose("cred created");

            return(creds);
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            Uri            serverUrl   = new Uri(vstsUrl);
            VssCredentials credentials = new VssClientCredentials();

            credentials.Storage = new VssClientCredentialStorage();

            VssConnection connection = new VssConnection(serverUrl, credentials);

            WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>();

            JsonPatchDocument patchDocument = new JsonPatchDocument();

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.Tags",
                Value     = "tag1"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.Title",
                Value     = "Sample task  with tags"
            }
                );

            var newWorkItem = workItemTrackingClient.CreateWorkItemAsync(patchDocument, "MyAgile2", "Task").Result;
        }
Esempio n. 4
0
 public bool Authenticate(string url, string userId, string password, string domain)
 {
     try
     {
         NetworkCredential credential = new NetworkCredential(userId, password, domain);
         WindowsCredential winCred    = new WindowsCredential(credential);
         VssCredentials    vssCred    = new VssClientCredentials(winCred)
         {
             PromptType = CredentialPromptType.DoNotPrompt
         };
         using (TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(url), vssCred))
         {
             tpc.EnsureAuthenticated();
             return(true);
         }
     }
     catch (TeamFoundationServiceUnavailableException ex)
     {
         logger.Error(ex, "Service not available");
         throw new ServiceUnavailableException(url, "Service not Available", ex);
     }
     catch (TeamFoundationServerUnauthorizedException ex)
     {
         logger.Error(ex, "Authentication Failure.");
         throw new TFSAuthenticationException("Authentication Failure.", ex);
     }
     catch (Exception ex)
     {
         logger.Error(ex, "Authentication Failure.");
         throw;
     }
 }
Esempio n. 5
0
        static void Main(string[] args)
        {
            var myCredentials = new VssClientCredentials();
            var connection    = new VssConnection(new Uri(@"http://server:8080/tfs/DefaultCollection"), myCredentials);
            WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>();
            int workitemid = 112;
            JsonPatchDocument patchDocument = new JsonPatchDocument();

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Test,
                Path      = "/rev",
                Value     = "6"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.AssignedTo",
                Value     = "Domain\\user"
            }
                );

            Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, workitemid).Result;
        }
Esempio n. 6
0
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            Tracing trace = context.GetTrace("PersonalAccessToken");

            trace.Info("GetVssCredentials()");

            if (CredentialData == null || !CredentialData.Data.ContainsKey("token"))
            {
                throw new InvalidOperationException("Must call ReadCredential first.");
            }

            string username = CredentialData.Data["Username"];

            trace.Info("username retrieved: {0} chars", username.Length);

            string password = CredentialData.Data["Password"];

            trace.Info("password retrieved: {0} chars", password.Length);

            // PAT uses a basic credential
            VssBasicCredential loginCred = new VssBasicCredential(username, password);
            VssCredentials     creds     = new VssClientCredentials(loginCred);

            trace.Verbose("cred created");

            return(creds);
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            var vssClientCredentials = new VssClientCredentials();

            vssClientCredentials.Storage = new VssClientCredentialStorage();

            VssConnection connection = new VssConnection(new Uri("https://reeferwatch.visualstudio.com"), vssClientCredentials);

            connection.ConnectAsync().Wait();

            var projectHttpClient = connection.GetClient <ProjectHttpClient>();
            var projects          = projectHttpClient.GetProjects().Result;
            var project           = projects.First();

            var buildHttpClient  = connection.GetClient <BuildHttpClient>();
            var buildDefinitions = buildHttpClient.GetDefinitionsAsync(project.Id).Result;

            System.Console.WriteLine($"{buildDefinitions.Count} builds in {project.Name}");

            foreach (var definitionReference in buildDefinitions)
            {
                var builds = buildHttpClient.GetBuildsAsync(project.Id, new[] { definitionReference.Id }).Result;
                System.Console.WriteLine($"{definitionReference.Name}: {string.Join(",", builds.Take(5).Select(x => x.Result.ToString()))}");
            }

            System.Console.ReadLine();
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            Console.WriteLine("Server URL");
            serverUrl = Console.ReadLine();

            Console.WriteLine("Collection URL");
            collectionUrl = Console.ReadLine();

            Console.WriteLine("Type 1 to list permissions, Type 2 to list and remove permissions");
            string option = Console.ReadLine();

            VssCredentials creds = new VssClientCredentials();

            creds.Storage = new VssClientCredentialStorage();

            connection = new VssConnection(new Uri(collectionUrl), creds);

            if (option.Equals("1"))
            {
                ListGitNamespacePermissions();
            }
            else if (option.Equals("2"))
            {
                ListAndRemoveGitNamespacePermissions();
            }
        }
Esempio n. 9
0
        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);

                DelegatingHandler[] handlers = new DelegatingHandler[]
                {
                    retryOnTimeoutMessageHandler
                };

                connection = ApiUtil.CreateConnection(uri, cred, handlers);
                connection.Settings.SendTimeout = TimeSpan.FromSeconds(Math.Max(_minTimeout.TotalSeconds, connection.Settings.SendTimeout.TotalSeconds));
                await connection.ConnectAsync().ConfigureAwait(false);

                if (!_vssConnections.TryAdd(uri, connection))
                {
                    // first writer wins. Every caller returned the same instance.
                    connection = _vssConnections[uri];
                }
            }

            return(connection);
        }
Esempio n. 10
0
        public async static void UpdateAllBuildDefinitionRetention()
        {
            var tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(collectionUrl));
            var bhc = tpc.GetClient <BuildHttpClient>();

            VssCredentials creds = new VssClientCredentials();

            creds.Storage = new VssClientCredentialStorage();
            connection    = new VssConnection(new Uri(collectionUrl), creds);
            ProjectHttpClient projectClient = connection.GetClient <ProjectHttpClient>();

            List <BuildDefinitionReference> buildDefinitions = new List <BuildDefinitionReference>();


            // Call to get the list of projects
            IEnumerable <TeamProjectReference> projects = projectClient.GetProjects(top: 1000).Result;

            foreach (var project in projects)
            {
                // Iterate (as needed) to get the full set of build definitions
                string continuationToken = null;
                do
                {
                    IPagedList <BuildDefinitionReference> buildDefinitionsPage = bhc.GetDefinitionsAsync2(
                        project: project.Name,
                        continuationToken: continuationToken).Result;

                    buildDefinitions.AddRange(buildDefinitionsPage);

                    continuationToken = buildDefinitionsPage.ContinuationToken;
                } while (!String.IsNullOrEmpty(continuationToken));
            }

            try
            {
                foreach (BuildDefinitionReference definition in buildDefinitions)
                {
                    string teamProject    = definition.Project.Name;
                    string definitionName = definition.Name;
                    int    definitionId   = definition.Id;
                    try
                    {
                        BuildDefinition buildDefTemplate = (await bhc.GetDefinitionAsync(teamProject, definitionId));
                        buildDefTemplate.RetentionRules[0].ArtifactsToDelete.Clear();
                        await bhc.UpdateDefinitionAsync(buildDefTemplate, teamProject);

                        Console.WriteLine("Completed - " + "Project Name: " + teamProject + "  - Build Definition Name: " + definitionName);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error - " + "Project Name: " + teamProject + "  - Build Definition Name: " + definitionName + "Error Msg: " + ex.Message);
                    }
                }
                Console.Write("UPDATE COMPLETED");
            }
            catch (Exception ex)
            {
                string exception = ex.ToString();
            }
        }
Esempio n. 11
0
        public static void LookupBranchesOnline() //Dictionary<string, string>
        {
            Uri tfsUri = new Uri(AppUtils.GetAppSetting <string>("TFPath"));
            //var vssCredentials = new VssCredentials("", );
            NetworkCredential netCred = new NetworkCredential(@"DOMAIN\user.name", @"Password1");
            var            winCred    = new Microsoft.VisualStudio.Services.Common.WindowsCredential(netCred);
            VssCredentials vssCred    = new VssClientCredentials(winCred);

            // Bonus - if you want to remain in control when
            // credentials are wrong, set 'CredentialPromptType.DoNotPrompt'.
            // This will thrown exception 'TFS30063' (without hanging!).
            // Then you can handle accordingly.
            vssCred.PromptType = CredentialPromptType.DoNotPrompt;

            // Now you can connect to TFS passing Uri and VssCredentials instances as parameters

            var tfsTeamProjectCollection = new TfsTeamProjectCollection(tfsUri, vssCred);

            // Finally, to make sure you are authenticated...
            tfsTeamProjectCollection.EnsureAuthenticated();

            var tfs      = new TfsTeamProjectCollection(tfsUri);
            var identity = tfs.AuthorizedIdentity;

            tfs.Authenticate();
            var versionControlServer = tfs.GetService <VersionControlServer>();
            var workspaces           = versionControlServer.QueryWorkspaces(null, null, null, WorkspacePermissions.NoneOrNotSupported);

            foreach (var ws in workspaces)
            {
                string comment = ws.Comment;
            }
        }
Esempio n. 12
0
        public async Task <IDictionary <string, string> > GetReleaseEnvironmentVariables(
            string projectId,
            string releaseDefinitionName,
            string environmentName)
        {
            if (string.IsNullOrWhiteSpace(projectId))
            {
                throw new ArgumentNullException(nameof(projectId));
            }

            if (string.IsNullOrWhiteSpace(releaseDefinitionName))
            {
                throw new ArgumentNullException(nameof(releaseDefinitionName));
            }

            if (string.IsNullOrWhiteSpace(environmentName))
            {
                throw new ArgumentNullException(nameof(environmentName));
            }

            var credentials = new VssClientCredentials
            {
                Storage = new VssClientCredentialStorage()
            };

            var connection = new VssConnection(this.tfsUri, credentials);

            var client = connection.GetClient <ReleaseHttpClient>();

            var releaseDefinitions = await client.GetReleaseDefinitionsAsync(
                projectId,
                searchText : null,
                expand : ReleaseDefinitionExpands.Environments | ReleaseDefinitionExpands.Variables);

            var releaseDefinition = releaseDefinitions.FirstOrDefault(r => r.Name == releaseDefinitionName);

            if (releaseDefinition == null)
            {
                throw new InvalidOperationException(
                          $"Release definition '{releaseDefinitionName}' not found in project '{projectId}'");
            }

            var environment = releaseDefinition.Environments.FirstOrDefault(e => e.Name == environmentName);

            if (environment == null)
            {
                throw new InvalidOperationException(
                          $"Release environment '{environmentName}' not found in release '{releaseDefinitionName}' in project '{projectId}'");
            }

            var releaseVariables = releaseDefinition.Variables.ToDictionary(
                kvp => kvp.Key,
                kvp => kvp.Value.Value);

            var environmentVariables = environment.Variables.ToDictionary(
                kvp => kvp.Key,
                kvp => kvp.Value.Value);

            return(releaseVariables.MergeLeft(environmentVariables));
        }
Esempio n. 13
0
        public virtual async Task SetUp()
        {
            var collectionUrl = Environment.GetEnvironmentVariable("WILINQ_TEST_TPCURL");

            if (string.IsNullOrWhiteSpace(collectionUrl))
            {
                throw new InvalidOperationException("Environment variable 'WILINQ_TEST_TPCURL' is missing");
            }
            var            personnalAccessToken = Environment.GetEnvironmentVariable("WILINQ_TEST_PAT");
            VssCredentials vssCredentials;

            if (string.IsNullOrWhiteSpace(personnalAccessToken))
            {
                vssCredentials = new VssClientCredentials
                {
                    Storage = new VssClientCredentialStorage()
                };
            }
            else
            {
                vssCredentials = new VssBasicCredential(string.Empty, personnalAccessToken);
            }

            var connection = new VssConnection(new Uri(collectionUrl), vssCredentials);

            await connection.ConnectAsync();

            Client = await connection.GetClientAsync <WorkItemTrackingHttpClient>();

            var projectHttpClient = await connection.GetClientAsync <ProjectHttpClient>();

            Project = await projectHttpClient.GetProject("WiLinqTestProject");

            TestSessionId = Guid.NewGuid().ToString();
        }
Esempio n. 14
0
        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);
        }
Esempio n. 15
0
    public WorkItemHandler()
    {
        XmlDocument doc = new XmlDocument();

        doc.Load("AzureDevops.xml");
        string azureDevOpsUrl = doc.DocumentElement.SelectSingleNode("/Data/Connection/Url").InnerText;

        project      = doc.DocumentElement.SelectSingleNode("/Data/Connection/Project").InnerText;
        areaPath     = doc.DocumentElement.SelectSingleNode("/Data/TestCase/AreaPath").InnerText;
        customFields = new List <KeyValuePair <string, string> >();
        XmlNodeList fieldList = doc.DocumentElement.SelectNodes("/Data/TestCase/CustomFields/CustomField");

        foreach (XmlNode field in fieldList)
        {
            customFields.Add(field.Attributes["id"].Value, field.Attributes["defaultvalue"].Value);
        }

        setup = new Setup();
        if (setup.IsTestAgentRun)
        {
            string accessToken = Environment.GetEnvironmentVariable("SYSTEM_ACCESSTOKEN");
            Assert.IsTrue(!string.IsNullOrEmpty(accessToken), "Cannot retrieve access token in pipeline");
            VssBasicCredential credentials = new VssBasicCredential("", accessToken);
            connection = new VssConnection(new Uri(azureDevOpsUrl), credentials);
        }
        else
        {
            VssClientCredentials credentials = new VssClientCredentials();
            connection = new VssConnection(new Uri(azureDevOpsUrl), credentials);
        }
        witClient = connection.GetClient <WorkItemTrackingHttpClient>();
    }
        public VstsClient(Uri projectUrl, string pat, VstsSettings settings)
        {
            if (projectUrl == null)
            {
                throw new ArgumentNullException("projectUrl");
            }

            if (projectUrl.LocalPath == "/")
            {
                throw new ArgumentException("Invalid URL: The URL must have the format: 'https://<account>.visualstudio.com/<project>'.", "projectUrl");
            }

            var urlWrapper = new UrlWrapper(projectUrl);

            _projectName = urlWrapper.ProjectName;
            var baseUrl = urlWrapper.ProjectCollectionUri;

            _settings = settings;

            VssCredentials credentials = string.IsNullOrEmpty(pat)
                ? credentials = new VssClientCredentials()
                : new VssBasicCredential(string.Empty, pat);

            var connection = new VssConnection(baseUrl, credentials);

            _client = connection.GetClient <WorkItemTrackingHttpClient>();
        }
Esempio n. 17
0
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            ArgUtil.NotNull(context, nameof(context));
            Tracing trace = context.GetTrace(nameof(PersonalAccessToken));

            trace.Info(nameof(GetVssCredentials));
            ArgUtil.NotNull(CredentialData, nameof(CredentialData));
            string token;

            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Token, out token))
            {
                token = null;
            }

            ArgUtil.NotNullOrEmpty(token, nameof(token));

            trace.Info("token retrieved: {0} chars", token.Length);

            // PAT uses a basic credential
            VssBasicCredential basicCred = new VssBasicCredential("VstsAgent", token);
            VssCredentials     creds     = new VssClientCredentials(basicCred);

            trace.Verbose("cred created");

            return(creds);
        }
Esempio n. 18
0
        public static void GetAllTeamProjects_Library()
        {
            // Interactively ask the user for credentials, caching them so the user isn't constantly prompted
            VssCredentials creds = new VssClientCredentials();

            creds.Storage = new VssClientCredentialStorage();

            // Connect to Azure DevOps Services
            connection = new VssConnection(new Uri(collectionUrl), creds);

            ProjectHttpClient projectClient = connection.GetClient <ProjectHttpClient>();

            IEnumerable <TeamProjectReference> projects = projectClient.GetProjects(top: 1000).Result;

            foreach (var project in projects)
            {
                try
                {
                    string projectName = project.Name.ToString();
                }
                catch (Exception ex)
                {
                }
            }
        }
Esempio n. 19
0
 public HttpClient BuildHttpClient()
 {
     VssCredentials credentials = new VssClientCredentials();
     credentials.Storage = new VssClientCredentialStorage("VssApp", "VisualStudio");
     HttpClient toReturn = new HttpClient(new VssHttpMessageHandler(credentials, new VssHttpRequestSettings()));
     toReturn.Timeout = TimeSpan.FromSeconds(30);
     toReturn.DefaultRequestHeaders.Add("User-Agent", userAgent);
     return toReturn;
 }
Esempio n. 20
0
        protected override TfsTeamProjectCollection GetTfsCredential(Uri uri)
        {
            var winCred = HasCredentials ?
                          new Microsoft.VisualStudio.Services.Common.WindowsCredential(GetCredential()) :
                          new Microsoft.VisualStudio.Services.Common.WindowsCredential(true);
            var vssCred = new VssClientCredentials(winCred);

            return(new TfsTeamProjectCollection(uri, vssCred));
        }
Esempio n. 21
0
        public AzureDevOpsAgent()
        {
            // Interactively ask the user for credentials, caching them so the user isn't constantly prompted
            VssCredentials creds = new VssClientCredentials();

            creds.Storage = new VssClientCredentialStorage();

            // Connect to Azure DevOps Services
            connection = new VssConnection(new Uri(c_collectionUri), creds);
        }
Esempio n. 22
0
        private static void Authenticate(TFSCredentials credentials)
        {
            NetworkCredential netCred = new NetworkCredential(credentials.username, credentials.password);

            Microsoft.VisualStudio.Services.Common.WindowsCredential winCred = new Microsoft.VisualStudio.Services.Common.WindowsCredential(netCred);
            VssCredentials vssCred = new VssClientCredentials(winCred);

            _tfs = new TfsTeamProjectCollection(new Uri("https://tfs.aurigo.com/tfs/DefaultCollection"), vssCred);
            _tfs.Authenticate();
        }
Esempio n. 23
0
        protected override TfsTeamProjectCollection GetTfsCredential(Uri uri)
        {
            var vssCred = HasCredentials
                ? new VssClientCredentials(new WindowsCredential(GetCredential()))
                : VssClientCredentials.LoadCachedCredentials(uri, false, CredentialPromptType.PromptIfNeeded);

            return(new TfsTeamProjectCollection(uri, vssCred));

#pragma warning restore 618
        }
        public WorkItemRevisionReplayMigrationContext(MigrationEngine me, WorkItemRevisionReplayMigrationConfig config)
            : base(me, config)
        {
            _config = config;
            PopulateIgnoreList();

            VssClientCredentials adoCreds = new VssClientCredentials();

            witClient = new WorkItemTrackingHttpClient(me.Target.Collection.Uri, adoCreds);
        }
Esempio n. 25
0
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            ArgUtil.NotNull(context, nameof(context));
            Tracing trace = context.GetTrace(nameof(NegotiateCredential));
            trace.Info(nameof(GetVssCredentials));
            ArgUtil.NotNull(CredentialData, nameof(CredentialData));

            // Get the user name from the credential data.
            string userName;
            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.UserName, out userName))
            {
                userName = null;
            }

            ArgUtil.NotNullOrEmpty(userName, nameof(userName));
            trace.Info("User name retrieved.");

            // Get the password from the credential data.
            string password;
            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Password, out password))
            {
                password = null;
            }

            ArgUtil.NotNullOrEmpty(password, nameof(password));
            trace.Info("Password retrieved.");

            // Get the URL from the credential data.
            string url;
            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Url, out url))
            {
                url = null;
            }

            ArgUtil.NotNullOrEmpty(url, nameof(url));
            trace.Info($"URL retrieved: {url}");

            // Create the Negotiate and NTLM credential object.
            var credential = new NetworkCredential(userName, password);
            var credentialCache = new CredentialCache();
            switch (Constants.Agent.Platform)
            {
                case Constants.OSPlatform.Linux:
                case Constants.OSPlatform.OSX:
                    credentialCache.Add(new Uri(url), "NTLM", credential);
                    break;
                case Constants.OSPlatform.Windows:
                    credentialCache.Add(new Uri(url), "Negotiate", credential);
                    break;
            }
            
            VssCredentials creds = new VssClientCredentials(new WindowsCredential(credentialCache));
            trace.Verbose("cred created");
            return creds;
        }
Esempio n. 26
0
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            Tracing trace = context.GetTrace("PersonalAccessToken");
            trace.Info("GetVssCredentials()");

            VssBasicCredential loginCred = new VssBasicCredential("test", "password");
            VssCredentials creds = new VssClientCredentials(loginCred);
            trace.Verbose("cred created");

            return creds;
        }        
Esempio n. 27
0
        public AzureDevOpsService(string organizationUrl, string username, string token, Guid projectId)
        {
            VssClientCredentials clientCredentials =
                new VssClientCredentials(new VssBasicCredential(username, token));

            OrganizationUrl = organizationUrl ?? throw new ArgumentNullException(nameof(organizationUrl));
            Username        = username ?? throw new ArgumentNullException(nameof(username));
            Token           = token ?? throw new ArgumentNullException(nameof(token));
            ProjectId       = projectId;
            Connection      = new VssConnection(new Uri(OrganizationUrl), clientCredentials);
        }
        public AzureDevOpsClient(string organizationName)
        {
            organizationName = organizationName.Trim();
            Endpoint         = new Uri(@"https://dev.azure.com/" + organizationName + "/");
            var creds = new VssClientCredentials(new WindowsCredential(false), new VssFederatedCredential(true), CredentialPromptType.PromptIfNeeded);

            azureDevopsConnection = new VssConnection(Endpoint, creds);
            azureDevopsConnection.ConnectAsync().Wait();

            buildClient   = azureDevopsConnection.GetClient <BuildHttpClient>();
            projectClient = azureDevopsConnection.GetClient <ProjectHttpClient>();
        }
Esempio n. 29
0
        private static void CreateAuthConnection(string VssAccountUrl)
        {
            // Create a connection to the specified account.
            // If you change the false to true, your credentials will be saved.
            var creds = new VssClientCredentials(true);

            vssConnection = new VssConnection(new Uri(VssAccountUrl), creds);

            // We need the clients for two services: Licensing and Identity
            licensingClient = vssConnection.GetClient <LicensingHttpClient>();
            identityClient  = vssConnection.GetClient <IdentityHttpClient>();
        }
        public AzureDevOpsClientContext(Uri url, VssCredentials credentials)
        {
            Url = url;

            if (credentials == null)
            {
                Credentials = new VssClientCredentials();
            }
            else
            {
                Credentials = credentials;
            }
        }
Esempio n. 31
0
        public void Connect(string serverName)
        {
            // Interactively ask the user for credentials, caching them so the user isn't constantly prompted
            VssCredentials creds = new VssClientCredentials();

            creds.Storage = new VssClientCredentialStorage();

            // Connect to Azure DevOps Services
            _connection = new VssConnection(new Uri(serverName), creds);
            _connection.ConnectAsync().SyncResult();

            Debug.WriteLine("Has authenticaed: " + _connection.HasAuthenticated);
        }
Esempio n. 32
0
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            Tracing trace = context.GetTrace("PersonalAccessToken");

            trace.Info("GetVssCredentials()");

            VssBasicCredential loginCred = new VssBasicCredential("test", "password");
            VssCredentials     creds     = new VssClientCredentials(loginCred);

            trace.Verbose("cred created");

            return(creds);
        }
Esempio n. 33
0
 /// <summary>
 /// Connects to the AzureDevOps server at the given url (e.g. https://myaccount.visualstudio.com)
 ///     If prompt is true, then we may prompt if needed - otherwise, we turn prompting off on credentials
 /// </summary>
 /// <param name="url">AzureDevOps URL to connect to</param>
 /// <param name="prompt">whether user should see any login prompts if needed</param>
 /// <returns></returns>
 internal Task ConnectToAzureDevOpsAccount(Uri url, CredentialPromptType prompt = CredentialPromptType.PromptIfNeeded)
 {
     lock (myLock)
     {
         // reset connection state
         Disconnect();
         var credentials = new VssClientCredentials(false);
         credentials.Storage    = new VssClientCredentialStorage();
         credentials.PromptType = prompt;
         _baseServerConnection  = new VssConnection(url, credentials);
         return(_baseServerConnection.ConnectAsync());
     }
 }
Esempio n. 34
0
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            ArgUtil.NotNull(context, nameof(context));
            Tracing trace = context.GetTrace(nameof(PersonalAccessToken));
            trace.Info(nameof(GetVssCredentials));
            ArgUtil.NotNull(CredentialData, nameof(CredentialData));
            string token;
            if (!CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Token, out token))
            {
                token = null;
            }

            ArgUtil.NotNullOrEmpty(token, nameof(token));

            trace.Info("token retrieved: {0} chars", token.Length);

            // PAT uses a basic credential
            VssBasicCredential basicCred = new VssBasicCredential("VstsAgent", token);
            VssCredentials creds = new VssClientCredentials(basicCred);
            trace.Verbose("cred created");

            return creds;
        }