tfscheckin-policy

How to create PolicyEnvelope for a custom checkin policy in visual studio 2010?


I create a custom checkin policy for TFS 2010 in visual studio 2010. The policy itself in working great. Now, I am trying to apply the custom policy from code. Below is my code:

try
        {
            var projectCollectionUri = new Uri("https://mydomain.com/tfs");
            var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(projectCollectionUri, new UICredentialsProvider());
            projectCollection.EnsureAuthenticated();

            var vcs = projectCollection.GetService<VersionControlServer>();

            var teamProject = vcs.GetTeamProject("myProject");

            foreach (PolicyType policyType in Workstation.Current.InstalledPolicyTypes)
            {
                if (policyType.Name.ToLower().Contains("MyPolicyType"))
                {
                    //teamProject.SetCheckinPolicies(new PolicyEnvelope[] { new PolicyEnvelope(workItemPolicy, policyType) });
                    //break;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

I am stuck at this line:

//teamProject.SetCheckinPolicies(new PolicyEnvelope[] { new PolicyEnvelope(workItemPolicy, policyType) });

How can I create the policy envelope for my custom policy? The code I am referencing is from the below location: http://bartwullems.blogspot.com/2012/02/team-foundation-server-2010-enable.html


Solution

  • You just need to replace the WorkItemPolicy in the example with your policy:

    For example:

    var myPolicy = new MyPolicy();
    
    foreach (PolicyType policyType in Workstation.Current.InstalledPolicyTypes)
    {
        if (policyType.Name == myPolicy.Type)
        {
            teamProject.SetCheckinPolicies(
                new PolicyEnvelope[]
                {
                    new PolicyEnvelope(myPolicy, policyType)
                });
            break;
        }
    }
    

    You may need to add a reference to the assembly containing your policy if you do not have it in you Console Application.