Showing posts with label TFS Programming. Show all posts
Showing posts with label TFS Programming. Show all posts

Tuesday, June 22, 2021

Close all overdue Azure DevOps work items with Python

As software engineers, we need to track our work items even if we are working as freelancers or for an enterprise. Those work items constitute the health of the project also helping the management to understand the high-level view. Every company has its own ALM software to track the work. One of the famous ALM is Azure DevOps (ADO hereafter) from Microsoft.

Problem

In an ideal situation, we should plan our tasks for every day. Good if we can plan in advance and close the work items as soon as it's done. But sometimes we may not be able to make the ADO work items sync with reality. It may be due to long release days. Unexpected support issues, shortage of team members, etc. At the end of the billing cycle finance department will be chasing us to close work items. At that time closing each and every item manually is time-consuming. There are many ways to tackle it such as import to Excel close all and sync. We may use any no-code low-code platforms such as Power Automate to automate the task. Developers who use those platforms normally called 'citizen developers'. I strongly recommend trying any of these methods to automate this type of work. There is no need to code.

The no-code, low-code platforms generally offer building blocks to do simple day-to-day operations then provide extensibility via plug-ins or by invoking web requests / Web APIs. The plug-ins require coding efforts. Invoking web requests needs deep knowledge of Web APIs and how the service is structured.

Potential solution

As developers, we are proud of our programming ability and may not want to become citizen developers. For those, there are SDKs available to automate Azure DevOps work items. Also when the no-code, low-code platform doesn't have required customizations, we have to use the SDKs or make direct Web API calls to Azure Dev Ops.

We can use the Python SDK given by Azure DevOps as one of the mediums to interact with Azure Dev Ops to close all the OverDue work items.

Code is available on GitHub.

How to use is already documented in the readme.md files. Please follow that.

Code walkthrough

The Git Repo has enough comments. I am also planning a YouTube video explaining the same.

Monday, May 20, 2013

Creating bug work item programatically using TFS 2010 sdk and assign to a user

If you had gone through my previous TFS SDK articles listed below you will be familiar with TFS programming.

http://joymonscode.blogspot.in/2009/05/beginning-tfs-programming.html
http://joymonscode.blogspot.in/2013/04/find-out-name-of-last-checked-in-user.html

As you know using TFS sdk is really simple as knowing how to create the service and basic TFS object model.So what is special about creating TFS bug work item and assign to a developer?

Changing 'Assigned to' field of Work Item object

The speciality is about how you specify the user in the bug. In other words how to set the "Assigned To" field of TFS work item from code? When we list out the bugs in Visual Studio, you might have noticed that the Assigned To column shows the display name. This gives an impression that the TFS is converting the user name to display name for the display purpose. But unfortunately its not.

Hope you know the difference about the username and display name. Username is the unique identification for a user. It didn't allows space in between. But in the display name it allows white spaces as its only for display purpose, not to uniquely identify the user.

Usual user name format - domain\username eg: "companyname\joyg"
Usual display name format - <full name> <last name> eg: "Joy George K"

The point here in creating and assigning TFS bug to a user is, we need to specify the display name in the 'Assigned To' field of WorkItem object instead of the user name. The challenge is most of the other services of TFS returns the username which needs to be converted to Display name before assigning the work item to the user. See the below code to create and assign a work item to a user

        private void AddBug(string userDisplayName)
        {
            WorkItemStore wis = GetWorkItemStore();
            Project tp = wis.Projects[_teamProject];
 
            WorkItemType wit = tp.WorkItemTypes["Bug"];
 
            WorkItem wi = new WorkItem(wit);
            //"[Assigned to] must be display name eg: Joy George K"
            wi.Fields["Assigned to"].Value = userDisplayName; 
            wi.Title = "Bug from TFS sdk demo";
            wi.Description = "Bug from TFS sdk demo";
            ArrayList al = wi.Validate();
            if(al.Count ==0) wi.Save();
        }
        private static WorkItemStore GetWorkItemStore()
        {             TeamFoundationServer tfs = new TeamFoundationServer(new Uri(Path.Combine(_myTFSUri, _teamProjectCollectionName)));             WorkItemStore vcs = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));             return vcs;         }

Get display name from username

As I told earlier, most of the other TFS services return username instead of display name. So it is required to convert username to display name, if you are using the result of other services to create work item against a particular user. Below is the code to convert user name to display name.

        private string GetDisplayNameFromUserName(string userName)
        {
            IGroupSecurityService grpservice = GetGroupSecurityService();
            return grpservice.ReadIdentityFromSource(SearchFactor.AccountName, userName).DisplayName;
        }

        private IGroupSecurityService GetGroupSecurityService()
        {
            TeamFoundationServer tfs = new TeamFoundationServer(new Uri(Path.Combine(_myTFSUri, _teamProjectCollectionName)));
            IGroupSecurityService gss = (IGroupSecurityService)tfs.GetService(typeof(IGroupSecurityService));
            return gss;
        }

Happy coding...

Tuesday, April 30, 2013

Find out name of last checked in user programatically using TFS 2010 SDK

Below is a code snippet used in a POC related to automated code review mechanism using FxCop and TFS 2010. The details of how that code review is going to work cannot be revealed now. May be after incorporation of the same into our projects and with permission.

Basics about TFS programming using TFS 2010 SDK

If you are new to TFS and programming TFS system, please read my earlier post about the same. Only change from the earlier post is the location of TFS SDK dlls. In VS 2010 the location is changed to

[Install drive]:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0

The main thing you need to know in programming TFS is, how to create the service object, which is interacting with the different features of TFS, such as work items, source code handling, user management etc...And of course the TFS object model exposed via the sdk dlls.

Getting the details of last checked in user of TFS file / folder

Once you obtained the instance to the corresponding service its the matter of querying for the result or performing the action using suitable method. In this case the TFS Service we need to get is VersionControlServer object and the change sets can be obtained using the  QueryHistory method.

//tfsFilePath should be in the TFS format ie starting with $\<TFS project>\<folder>
        
private string GetLastCheckedInUser(string tfsFilePath)
        {
            IGroupSecurityService grpservice = GetGroupSecurityService();
            VersionControlServer vcs = GetVersionControlServer();
 
            System.Collections.IEnumerable enumerableResult = vcs.QueryHistory(
                path: tfsFilePath,
                version: VersionSpec.Latest,
                deletionId: 0,
                recursion: RecursionType.Full,
                user: "",
                versionFrom: null,
                versionTo: VersionSpec.Latest,
                maxCount: 1,
                includeChanges: true,
                slotMode: true,
                includeDownloadInfo: false,
                sortAscending: false);
            //sortAscending give the last checked in user. enumerableResult is supposed to contain only one item as the maxCount is 1
            foreach (Changeset cs in enumerableResult)
            {
                string comitter = cs.Committer;
                //eventhough cs.CommitterDisplayName property is available, sometime it may return the result as domain\\username.So convert it to displayName using group account service.
                return grpservice.ReadIdentityFromSource(SearchFactor.AccountName, cs.Committer).DisplayName;
            }
            return null;
        }

If you alter the QueryHistory method you can achieve so many things.

Friday, May 22, 2009

Beginning tfs programming

Some readers may not have knowledge about the new project management framework introduced by Microsoft.So let’s start from what is Team Foundation Server.

What is tfs
Simply saying tfs is a replacement for the existing source control mechanisms such as VSS.But it has got so many additional features like bug tracking,bug automation,reporting etc... In earlier days we have use different tools to do these tasks such as VSS for source control,OnTime for bug tracking etc…Now everything  under one umbrella.So it is more like a project management environment.See what wikipedia says about tfs.

WorkItems contains all the bugs,feature request along with all other tasks.The main advantage of tfs which I have seen is we can associate a source file check in with a bug id easily.

Introduction to Team Foundation Server programming.
Another big advantage of tfs is it’s programming interface.We can easily develop programs which access tfs.We can create work items,log bugs view work items etc…
Microsoft has provided .net libraries for working with tfs.Those dlls normally reside in the folder
[Install drive]:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies
Most of the tfs related dlls have name starting with “Microsoft.TeamFoundation”. Here are the commonly used tfs dlls in developing applications.

  • Microsoft.TeamFoundation.Client.dll
  • Microsoft.TeamFoundation.WorkItemTracking.Client.dll

Authenticating into tfs server
Like any other source control system tfs too stores files and data in a remote server and it needs authentication to that server before accessing tfs resources.Here is the code which authenticate a user into tfs system from our application.

NetworkCredential tfsCredential = new NetworkCredential(login, password);
TeamFoundationServer tfs = new TeamFoundationServer(tfsName, tfsCredential);
tfs.Authenticate();

Here login is the login id of the user and tfs name is the full url of the tfs server.eg https://mytfs.mycompany.com:443/
Once the user is authenticated we can query work items as well.

Listing all projects of user in tfs


//Connecting Server
NetworkCredential tfsCredential = new NetworkCredential(login, password);
TeamFoundationServer tfs = new TeamFoundationServer(tfsName, tfsCredential);
tfs.Authenticate();

WorkItemStore wis = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));

//Iterate Through Projects
foreach (Project project in wis.Projects)
{
Console.WriteLine(project.Name);
lvProjects.Items.Add(new ListViewItem() { Text = project.Name });
}


No need to explain I think.Just adding all the projects into a ListView.

Listing work items in a Project


private void LoadWorkItems(Project project)
{
WorkItemCollection wic = project.Store.Query(
" SELECT [System.Id], [System.WorkItemType]," +
" [System.State], [System.AssignedTo], [System.Title] " +
" FROM WorkItems " +
" WHERE [System.TeamProject] = '" + project.Name +
"' ORDER BY [System.WorkItemType], [System.Id]");
foreach (WorkItem wi in wic)
{
lbWorkItems.Items.Add(wi);
}
}


Again a self explanatory code.Adds all work items into another list box.


A WIME (Works In My Environment) sample is available here.