How to disable all whitespace autoformatting in Visual Studio 2015? - c#

I really like the new Visual Studio 2015, but the auto formatting is a bit too much extensive for my liking. Especially I like to have control over whitespace:
public class TipStats
{
public int Points { get; set; }
public int Position { get; set; }
public decimal Percentage { get; set; }
}
I only see three autoformat settings in my settings, and I have ticked them all off - still Visual Studio is autoformatting my whitespace.
Are there any other hidden settings that I need to know for disabling all whitespace autoformatting?
Update
As #Saragis notes Ignore spaces in declaration statements works sometimes for this specific example, but still there all kind of autoformat forces working against what I want.
Most options seem to only define how you want your autoformatting. I'm looking for the setting that defines if you want autoformatting.
PS: I'm having only problems with autoformatting I still use CTRL+K, F to manual format parts of my code now and then.
Update - Added feature request on UserVoice
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/9795837-add-an-ignore-space-for-all-format-options

I realised I misunderstood the question in my original answer, so have added a partial answer disabling autoformatting for white space.
If you select ignore white space on all options where it is offered, it will not reformat the white space of those areas of code.
These screen shots are taken from VS2015 Enterprise.
I'm starting from the beginning to help anyone who lands here.
Go to Tools -> Options.
Scroll down to Text Editor. It's worth clicking through the all the general tabs. And the All languages tabs. There are some shared formatting settings that can be set, like line wraps.
Then go to the languages you wish to customise (I'm showing C#) and click on formatting. There you will find options, I have expanded the spacing one, as per the title of your question.
Then you can explore each of these tabs to customise your format for each language.
edit- since question has actually changed
To reduce the incidents of autoformatting, uncheck options like these:
The only way you can manage the autoformatting is to play with these settings.
You can also use regex with find and replace to remove space from files, but do so carefully.
Beyond these tips to customise your autoformatting, to reduce VS process of autoformatting and to manually autoformat, that's all I can think of.
There is also this:
Under Edit -> Advanced -> Delete Horizontal White Space

The answer from Yvette Colomb is fine, but it does neither work on declarations inside functions, nor on enums (where in my opinion it is needed most).
Thus I had the idea to just add a comment between the variable and the operator, which simply breaks the obvious rule "set exactly one space character between variable (or enum name) and operator (=)", because there is no operator following the variable any longer! Not very nice, but also not too bad and IMHO it has definitely more advantages than disadvantages. :-)

Disable virtual space
Virtual space is a headache, please disable it int Tool>Options>Text Editor>C#>General. Life is better.

For the last version of Visual Studio :
Go Preferences :
Go Source code > C# :
Set Policy to custom :
Go C# format and tap on edit :
Set like me the New Lines :
And voila.

Related

Message template should be compile time constant

I have this code
[HttpGet("average/{videoGuid}")]
public async Task<IActionResult> AverageRatingOfVideo([FromRoute] string videoGuid)
{
_logger.LogInformation($"Finding average rating of video : {videoGuid}");
var avg = await _ratingService.GetVideoRatingAverageAsync(videoGuid);
return Ok(avg);
}
and I'm getting a warning here $"Finding average rating of video : {videoGuid}"
Message template should be compile time constant
I'm using Rider, there is no suggestion to fix this warning.
I can't understand why this gives me a warning, how could I fix this ?
The way to get rid of the warning is to supply the variable videoGuid separately, like this:
_logger.LogInformation("Finding average rating of video : {VideoGuid}", videoGuid);
Here, I first removed the $ sign, thereby turning off the string interpolation performed by C#. The {videoGuid} in the string now becomes a "property" instead, and so I pass the variable as a second argument to LogInformation. Rider also complains that properties in strings should start with a capital letter, so I changed it to {VideoGuid}.
Now for the real question: Why is there a warning?
The answer is that string interpolation prevents structured logging. When you pass the variables after the message, you make it possible for the logger to save them separately. If you just save the log to a file you may not see a difference, but if you later decide to log to a database or in some JSON format, you can just change your logging sink and you will be able to search through the logs much easier without changing all the log statements in your code.
There's a good discussion of this over on Software Engineering Stack Exchange.
This is a false positive in the Serilog extension for Rider but other way to remove this warning is to disable the warning once (or globally in your class file).
// ReSharper disable once TemplateIsNotCompileTimeConstantProblem
_logger.LogInformation(messageTemplate);
Not the best solution but it's an option too.
Now, check Rof's answer about Why the warning.

How to customize formatting of code that is generated by "Encapsulate Field"?

Previously I am fairly certain that the "Encapsulate Field" command would turn something like the following:
public int SomeNumber;
into the following (what I want from VS 2015):
private int someNumber;
public int SomeNumber {
get { return someNumber; }
set { someNumber = value; }
}
but in Visual Studio 2015 I am seeing the following:
private int someNumber;
public int SomeNumber {
get {
return someNumber;
}
set {
someNumber = value;
}
}
Is there a way to fix this?
This was a design change in VS2015. In previous versions, the refactoring command paid attention to the Tools > Options > Text Editor > C# > Wrapping > "Leave block on single line" option. With it turned on, you'll get the property getter and setter body the way it encoded in the snippet, braces on the same line. The way you like it.
Different in VS2015, it now pays attention to the Tools > Options > Text Editor > C# > Formatting > New Lines > "Place open brace on new line for methods" setting. You get to choose between "egyptian" braces or having the opening brace separate. Neither of which you like.
Accidents happen when Microsoft creates new VS versions, this was not an accident. Whether this was done by "popular demand" is hard to reverse-engineer, I consider it pretty likely since this refactoring is usually done to write a non-trivial getter or setter, the kind that won't fit a single line. Providing us with a choice between all three possible formatting preferences looks like a problem to me, the existing formatting options are not a good match.
Only real option is to let Microsoft know that you are not happy with the change. There is an existing UserVoice article that proposes a change. You can vote for it or write your own. Post a link to it in your question so other SO users can vote.
Will that help you:
-Encapsulate Field Refactoring (C#):
https://msdn.microsoft.com/en-us/library/a5adyhe9.aspx
This website seems to offer a solution a the end of the topic.
Check also this post :
-Different Refactoring style for field encapsulation: how to make Visual Studio change it?
Different Refactoring style for field encapsulation: how to make Visual Studio change it?
This one is corresponding to your question in a certain manner: the question is really related to yours :)
I myself have tried changing the snippet file to suite my file but VS doesn't take effect. What I end up doing is
Encapsulate the fields as usual.
Copy and paste the code into notepad++ and do a Find and Replace.
Find:
(\{)*(\s*)*(get|set)\r\n\s+{\r\n\s+(.*)\r\n\s+\}\s+
Replace with:
$1$3\{$4\}
Paste the result back into VS. VS will format it follow the "Leave block on single line".

it is possible have different editor styles in visual studio 2010?

Well in short i am a big fan of writing nice looking code, there is a great article here
the beauty of doom 3 source code I have been using different code editors before visual studio.
And i liked a compact writing style.
I dont like almost empty white lines like
public void my function(string s)
{ //almost empty line
string n = domystuff();
if (n=="blanc")
{ //almost empty
mycode("should start a row earlier on { line");
} //..
else
{
ohno.notagain("another two blanc lines above and below else");
Altough.it.compiles("equaly");
myscreen.used = not.optimal;
}
}
If code is better written, then its nice to read, if something is nice to read with much white lines then the white lines spoil it. So i wonder can this auto-formatting be changed in VS2010 ?
C# as a language has a set of coding conventions which C# programmers expect to be fairly consistent from project to project. If you want to use the One True Brace style, switch to Java.
If you insist on being the odd man out, you can configure the Visual Studio auto-formatter in Tools → Options... → Text Editor → C# → Formatting.

VS2010: Automatically insert date and initials to single line comments

Greetings Friends,
What is the best way (least amount of keystrokes) to get Visual Studio 2010 to automatically insert the current date and my name/initials whenever I put a single line comment into my codebase? This should support C# and it'd be even better if it worked in my .aspx pages too.
Thanks -- I know someone out there has the perfect solution :).
Create a macro and assign a Shortcut key.
The easiest way is go to Tools->Macros->Macro Explorer and edit one of the samples, I used Samples->VSEditor, right click that one and edit.
Now youre in the Macro editor
Now create this function.
Sub NewCommentLinePersonal()
Dim textSelection As EnvDTE.TextSelection
textSelection = DTE.ActiveWindow.Selection
textSelection.NewLine()
textSelection.Insert(Utilities.LineOrientedCommentStart())
textSelection.Insert(" " + Date.Now + " - Your Initial ")
End Sub
then go to Tools->Options->Environment->Keyboard and type the NewCommentLinePersonal on textbox "Show commands containing:" then choose your shortcut key
Perhaps another way of approaching it, assuming the insertion of a timestamp and name is being done for change tracking, is to lean on source control.
For example, in my current codebase, we deprecated the use of putting in change comments, since we found that the field of green was cluttering things, and if I ever needed to see who changed what, I could simply look in our source control system, and even see how this one change was related to other modifications within the same changeset.

ReSharper formatting: align equal operands

Note to Googlers, this question is somewhat out of date as the requested feature is now supported in the current version of ReSharper 2017.3.1
I like to formatting my code to align right side of equal operands.
Like here:
bool canRead = false;
bool canReadClass = true;
string className = boType.Name;
I've switch to ReSharper recently and found it very useful but cannot find option allowing me format code in described way.
Do you know if there is such option / plugin?
Maybe you know other than ReSharp solution allowing that?
EDIT:
How to decide what part of code shall be aligned?
My convention is aligning all variables in same block.
By "block" I meant part of code not divided by empty lines.
eg
// First block
int count = 10;
string name = "abc";
bool calculate = true;
.....
.....
// Second block
MyOwnType myType = new MyOwntype();
int count = 10;
EDIT -2
I've opened R# ticket for this. If anyone interested please vote!
There is (currently) no way to do this out of the box in ReSharper. Fortunately, ReSharper has a very rich extensibility API (albeit poorly documented). I've spent a lot of time with Reflector trying to figure things out.
We use a similar alignment guideline for class members in a company I work for (to the extreme, we also align method parameters). I wrote a plugin for ReSharper to help me do just that. It's a "Code Cleanup" module, which runs sometime during the code cleanup (Ctrl-E, Ctrl-F) and aligns the code for you. It also makes the class sealed, if possible.
Some examples:
Method parameters:
public void DoSomething(string name,
int age,
IEnumerable coll)
(you will need to change Wrap formal parameters to Chop always in Options->Formatting Style->Line Breaks and Wrapping for this to work properly)
Constants:
private const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
private const int CONNECT_COMMANDLINE = 0x00000800;
private const int CONNECT_INTERACTIVE = 0x00000008;
private const string RESOURCE_NAME = "Unknown";
You can download the source code from my SkyDrive.
Edit I seem to have lost access to that SkyDrive, and lost the files too. This was before github :(
Please note that you'll need several things to compile/debug it:
Update the Command Line Arguments
in Debug tab in Project
Properties with the correct path of
the output DLL:
/ReSharper.Plugin
"X:\<projects>\MyCompany.CodeFormatter\MyCompany.CodeFormatter\bin\Debug\MyCompany.CodeFormatter.dll"
This allows debugging the plugin via
F5, and it will be
automatically installed in
ReSharper's Plugins in the new
Visual Studio instance which will
open.
The plugin is for ReSharper 4.5 and it references the DLLs of this version. If you installed ReSharper anywhere else except C:\Program Files\JetBrains\ReSharper, you will have to fix the references.
This does not align variables inside methods, but it shouldn't be hard to add :)
After you install this, just run Code Cleanup to fix your alignment (I never got a reply from JetBrains about how to do this during brace/semicolon formatting, unfortunately).
Assembly was renamed to protect the innocent :)
Good luck!
I think it is worth noting that the Visual Studio Productivity Power Tools have an Align Assignments feature.
Here's a link to the Visual Studio 2013 Productivity Power Tools.
You can try this: Code Alignment
It supports
Align by... (Dialog)
Align by position... (Dialog)
Align by Equals
Align by m_
Align by "
Align by .
Align by Space
Productivity Power Tools 2012 also has a command for this: ctrl-alt-]
Other goodies are obviously there as well.
As far as I know, this is unfortunately not possible using Resharper.
Years late, but further to the comment from #MickyD, Resharper can do this for you, see Resharper blog. Go to Resharper/ Options/ Code Editing/ C#/ Tabs, Indents, Alignment. Scroll to the bottom of the options in the right hand window pane to find "Align Similar Code in Columns", click things, enjoy.

Categories