Visual Studio/C# auto-format. Can I control newline after attributes - c#

Visual studio keeps doing this:
[DataContract]
public class MyContract
{
[DataMember]
public bool MyBool { get; set; }
[DataMember]
public string MyString { get; set; }
}
I would like this:
[DataContract]
public class MyContract
{
[DataMember] public bool MyBool { get; set; }
[DataMember] public string MyString { get; set; }
}
No big deal if the 'public class MyContract' is on the same line as the [DataContract].
Visual studio seems to have a lot of detailed autoformatting options, but I can't find any regarding newlines after attributes. Am I missing something here? Or is it just not available.
EDIT: At very least, I'd like a "don't change what I entered" formatting option, as opposed to a "always insert" or "always remove" newline option. It's super-annoying that it keeps unformatting my code after I type.

What I usually do is hit Ctrl-Z the very moment autoformat jumps in where I don't appreciate it.
I.e., on a closing accolade, which formats a whole class or method. Type the closing accolade, see it changing the way you don't like it and then hit Ctrl-Z. (I know you were looking for an actual option, I don't know if any exists).

Not sure if it works for attributes, but look under Tools -> Options -> Text Editor -> C# -> Formatting -> Wrapping -> Leave block on single line or Leave statements and member declarations on the same line.

ReSharper can do that. It has options for:
Place type attribute on same line
Place method attribute on same line
Place property/indexer/event attribute on same line (this is the one you want)
Place field attribute on same line
It costs a few bucks but if you're as obsessive as I am it's worth every penny. ;)
I also remap Ctrl+K, Ctrl+D to ReSharper's silent format code to experience formatting bliss.

What worked best for me was to disable auto format on ; and paste. I hardly ever want auto format at these times anyways. This allows you to type out attributes and move them around without pesky interference.
Options > Text Editor > C# > Formatting > General

It is ReSharper. Extensions/ReSharper/Options/Code Editiong/C#/Formatting Style/ Line Breakes and Wrapping:
Line Breaks and Wrapping:

Yeah, Ctrl+E, D is your friend. You can optimize the formatting in Text editor options

Related

How to Remove "nameOf in place of string" Error in VisualStudio

On loading the solution in VisualStudio, I get tons of error with "CA1507 Use nameof in place of string literal" error.
I can suppress it or add nameOf in my code but I dont want that. Also, It is occurring in more than 300 places in the code and only I am getting this error in my team.
All other devs in my team are not getting this error when they load the sln file.
Actual code :
[JsonProperty("code")] public string code { get; set; }
Error gets remove when I do this (but why I need to do this and no other devs in my team) :
[JsonProperty(nameof(code))] public string code { get; set; }
Other devs are saying some issue with how VS has loaded the solution. Also, I can't use nameOf because JSON properties don't match property names
Screenshot of Error
Firstly, if the letter case matches, then you don't need to add an attribute to the property.
// This is an unnecessary attribute, because the case of the word `code` is the same.
[JsonProperty("code")]
public string code { get; set; }
Just remove the attribute.
The attribute makes sense if the property casing is different from the field casing in json.
// code != Code - no warning
[JsonProperty("code")]
public string Code { get; set; }
You can always Suppress a warning.
The fact that you get an error message instead of a warning means that the TreatWarningsAsErrors compiler option is enabled in the project.
According to the documentation for the warning:
"To disable this entire category of rules, set the severity for the category to none in the configuration file."
EditorConfig
[*.{cs,vb}]
dotnet_diagnostic.CA1507.severity = none
why I need to do this and no other devs in my team
Check if you have a .editorconfig or .ruleset file on your machine that other devs don't have.
Adding an .editorconfig to version control that sets a specific severity will make the situation consistent across machines.

Is it possible to apply a VS2019 suggestion for an entire document

Is there a way to enact a Visual Studio suggestion (such as 'Fix Naming Violation') for an entire document or project? EDIT 2: I would like to do so for all class property names, which are all different in spelling.
When creating c# models for a json model that is known, you can use Paste Special to get the basic layout. However, since json is commonly camel case, the property names get pasted in the same way. The 'Fix Naming Violation' suggestion shows for each property, but I cannot seem to find a way to do so more globally.
I know you can change the naming violation rules, but was still curious to know if this is possible so as to follow C# convention.
I would post a screenshot but I don't have enough reputation.
EDIT 1:
From:
public string classProperty1 { get; set; }
public string classProperty2 { get; set; }
public string classProperty3 { get; set; }
To
public string ClassProperty1 { get; set; }
public string ClassProperty2 { get; set; }
public string ClassProperty3 { get; set; }
Step 1:
Just hover over and locate the suggestion or just hit Ctrl + . on where you want suggestions.
For eg:
Step 2:
Under the Preview Changes section, choose the scope of the suggested fix.
You get Document, Project and Solution.
For example, I want to apply this suggestion to the whole Solution.
Make selections if you'd like.
Step 3:
Click Apply.

C# run project while ignoring one class

I want to run my project, and I have one class that makes errors - I will fix it later ,but now I want to run the project without reference to the class that makes errors.
How can I do it?
You can do right click on that file and select exclude from project for now.
It is something like Image bleow.
Other way is to comment the logic that is not desired and continue working on without excluding.
You need to comment your class and all usages of this class. It can be done by selecting code block that you need to comment and pressing Ctrl+K, Ctrl+C.
If you need to uncomment - Ctrl+K, Ctrl+U on selected commented block.
Also you need to note that commenting your class usages in project also might produce new errors.
Comment out its inner code. This way you can still reference that class from your code but it will no longer show errors unless you are refering to method or property of this class which is commented out.
public ProblemClass
{
// public string Name { get; set; }
// ...
// ...
}

particular auto-format for Properties C# VS2010

I am using VS2010.
Auto formatting upon using '}' has been extremely useful for me, however recently it's been quite a pain while I've been working on a library.
If i use the line:
public Single ExampleProperty { get; set; }
It auto formats to:
public Single ExampleProperty
{
get;
set;
}
How can i stop this from happening? I don't want to disable auto-formatting, i just want to enable something like 'allow properties to be defined on a single line' or something.
Tools -> Options -> Text Editor -> C# -> Formatting -> Wrapping -> Leave block on single line
This should be what you are looking for

Can ReSharper generate code that copies properties from one object to another?

I'm looking for a way to accelerate a repeatable task when I write code. I have ReSharper and I'm thinking a customization could do what I need.
I have two objects of the same type. I want to copy all of the public properties of one object to the other object. I want the tool, ReSharper in this case, to do generate the code for me. I'll tell it the names of the first object and the second object. I want it to find all the public properties of the first object and copy the values to the second object.
Here's the type of code I'm looking to have generated with a tool like ReSharper:
foo.Name = moo.Name;
foo.Age = moo.Age;
foo.City = moo.City;
Automating this simple code that copies values from right to left would save a ton of time and I'm thinking that ReSharper can do it. However, I haven't seen anything pop-up in searches for it though.
I'm not looking for a CodeSmith code generation technique or T4 template because I only want it to generate these specific lines inside my class, not generate and entire class or a separate file.
Does anyone know a way to press a few keystrokes, enter the "foo" and "moo" object names above and have the tool generate these copy from right to left lines of code?
Update:
I've found some documentation on building extensions to ReSharper, and this can probably be achieved by that path, but it looks really involved.
http://www.jetbrains.net/confluence/display/ReSharper/PowerToys+Pack+3.0+User+Guide
This is beginning to look like a weekend challenge unless someone else has already written it.
It's really easy. ReSharper doesn't do it, but you can use a super duper REGEX!
In Visual Studio:
public string Email { get; set; }
public string CellPhone { get; set; }
public int NumChildren { get; set; }
public DateTime BirthDate { get; set; }
Select all your properties. Hit CTRL-D to copy down.
Now hit CTRL-H to replace. Make sure .* is selected for Regex matching.
Replace: public [\w?]* (\w*) .* (This Regex may need to be tweaked)
With: dest.$1 = source.$1;
Now you have some beautiful code you can put in a method of your choosing:
dest.Email = source.Email;
dest.CellPhone = source.CellPhone;
dest.NumChildren = source.NumChildren;
dest.BirthDate = source.BirthDate;
EDIT: New alternatives
You can use AutoMapper for dynamic runtime mapping.
Mapping Generator is really nice for static mapping. It can generate the code above and it works well with R#.
This is somewhat derivative from answer by #Jess (his regex didn't work for me on VS2013) but instead of using Visual Studio I am using regex101
Click link above and just paste your properties into Test string field and you will get them mapped.
Regex I used
public [A-Za-z\?]* ([A-Za-z0-9]*) .*
and replace
Dest.$1 = Source.$1
hope this saves you some time.
I don't believe Resharper can do this, but Open Source AutoMapper can. New to AutoMapper? Check out the Getting Started page.
I agree with #Ben Griswold.
In most situations, Automapper is the way to go.
But when you truly want to generate code that copies properties from one object to another, try this:
Create a brand new class and derive from the class from which you want to copy properties.
Right-click on this new derived class and click 'Refactor > Extract Interface'.
Check all properties that you wish to copy.
Choose 'Place beside' because this interface will be only temporary.
Click 'Next'.
Modify your derived class so that you are no longer inheriting from the base class and you are only implementing your new interface. Expect to see a red squiggle.
Place your cursor over the red squiggle and hit 'ALT-ENTER' to 'Implement Members'.
Click 'Finish'.
Delete that temporary interface and modify your class so that you are no longer implementing it.
Here's a simple class to clone an object. It's not exactly what you asked for but perhaps this will be useful for you:
//.Net 2.0
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace YourNameSpace {
public static class ObjectCloner {
public static T Clone<T>(T obj) {
using (MemoryStream buffer = new MemoryStream()) {
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(buffer, obj);
buffer.Position = 0;
T temp = (T)formatter.Deserialize(buffer);
return temp;
}
}
}
}
Based on #Matas answer I created a more robust version using regex101 that ignores generics, attributes and comments and normalizes spaces.
Regex: *((\/+.*\n*.*)|(\[.*\]\n*.*))*public [A-Za-z\_\?\<\>]* ([A-Za-z0-9\_]*).*(\n| )*
Replace: $4 = person.$4,\n
This is the kind of thing for which Cog shines. Basically, Cog is code generation tool. Code is generated via Python.
Simply copying values from one side to the other is pretty ugly.
You might find it better to create a method to include in your classes that uses reflection to copy public properties. You could save this method in resharper to regenerate into other classes you need this functionality in.

Categories