Exemplo n.º 1
0
 private static BuildHttpClient CreateClient(string accessToken)
 {
     var collectionUri = new Uri("https://riskfirst.visualstudio.com/DefaultCollection", UriKind.Absolute);
     var cred = new VssBasicCredential(string.Empty, accessToken);
     var buildClient = new BuildHttpClient(collectionUri, cred);
     return buildClient;
 }
Exemplo n.º 2
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;
        }        
Exemplo n.º 3
0
        private static VssConnection GetVssConnection()
        {
            string pat = Environment.GetEnvironmentVariable(Program.PAT_ENV_VAR);

            if (string.IsNullOrEmpty(pat))
            {
                throw new ArgumentException("On .NET Core, you must set an environment variable " + Program.PAT_ENV_VAR + " with a personal access token.");
            }

            var creds = new VssBasicCredential("pat", pat);

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

            return(connection);
        }
Exemplo n.º 4
0
 public async Task <string> ExecuteAsync(IRule rule, WorkItemEventContext eventContext, CancellationToken cancellationToken)
 {
     logger.WriteVerbose($"Connecting to Azure DevOps using {configuration.DevOpsTokenType}...");
     if (configuration.DevOpsTokenType == DevOpsTokenType.PAT)
     {
         var clientCredentials = new VssBasicCredential(configuration.DevOpsTokenType.ToString(), configuration.DevOpsToken);
         // see https://rules.sonarsource.com/csharp/RSPEC-4457
         return(await ExecAsyncImpl(rule, eventContext, clientCredentials, cancellationToken));
     }
     else
     {
         logger.WriteError($"Azure DevOps Token type {configuration.DevOpsTokenType} not supported!");
         throw new ArgumentException($"Azure DevOps Token type {configuration.DevOpsTokenType} not supported.");
     }
 }
Exemplo n.º 5
0
        /// <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>();
        }
Exemplo n.º 6
0
 private static VsWebApi.VssConnection EstablishRestConnection(Settings settings)
 {
     try
     {
         Logger.Log(LogLevel.Info, "Connecting to Azure DevOps/TFS...");
         var credentials = new VssBasicCredential("", settings.Pat);
         var uri         = new Uri(settings.Account);
         return(new VsWebApi.VssConnection(uri, credentials));
     }
     catch (Exception ex)
     {
         Logger.Log(ex, $"Cannot establish connection to Azure DevOps/TFS.", LogLevel.Critical);
         return(null);
     }
 }
Exemplo n.º 7
0
        public async Task <Release> CreateReleaseAsync(ReleaseDefinition releaseDefinition, Build build)
        {
            var clientCredentials = new VssBasicCredential(string.Empty, _connectInfo.PAT);
            var connection        = new VssConnection(_connectInfo.ServerUrl, clientCredentials);

            var releaseServer = connection.GetClient <ReleaseHttpClient>(); // connect to the build server subpart

            var releaseStartMetaData = new ReleaseStartMetadata()
            {
                DefinitionId = releaseDefinition.Id,
                IsDraft      = false,
            };

            return(await releaseServer.CreateReleaseAsync(releaseStartMetaData, project : _connectInfo.ProjectId));
        }
        public async Task HandleBuild(BuildRequest build, string pat, Uri projectCollectionUri)
        {
            if (string.IsNullOrEmpty(build.SourceBranch))
            {
                return;
            }

            var creds      = new VssBasicCredential(string.Empty, pat);
            var connection = new VssConnection(new Uri(projectCollectionUri, "DefaultCollection"), creds);

            var gitClient = connection.GetClient <GitHttpClient>();

            var prs = await gitClient.GetPullRequestsAsync(build.TeamProject, build.RepositoryId,
                                                           new GitPullRequestSearchCriteria { SourceRefName = build.SourceBranch, Status = PullRequestStatus.Active });

            foreach (var pr in prs)
            {
                // Delete Status from PRCreate
                var oldstatuses = await gitClient.GetPullRequestStatusesAsync(build.TeamProject, build.RepositoryId, pr.PullRequestId);

                var toDeleteStatuses = oldstatuses.Where(s => s.Context.Name == "PrAnnotator");
                foreach (var oldstatus in toDeleteStatuses)
                {
                    await gitClient.DeletePullRequestStatusAsync(build.TeamProject, build.RepositoryId, pr.PullRequestId, oldstatus.Id);
                }

                var prStatus = new GitPullRequestStatus
                {
                    State       = build.Status == "completed" ? GitStatusState.Succeeded : GitStatusState.Failed,
                    Description = $"{build.DefinitionName}: Build {build.Status}",
                    Context     = new GitStatusContext {
                        Genre = "Build", Name = build.DefinitionName
                    },
                    TargetUrl = build.BuildUri
                };

                //await gitClient.CreatePullRequestStatusAsync(prStatus, build.TeamProject, pr.Repository.Id, pr.PullRequestId).ConfigureAwait(false);

                var iterations = await gitClient.GetPullRequestIterationsAsync(pr.Repository.Id, pr.PullRequestId);

                var id = iterations.Last(i => i.SourceRefCommit.CommitId == build.SourceVersion).Id;
                if (id != null)
                {
                    prStatus.Description = $"Update {id.Value}: {prStatus.Description}";
                    await gitClient.CreatePullRequestIterationStatusAsync(prStatus, pr.Repository.Id, pr.PullRequestId, id.Value);
                }
            }
        }
Exemplo n.º 9
0
        internal async Task <string> Execute(dynamic data)
        {
            string collectionUrl = data.resourceContainers.collection.baseUrl;
            string eventType     = data.eventType;
            int    workItemId    = (eventType != "workitem.updated")
                ? data.resource.id
                : data.resource.workItemId;
            Guid   teamProjectId   = data.resourceContainers.project.id;
            string teamProjectName = (eventType != "workitem.updated")
                ? data.resource.fields["System.TeamProject"]
                : data.resource.revision.fields["System.TeamProject"];

            logger.WriteVerbose($"Connecting to Azure DevOps using {configuration.DevOpsTokenType}...");
            var clientCredentials = default(VssCredentials);

            if (configuration.DevOpsTokenType == DevOpsTokenType.PAT)
            {
                clientCredentials = new VssBasicCredential(configuration.DevOpsTokenType.ToString(), configuration.DevOpsToken);
            }
            else
            {
                logger.WriteError($"Azure DevOps Token type {configuration.DevOpsTokenType} not supported!");
                throw new ArgumentOutOfRangeException(nameof(configuration.DevOpsTokenType));
            }

            using (var devops = new VssConnection(new Uri(collectionUrl), clientCredentials))
            {
                await devops.ConnectAsync();

                logger.WriteInfo($"Connected to Azure DevOps");
                using (var witClient = devops.GetClient <WorkItemTrackingHttpClient>())
                {
                    string ruleFilePath = Path.Combine(functionDirectory, $"{ruleName}.rule");
                    if (!File.Exists(ruleFilePath))
                    {
                        logger.WriteError($"Rule code not found at {ruleFilePath}");
                        return("Rule file not found!");
                    }

                    logger.WriteVerbose($"Rule code found at {ruleFilePath}");
                    string[] ruleCode = File.ReadAllLines(ruleFilePath);

                    var engine = new Engine.RuleEngine(logger, ruleCode, configuration.SaveMode);

                    return(await engine.ExecuteAsync(collectionUrl, teamProjectId, teamProjectName, configuration.DevOpsToken, workItemId, witClient));
                }
            }
        }
        public List <AzureTestCase> FindTestCasesByAssociatedAutomation(string fullTestName, string testStorage)
        {
            // Create a wiql object and build our query
            var wiql = new Wiql()
            {
                // NOTE: Even if other columns are specified, only the ID & URL will be available in the WorkItemReference
                Query = "Select [Id] " +
                        "From WorkItems " +
                        "Where [Work Item Type] = 'Test Case' " +
                        "And [System.TeamProject] = '" + _project + "' " +
                        $"And [Microsoft.VSTS.TCM.AutomatedTestName] = '{fullTestName}'" +
                        $"And [Microsoft.VSTS.TCM.AutomatedTestStorage] = '{testStorage}'",
            };

            var credentials = new VssBasicCredential(string.Empty, _personalAccessToken);

            try
            {
                // create instance of work item tracking http client
                using var httpClient = new WorkItemTrackingHttpClient(new Uri(_uri), credentials);

                // execute the query to get the list of work items in the results
                var result = httpClient.QueryByWiqlAsync(wiql).Result;
                var ids    = result.WorkItems.Select(item => item.Id).ToArray();

                // some error handling
                if (ids.Length == 0)
                {
                    return(new List <AzureTestCase>());
                }

                var resultTestCases = new List <AzureTestCase>();

                // build a list of the fields we want to see
                var fields = new[] { "System.Id", "System.Title", "System.State" };

                foreach (var item in httpClient.GetWorkItemsAsync(ids, expand: WorkItemExpand.Relations).Result)
                {
                    resultTestCases.Add(ConvertWorkItemToAzureTestCase(item));
                }

                return(resultTestCases);
            }
            catch
            {
                return(new List <AzureTestCase>());
            }
        }
Exemplo n.º 11
0
        static public void GetChangesetWorkItemFromLabel(string tfsCollectionUrl, string personalAccessToken)
        {
            Console.WriteLine("Loading Labels Items and associated work items ... ");

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

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

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

                TfvcLabelRequestData tfvcLabelRequestData = new TfvcLabelRequestData();

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

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

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

            Console.ReadLine();
        }
Exemplo n.º 12
0
        public static void GetTeams(TfsConnection teamProjectCollection)
        {
            Uri                _uri         = teamProjectCollection.Uri;
            string             user         = ConfigurationManager.AppSettings["TfsClientUser"];
            string             password     = ConfigurationManager.AppSettings["TfsClientPassword"];
            VssBasicCredential _credentials = new VssBasicCredential(user, password);

            using (ProjectHttpClient projectHttpClient = new ProjectHttpClient(_uri, _credentials))
            {
                IEnumerable <TeamProjectReference> projects = projectHttpClient.GetProjects().Result;
                IEnumerable <WebApiTeam>           teams    = GetTeams(projects.First().Name, _credentials, _uri);

                var configSvc = teamProjectCollection.GetService <TeamSettingsConfigurationService>();
                var configs   = configSvc.GetTeamConfigurations(teams.Select(x => x.Id));
            }
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            VssCredentials creds      = new VssBasicCredential(string.Empty, pat);
            VssConnection  connection = new VssConnection(new Uri(collectionUri), creds);

            //Console.WriteLine("******Bug List******");
            //var bugList = getBugs(connection);
            Console.WriteLine("******My Code Reviews List******");
            var codeReviewsList = getMyCodeReviews(connection);

            Console.WriteLine("******Update Code Review******");
            Console.WriteLine("Please enter CodeReviewRequest Id : ");
            int id = int.Parse(Console.ReadLine());

            ChangeFieldValue(connection, id);
        }
        /// <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>();
        }
Exemplo n.º 15
0
 // This method will upload attachment and return url for file and Id
 private static AttachmentReference UploadAttachment(Uri uri, VssBasicCredential credentials)
 {
     try
     {
         VssConnection _tpc = new VssConnection(uri, credentials);
         WorkItemTrackingHttpClient workItemTrackingHttpClient = _tpc.GetClient <WorkItemTrackingHttpClient>();
         AttachmentReference        attachment = workItemTrackingHttpClient.CreateAttachmentAsync(PathOfAttachment).Result;
         // Save the attachment ID for the "download" sample call later
         return(attachment);
     }
     catch (Exception ex)
     {
         Log.Logger.Error("Error occurred while Attaching Attachment in bug" + ex);
         return(null);
     }
 }
Exemplo n.º 16
0
        static public void GetWorkItem(string tfsCollectionUrl, string personalAccessToken, int id)
        {
            Console.WriteLine("Getting WorkItem ID " + id);

            VssBasicCredential credentials = new VssBasicCredential(string.Empty, personalAccessToken);
            VssConnection      connection  = new VssConnection(new Uri(tfsCollectionUrl), credentials);

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

            WorkItem workitem = workItemTrackingHttpClient.GetWorkItemAsync(id).Result;


            Console.WriteLine(workitem.Fields["System.Title"]);

            Console.ReadLine();
        }
Exemplo n.º 17
0
        /// <nodoc />
        public Api(ILogger logger)
        {
            m_logger = logger ?? throw new ArgumentNullException(nameof(logger));

            BuildId          = Environment.GetEnvironmentVariable(Constants.BuildIdVarName);
            TeamProject      = Environment.GetEnvironmentVariable(Constants.TeamProjectVarName);
            ServerUri        = Environment.GetEnvironmentVariable(Constants.ServerUriVarName);
            AccessToken      = Environment.GetEnvironmentVariable(Constants.AccessTokenVarName);
            AgentName        = Environment.GetEnvironmentVariable(Constants.AgentNameVarName);
            SourcesDirectory = Environment.GetEnvironmentVariable(Constants.SourcesDirectoryVarName);
            TeamProjectId    = Environment.GetEnvironmentVariable(Constants.TeamProjectIdVarName);
            TimelineId       = Environment.GetEnvironmentVariable(Constants.TimelineIdVarName);
            PlanId           = Environment.GetEnvironmentVariable(Constants.PlanIdVarName);
            RepositoryUrl    = Environment.GetEnvironmentVariable(Constants.RepositoryUrlVariableName);

            string jobPositionInPhase = Environment.GetEnvironmentVariable(Constants.JobsPositionInPhaseVarName);

            if (string.IsNullOrWhiteSpace(jobPositionInPhase))
            {
                m_logger.Info("The job position in the build phase could not be determined. Therefore it must be a single machine build");
                JobPositionInPhase = 1;
                TotalJobsInPhase   = 1;
            }
            else
            {
                if (!int.TryParse(jobPositionInPhase, out int position))
                {
                    throw new ApplicationException($"The env var {Constants.JobsPositionInPhaseVarName} contains a value that cannot be parsed to int");
                }

                JobPositionInPhase = position;
                string totalJobsInPhase = Environment.GetEnvironmentVariable(Constants.TotalJobsInPhaseVarName);

                if (!int.TryParse(totalJobsInPhase, out int totalJobs))
                {
                    throw new ApplicationException($"The env var {Constants.TotalJobsInPhaseVarName} contains a value that cannot be parsed to int");
                }

                TotalJobsInPhase = totalJobs;
            }

            var server = new Uri(ServerUri);
            var cred   = new VssBasicCredential(string.Empty, AccessToken);

            m_taskClient  = new TaskHttpClient(server, cred);
            m_buildClient = new BuildHttpClient(server, cred);
        }
Exemplo n.º 18
0
        //private JObject ConvertToHierarchy(JArray items)
        //{
        //    var dict = new Dictionary<int, JToken>();

        //    foreach (var item in items)
        //    {
        //        var id = Int32.Parse(item["ID"].ToString());

        //        dict.Add(id, item);
        //    }

        //    foreach (var item in dict.Values)
        //    {
        //        if (item["System.Parent"] != null)
        //        {
        //            int parentNumber = Int32.Parse(item["System.Parent"].ToString());
        //            var parentItem = (JObject)dict[parentNumber];
        //            if (parentItem.ContainsKey("items") == false) { parentItem.Add("items", new JArray()); }
        //            var subItems = (JArray)parentItem["items"];
        //            subItems.Add(item);
        //        }
        //    }

        //    return (JObject)dict.FirstOrDefault().Value;
        //}

        private async Task <List <WorkItem> > GetItems(string uri, string pat, string project)
        {
            var credentials = new VssBasicCredential(string.Empty, pat);

            // create a wiql object and build our query
            var wiql = new Wiql()
            {
                // NOTE: Even if other columns are specified, only the ID & URL will be available in the WorkItemReference
                Query = "Select [Id] " +
                        "From WorkItems " +
                        //"Where [Work Item Type] = 'Epic' " +
                        "Where [System.TeamProject] = '" + project + "'",
            };

            // create instance of work item tracking http client
            using (var httpClient = new WorkItemTrackingHttpClient(new Uri(uri), credentials))
            {
                // execute the query to get the list of work items in the results
                var result = await httpClient.QueryByWiqlAsync(wiql).ConfigureAwait(false);

                var ids = result.WorkItems.Select(item => item.Id).ToArray();

                // some error handling
                if (ids.Length == 0)
                {
                    return(null);
                }

                // build a list of the fields we want to see
                //var fields = new[] { "System.Id", "System.Title", "System.State, System.Parent" };
                //System.AreaPath
                //System.TeamProject
                //System.IterationPath
                //System.WorkItemType
                //System.State
                //System.Reason
                //System.CreatedDate
                //System.CreatedBy
                //System.ChangedDate
                //System.ChangedBy
                //System.CommentCount

                // get work items for the ids found in query
                //return await httpClient.GetWorkItemsAsync(ids, fields, result.AsOf).ConfigureAwait(false);
                return(await httpClient.GetWorkItemsAsync(ids, expand : WorkItemExpand.Relations).ConfigureAwait(false));
            }
        }
Exemplo n.º 19
0
        public ActionResult Index()
        {
            var accountUri          = new Uri(ConfigurationManager.AppSettings["Vsts.Uri"]);
            var personalAccessToken = ConfigurationManager.AppSettings["Vsts.PersonalAccessToken"];

            var vssBasicCredential = new VssBasicCredential(String.Empty, personalAccessToken);

            // Create a connection to the account
            var vssConnection = new VssConnection(accountUri, vssBasicCredential);

            // Hangs here on subsequent request... doesn't happen on development server but does happen when hosted via IIS
            using (var workHttpClient = vssConnection.GetClient <WorkHttpClient>())
            {
            }

            return(View());
        }
Exemplo n.º 20
0
        public static WorkItem CreateBugInVSO(IWebDriver driver, Fields fields)
        {
            try
            {
                PathOfAttachment = ScreenShotCapture.CaptureScreenShotOfCurrentBrowser(driver, fields.PathOfFile);
                ListParams.AddRange(GetAllField(fields));
                Uri                 uri = new Uri(_uri);
                string              personalAccessToken = _personalAccessToken;
                string              project             = _project;
                VssBasicCredential  credentials         = new VssBasicCredential("", _personalAccessToken);
                AttachmentReference attachment          = UploadAttachment(uri, credentials);
                ListParams.Add(new Params()
                {
                    Path  = "/relations/-",
                    Value = new
                    {
                        rel        = "AttachedFile",
                        url        = attachment.Url,
                        attributes = new { comment = fields.Comments }
                    }
                });
                JsonPatchDocument patchDocument = new JsonPatchDocument();
                //add fields and their values to your patch document
                foreach (var item in ListParams)
                {
                    patchDocument.Add(
                        new JsonPatchOperation()
                    {
                        Operation = Operation.Add,
                        Path      = item.Path,
                        Value     = item.Value,
                    }
                        );
                }
                VssConnection connection = new VssConnection(uri, credentials);
                WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>();

                WorkItem result = workItemTrackingHttpClient.CreateWorkItemAsync(patchDocument, project, "Bug").Result;
                return(result);
            }
            catch (AggregateException ex)
            {
                Log.Logger.Error("Error occurred while Creating bug in VSO" + ex);
                return(null);
            }
        }
Exemplo n.º 21
0
        /// <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];

            searchString = element.SearchString;
            projectName  = element.Project;
            searchPeriod = TimeSpan.FromDays(element.SearchPeriodDays);

            // 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

            VssCredentials vssCredentials;

            switch (element.LoginMethod)
            {
            case 1:
                /* this is basic auth if on tfs2015 */
                // Ultimately you want a VssCredentials instance so...
                NetworkCredential netCred = new NetworkCredential(element.Username, element.Password);
                WindowsCredential winCred = new WindowsCredential(netCred);
                vssCredentials = 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.
                vssCredentials.PromptType = CredentialPromptType.DoNotPrompt;
                /*********************************************************************/
                break;

            default:
                vssCredentials = new VssBasicCredential("", element.AccessToken);
                break;
            }

            var connection = new VssConnection(new Uri(element.ProjectCollection), vssCredentials);

            _witClient = connection.GetClient <WorkItemTrackingHttpClient>();
        }
Exemplo n.º 22
0
        public static WorkItemClientConnection CreateClient(ConfigConnection connection)
        {
            Uri url = new Uri(connection.Account.TrimEnd('/'));

            VssCredentials credentials;

            if (connection.UseIntegratedAuth)
            {
                credentials = new VssCredentials(true);
            }
            else
            {
                credentials = new VssBasicCredential("", connection.AccessToken);
            }

            return(new WorkItemClientConnection(url, credentials));
        }
Exemplo n.º 23
0
        private Boolean ConnectToTfs(String accountUri, String accessToken)
        {
            //login for VSTS
            VssCredentials creds = new VssBasicCredential(
                String.Empty,
                accessToken);

            creds.Storage = new VssClientCredentialStorage();

            // Connect to VSTS
            _tfsCollection = new TfsTeamProjectCollection(new Uri(accountUri), creds);
            _tfsCollection.Authenticate();

            _vssConnection = new VssConnection(new Uri(accountUri), creds);
            _vssConnection.ConnectAsync().Wait();
            return(true);
        }
Exemplo n.º 24
0
        public static async Task <string> CreateWIinDevops(string WItitle, string projectName, string WIType)
        {
            var PAT = "7awtul6zkle7untncpxvqq25yvwgz6fb2qr6stxozzm6qr7swxca";


            var credentials = new VssBasicCredential(string.Empty, PAT);

            var operations = new JsonPatchDocument();

            AddPatch(operations, "/fields/System.Title", WItitle);
            AddPatch(operations, "/fields/System.Description", WItitle);
            var witClient =
                new WorkItemTrackingHttpClient(new Uri("https://dev.azure.com/adfd365"), credentials);
            var result = await witClient.CreateWorkItemAsync(operations, projectName, WIType);

            return(result.Id.ToString());
        }
Exemplo n.º 25
0
        private async Task <VssConnection> GetVssConnectionAsync(string organization)
        {
            var vssConnectionCacheKey = $"{organization}_vssConnectionCacheKey";

            var connection = await cache.GetOrCreateAsync(vssConnectionCacheKey, async (entry) =>
            {
                var azureDevOpsPersonalAccessToken = await GetAzureDevOpsPersonalAccessTokenAsync();
                var credentials = new VssBasicCredential("nobody", azureDevOpsPersonalAccessToken);
                var baseUri     = new Uri($"https://dev.azure.com/{organization}");
                var connection  = new VssConnection(baseUri, credentials);

                entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60);
                return(connection);
            });

            return(connection);
        }
Exemplo n.º 26
0
        internal async Task <string> ExecuteAsync(WorkItemEventContext eventContext, CancellationToken cancellationToken)
        {
            logger.WriteVerbose($"Connecting to Azure DevOps using {configuration.DevOpsTokenType}...");
            var clientCredentials = default(VssCredentials);

            if (configuration.DevOpsTokenType == DevOpsTokenType.PAT)
            {
                clientCredentials = new VssBasicCredential(configuration.DevOpsTokenType.ToString(), configuration.DevOpsToken);
            }
            else
            {
                logger.WriteError($"Azure DevOps Token type {configuration.DevOpsTokenType} not supported!");
                throw new ArgumentOutOfRangeException(nameof(configuration.DevOpsTokenType));
            }

            cancellationToken.ThrowIfCancellationRequested();

            // TODO improve from https://github.com/Microsoft/vsts-work-item-migrator
            using (var devops = new VssConnection(eventContext.CollectionUri, clientCredentials))
            {
                await devops.ConnectAsync(cancellationToken);

                logger.WriteInfo($"Connected to Azure DevOps");
                using (var clientsContext = new AzureDevOpsClientsContext(devops))
                {
                    string ruleFilePath = Path.Combine(functionDirectory, $"{ruleName}.rule");
                    if (!File.Exists(ruleFilePath))
                    {
                        logger.WriteError($"Rule code not found at {ruleFilePath}");
                        return("Rule file not found!");
                    }

                    logger.WriteVerbose($"Rule code found at {ruleFilePath}");
                    string[] ruleCode;
                    using (var fileStream = File.OpenRead(ruleFilePath))
                    {
                        var reader = new StreamReader(fileStream);
                        ruleCode = await ReadAllLinesAsync(reader);
                    }

                    var engine = new Engine.RuleEngine(logger, ruleCode, configuration.SaveMode, configuration.DryRun);

                    return(await engine.ExecuteAsync(eventContext.ProjectId, eventContext.WorkItemPayload, clientsContext, cancellationToken));
                }
            }
        }
Exemplo n.º 27
0
        private TfsTeamProjectCollection GetTfsCollection()
        {
            if (_Collection is null)
            {
                var            startTime = DateTime.UtcNow;
                var            timer     = System.Diagnostics.Stopwatch.StartNew();
                VssCredentials vssCredentials;
                try
                {
                    Log.LogDebug("TfsWorkItemEndPoint::GetTfsCollection:AuthenticationMode({0})", _Options.AuthenticationMode.ToString());
                    switch (_Options.AuthenticationMode)
                    {
                    case AuthenticationMode.AccessToken:
                        Log.LogDebug("TfsWorkItemEndPoint::GetTfsCollection: Connecting Using PAT Authentication ", _Options.Organisation);
                        vssCredentials = new VssBasicCredential(string.Empty, _Options.AccessToken);
                        _Collection    = new TfsTeamProjectCollection(new Uri(_Options.Organisation), vssCredentials);
                        break;

                    case AuthenticationMode.Prompt:
                        Log.LogDebug("TfsWorkItemEndPoint::EnsureDataSource: Connecting Using Interactive Authentication ", _Options.Organisation);
                        _Collection = new TfsTeamProjectCollection(new Uri(_Options.Organisation));
                        break;

                    default:
                        Log.LogDebug("TfsWorkItemEndPoint::EnsureDataSource: Connecting Using Interactive Authentication ", _Options.Organisation);
                        _Collection = new TfsTeamProjectCollection(new Uri(_Options.Organisation));
                        break;
                    }
                    Log.LogDebug("TfsWorkItemEndPoint::GetTfsCollection: Connected ");
                    Log.LogDebug("TfsWorkItemEndPoint::GetTfsCollection: validating security for {@AuthorizedIdentity} ", _Collection.AuthorizedIdentity);
                    _Collection.EnsureAuthenticated();
                    timer.Stop();
                    Log.LogInformation("TfsWorkItemEndPoint::GetTfsCollection: Access granted to {CollectionUrl} for {Name} ({Account})", _Options.Organisation, _Collection.AuthorizedIdentity.DisplayName, _Collection.AuthorizedIdentity.UniqueName);
                    Telemetry.TrackDependency(new DependencyTelemetry("TfsObjectModel", _Options.Organisation, "GetTfsCollection", null, startTime, timer.Elapsed, "200", true));
                }
                catch (Exception ex)
                {
                    timer.Stop();
                    Telemetry.TrackDependency(new DependencyTelemetry("TfsObjectModel", _Options.Organisation, "GetTfsCollection", null, startTime, timer.Elapsed, "500", false));
                    Log.LogError(ex, "Unable to connect to {Organisation}", _Options.Organisation);
                    throw;
                }
            }
            return(_Collection);
        }
Exemplo n.º 28
0
        private VssConnection GetConnection()
        {
            VssConnection result = null;

            if (_accessToken != null)
            {
                var creds = new VssBasicCredential(string.Empty, _accessToken);
                result = new VssConnection(_uri, creds);

                if (!_connected)
                {
                    _connected = true;
                    Connected?.Invoke(this, _uri.AbsoluteUri);
                }
            }

            return(result);
        }
Exemplo n.º 29
0
        private WorkItemQueryResult WorkItemResponse(Uri azureDevOpsUri, VssBasicCredential personalAccessToken, string azureDevOpsWiqlString)
        {
            WorkItemQueryResult workItemQueryResult;
            Wiql azureDevOpsWiqlQuery = new Wiql()
            {
                Query = azureDevOpsWiqlString
            };

            using (WorkItemTrackingHttpClient workItemTrackingHttpClient =
                       new WorkItemTrackingHttpClient(azureDevOpsUri, personalAccessToken))
            {
                //execute the query to get the list of work items in the results
                workItemQueryResult =
                    workItemTrackingHttpClient.QueryByWiqlAsync(azureDevOpsWiqlQuery).Result;
            }

            return(workItemQueryResult);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Execute une requete WIQL pour retourner une liste de workItem en utilisant la librairie .NET client
        /// </summary>
        /// <returns>List of Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItem</returns>
        public async Task <List <WorkItem> > GetWorkItemByQuery(string query)
        {
            Uri uri = new Uri(_uri);
            VssBasicCredential credentials = new VssBasicCredential("", _personalAccessToken);

            // Création de la requete
            Wiql wiql = new Wiql()
            {
                Query = query
            };

            // instance http client
            using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(uri, credentials))
            {
                // execute la requete
                WorkItemQueryResult workItemQueryResult = await workItemTrackingHttpClient.QueryByWiqlAsync(wiql);

                //Au cas ou il y aurait un problème ou qu'il n'y ai pas de workitem
                if (workItemQueryResult.WorkItems.Count() != 0)
                {
                    //listing des ID des WorkItem à charger
                    List <int> list = new List <int>();
                    foreach (var item in workItemQueryResult.WorkItems)
                    {
                        list.Add(item.Id);
                    }
                    int[] arr = list.ToArray();

                    //List des champs a récuperer dans le workItem
                    //string[] fields = new string[3];
                    //fields[0] = "System.Id";
                    //fields[1] = "System.Title";
                    //fields[2] = "System.State";
                    //var workItems = await workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf);

                    //Récupération des workItems selon leurs ID  avec tous leur champs
                    var workItems = await workItemTrackingHttpClient.GetWorkItemsAsync(arr, asOf : workItemQueryResult.AsOf);

                    return(workItems);
                }

                return(null);
            }
        }
        public static List <WorkItem> GetWorkItems(string workItemId)
        {
            var credentials = new VssBasicCredential(string.Empty, _personalAccessToken);

            try
            {
                // create instance of work item tracking http client
                using var httpClient = new WorkItemTrackingHttpClient(new Uri(_uri), credentials);

                // execute the query to get the list of work items in the results
                var result = httpClient.GetWorkItemsAsync(new int[] { workItemId.ToInt() }).Result;

                return(httpClient.GetWorkItemsAsync(new int[] { workItemId.ToInt() }).Result);
            }
            catch
            {
                return(new List <WorkItem>());
            }
        }
Exemplo n.º 32
0
        public static async Task LinkWIinDevOpstoEachother(int mainwiid, int childwiid)
        {
            var PAT         = "7awtul6zkle7untncpxvqq25yvwgz6fb2qr6stxozzm6qr7swxca";
            var projectName = "The Hershey Corporation various affiliates H Choc World";
            //  var workItemType = "Product Backlog Item";

            var credentials = new VssBasicCredential(string.Empty, PAT);


            var operations = new JsonPatchDocument();

            AddPatchTest(operations, $"https://dev.azure.com/adfd365/_apis/wit/workItems/{childwiid}");
            //  AddPatch(operations, "/relations/-", values);
            // AddPatch(operations, "/fields/System.Description", "Implementation Model");
            var witClient =
                new WorkItemTrackingHttpClient(new Uri("https://dev.azure.com/adfd365"), credentials);

            var resukt = await witClient.UpdateWorkItemAsync(operations, projectName, mainwiid);
        }
Exemplo n.º 33
0
        private static VssConnection CreateConnection(AbstractCommandLineOptions options)
        {
            VssCredentials creds;

            if (!string.IsNullOrEmpty(options.PersonalAccessToken))
            {
                creds = new VssBasicCredential(string.Empty, options.PersonalAccessToken);
            }
            else if (!string.IsNullOrEmpty(options.Username))
            {
                creds = new VssCredentials(new WindowsCredential(new NetworkCredential(options.Username, options.Password)));
            }
            else
            {
                creds = new VssCredentials(new WindowsCredential(true));
            }

            return(new VssConnection(new Uri(options.CollectionUrl), creds));
        }
Exemplo 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;
        }