How to Remove "nameOf in place of string" Error in VisualStudio - c#

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.

Related

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.

Workaround for Compiler Error CS0542: member names cannot be the same as their enclosing type

I've got a fairly large VB.NET project that was built by a former employee. He got most of it working, but not all of it.
It has been running like this for 2 years, I know. Perhaps 3.
Now, Management is pushing to get this project revived and finish up what was never done.
The project has been assigned to me, and I have been given a month to get up to speed on it.
I am re-writing it in C#, because my coding is stronger in that language.
One of the good ideas he used was to structure the class so that they mimicked the database tables:
table name becomes class name
column names become property names
column datatypes become property datatypes
Here is one small example:
Public Class Acct_Code
Private _Acct_Code_ID As String = String.Empty
Private _Acct_Code As String = String.Empty
Public Property Acct_Code_ID() As String
Get
Return _Acct_Code_ID
End Get
Set(ByVal value As String)
_Acct_Code_ID = value
End Set
End Property
Public Property Acct_Code() As String
Get
Return _Acct_Code
End Get
Set(ByVal value As String)
_Acct_Code = value
End Set
End Property
End Class
Currently, I cannot put this VB code in C# because of Error CS0542 that says:
Error Message
'user-defined type' : member names cannot be the same as their enclosing type
A name was used more than once in the same construct. This error might be caused by inadvertently putting a return type on a constructor.
I understand either the class or the property should be renamed; however, I would like to get this project working piece at a time instead of being over here creating code that will not work at all.
Does anyone know of a way to work around this compiler error - just temporarily until I get the project built?
I know there are ways to ignore warnings and ignore exceptions, but I don't know a way to ignore a compiler error.
To work around the compiler error, just split your class into a base class and a derived class and then move the offending members into the base class.
class A
{
public string B { get; set; } // <-- This compiles just right!
}
class B : A
{
}
You can't ignore a violation of the rules of the language. You must fix the names.
You may well want to try to fix the names in VB before porting, as then you can have a working codebase at all times... which will allow you to take advantage of refactoring. Then when you're sure that all the member names are different from the type names, you can port to C#.
As an aside, when you port that code you should take advantage of automatically implemented properties, leaving:
public class Account
{
public string Id { get; set; }
public string Code { get; set; }
}
(Then try to move away from allowing objects to mutate in all possible ways... that's a different matter :)

XmlException in WCF deserialization: "Name cannot begin with '<'" - in automatic property backing fields

I have started experiencing errors in WCF deserialization today - in code which has been unchanged and working for months.
The issue is that I am getting runtime XmlExceptions saying 'Name cannot begin with the '<' character'. I have debugged into the .NET source, and it seems the error is in deserializing return objects from our WCF service calls. These objects are defined using automatic properties, and it seems the backing fields are given names like <MyProperty>k_BackingField, which is where the XmlException is coming from.
I've seen a couple of other references online where the solution people accept is "I changed my code to not use automatic properties", which isn't really acceptable to me, as I would have 100s of objects to change, (with 1000s of properties amongst them). Also, this same code was working fine when I ran it last week, and doesn't seem to affect all serialized DTOs, only some.
To make it even more frustrating, it seems mildly intermittent. On occasion this morning, there has been no exception thrown...!
Questions;
Why has this problem suddenly appeared in unchanged code and unchanged framework source?
How do I fix this without modifying all the DTOs to use fully implemented properties?
UPDATE: After a day or so of working fine, this issue has reappeared - no reason I can find why it would work/not work/work again, but here we are.
I have tracked the problem down further to be related to some code I have on my ServiceContracts using the ServiceKnownType attribute, which is used to define known types for serialization. It seems that although the types being reported with errors are not even part of the service call I am making at the time, that this error is occurring on types which are part of this known types 'publishing' behaviour.
The problem occurs when I use some proxy creation code to apply some service behaviours;
IOperationBehavior innerBehavior = new PreserveReferencesOperationBehavior(
description, this.preserveReferences, this.maxItemsInObjectGraph);
innerBehavior.ApplyClientBehavior(description, proxy);
I cannot debug the ApplyClientBehavior code as it is part of System.ServiceModel (or can I?), but something in that method is trying to validate all types I have published using my ServiceKnownType attribute, and breaking on some of them with this XmlException. I have NO IDEA why some of the types are failing - and only for some of their properties.
This is an example of the types which are getting errors reported against them;
[Serializable]
public class MyDataObject
{
public ActivitySession(string id)
{
this.Id = id;
this.IsOpen = true;
}
public string Id { get; set; }
public bool IsValid { get; set; }
}
The exception reported an error against Id -> <Id>k_BackingField cannot start with '<'
So nothing controversial in that class, and no inheritance to consider. It's not even part of a service contract, only it was previously published as a known type for serialization.
This is getting quite esoteric now, so I'm not expecting an answer, but just updating where the problem is at.
I think I have found more information to help explain this issue, (at least in so far as why the error is appearing on certain types only).
The DTOs which are getting exceptions reported against them are;
published as part of my [ServiceKnownType] attribute
marked with [Serializable]
NOT marked with [DataContract]
Adding the [DataContract] attribute to the type resolves this issue. I have no idea why, and still no idea why this error is intermittent in when it happens, but consistent in what it affects.
I looked at this question also: WCF Service Reference - Getting "XmlException: Name cannot begin with the '<' character, hexadecimal value 0x3C" on Client Side
regarding this exception:
System.Xml.XmlException: 'Name cannot begin with the '<' character,
hexadecimal value 0x3C.'
Check if you load any xml files that they are valid (e.g. do not contain typo's like < or >
If you are using services + WCF, have a look at your Service interfaces (the interfaces with ServiceContract). This will be a good starting point. Now check to see if you have any DTO parameters in methods from the interface. Go to these DTO's and see if these DTO classes have [Serializable] or [DataContract] or similar attributes. If these classes also contain automatic properties, change them the properties to the notation with your own backing field like:
private Foo _Bar;
public Foo Bar { get { return _Bar; } set { _Bar = value; } }
If you are lucky you will see the errors go away!
There seems to be a problem with automatic properties where the automatically generated backing field has a name similar to e.g. <>something, <>d_whatever or things like that. These names start with '<' character, resulting in that error.
In case of services and WCF, your service interfaces and callbacks (with datacontract) are a good place to start replacing the automatic properties. At least it gives you an idea where to start instead of replacing thousands of automatic properties.
Additionally try to catch FirstChanceExceptions by adding this code at the start of your application and write the messages to the console.
This will help a lot to see if the number of "Name cannot begin with the '<' character" messages is reduced or not.
AppDomain.CurrentDomain.FirstChanceException +=
(object source, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e) =>
{
Console.WriteLine("FirstChanceException event raised in {0}: {1}",
AppDomain.CurrentDomain.FriendlyName, e.Exception.Message);
};
https://learn.microsoft.com/en-us/dotnet/framework/app-domains/how-to-receive-first-chance-exception-notifications
This is what I found so far. Hope it helps.
I have a workaround in place now, however it's not something I can rely on -> the DTOs which are causing the problem have been removed from the [ServiceKnownType] publisher, which makes the error go away.
I'm wondering if the problem is to do with the member names I am getting exceptions on. So far I have seen it complain about;
Id
Address
UserName
It would be reasonable to expect those particular property names are in use somewhere else in the serialization or service model, causing them to be compiled differently, I guess.
I was hitting this issue today (first-chance exception, no apparent problem otherwise). In my case NetDataContractSerializer (NDCS) was serializing IFieldData[] (from CSLA.NET library). NDCS can serialize arrays, it is also able to serialize objects that don’t have [DataContract] attribute applied to it. In that case the serializer infers the contract – all public read/write properties and fields of the type are serialized. It is documented here: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/using-data-contracts
So in my case, one of the objects in the array had a reference to Fraction (my own class) defined as follows:
public sealed class Fraction
{
public int Numerator { get; private set; }
public int Denominator { get; private set; }
public double Value { get; private set; }
}
It is causing WCF to throw the "Name cannot begin..." exception, which is caused by the fact that the automatic properties are using generated private fields named like <Numerator>k__BackingField. If you add [DataContract] attribute to the class, then you must explicitly mark what needs to be serialized by [DataMember] attribute. That makes the exception go away. The serializer is not touching the private fields anymore.
In my opinion, it is a bug in WCF. The inferred contract should be only using the public surface of the class, which does not have any naming problems. It should not be snooping on private fields (compiler-generated or not).
My answer supports/supplements what RJ Lohan and juFo said earlier and I upvoted their answers.
The best way to figure out which field is giving you the problem is to inspect the StackTrace as the error comes up:
The answer, in my case, was to change the auto property to have explicitly declared backing fields to avoid the possibility of this naming. So
public string ScreenName { get; set; }
becomes:
private string _screenName;
public string ScreenName { get { return _screenName; } set { _screenName = value; } }
For anyone else having this issue: If you have XmlException checked in Visual Studio's exception settings, it'll throw even if the exception will get handled in System.Runtime.Serialization. I spent a good 20 or so hours trying to work out why my code had suddenly stopped working when I turned on all exceptions - it wasn't actually a fatal exception, it was just ~1200 caught XmlExceptions.

Compile Time Type Assignment

I'm working on a custom validation framework for my WPF/C# application.
What I'm looking to do is to retrieve strings from the resource file where the viewmodel is declared, but in the actual validation code it self. This particular string is the same resource used by label on the editing UI Form.
My code works fine with the following syntax -
[Required(TypeRes = typeof(Resources))]
public string RequiredStringWithDesc { get; set; }
But what I"m looking for is something that is syntacticly cleaner looking. I was trying to use
const Type LocalRes = typeof(Resources);
[Required(TypeRes = LocalRes)]
public string RequiredStringWithDesc { get; set; }
Any suggestions on a simpler syntax? The old c++ DEFINE statement here would work well.
FYI: the reasons for going to this much work has to do with how we are doing localization and UI construction.
EDIT To answer a couple of questions about why are we doing this?
We are going to be using the same string from the resource file to -
On the edit screen, this is the label to identify the field.
In the datamodel, if there is a validation error, we are using this to correctly label the problem in the log file.
In the Viewmodel, we are reusing this label in the validation error message to reinforce where the problem is to the user.
This is part of a real time inspection system and some of the failure modes relate directly back to these data fields. So we can easily get the correctly localized label to apply to run-time fault messages
The general concept is that this simplifies presenting consistent messages to the user while only creating things once. With regards to validation attributes (and this question), we need to be able to get the Resource file type to load the correct message.
Create a new attribute class which inherits from the RequiredAttribute and set default values.
public class LocalizedRequiredAttribute : RequiredAttribute {
public LocalizedRequiredAttribute() { /* TypeDef = typeof(Resources);*/ }
}
public class MyModel {
[LocalizedRequired]
public string RequiredStringWithDesc { get; set; }
}

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

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

Categories