public WorkItemDelete DeleteWorkItem()
        {
            int id = Convert.ToInt32(Context.GetValue <WorkItem>("$newWorkItem2").Id);

            // Get a client
            VssConnection connection = Context.Connection;
            WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>();

            // Delete the work item (but don't destroy it completely)
            WorkItemDelete results = workItemTrackingClient.DeleteWorkItemAsync(id, destroy: false).Result;

            return(results);
        }
Exemplo n.º 2
0
        public void GetReadOnlyWorkItemFields()
        {
            VssConnection connection = Context.Connection;
            WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>();

            List <WorkItemField> result = workItemTrackingClient.GetFieldsAsync().Result;

            Console.WriteLine("Read only fields:");
            foreach (var workitemField in result.Where(field => field.ReadOnly))
            {
                Console.WriteLine(" * {0} ({1})", workitemField.Name, workitemField.ReferenceName);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Extends the project for a specific work item type LINQ Query.
        /// </summary>
        /// <typeparam name="T">Type of work item</typeparam>
        /// <typeparam name="THelper">Related creator provider</typeparam>
        /// <param name="workItemTrackingHttpClient"></param>
        /// <param name="project">The project.</param>
        /// <returns></returns>
        internal static IQueryable <T> SetOf <T, THelper>(this WorkItemTrackingHttpClient workItemTrackingHttpClient,
                                                          ProjectInfo project)
            where T : GenericWorkItem
            where THelper : ICustomWorkItemHelper <T>, new()
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            return(new Query <T>(new WorkItemLinqQueryProvider <T>(workItemTrackingHttpClient, project.Name,
                                                                   new THelper())));
        }
Exemplo n.º 4
0
        public async Task <List <WorkItem> > GetTestCaseByID(int id)
        {
            WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>();
            string Wiql = "SELECT [System.Title], [System.WorkItemType] FROM WorkItems WHERE [System.ID] = " + id;
            // "'PlayGround' AND" + "[System.WorkItemType] = 'Test Suite'";
            WorkItemQueryResult result = await witClient.QueryByWiqlAsync(new Wiql { Query = Wiql });

            IEnumerable <int> woritem_ids = result.WorkItems.Select(p => p.Id);
            List <WorkItem>   workitems   = await
                                            witClient.GetWorkItemsAsync(woritem_ids, null, null, null, null, default(System.Threading.CancellationToken));

            return(workitems);
        }
Exemplo n.º 5
0
        public WorkItem UpdateWorkItemLinkToCommit()
        {
            int id = Convert.ToInt32(Context.GetValue <WorkItem>("$newWorkItem2").Id);

            System.Guid repositoryId = new Guid("2f3d611a-f012-4b39-b157-8db63f380226");
            string      commitId     = "be67f8871a4d2c75f13a51c1d3c30ac0d74d4ef4";

            VssConnection connection = Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            //you will need to edit this line and enter a legit repo id and commit id
            //these are samples and will not work
            var commit    = gitClient.GetCommitAsync(commitId, repositoryId).Result;
            var commitUri = commit.Url;

            JsonPatchDocument patchDocument = new JsonPatchDocument();

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

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/relations/-",
                Value     = new
                {
                    rel        = "ArtifactLink",
                    url        = commitUri,
                    attributes = new
                    {
                        comment = "Fixed in Commit",
                        name    = "commit"
                    }
                }
            }
                );


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

            WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result;

            return(result);
        }
Exemplo n.º 6
0
        RunGetTasksQuery(Project project)
        {
            VssBasicCredential credentials = new VssBasicCredential("", project.PersonalAccessToken);

            //create a wiql object and build our query
            Wiql wiql = new Wiql()
            {
                Query = "Select " +
                        " [System.Id], [System.WorkItemType], [System.Title], [System.CreatedDate] " +
                        "From WorkItems " +
                        "Where " +
                        "[System.TeamProject] = '" + project.Name.ToString() + "' " +
                        "And [System.State] <> 'Closed' " +
                        "Order By [State] Asc, [Changed Date] Desc"
            };

            //create instance of work item tracking http client
            using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(new Uri(project.Url.ToString()), credentials))
            {
                //execute the query to get the list of work items in the results
                WorkItemQueryResult workItemQueryResult = await workItemTrackingHttpClient.QueryByWiqlAsync(wiql);

                //some error handling
                if (workItemQueryResult.WorkItems.Count() != 0)
                {
                    //need to get the list of our work item ids and put them into an array
                    List <int> list = new List <int>();
                    foreach (var item in workItemQueryResult.WorkItems)
                    {
                        list.Add(item.Id);
                    }
                    int[] arr = list.ToArray();

                    //build a list of the fields we want to see
                    string[] fields = new string[4];
                    fields[0] = "System.Id";
                    fields[1] = "System.WorkItemType";
                    fields[2] = "System.Title";
                    fields[3] = "System.CreatedDate";

                    //get work items for the ids found in query
                    var workItems = await workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf);

                    Console.WriteLine("Query Results: {0} items found", workItems.Count);

                    return(workItems);
                }

                return(null);
            }
        }
Exemplo n.º 7
0
        private static void CloneWorkItem(WorkItemTrackingHttpClient witClient, int wiIdToClone, string NewTeamProject = "", bool CopyLink = false)
        {
            WorkItem wiToClone = (CopyLink) ? witClient.GetWorkItemAsync(wiIdToClone, expand: WorkItemExpand.Relations).Result
                : witClient.GetWorkItemAsync(wiIdToClone).Result;

            string teamProjectName = (NewTeamProject != "") ? NewTeamProject : wiToClone.Fields["System.TeamProject"].ToString();
            string wiType          = wiToClone.Fields["System.WorkItemType"].ToString();

            JsonPatchDocument patchDocument = new JsonPatchDocument();

            foreach (var key in wiToClone.Fields.Keys) //copy fields
            {
                if (!systemFields.Contains(key) && !customFields.Contains(key))
                {
                    if (NewTeamProject == "" ||
                        (NewTeamProject != "" && key != "System.AreaPath" && key != "System.IterationPath")) //do not copy area and iteration into another project
                    {
                        patchDocument.Add(new JsonPatchOperation()
                        {
                            Operation = Operation.Add,
                            Path      = "/fields/" + key,
                            Value     = wiToClone.Fields[key]
                        });
                    }
                }
            }

            if (CopyLink) //copy links
            {
                foreach (var link in wiToClone.Relations)
                {
                    if (link.Rel != ChildRefStr)
                    {
                        patchDocument.Add(new JsonPatchOperation()
                        {
                            Operation = Operation.Add,
                            Path      = "/relations/-",
                            Value     = new
                            {
                                rel = link.Rel,
                                url = link.Url
                            }
                        });
                    }
                }
            }

            WorkItem clonedWi = witClient.CreateWorkItemAsync(patchDocument, teamProjectName, wiType).Result;

            Console.WriteLine("New work item: " + clonedWi.Id);
        }
        private AttachmentReference UploadAttachment(AzureDevOpsWorkItemAttachment attachment)
        {
            AttachmentReference uploadedFile;

            var name = Path.GetFileName(attachment.AttachmentPath);

            using (var attStream = new FileStream(attachment.AttachmentPath, FileMode.Open, FileAccess.Read))
            {
                uploadedFile = WorkItemTrackingHttpClient.CreateAttachmentAsync(attStream, ProjectName, fileName: name)
                               .Result;
            }

            return(uploadedFile);
        }
Exemplo n.º 9
0
        public IEnumerable <WorkItem> GetWorkItemsFromQuery()
        {
            string project   = ClientSampleHelpers.FindAnyProject(this.Context).Name;
            string queryName = "Shared Queries/Current Sprint";

            VssConnection connection = Context.Connection;
            WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>();

            QueryHierarchyItem queryItem;

            try
            {
                // get the query object based on the query name and project
                queryItem = workItemTrackingClient.GetQueryAsync(project, queryName).Result;
            }
            catch (Exception ex)
            {
                // query was likely not found
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(ex.InnerException.Message);
                Console.ForegroundColor = ConsoleColor.White;

                return(null);
            }

            // now we have the query, so let'ss execute it and get the results
            WorkItemQueryResult queryResult = workItemTrackingClient.QueryByIdAsync(queryItem.Id).Result;

            if (queryResult.WorkItems.Count() == 0)
            {
                return(new List <WorkItem>());
            }
            else
            {
                // need to get the list of our work item id's and put them into an array
                int[] workItemIds = queryResult.WorkItems.Select <WorkItemReference, int>(wif => { return(wif.Id); }).ToArray();

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

                IEnumerable <WorkItem> workItems = workItemTrackingClient.GetWorkItemsAsync(workItemIds, fields, queryResult.AsOf).Result;

                return(workItems);
            }
        }
Exemplo n.º 10
0
 public static async Task <IList <WitBatchResponse> > ExecuteBatchRequest(WorkItemTrackingHttpClient targetWorkItemTrackingClient, IList <WitBatchRequest> witBatchRequests)
 {
     //we cannot add retrylogic here as we will need to reconstruct the entire content
     try
     {
         return(await targetWorkItemTrackingClient.ExecuteBatchRequest(witBatchRequests));
     }
     catch (Exception e)
     {
         Logger.LogError(LogDestination.File, $"Exception in MakeRequest {e.Message}");
         throw e;
         //we continue migration even if something failed
     }
 }
Exemplo n.º 11
0
        public WorkItemDelete RestoreItem(int id)
        {
            VssConnection connection = new VssConnection(_uri, _credentials);
            WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>();

            WorkItemDeleteUpdate payload = new WorkItemDeleteUpdate()
            {
                IsDeleted = false
            };

            WorkItemDelete result = workItemTrackingHttpClient.RestoreWorkItemAsync(payload, id).Result;

            return(result);
        }
Exemplo n.º 12
0
        public TFSClient(string url, string username, string passwordOrPAT)
        {
            _uri           = url;
            _username      = username;
            _passwordOrPAT = passwordOrPAT;
            VssBasicCredential credentials = new VssBasicCredential(_username, _passwordOrPAT);
            Uri uri = new Uri(_uri);

            _connection        = new VssConnection(uri, credentials);
            workItemClient     = _connection.GetClient <WorkItemTrackingHttpClient>();
            teamClient         = _connection.GetClient <TeamHttpClient>();
            projectClient      = _connection.GetClient <ProjectHttpClient>();
            serviceHooksClient = _connection.GetClient <ServiceHooksPublisherHttpClient>();
        }
        public void PermenentlyDeleteMultipleWorkItems()
        {
            int[] ids = { 72, 73, 81 }; //TODO

            VssConnection connection = Context.Connection;
            WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>();

            List <WorkItemDeleteReference> result = workItemTrackingClient.GetDeletedWorkItemsAsync(ids).Result;

            foreach (var item in result)
            {
                workItemTrackingClient.DestroyWorkItemAsync(Convert.ToInt32(item.Id));
            }
        }
Exemplo n.º 14
0
        public void GetReadOnlyWorkItemFields()
        {
            Uri uri = new Uri(_uri);
            VssBasicCredential         credentials            = new VssBasicCredential("", _personalAccessToken);
            WorkItemTrackingHttpClient workItemTrackingClient = new WorkItemTrackingHttpClient(uri, credentials);

            List <WorkItemField> result = workItemTrackingClient.GetFieldsAsync().Result;

            Console.WriteLine("Read only fields:");
            foreach (var workitemField in result)
            {
                Console.WriteLine(" * {0} ({1})", workitemField.Name, workitemField.ReferenceName);
            }
        }
Exemplo n.º 15
0
        private async Task <List <WorkItem> > GetWorkItemsAsync(WorkItemTrackingHttpClient client, IEnumerable <int> ids)
        {
            var result     = new List <WorkItem>();
            var batchedIds = Batch(ids, 200);

            foreach (var batch in batchedIds)
            {
                var items = await client.GetWorkItemsAsync(batch, expand : WorkItemExpand.All);

                result.AddRange(items);
            }

            return(result);
        }
Exemplo n.º 16
0
        public static void ChangeState(WorkItemTrackingHttpClient client, int id, string state)
        {
            var patchDocument = new JsonPatchDocument
            {
                new JsonPatchOperation()
                {
                    Operation = Operation.Add,
                    Path      = "/fields/System.State",
                    Value     = state
                }
            };

            client.UpdateWorkItemAsync(patchDocument, id).Wait();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Execute a WIQL query to return a list of bugs using the .NET client library
        /// </summary>
        /// <returns>List of Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItem</returns>
        public async Task <List <WorkItem> > ExecuteWorkItemsQuery()
        {
            Uri    uri = new Uri(GlobalConfiguration.Instance._uri);
            string personalAccessToken = GlobalConfiguration.Instance._tokenPA;
            string project             = GlobalConfiguration.Instance._project;

            VssBasicCredential credentials = new VssBasicCredential("", GlobalConfiguration.Instance._tokenPA);

            //create a wiql object and build our query
            Wiql wiql = new Wiql()
            {
                Query = "Select [Id], [State], [Title],[Changed Date]" +
                        "From WorkItems " +
                        "Order By [State] Asc, [Changed Date] Desc"
            };

            //create instance of work item tracking http client
            using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(uri, credentials))
            {
                //execute the query to get the list of work items in the results
                WorkItemQueryResult workItemQueryResult = await workItemTrackingHttpClient.QueryByWiqlAsync(wiql);

                //some error handling
                if (workItemQueryResult.WorkItems.Count() != 0)
                {
                    //need to get the list of our work item ids and put them into an array
                    List <int> list = new List <int>();
                    foreach (var item in workItemQueryResult.WorkItems)
                    {
                        list.Add(item.Id);
                    }
                    int[] arrWIQueryResult = list.ToArray();

                    //build a list of the fields we want to see
                    string[] wiProperties = new string[4];
                    wiProperties[0] = "System.Id";
                    wiProperties[1] = "System.State";
                    wiProperties[2] = "System.Title";
                    wiProperties[3] = "System.ChangedDate";


                    //get work items for the ids found in query
                    var workItems = await workItemTrackingHttpClient.GetWorkItemsAsync(arrWIQueryResult, wiProperties, workItemQueryResult.AsOf);

                    return(workItems);
                }

                return(null);
            }
        }
Exemplo n.º 18
0
        public WorkItemMigrationContext(MigrationEngine me, WorkItemMigrationConfig config)
            : base(me, config)
        {
            _config = config;
            PopulateIgnoreList();

            VssClientCredentials adoCreds = new VssClientCredentials();

            _witClient = new WorkItemTrackingHttpClient(me.Target.Collection.Uri, adoCreds);

            var workItemServer = me.Source.Collection.GetService <WorkItemServer>();

            attachmentOMatic = new AttachmentOMatic(workItemServer, config.AttachmentWorkingPath);
        }
Exemplo n.º 19
0
        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>());
            }

            return(new List <AzureTestCase>());
        }
Exemplo n.º 20
0
        public WorkItemClassificationNode RenameArea(string project, string path, string name)
        {
            WorkItemClassificationNode node = new WorkItemClassificationNode()
            {
                Name          = name,
                StructureType = TreeNodeStructureType.Area
            };

            VssConnection connection = new VssConnection(_uri, _credentials);
            WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>();
            WorkItemClassificationNode result = workItemTrackingHttpClient.UpdateClassificationNodeAsync(node, project, TreeStructureGroup.Areas, path).Result;

            return(result);
        }
Exemplo n.º 21
0
 public async Task <WorkItem> GetWorkItem(VssConnection connection, int id)
 {
     using (WorkItemTrackingHttpClient client = connection.GetClient <WorkItemTrackingHttpClient>())
     {
         try
         {
             return(await client.GetWorkItemAsync(id, null, null, WorkItemExpand.Relations));
         }
         catch (Exception)
         {
             return(null);
         }
     }
 }
Exemplo n.º 22
0
        public WorkItem UpdateWorkItemBoardColumn()
        {
            string targetColumn = "Testing"; //need to set to match your board

            VssConnection connection             = Context.Connection;
            WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>();

            JsonPatchDocument patchDocument = new JsonPatchDocument();

            //create a work item that drops into the new column by default
            WorkItem workItem = this.CreateWorkItem("Board Column Test", "User Story");

            string wefField = "";

            //find the WEF field
            //todo: do something smarter rather than loop through all fields to find the WEF
            foreach (var field in workItem.Fields)
            {
                if (field.Key.Contains("_Kanban.Column"))
                {
                    wefField = field.Key.ToString();
                    break;
                }
            }

            //build a patch document to update the WEF field
            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Test,
                Path      = "/rev",
                Value     = "1"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/" + wefField,
                Value     = targetColumn
            }
                );

            WorkItem result = witClient.UpdateWorkItemAsync(patchDocument, Convert.ToInt32(workItem.Id)).Result;

            Context.Log("Updated work item to teams board column '" + targetColumn + "'");

            return(result);
        }
Exemplo n.º 23
0
        public WorkItemClassificationNode MoveIteration(string project, string targetIteration, int id)
        {
            WorkItemClassificationNode node = new WorkItemClassificationNode()
            {
                Id            = id,
                StructureType = TreeNodeStructureType.Iteration
            };

            VssConnection connection = new VssConnection(_uri, _credentials);
            WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>();
            WorkItemClassificationNode result = workItemTrackingHttpClient.UpdateClassificationNodeAsync(node, project, TreeStructureGroup.Iterations, targetIteration).Result;

            return(result);
        }
        public static async Task <IEnumerable <WorkItem> > GetWorkItemsAsync(this WorkItemTrackingHttpClient source, IEnumerable <int> ids, bool includeChildren, CancellationToken cancellationToken)
        {
            var expandFlags = WorkItemExpand.Fields;

            if (includeChildren)
            {
                expandFlags = WorkItemExpand.All;
            }

            var results = await source.TryCatchAsync(c => c.GetWorkItemsAsync(ids, expand: expandFlags, errorPolicy: WorkItemErrorPolicy.Omit, cancellationToken: cancellationToken)).ConfigureAwait(false);


            return(results ?? Enumerable.Empty <WorkItem>());
        }
Exemplo n.º 25
0
        /// <summary>
        /// Given an int array, get the list of workitems. Retries 5 times for connection timeouts etc.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async static Task <IList <WorkItem> > GetWorkItemsAsync(WorkItemTrackingHttpClient client, IEnumerable <int> ids, IEnumerable <string> fields = null, WorkItemExpand?expand = null)
        {
            Logger.LogDebug(LogDestination.File, $"Getting work items for {client.BaseAddress.Host}");

            if (ids == null)
            {
                throw new ArgumentNullException(nameof(ids));
            }

            return(await RetryHelper.RetryAsync(async() =>
            {
                return await client.GetWorkItemsAsync(ids, fields: fields, expand: expand);
            }, 5));
        }
Exemplo n.º 26
0
        public WorkItem AddAttachment()
        {
            int    id       = Convert.ToInt32(Context.GetValue <WorkItem>("$newWorkItem3").Id);
            string filePath = ClientSampleHelpers.GetSampleTextFile();

            VssConnection connection = Context.Connection;
            WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>();

            // upload attachment to store and get a reference to that file
            AttachmentReference attachmentReference = workItemTrackingClient.CreateAttachmentAsync(filePath).Result;

            JsonPatchDocument patchDocument = new JsonPatchDocument();

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

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.History",
                Value     = "Adding the necessary spec"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/relations/-",
                Value     = new
                {
                    rel        = "AttachedFile",
                    url        = attachmentReference.Url,
                    attributes = new { comment = "VanDelay Industries - Spec" }
                }
            }
                );

            WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result;

            return(result);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Upload attachment of file at the given path to the issue with given issue id
        ///     from "AzureDevOps-dotnet-samples" repo
        /// Also adds comment about snapshot to work item
        /// </summary>
        /// <param name="path">path to file that should be attached</param>
        /// <param name="issueId">issue id to attach file to</param>
        /// <returns>Task with completed issue ID or null if user is not connected to AzureDevOps</returns>
        internal async Task <int?> AttachTestResultToIssue(string path, int issueId)
        {
            if (!ConnectedToAzureDevOps)
            {
                return(null);
            }
            WorkItemTrackingHttpClient wit = _baseServerConnection.GetClient <WorkItemTrackingHttpClient>();
            AttachmentReference        attachment;

            using (FileStream outputStream = new FileStream(path, FileMode.Open))
            {
                attachment = await wit.CreateAttachmentAsync(outputStream, Invariant($"{issueId}.a11ytest")).ConfigureAwait(false);
            }
            JsonPatchDocument patchDoc = new JsonPatchDocument();

            patchDoc.Add(new JsonPatchOperation()
            {
                Operation = Operation.Test,
                Path      = "/rev",
                Value     = "1"
            }
                         );
            patchDoc.Add(new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.History",
                Value     = "Attached an Accessibility Insights for Windows test file and screenshot."
            }
                         );
            patchDoc.Add(new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/relations/-",
                Value     = new
                {
                    rel        = "AttachedFile",
                    url        = attachment.Url,
                    attributes = new { comment = "Accessibility Insights for Windows test file" }
                }
            }
                         );

#pragma warning disable CA2007 // Do not directly await a Task
#pragma warning disable CA2008 // Do not create tasks without passing a TaskScheduler
            return(await wit.UpdateWorkItemAsync(patchDoc, issueId).ContinueWith(t => t.Result.Id));

#pragma warning restore CA2008 // Do not create tasks without passing a TaskScheduler
#pragma warning restore CA2007 // Do not directly await a Task
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            Uri    accountUri          = new Uri(Helper.ThisIsMyVSTS);
            String personalAccessToken = Helper.ThisIsMyPAT;
            var    workItemIds         = new List <int>();

            workItemIds.Add(1744);      // this is a random list of work item ids in the tpc
            workItemIds.Add(1665);
            workItemIds.Add(29);

            // Create a connection to the account
            VssConnection connection = new VssConnection(accountUri, new VssBasicCredential(string.Empty, personalAccessToken));

            // Get an instance of the work item tracking client
            WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>();

            try
            {
                foreach (var wID in workItemIds)
                {
                    Console.WriteLine("*****************************");
                    Console.WriteLine("*****************************");
                    Console.WriteLine("*** WORK ITEM: {0} *******", wID);
                    Console.WriteLine("*****************************");
                    Console.WriteLine("*****************************");


                    // Get the specified work item
                    WorkItem workitem = witClient.GetWorkItemAsync(wID).Result;

                    // Output the work item's field values
                    foreach (var field in workitem.Fields)
                    {
                        Console.WriteLine("  {0}: {1}", field.Key, field.Value);
                    }

                    Console.WriteLine();
                    Console.WriteLine();
                }
            }
            catch (AggregateException aex)
            {
                VssServiceException vssex = aex.InnerException as VssServiceException;
                if (vssex != null)
                {
                    Console.WriteLine(vssex.Message);
                }
            }
        }
Exemplo n.º 29
0
        private static void GetWorkitems(VssConnection connection, bool update = false)
        {
            Console.WriteLine("Loading workitem info");
            WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>();

            var workitemIds = new int[] { 9, 10 };

            string[] fieldNames = new string[] {
                "System.Id",
                "System.Title",
                "System.WorkItemType"
                // , "Microsoft.VSTS.Scheduling.RemainingWork"
            };

            List <WorkItem> workitems = workItemTrackingClient.GetWorkItemsAsync(workitemIds, fieldNames).Result;

            foreach (var workitem in workitems)
            {
                Console.WriteLine($"Workitem found: {workitem.Id}");
                foreach (var fieldName in fieldNames)
                {
                    Console.Write("  {0}: {1}", fieldName, workitem.Fields[fieldName]);
                }
                Console.WriteLine();
            }

            if (update)
            {
                // create a patchDocument
                JsonPatchDocument patchDocument = new JsonPatchDocument();

                patchDocument.Add(
                    new JsonPatchOperation()
                {
                    Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Add,
                    Path      = "/fields/System.WorkItemType",
                    Value     = "Epic",
                    //From = changedBy
                }
                    );

                var workItemId = workitemIds[1];
                Console.WriteLine($"Updating workitem with id {workItemId}");
                // call for the update
                //var result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, workItemId).Result;
                // show result
                //Console.WriteLine($"Workitem change result: {result.Id}, WorkItemType: {result.Fields["System.WorkItemType"]}");
            }
        }
Exemplo n.º 30
0
        public string CreateWorkItem(string projectName)
        {
            JsonPatchDocument patchDocument = new JsonPatchDocument();

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/System.Title",
                Value     = "Authorization Errors"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/Microsoft.VSTS.TCM.ReproSteps",
                Value     = "Our authorization logic needs to allow for users with Microsoft accounts (formerly Live Ids) - http:// msdn.microsoft.com/en-us/library/live/hh826547.aspx"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/Microsoft.VSTS.Common.Priority",
                Value     = "1"
            }
                );

            patchDocument.Add(
                new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "/fields/Microsoft.VSTS.Common.Severity",
                Value     = "2 - High"
            }
                );

            using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(_uri, _credentials))
            {
                WorkItem result = workItemTrackingHttpClient.CreateWorkItemAsync(patchDocument, projectName, "Bug").Result;
            }

            patchDocument = null;

            return("success");
        }
Exemplo n.º 31
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>();
        }
 private WorkItemTrackingHttpClient CreateWorkItemHttpClient()
 {
     var uri = string.Format(CollectionUri, Connection.ServerUrl, Connection.Collection);
     WorkItemTrackingHttpClient witClient = null;
     if (Regex.IsMatch(uri, "visualstudio.com"))
     {
         witClient = new WorkItemTrackingHttpClient(new Uri(uri), new VssBasicCredential(Connection.UserName, Connection.Password));
     }
     else
     {
         witClient = new WorkItemTrackingHttpClient(new Uri(uri), new VssCredentials(new WindowsCredential(new NetworkCredential(Connection.UserName, Connection.Password))));
     }
     return witClient;
 }