Running StyleCop from Your Code

This is a very simple example of how StyleCop could be run from your code.

Create Console Application

Create C# console application targeting .NET 3.5 or .NET 4.0 (full version, not "Client Profile").

Add references to the following binaries (can be found in StyleCop installation folder):
  • StyleCop
  • StyleCop.CSharp
  • StyleCop.CSharp.Rules

Use source code below as an example:

using System;
using StyleCop;

namespace StyleCopRun.Simple
{
	/// <summary>
	/// Simple example for running StyleCop environment.
	/// </summary>
	public class Program
	{
		/// <summary>
		/// Main program entry.
		/// </summary>
		public static void Main(string[] args)
		{
			string projectPath = @"D:\TestProject\";
			string filePath = @"D:\TestProject\Class1.cs";

			StyleCopConsole console = new StyleCopConsole(
				null,
				false,
				null,
				null,
				true);

			CodeProject project = new CodeProject(
				0,
				projectPath,
				new Configuration(null));

			console.Core.Environment.AddSourceCode(project, filePath, null);

			console.OutputGenerated += OnOutputGenerated;
			console.ViolationEncountered += OnViolationEncountered;
			console.Start(new[] { project }, true);
			console.OutputGenerated -= OnOutputGenerated;
			console.ViolationEncountered -= OnViolationEncountered;
			console.Dispose();

			Console.WriteLine("Press any key to exit...");
			Console.ReadKey();
		}

		/// <summary>
		/// Handles generated output.
		/// </summary>
		private static void OnOutputGenerated(
			object sender,
			OutputEventArgs e)
		{
			Console.WriteLine(e.Output);
		}

		/// <summary>
		/// Handles encountered violations.
		/// </summary>
		private static void OnViolationEncountered(
			object sender,
			ViolationEventArgs e)
		{
			Console.WriteLine(
				"{0}: {1}",
				e.Violation.Rule.CheckId,
				e.Message);
		}
	}
}

Run Your Application

After running it should display a console with some output:

StyleCopRunSimple.png

Last edited Mar 18, 2012 at 3:48 PM by shuruev, version 7

Comments

haison8x Jul 17, 2013 at 3:01 AM 
I build a custom dll CustomStyleCop.dll to override some rule of original StyleCop. However it only runs with Visual Studio but Console. Can you help me?