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").
Consider downloading the sample project to try it out.

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 System.IO;
using System.Reflection;
using StyleCop;

namespace StyleCopRun
{
	/// <summary>
	/// Simple example for running StyleCop environment.
	/// </summary>
	public class Program
	{
		/// <summary>
		/// Main program entry.
		/// </summary>
		public static void Main(string[] args)
		{
			var projectPath = Path.GetDirectoryName(
				Path.GetDirectoryName(
					Path.GetDirectoryName(
						Assembly.GetExecutingAssembly().Location)));

			string filePath = Path.Combine(projectPath, "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.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:

StyleCopRun.png

Last edited May 7 at 1:54 AM by shuruev, version 9

Comments

haison8x Jul 17, 2013 at 4: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?