Blog

Custom TDS Validators

April 15, 2015 | Charlie Turano

#TBT - Throwback Thursday

With the increased popularity of a modular architecture the likelihood of broken builds increase. Accordingly, we've been getting a lot of questions about the TDS Build Validators. TDS Build Validators were introduced in version 5.0; while they are not necessarily vital to the overall TDS build process, they can be very useful when setting up warnings and constraints against certain conditions that might occur during a build process. Custom Validators are a good option, and we at Hedgehog Development want TDS users to know that they are out there and available for use. We think this classic post is extremely relevant today. Enjoy! - CT (2/10/2016)

Introduction

One of the coolest new features of TDS 5 was Validators. Validators allow a developer to have the build automatically check the Sitecore items in the TDS project against specific criteria and generate warnings or errors if the item meets the criteria.

TDS offers a good selection of validators right out of the box. Recently, Nikola, who is one of our Sitecore MVP's, created a couple of custom validators and released them on our GitHib. You can find them here: TDS Custom Validators. Please feel free to add to the Validators there so we can share them with the rest of the community.

This blog post will document the process of setting up your own custom validator.

Setting up the project

Custom validators are contained in a standard class library project. They require references to two assemblies and need to be located in the C:\Program Files (x86)\MSBuild\HedgehogDevelopment\SitecoreProject\v9.0 folder.

The two assemblies from TDS you need to reference are located in C:\Program Files (x86)\MSBuild\HedgehogDevelopment\SitecoreProject\v9.0. The names of the assemblies are HedgehogDevelopment.SitecoreCommon.Data.dll and HedgehogDevelopment.SitecoreProject.Tasks.dll.

Once the references have been added to your project, we have one last task before creating the validator class. TDS needs an attribute on the assembly so it can easily find the assemblies containing validators. This is done in the Properties/AssemblyInfo.cs file by adding the following to the bottom of the file:

// This assembly contains TDS Validators
[assembly: HedgehogDevelopment.SitecoreProject.Tasks.ProjectAnalysis.ContainsValidators]

Creating the validator

Adding a validator class only requires a few simple steps:

  1. Add a class to the project
  2. Make the class public
  3. Set the class to inherit from UserConfigurableValidator (this is in the namespace HedgehogDevelopment.SitecoreProject.Tasks.ProjectAnalysis)
  4. Add a Validator attribute to the class.

Your class should look something like:

[Validator("SAMPLE001", Status.Warn, 
    Description = "Ensures all children of an item begins with 'A'")]
public class EnsureChildrenStartWithA : UserConfigurableValidator
{
    public override IEnumerable<Problem> Validate(Dictionary<Guid,
        SitecoreDeployInfo> projectItems, XDocument scprojDocument)
    {
    }
}

 

You can provide a more robust description and links to help text when you declare the Validator attribute. This is done using the named parameters exposed by the Validator attribute.

If you want to provide some default properties for the user, you can override the GetDefaultSettings() method like this:

public override ValidatorSettings GetDefaultSettings()
{
    //Return a default list of locations to check
    return new ValidatorSettings
    {
        Properties = new List<string> { "/sitecore/content/Home" }
    };
}

The validation code

I chose to make a very simple validator as an example. This validator makes sure all children of an item begin with the letter 'A'. The validator has no real use. I created it because I wanted to focus on the creation of the validator instead of implementing a validation rule.

The final code for the validator:

[Validator("SAMPLE001", Status.Warn, Description = "Ensures all children of an item begins with 'A'")]
public class EnsureChildrenStartWithA : UserConfigurableValidator
{
    public override IEnumerable<Problem> Validate(Dictionary<Guid,
            SitecoreDeployInfo> projectItems, XDocument scprojDocument)
    {
#if DEBUG
        Debugger.Launch();
#endif

        //Loop through the parsed project items
        foreach (SitecoreDeployInfo projectItem in projectItems.Values)
        {
            //Get the parent path from the parsed information
            string itemParent = projectItem.Item.Parent.SitecoreItemPath;

            //Loop through all user specified paths in the Settings
            foreach (string parentPath in Settings.Properties)
            {
                //See if they match using a case insensitive compare
                if (string.Compare(itemParent, parentPath, true) == 0)
                {
                    //See if the item name starts with 'A'
                    if (!projectItem.ParsedItem.Name.StartsWith("A"))
                    {
                        //return an error if it does
                        yield return new Problem(this, new ProblemLocation(projectItem.Item.ItemFile), 
                                string.Format("Item '{0}' doesn't start with 'A'", projectItem.ParsedItem.Path));
                    }
                }
            }
        }
    }

    public override ValidatorSettings GetDefaultSettings()
    {
        //Return a default list of locations to check
        return new ValidatorSettings
        {
            Properties = new List<string> { "/sitecore/content/Home" }
        };
    }
}

Installing the Validator

Installing the validator is as simple as copying the compiled assembly (and .pdb) into the folder C:\Program Files (x86)\MSBuild\HedgehogDevelopment\SitecoreProject\v9.0. When you open the Validator tab on the TDS project property page, the validator will be loaded and shown in the list of known validators. If you wish to copy a new version of the validator assembly into the folder, you may need to shutdown Visual Studio to unlock the file.

Debugging the Validator

The easiest way to debug the validator is to call the Debugger.Launch() method in the validator. This will prompt the developer to launch/attach a debugger when the validator is executed during the build process.

Conclusion

Creating and debugging custom validators is very simple. The code in this project should serve as a good starting point for creating your own validators. The validators Nikola created on GitHub are really good examples of how to create more advanced custom validators. Please feel free to grab our repo and add some validators of your own!

TDS Validators Best Of TDS 2015

Related Blog Posts

Sitecore Package Deployer
Creating an automated deployment process around Sitecore update packages can be difficult. The Sitecore Package Deployer is designed to simplify that process by automatically deploying packages from a folder on the Sitecore server.
Setting Visual Studio Online up with TDS
More and more people are starting to use Visual Studio Online. Since TDS 5.0, we supported use with Visual Studio Online. The set up; however, is a bit different with VSO than your local installation.&nbsp;This post will explain how to set up TDS within Visual Studio Online.
Enabling HTTPS Support in TDS
A lot of people ask about leveraging a HTTPS connection between their machine and the server. This connection is fully supported, out of the box with TDS. To implement this type of connection you simply need to make sure your certificates are properly managed.
Setting Up Authenticated Access with TDS
Every now and again TDS users want to use an authenticated connection to the server. A majority of our users use unauthenticated, but we still need to support authenticated connections. Setting up an authenticated connection is simple and only requires a few additions to your TDS .config files.