VSTS - How to create and deploy custom check-in policy

Posted by: Subodh Sohoni , on 5/26/2008, in Category VSTS & TFS (Azure DevOps)
Views: 55734
Abstract: In this article, we are going to take an overview regarding how to create and deploy custom check-in policy. We will explore these topics with an example which refers to a custom workitem type “Code Review” which was created in earlier series of articles.
VSTS - How to create and deploy custom check-in policy
 
In this article, we are going to take an overview regarding how to create and deploy custom check-in policy. We will explore these topics with an example which refers to a custom workitem type “Code Review” which was created in earlier series of articles.
Check-in policy is a watch dog which prevents code to be checked-in if that code does not fulfill certain conditions. Team Foundation Server has three built in check-in policies.
1. Code Analysis Policy: If the static code analysis is not successful the check-in is prevented. This ensures the best practices of coding are adhered to.
2. Workitem Association Policy: If a workitem is not associated with check-in then the check-in does not succeed. Synchronization of work done by a team member and the state of the workitem assigned to do that work is achieved by association of that workitem with the check-in.
3. Test Policy: If the tests in a provided test list fail then the code is not allowed to be checked-in.
Many a times, need arises to ensure some other practice to be followed for the check-in to go ahead. An example that we are going to expand is of code review. Many organizations need that the code be reviewed by another programmer or team lead before it is checked-in. We can implement this governance with the help of a Custom Check-in Policy and the custom workitem type “Code Review”.
The policy workflow will be as follows: Programmer completes the coding involving some files and wants to check them in. Code review policy will not allow that code to be checked-in without it being associated with a workitem of the type “Code Review” that has the status set to “Approved”. This state can be set only by the code reviewer which may be a member of “Code Reviewers” custom group. The programmer puts the code in a shelve set , creates a new workitem of the type “Code Review” and then assigns it to code reviewer. Name of the shelve set is also mentioned in the location field of the workitem. Code reviewer opens the workitem and unshelves the code to review it. Once the code is approved by the reviewer and “Approved” state is set on the workitem, that workitem is assigned back to the programmer so that now that programmer can associate that workitem with the check-in so that the check-in policy will allow the check-in to go ahead.
For this workflow we need to create a custom check-in policy which will check that a workitem of the type “Code Review” is associated with the check-in. We will create this check-in policy and deploy it on the workstations. Custom check-in policy is a component (dll) created using Microsoft .NET code.
 
Creating Custom Check-in Policy
We begin creating the custom check-in policy by starting a new project of the type class library. I gave a name “CodeReviewPolicy” to the project so that the assembly name will be “CodeReviewPolicy.dll”. Code in this uses TFS Object Model. To provide APIs of TFS Object Model we provide references to following assemblies which are provided along with the TFS:
1. Microsoft.TeamFoundation.VersionControl.Client.dll (This is required to access the checkin which is part of the version control.)
2. Microsoft.TeamFoundation.WorkitemTracking.Client.dll (This is required to access the workitems related data.)
Location of these assemblies is at: \Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies
We start the coding by setting the Microsoft.TeamFoundation.VersionControl.Client.PolicyBase abstract class as the base class to the class in newly created class library. PolicyBase class implements two custom interfaces IPolicyDefinition and IPolicyEvaluation. Let us find out how these interfaces provide us template for necessary methods and properties and how to implement those.
In IPolicyDefinition get methods and properties to define the basic structure of the policy. It has a only one method named ‘Edit’ which is used to open a custom UI for editing the configuration of policy when edit button is clicked in the Add / Remove Checkin Policy dialog box. It also has following properties:
CanEdit (Boolean): Allow the ‘Edit’ method to show configuration UI or not.
Description (String): How the policy works
InstallationInstructions (String): If the policy is enabled on the TFS but is not present and installed on the client, what message should be shown to user to download and install the policy assembly.
 Type (String): Name of the checkin policy that appears in the Add / Remove checkin policydialog box.
TypeDescription(String): Long description of checkin policy.
The IPolicyEvaluation interface provides an event of the type PolicyStateChangedHandler which is raised when the policy state is changed.
The most important method offered by this interface is Evaluate which returns all the data if evaluation fails. This method is called at either of these instances:
1. When activated.
2. When user explicitely selects the policy in the checkin dialog box and then selects ‘evaluate’ from the context menu by right clicking on it.
3. When the pending changes are changed or refreshed.
We put our custom logic in this method. For example we want to check that a “Code Review” type workitem that has status ‘Approved’ is associated with this check-in. Code for that uses Team Foundation object model and looks like this:
public override PolicyFailure[] Evaluate()
        {
            if (this.Disposed)
            {
                throw new ObjectDisposedException(Strings.policyType, Strings.policyDisposedMessage);
            }
 
            ArrayList changes = new ArrayList();
            WorkItem AssociatedCodeReview = null;
 
           // Get the associated code review from all workitems associated with checkin  
            foreach (WorkItemCheckinInfo wi in this.PendingCheckin.WorkItems.CheckedWorkItems)
            {
                if (wi.WorkItem.Type.Name == "Code Review")
                {
                    AssociatedCodeReview = wi.WorkItem;
                    break;
                }
            }
            //Check that associated code review is present and has ‘Approved’ state.
            if (AssociatedCodeReview == null || AssociatedCodeReview.State != "Approved")
            {
                PolicyFailure failure = new PolicyFailure(Strings.activateMessage, this);
                changes.Add(failure);
            }
            return (PolicyFailure[])changes.ToArray(typeof(PolicyFailure));
        }
 
Full code can be downloaded from accompanying file over here.
Deployment of custom check-in policy
Once the policy is created, it is added to the list of available policies by making an entry in the registry. We begin by creating the registry entry on the TFS. The key which is required to be edited: HKEY_LOCAL_MACHINE/Software/Microsoft/VisualStudio/9.0/TeamFoundation/SourceControl/CheckinPolicies. We create a new string value in this key. Name of the string value is the name of the file which contains our custom policy; without the extension(.dll). In our example it is “CodeReviewPolicy”. The value to this string is the name with path of the assembly we have created (for example: C:\Documents and Settings\TFSSETUP\My Documents\Visual Studio 2008\Projects\CodeReviewPolicy\CodeReviewPolicy\bin\Debug\CodeReviewPolicy.dll).
We can enable this policy from the Team Explorer. When we open Team Project Settings – Source Control – Check-In policy – Add, we can see “Code Review Policy” listed there. We add that policy. Now we need to deploy the policy assembly to the client workstations. We can do that by sending the path of the assembly in the intranet or we can put it to download from a ftp site or a virtual directory. We can also use the click-once technology or smart client technology to distribute the assembly. When a policy is enabled on the TFS for a Team Project but is not installed on the client then at the time of check-in the message which is set in the property “InstallationInstruction” is shown to the users. These installation instructions should mention the site or the location from where the assembly can be downloaded and way to install it by creating the necessary registry entry.
Conclusion
Custom check-in policy helps us in ensuring that certain conditions are met for the check-in to succeed. In this article we have seen how to create a custom check-in policy and deploy it.   I hope this article was useful and I thank you for viewing it.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Subodh is a consultant and corporate trainer. He has overall 28+ years of experience. His specialization is Application Lifecycle Management and Team Foundation Server. He is Microsoft MVP – VS ALM, MCSD – ALM and MCT. He has conducted more than 300 corporate trainings and consulting assignments. He is also a Professional SCRUM Master. He guides teams to become Agile and implement SCRUM. Subodh is authorized by Microsoft to do ALM Assessments on behalf of Microsoft. Follow him on twitter @subodhsohoni


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by annie on Tuesday, March 31, 2009 9:07 AM
I tried this out,deployed the policy, but when I try to check-in , I get INternal Error on Check-in policy, and then a msg on the Source control tab "Error loading policy( The Policy assembly 'Version=1.0.0.0,Culture=neutral,PublicKeyToken=null' is not registered).Installation instructions:Sorry,NO instructions are available at this time".
Comment posted by Jitendra Biyani on Wednesday, June 10, 2009 10:23 AM
I follow all instructions as it is and I found the policy in the list box. But when I select and add it nothing happens. Though I m able to add another policy like 'Code Analysis' but I am not able to add this 'Code Review Policy'.

Please help me out urgently.
Comment posted by Nick Henny on Thursday, July 9, 2009 3:29 PM
I have the same problem as Jitendra...I see the policy in the "add check-in policy" but it never gets added...Check-in Policy tab remains blank...what am I missing?
Comment posted by Subodh Sohoni on Friday, July 17, 2009 11:49 PM
I am sorry for the delayed response. The issue had me foxed for some time. I also had this problem sometimes. I realized that this problem comes when we derive our class from abstract class PolicyBase. It inturn implements two interfaces IPolicyDefinition and IPolicyEvaluation. If we directly implement those then this problem is resolved. One example that I have created is published recently. You may have a look at: http://www.dotnetcurry.com/ShowArticle.aspx?ID=350.
Comment posted by DeLon on Saturday, July 18, 2009 11:18 AM
useful link.
Comment posted by Yigael Oscar on Wednesday, February 16, 2011 10:44 AM
Is there an updated version for TFS 2010?
Comment posted by Make on Thursday, May 7, 2015 4:00 AM
Useful blog thank you. I need code control in exclude sql statement. How to control code in sql statement?

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook