How can I automate the removal of XML Documentation Comments? - c#

Does someone have a script or snippet for Visual Studio that automatically removes comment headers for functions or classes?
I want to remove comments like.
/// <summary>
///
/// </summary>
Actually anything that removes comments starting with /// would really help. We have projects with massive amount of GhostDoc comment that really just hides the code and we are not using the document output. It is a tedious work for us to remove theese comments.

Open Quick Replace (CTRL + H) in Visual Studio and replace :b+///.*\n with an empty string (ensure you set Use to Regular expressions). This should allow you to get rid of the comments in the specified scope.

You can use this Regex \/\/\/.*<summary>.*<\/summary>, with these options gms, to match the string. You can replace that with nothing. This can be done in Notepad++ or Visual Studio.
Here is a Regex 101 to prove it.

You can use Python (with regexps, if you wish):
#! /usr/bin/python
import sys
if len(sys.argv) < 2:
print( "Usage: removelines <source-file>" )
exit(0)
InFileName = sys.argv[1]
Out = open( InFileName + ".out", "w" );
for Line in open( InFileName ).readlines():
if Line.lstrip().find( "///" ) == 0:
print( "Skipping line", Line )
continue
Out.write( Line )

You could use find and replace in files in Notepad++ (or any other advanced text editor) using regex.

You can just do find and replace with an empty string in visual studio. You already have the strings you want to get rid of. You could also parse the code files as text and remove any line that starts with a comment character.

Related

Stop auto adding "///" in XML Doc Comments. (C#)

How do I stop Visual Studio from automatically adding "///" in XML documentation comments when adding new lines.
For the following examples the '|' character stands for the cursor position.
For example when pressing enter at this line:
/// Some comment |
Is automatically enters "///" at the beginning of the next line:
/// Some comment
/// |
What I want is simply this:
/// Some comment
|
How do I make this happen?
The triple slash pattern is a shortcut to invoke the VS XML documentation feature set. If you don't want that behavior, you could just use the more conventional double slash pattern; it won't produce automatic insertions on new lines.

Why do I get an CS1056 Unexpected character '' on this code

I'm getting this unexpected character '' error and I don't understand why.
var list = new List<MyModel>();
list.Add(new MyModel() {
variable1 = 942,
variable2 = 2001,
variable3 = "my text",
variable4 = 123
​}); // CS1056 Unexpected character '' on this line
From what the error says and the actual error code I got from an Online compiler after copy/pasting, Your code on this line contains a character that is not visible but that the compiler is trying to interpret. Simply try erase every character starting at your closing bracket towards your number 3 and press Enter again It should be working (it did work for me)
I just deleted the file Version=v4.0.AssemblyAttributes.cs(1,1,1,1) located in my temp folder C:\Users\MyUser\AppData\Local\Temp and then it works perfectly.
For .NET Core you have to delete .NETCoreApp,Version=v2.1.AssemblyAttributes.cs
As mentioned by Daneau in the accepted answer, the problem is by a character that is not visible in the IDE.
Here are several solutions to find the invisible character with Notepad++.
Solutions 1: Show Symbol
Copy the code to Notepad++,
Select View -> Show Symbol -> Show All Characters
This can show invisible control characters.
Solutions 2: Convert to ANSI
Copy the code to Notepad++,
Select Encoding- > Convert to ANSI
This will convert the invisible character to ? if it is a none ANSI character.
Solutions 3: Remove none ASCII characters
Copy the code to Notepad++,
Open the Find window (Ctrl+F)
Select the Replace tab
in "Find what" write: [^\x00-\x7F]
Leave "Replace with" empty
In "Search Mode" select "Regular expression"
Find and remove the none ASCII characters
This will remove none ASCII characters.
Note: This can remove valid non ASCII characters (in strings and comments) so try to skip those if you have any.
Tip: Use HEX-Editor plugin
Use Notepad++ HEX-Editor plugin to see the binary code of text. Any character out of the range of 0x00 - 0x7F (0 - 127) is a non ASCII character and a suspect of being the problem.
Just reporting my direct experience.
As Daneau wrote, I had a character (ASCII DLE, I copied while messing up a zebra printer) hiding in the text. I could not afford to rewrite everything, so I used notepad++ "View->Show Symbol->Show All Characters" feature.
I apologize for not commenting Daneau entry, but I don't have enough reputation.
Write the code again without copying it. That worked for me
go to C:\Users\UserName\AppData\Local\Temp\ and clear the data or remove the file specified in the error, that will solve the issue.
VS will add the required file on auto, no worries.
I got this error when I moved my application from one folder to another, I resolved this by deleting the Debug folder inside the obj folder.
It indeed has to do with copy pasting code and characters that you cannot see. The easiest way to fix it is by passing your copy pasted code into a note application or simple text program which will automatically remove these invisible characters. After that simply copy the code from the text editor and paste it into your IDE.
For some reason this happened to me on every project in my solution. My fix was to delete all bin and obj folders in my solution.

How do you add a blank commented line in T4 using Ghostdoc Pro in Visual Studio?

Inside of the "Rules" settings in GhostDoc Pro it allows me to use T4 to format my comments. However it randomly adds line breaks(which I have sorted out), and also will not allow me to add a single line of triple forward slashes.
For example:
///======================================================
///Class: TripleSlash
/// //<-----How do I add just a blank line like so?
///<summary>
/// Class of the triple slashing breed
///</summary>
///======================================================
I have tried adding a StringBuilder.Append("///"); I have tried just simply adding the three slashes. However it seems that GhostDoc Pro removes any line of T4 or C# code that would add a blank triple forward slash commented line.
I feel like I'm overlooking something simple.
T4 for Ghostdoc does not support inserting a line break or a blank line.
sad day.

removing #region

I had to take over a c# project. The guy who developed the software in the first place was deeply in love with #region because he wrapped everything with regions.
It makes me almost crazy and I was looking for a tool or addon to remove all #region from the project. Is there something around?
Just use Visual Studio's built-in "Find and Replace" (or "Replace in Files", which you can open by pressing Ctrl + Shift + H).
To remove #region, you'll need to enable Regular Expression matching; in the "Replace In Files" dialog, check "Use: Regular Expressions". Then, use the following pattern: "\#region .*\n", replacing matches with "" (the empty string).
To remove #endregion, do the same, but use "\#endregion .*\n" as your pattern. Regular Expressions might be overkill for #endregion, but it wouldn't hurt (in case the previous developer ever left comments on the same line as an #endregion or something).
Note: Others have posted patterns that should work for you as well, they're slightly different than mine but you get the general idea.
Use one regex ^[ \t]*\#[ \t]*(region|endregion).*\n to find both: region and endregion. After replacing by empty string, the whole line with leading spaces will be removed.
[ \t]* - finds leading spaces
\#[ \t]*(region|endregion) - finds #region or #endregion (and also very rare case with spaces after #)
.*\n - finds everything after #region or #endregion (but in the same line)
EDIT: Answer changed to be compatible with old Visual Studio regex syntax. Was: ^[ \t]*\#(end)?region.*\n (question marks do not work for old syntax)
EDIT 2: Added [ \t]* after # to handle very rare case found by #Volkirith
In Find and Replace use {[#]<region[^]*} for Find what: and replace it with empty string.
#EndRegion is simple enough to replace.
Should you have to cooperate with region lovers (and keep regions untouched ), then I would recommend "I hate #Regions" Visual Studio extension. It makes regions tolerable - all regions are expanded by default and #region directives are rendered with very small font.
For anyone using ReSharper it's just a simple Atr-Enter on the region line. You will then have the option to remove regions in file, in project, or in solution.
More info on JetBrains.
To remove #region with a newline after it, replace following with empty string:
^(?([^\r\n])\s)*\#region\ ([^\r\n])*\r?\n(?([^\r\n])\s)*\r?\n
To replace #endregion with a leading empty line, replace following with an empty string:
^(?([^\r\n])\s)*\r?\n(?([^\r\n])\s)*\#endregion([^\r\n])*\r?\n
How about writing your own program for it, to replace regions with nothing in all *.cs files in basePath recursively ?
(Hint: Careful with reading files as UTF8 if they aren't.)
public static void StripRegions(string fileName, System.Text.RegularExpressions.Regex re)
{
string input = System.IO.File.ReadAllText(fileName, System.Text.Encoding.UTF8);
string output = re.Replace(input, "");
System.IO.File.WriteAllText(fileName, output, System.Text.Encoding.UTF8);
}
public static void StripRegions(string basePath)
{
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(#"(^[ \t]*\#[ \t]*(region|endregion).*)(\r)?\n", System.Text.RegularExpressions.RegexOptions.Multiline);
foreach (string file in System.IO.Directory.GetFiles(basePath, "*.cs", System.IO.SearchOption.AllDirectories))
{
StripRegions(file, re);
}
}
Usage:
StripRegions(#"C:\sources\TestProject")
You can use the wildcard find/replace:
*\#region *
*\#endregion
And replace with no value. (Note the # needs to be escaped, as visual stuido uses it to match "any number")

How can I delete all the comments in my code?

I'm new to C#, and want to develope a program with which I could delete the comments after // in my code. Is there any simple code recommended for this purpose?
It has been suggested that you just search for "//" and trim.
Because you have limited yourself to single-line commands this seems like a relatively simple exercise however it has some tricky cases you need to be thinking about if you intend for the output of the program to be a valid C# application with identical behavior to the input program.
Here are some examples where just searching for "//" and trimming won't work.
Comment in Literal:
string foo = "this is // not a comment";
Comment in Comment
/* you should not trim // this one */
Comment in Comment Part Deux
// This is a comment // so don't just remove this!
Multi-line Comment Adjacency
/* you should not *//* trim this these */
There are certainly other edge cases but these are some low-hanging fruit to think about.
First point, this seems like a bad idea. Comments are useful.
Taking it as an exercise,
Edit: This is a simple solution that will fail on all the case #Bubbafat mentions (and propbably some more). It would still work OK on most source files.
read the text one line at a time.
find the last occurrence of //, if any using String.LastIndexOf()
remove the text after (including) the '//' when found
write the line to the output
ad 1: You can open an TextReader using System.IO.File.OpenText(), or File.ReadLines() if you can use Fx4
Also open an output file using System.IO.File.WriteText()
ad 3: int pos = line.LastIndexOf("//"); if (pos >= 0) { line = line.Substring(0, pos); }

Categories