Display tfs work items in GridView using SharePoint Visual Web Part

Here I am explaining, how to displayTFS work items (assigned task) inside your SharePoint application using Visual Web part. This will work for SharePoint on-premise versions like SharePoint 2013/2016.

If you are new to visual web part in SharePoint, read an article on Create and Deploy Visual web part in SharePoint 2013/2016 using Visual Studio 2015/2017.

Display tfs work items in SharePoint

Step-1: First create a visual web part by following the above article.

Step-2: Before we start we need to add below DLLs in the visual web part. Please look into the below screenshot where I have added all required DLL files.

display tfs work items in sharepoint
display tfs work items in sharepoint

Step-3: Next, we need to provide our TFS server URL for communicate with TFS.

tfs work items sharepoint
tfs work items sharepoint

Step-4: In this step, we need to write a query to get the work items or task list from TFS server.

try {
    Wiql wiql = new Wiql() {
        Query = "SELECT [Id], [Title], [State] FROM workitems WHERE [Work Item Type] = 'Task' AND [Assigned To] = @Me"
    };
    using(WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(uri, new VssCredentials())) {
        //execute the query to get the list of work items in the results
        WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;

        //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.Title";
            fields[2] = "System.CreatedDate";
            fields[3] = "System.Reason";


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

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


            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(Int32));
            dt.Columns.Add("Task Name", typeof(string));
            dt.Columns.Add("Task Created Date", typeof(string));
            dt.Columns.Add("Task Status", typeof(string));


            //loop though work items and write to console
            foreach(var workItem in workItems) {
                //Console.WriteLine("ID:{0} Title:{1},AssignedTo:{2},CreatedBy{3}", workItem.Id, workItem.Fields["System.Title"], workItem.Fields["System.RelatedLinkCount"], workItem.Fields["System.AssignedTo"], workItem.Fields["System.CreatedBy"]);
                dt.Rows.Add(workItem.Id, workItem.Fields["System.Title"], workItem.Fields["System.CreatedDate"], workItem.Fields["System.Reason"]);
            }

            GridView11.DataSource = dt;
            GridView11.DataBind();
        }
    }
} catch (Exception ex) {

    // System.Web.HttpContext.Current.Response.Write(ex.Message);
}

Step-5: Now we have to call Grid View Row Data Bound event

tfs work items sharepoint
display tfs work items sharepoint

Step-6: Here I am going to post my whole code so that it will helpful for you.

HTML Code:

<div>
     <h1>TFS Task</h1>
    <asp:GridView ID="GridView11" runat="server" OnRowDataBound="GridView11_RowDataBound"></asp:GridView>
</div>

SharePoint Server Side code:

Below is the full SharePoint server side code to display tfs work items in SharePoint.

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI.WebControls.WebParts;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
using System.Net.Http;
using System.Data;
using System.Collections.Generic;
using System.Web.UI.WebControls;

namespace Rajkiran.Intranet.WebParts.TaskHistory
{

    public partial class TaskHistory : WebPart
    {
        Uri uri = new Uri("http://rajTFS:8080/tfs/tfsrajCollection/");
        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
        // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public TaskHistory()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            getTfsTaskHistory();

        }
        public void getTfsTaskHistory()
        {
            try
            {
                Wiql wiql = new Wiql()
                {
                    Query = "SELECT [Id], [Title], [State] FROM workitems WHERE [Work Item Type] = 'Task' AND [Assigned To] = @Me"
                };
                using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(uri, new VssCredentials()))
                {
                    //execute the query to get the list of work items in the results
                    WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;

                    //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.Title";
                        fields[2] = "System.CreatedDate";
                        fields[3] = "System.Reason";
                       

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

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


                        DataTable dt = new DataTable();
                        dt.Columns.Add("ID", typeof(Int32));
                        dt.Columns.Add("Task Name", typeof(string));
                        dt.Columns.Add("Task Created Date", typeof(string));
                        dt.Columns.Add("Task Status", typeof(string));
                       

                        //loop though work items and write to console
                        foreach (var workItem in workItems)
                        {
                            //Console.WriteLine("ID:{0} Title:{1},AssignedTo:{2},CreatedBy{3}", workItem.Id, workItem.Fields["System.Title"], workItem.Fields["System.RelatedLinkCount"], workItem.Fields["System.AssignedTo"], workItem.Fields["System.CreatedBy"]);
                            dt.Rows.Add(workItem.Id, workItem.Fields["System.Title"], workItem.Fields["System.CreatedDate"],workItem.Fields["System.Reason"]);
                        }

                        GridView11.DataSource = dt;
                        GridView11.DataBind();
                    }
                }
            }


            catch (Exception ex)
            {

              //  System.Web.HttpContext.Current.Response.Write(ex.Message);
            }
        }

        protected void GridView11_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                //add the thead and tbody section programatically
                e.Row.TableSection = TableRowSection.TableHeader;
            }
        }
    }
}

Once you execute this code, you will get the TFS assigned task in a tabular format in SharePoint. You can also bind the same data in jQuery data table.

In above code, I have applied my query for fetching TFS task so we can also apply the same query for getting TFS bugs, Epic, feature and backlog Items by changing one line of code .

 Query = "SELECT [Id], [Title], [State] FROM workitems WHERE [Work Item Type] = 'Task' AND [Assigned To] = @Me"

In above code, we need to change the Work item Type for changing the task to Epic or other. Here I am not able to share my output window due to security reason.

Note: The code is fully tested from my side.

You may like following SharePoint visual web par tutorials:

Hope this SharePoint tutorial helps to display tfs work items in SharePoint visual web part.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>