![]() |
General Programming »
Macros and Add-ins »
VS.NET Addins
Intermediate
License: The Code Project Open License (CPOL)
Commenter - A CodeRush Plugin which Helps you to Comment your CodeBy exDreamDuckWriting a CodeRush plugin commenter will help you to comment your code and make it easier to navigate through your code. |
C++, C#, Windows, .NET 1.0, .NET 1.1, .NET 2.0VS.NET2003, VS2005, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
Commenter is a plugin for CodeRush, which is an addin for Visual Studio (Visual Studio 2002, 2003, 2005 and 2008 are supported). Basically Commenter will help you to comment your code and make it easier to navigate through your code. Currently Commenter supports only C#, but C++ might work too (but may need some additional testing). Support for VB.NET might be added if requested, don't know if VB guys would like such a feature. The project files use Visual Studio 2003, but you can convert them to Visual Studio 2005 or Visual Studio 2002 as well and everything should work fine too. (Note: Since v1.8 all files are for Visual Studio 2008.)
This article is still based on the CR_Commenter version 1.0, since 2004 CR_Commenter was updated 9 times already and is in version 1.9 right now (2008-11-27). For an updated feature list and many more screenshots, check out this blog entry!
Just be sure to change the start-program to the correct devenv.exe too (for testing).
Note: I have nothing to do with the Developers of CodeRush, I just like their tool and think it's easier to write Visual Studio plugins with it.
I will also cover how to write and use a CodeRush plugin, it seems like there is no tutorial on the net for this. The Commenter could also be implemented as a native Visual Studio plugin, but this would be much harder (parsing, etc.), also anyone using my plugin should also useCodeRush to improve his development speed.
Let's take a look at some actual code and how it would look when using Commenter:
As you can see in the image above, there are several features supported in Commenter. The Commenter will only do its work when you press '}' to end a code block, the only exception is when you double-click on an auto-generated comment, then your cursor will jump to the class or method.
The features are listed below:
public function or class, but may need XML comments (e.g. for checking your code with FxCop), an XML comment will be generated for you. You should of course modify this comment or add text to it when required. Just having an XML comment will motivate you most times to write some comments there anyway. When opening the DevExpress -> Options page, you can select the Commenter options page and configurate the Commenter and use as many features as you like. The options page looks like this:
First of all, you need to have CodeRush installed, you can use the trial version without any limitations (except some nag box at startup I think) and start writing plugins for that. But you should support the guys at DevExpress for their work and buy the product.
It's also good to make yourself comfortable with CodeRush, the available plugins and how everything works before you start programming a plugin, also read the help!
Ok, first step it to start Visual Studio and select DevExpress -> New plugin from the menu. Now select your language (C#/VB.NET), enter the name of the project and click a couple of times next (see if you want to make some other choices like including an options page for your plugin). I called my project CR_Test, CR_ is the default name prefix for all plugin DLL files, CodeRush will automatically rename the plugin to Test and the source file to TestPlugIn.cs (the project is still named CR_Test):
Ok, now we got a TestPlugIn.cs, click on properties in design view and select events (the yellow flash icon, in case you don't know). Now you see a lot of standard Visual Studio plugin events and CodeRush events. At first it won't be easy to find out which event is the correct one for your project. There is also an incredible mass of classes and functions in CodeRush, which makes it very hard to start doing anything at first (because you don't know where to start). Here is a quick overview about some important CodeRush classes, you might need:
EventArgs passed to you from the event. e.g. TextView, pressed character, the document, the current selection, etc. CodeRush.TextDocument, you can get the current source file the user is working on with (you won't need that if EventArgs gives you the document instance already):
// The text document we are currently working on
TextDocument document = (TextDocument)
CodeRush.Documents.ActiveTextDocument;
Don't forget to check if document is valid now, maybe there is currently no active file selected, then we can't proceed. When you are not sure everything is parsed correctly (maybe something was changed), just call document.ParseIfTextChanged();
CodeRush.Selection (if you get an active document, use document.Selection) contains information about the currently selected code, most likely you will be interested in the current cursor position:
int currentLine = document.Selection.ActivePoint.Line,
currentLineOffset = document.Selection.ActivePoint.LineCharOffset;
CodeRush.Source.Active, there are also a lot of other Active- properties (current class, namespace, method, etc.) and all nodes are connected to each other (we got a parent, children and detail nodes):
.Nodes, detail nodes (e.g. for parameters or conditions) can be accessed with .DetailNodes and the parent can be found at .Parent.
// Get active section (don't forget to check if its valid!)
LanguageElement activeSection = CodeRush.Source.Active;
LanguageElement activeNamespace = CodeRush.Source.ActiveNamespace;
// Get type (class, method, if, while, namespace, etc.)
LanguageElementType sectionType = activeSection.ElementType;
LanguageElement contains only the common properties of elements, but if you got an if condition block, a while code block, a method, the namespace, etc., you might want to access the more specified derived classes. For example, we need DelimiterCapableBlock to check code blocks:
// First check if activeSection is a sub class
//of DelimterCapableBlock
if (activeSection.GetType().IsSubclassOf(
typeof(DelimiterCapableBlock)))
{
DelimiterCapableBlock codeBlock =
(DelimiterCapableBlock)activeSection;
// Check out some properties
bool isCodeBlock = codeBlock.HasDelimitedBlock;
} // if (activeSection.GetType)
CodeRush.TextView may be provided by EventArgs, it will help you to navigate through the currently visible source code and allows you to jump around or select anything. document.FileNode.PathSegment or when you need the current line from TextView use ea.TextView.Caret.LineText, you will have to find out this stuff by yourself when trying to solve your problems. Sometimes it may be easier to implement functionality yourself, if you can't find it, it may not exist or it does not match your requirements. The Commenter uses some of my helper classes to simplify things:
CodeRushHelper: Provides some functionality required by Commenter to get names of sections recursively or find code blocks by the element name. Log: Helper class to log info text, errors and exceptions to a text file, sometimes debugging complex problems is harder than just log what's happening and then see in the log what's going on. It's also useful to profile code and check out which parts are slow or need optimizations. StringHelper: A rich class providing a lot of extra functionality for comparing, checking, writing and handling text strings. Okay, enough bubbling around, let's write some actual code. I will only show you a very small part of Commenter (because it would be too complex for this tutorial, read the Commenter source code to find out more about how it works). We will try to add a simple comment with the type of the code block. This means we will convert a code block like this...
if (money > 1000)
{
money *= 2;
}
... to the following:
if (money > 1000)
{
money *= 2;
} // if
First of all, we add an Event to catch if '}' was pressed. Use TestPlugIn designer view -> Properties -> Events and create a EditorCharacterTyped event and paste this code (some of it was already explained above):
private void TestPlugIn_EditorCharacterTyped(
EditorCharacterTypedEventArgs ea)
{
// Only check if '}' was pressed
if (ea.Character == '}' &&
CodeRush.Source.ActiveFileNode != null &&
CodeRush.Source.ActiveFileNode.Document != null)
{
// The text document we are currently working on
TextDocument document = (TextDocument)
CodeRush.Documents.ActiveTextDocument;
int currentLine = document.Selection.ActivePoint.Line,
currentLineOffset = document.Selection.ActivePoint.LineCharOffset;
// Get active code block
LanguageElement activeCodeBlock = CodeRush.Source.Active;
if (activeCodeBlock == null)
// Can't continue if code block is not valid.
return;
// Get code block type (class, method, if, while, namespace, etc.)
LanguageElementType codeBlockType = activeCodeBlock.ElementType;
string lineText = ea.TextView.Caret.LineText;
// Continue only if line ends with '}', don't overwrite
// already existing comment
if (lineText.EndsWith("}"))
{
lineText = lineText.TrimEnd() + " // " +
codeBlockType.ToString().ToLower();
// And write it to source file
document.SetText(
currentLine, 1,
currentLine, currentLineOffset,
lineText);
} // if (lineText.EndsWith)
} // if (ea.Character)
} // TestPlugIn_EditorCharacterTyped(ea)
This event is called whenever the user presses any key in the Visual Studio editor. When this key was '}' and we got a valid source code document, we will get the document, the current line and offset, the activeCodeBlock and its element type. Then this code will try to modify the current line and add the " // "+type comment to it.
When you try it out, you will see that the commenting works, but we don't get the correct code block name. It will be always the parent or nextcode block, this is because the cursor is outside the codeblock when pressing '}' and the next or parent code block is returned when calling CodeRush.Source.Active. To fix this, we have to move the cursor to the beginning of the current line (insert this before activeCodeBlock):
document.Selection.StartOfLine(
EnvDTE.vsStartOfLineOptions.vsStartOfLineOptionsFirstText);
Now it works, but the cursor is at the wrong position, so we have to fix that again at the end of the function with:
document.Selection.MoveToLineAndOffset(
currentLine,
currentLineOffset);
Note: When finished testing CR_Test.dll, you have to close Visual Studio and remove CR_Test.dll from the DevExpress\CodeRush\1.1\Bin\Plugins directory! You will have to do the same thing every time you want to edit your plugin solution. If the *.dll, is not removed, the solution is not able to copy and execute the new version of the plugin. Now from here on, try out other Events and add your own plugin ideas, you can do a lot more with CodeRush, like adding new tool windows in Visual Studio. Check out the sourcecode of Commenter to find out how it works and learn more about writing a CodeRush plugin.
That's it for this tutorial. I hope this gave you some insight on the Commenter plugin. If you find any bugs, have suggestions or want some additional features or support for another language, please leave a comment below. Feel free to use the Commenter, the program and sourcecode are completely free.
Articles and more detail about each version can be found on my blog!
public methods too and will produce better comments. if and for, more intelligent block reconstruction and naming.string or comment, even if CodeRush has not processed the whole file yet (double checking now). E.g. the following string will not longer produce any comments:SQL = String.Format("UPDATE GC SET Status = {0} WHERE ID = {1}", Msg, ID);
CR_Commenter choose the name automatically, allow editing after pressing Ctrl+3).#if DEBUG in Using directives (caused trouble, was removed)#if DEBUG and #endif, especially at the beginning and end of the Using directives region.#using Using directives issue when using directives got mixed up.pragma region - #pragma endregion" support (thanks for testing to Enrico)#includes region, do not modify include linesEdit.ToggleOutliningExpansion and Edit.ToggleAllOutlining as fallbacks)
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 29 Nov 2008 Editor: Deeksha Shenoy |
Copyright 2004 by exDreamDuck Everything else Copyright © CodeProject, 1999-2009 Web18 | Advertise on the Code Project |