Documentation Center

Sample .NET spam filter implementation

This sample spam filter in Java rejects comments if they contain one of the strings configured in web.config.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tridion.ContentDelivery.UGC.WebService;
using Tridion.ContentDelivery.UGC.Web.Model;
using Tridion.ContentDelivery.UGC.Web.Utilities;
using Tridion.ContentDelivery.AmbientData;
using System.Configuration;

namespace UGCSample
{
  public class WordsSpamFilter : SpamFilter
  {
    // Collect a list of disallowed words

    IList<string> spamWords = new List<string>;
    
    public WordsSpamFilter()
    {
      bool hasExcludes = true;
      int i = 1;
      while (hasExcludes)
      {
        string spamFilterWord = ConfigurationSettings.AppSettings("Comment.SpamFilter.Exclude" + i);
        if (!string.IsNullOrEmpty(spamFilterWord))
        {
          spamWords.Add(spamFilterWord);
        }
        else
        {
          hasExcludes = false;
        }
        i++;
      }
    }

    /// <summary>
    /// Validate a comment.
    /// </summary>
    /// <param name="claimStore">The Claim Store from the current request.</param>
    /// <param name="comment">The comment to validate.</param>
    /// <returns>A valid comment.</returns>
    /// <exception cref="SpamFilterException">If comment is regarded as spam.</exception>
    public Comment ValidateComment(ClaimStore claimStore, Commant comment)
    {
      string commentContent = comment.Content;

      if (String.IsNullOrEmpty(commentContent))
      {
        throw new SpamFilterException("Comment cannot be empty.");
      }
      else
      {
        foreach (string spamWord in spamWords) 
        {
          if (commentContent.contains(spamWord))
          {
            throw new SpamFilterException("Comment rejected: contains the word '" + spamWord + "'");
          }
        }
        // The comment contains none of the configured words, so it is acceptable.
        return comment;
      }
    }
  }
}

The accompanying configuration fragment found in the web.config could, for example, be as follows:

<add key="Comment.SpamFilter.Assembly" value="UGCSample" />
<add key="Comment.SpamFilter.Implementation" value="UGCSample.WordsSpamFilter" />
<add key="Comment.SpamFilter.Exclude1" value="poker" />
<add key="Comment.SpamFilter.Exclude2" value="enlargement" />
<add key="Comment.SpamFilter.Exclude3" value="NOW!" />

This would make the class reject any comment containing the strings "poker", "enlargement" and "NOW!"