Ignore ReSharper naming rules for DTOs - c#

I have ReSharper naming rules set up such that all property names must be PascalCase. However there are times when I have to use a different naming style to work with serialization. For example, backbone.js expects objects to have an Id named 'id'.
I'd prefer to have my objects match the expectations of serializers rather than use fancy serialization attributes to change the way things are named. Is there a way to mark my DTO classes as such so resharper doesn't complain about them? What about a conventions-based approach, like "Exempt any class whose name ends with 'Dto' or is in a namespace called 'Dto'? Additionally, I'd rather not use the special //disable rule XX comment blocks. I find them really distracting
public class PersonDto
{
public int id {get;set;} //i want resharper to accept this as a valid name,
// but only in this context.
public string Name {get;set;}
public string _CID {get;set;} //some external api is sending me data named like this
}

You can disable inspection for any files. In the Resharper options, go to Code Inspection: Settings and click on "Edit Items to Skip". Add *.DTO.cs to the "File masks to skip" list.

Related

Is this really a simplification?

So I have a pretty simple class with an Id field, and the Id can be set in the constructor.
Typically I will use this to clearly identify the class property as opposed to the method argument. To me this seems clearer.
IDE0003 wants me to remove the this, with the message 'Name can be simplified', is that correct?
This seems less clear to me, and also allows a casing error to easily result in id = id.
This other question has an answer that says you can configure the editor to remove the behavior. Personally I like "this"
Tools > Options > Text Editor > C# > Code Style and check Qualify member access with 'this'
Visual Studio 2015 - Change Light Bulb, Quick Action settings
The this keyword almost always is unnecessary, see When do you use the "this" keyword?.
allows a casing error to easily result in id = id
That will yield another warning on its own:
Assignment made to same variable; did you mean to assign something else?
If you use General Naming Conventions then the this keyword is redundant because the parameter should be id and the property should be Id based on Naming Guidelines. So it seems clear:
public int Id
{
get;
private set;
}
public VSOMessage(int id)
{
Id = id;
}
Please note that the guidelines itself don't say, to use or not use this keyword but because C# is case sensitive, it would be a simplification to remove this keyword but when you don't use Naming Conventions then you may naming the property id instead ofId so you should use this keyword in such cases.
If you want to prevent the warning in code rather then updating Visual Studio settings, use the SuppressMessage data annotation, which will prevent the warning.
It looks something like this:
[SuppressMessage("Reason #Enter whatever you'd like", "ID, must match what intellsense is showing it looks something like this: IDE0001", Justification = "(optional, your own description")]
Here is an exact example for your "this" variable situation:
[SuppressMessage("IntelliSenseCorrection", "IDE0003", Justification = "Allowing usage of 'this' keyword to maintain consistency/readability of code.")]

Rename Generic Class in WebAPI

I have a Generic Envelope class that i use as the common return object for the WebAPI as follows:
public class ApiEnvelope<T>
{
public bool Success { get; set; }
public Error Error { get; set; }
public Data<T> Data { get; set; }
}
Then I construct a HttpResponseMessage using:
Request.CreateResponse<ApiEnvelope<whatever>>(HttpStatusCude.OK, model);
The problem i have is that i would like the xml to be somewhat standard however the root name of the xml being returned is not standard and is coming through as ApiEnvelopeOfwhatever.
My question is how can i get the root name to be ApiEnvelope regardless of the type?
With generic class you got no chance, remove generic specification and set Data propert type to object.
I had a similar question and I got a decent answer, (I know this is old but it was a good answer): How to resolve Swashbuckle/Swagger -UI model naming issue for generics?
Now this is only part of the solution for your question, so you should look at Github repo: MakeGenericAgain. Use that to "regeneric" the resultant generated code, (big heads up: if you use this on the entire code and not just names of types, you will have a mess if you have properties name things like "NumberOfUnits" because that becomes "Number").
Sidenote:
If you want to "level up" your skills here, then use Rolsyn's SyntaxWalker to apply the renaming, and at the same time "cleanup" duplicated classes, as many design their REST-APIs with few shared "models" so a User and a Company might hace identical "Address" -properties based on identically shaped classes but it they are defined twice your NSwag -generated code will have Address and Address2, however using Roslyn, you can identify these ande rewrite the code to give a "perfect result".

Workaround for Reflection Bug in Dotfuscator?

Greetings all,
I am calling Type.GetProperties(), but after running Dotfuscator, it is returning zero items, when it returned more than zero before.
public class Test
{
public int Number { get; set; }
public void ShowInfo()
{
Type type = this.GetType();
PropertyInfo[] props = type.GetProperties();
Console.WriteLine("type [" + type.Name + "] props count: " + props.Length);
}
}
If I exclude the "Number" property from renaming within Dotfuscator, then it works, but otherwise it doesn't. However, it is not possible for me to do this for all properties in my project, as it would lead to possible bugs.
Are there any workarounds for this method? Or even other "free" obfuscation applications I could use?
I have already tried looking on their website to submit a bug, but I am only using the community edition so there doesn't seem to be as much support for it.
Dotfuscator automatically strips properties (which are just metadata anyway - the real work is done by the get/set pair of methods that are automatically created) during renaming. It also renames the underlying get/set methods as well. Depending on what you are trying to do, you'll need to exclude either the property metadata itself, or the get/set methods (or possibly both) from renaming.
If you need to keep the property metadata intact (for example, to simply list the properties in a Type), you can instruct Dotfuscator to exclude properties from renaming by checking them in the tree view on the Renaming Exclusions tab or using a custom regex property rule. This will only exclude the property metadata - the get/set methods will still be renamed.
If you need to keep the get/set methods (because, for example, you are trying to get or set a property's value by reflection), you can instruct Dotfuscator to exclude those methods from renaming by expanding the property in the tree view and checking the get/set methods underneath, or by using a custom regex method rule.
As the process of obfuscation is not limited to renaming your class members, you can't be sure of that. That's the problem with obfuscation: You basically can't make any assumptions about your class anymore regarding the result of reflection. The only way I can think of is to not use reflection but expressions.
Have a look at this question and its answer to know, what I mean with "expressions": How to raise PropertyChanged event without using string name

CA1726: FxCop Forbidden Word: Flags

someone wants me to make other people's code compliant to some FxCop ruleset which includes rule CA1726:Use preferred terms. Most of the terms/replacements are all right and I can understand that one has to decide on one single way to name things.
However, what's the deal with the term 'flags'? Can anyone explain to me why I shall not use this name? (before I go and complain about it at my boss ;) )
Say, I have a data object which has a member of class 'flags' which bundles a large number of properties that define how to handle the data object. How else would you call this?
In the book Framework Design Guidelines, which is what FxCop is based on, the authors say that using Flag or Flags is a bad idea. Their alternative suggestion is that when naming enumerations that you use a singular name for standard enums and a plural name for bit field (flags) enums.
For example if you wanted to create an enum listing different visibilities then you would name it Visibilities instead of VisibilityFlags or Visibility:
[Flags]
public enum Visibilities {
Public,
Private
}
The only items considered flags in .NET by the authors are these bitfield enumerations due to the keyword Flags attribute.
I would say that the property should be named aptly, and that the term Flags characterises the property rather than describing it.
Flag or Flags | There is no replacement term. Do not use.
For instance, Flags is generally used with enumerations (that are decorated with the appropriate attribute) and we certainly don't need to explicitly state so within the name / identifier of a property:
[Flags]
enum StorageMode
{
None = 0,
Next = 1,
...
Last = 32
}
class StorableItem
{
public StorageMode StorageMode { get; set; }
}
But, in your case, I get the feeling that whatever is named, or contains within its name, Flags, isn't actually a set of flags in the above sense - which just brings up another reason as to why to avoid it.

C# Attributes and their uses

I really don't know much about attributes in general in C#, I've seen them in use in a lot of different ways/places but I don't think I see the importance of some of them. Some definitely have importance because they provide a noticeable function, such as [Serializable]. Yet, others don't seem so important, such as one my coworker uses to mark properties with [DataMember].
I suppose my question is, what are attributes and how are they useful? Is there a way to create my own attributes and how can I tell if fields/methods/classes/whatever have particular attributes or what values are set in those attributes?
what are attributes?
Attributes enable you to embed information about a type or method in the metadata which describes that type or method.
You typically want to use attributes to describe facts about the mechanism of the type or method rather than the meaning of the type or method. For example, suppose you have a type Employee. A fact about the meaning of Employee is that it is a kind of Person, that an Employee has a Manager, and so on. A fact about the mechanism of Employee is that it can be the target of data binding, or it can be serialized to disk, or whatever. An employee cannot be serialized to disk, but the class Employee can be. Attributes let you separate information about the technical details from the semantic model.
Is there a way to create my own attributes?
Yes. Create a class which extends Attribute. By convention you want to name it "FooAttribute". If you do so you can use either the [Foo] syntax or the [FooAttribute] syntax at your discretion.
How can I tell if fields/methods/classes/whatever have particular attributes or what values are set in those attributes?
Use the GetCustomAttributes method on the reflection objects.
Where should I read for more information?
Start with the attributes tutorial:
http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx
And then read all of chapter 17 of the C# specification.
Attributes are a means by which you can associate metadata with types in .NET. This allows you to check for a type and get information about it that's separate from the "runtime" information of the type.
This can be very useful. You mentioned [Serializable], but other simple examples include many of the System.ComponentModel types, such as Description, which is used by the property grid to "describe" properties when you work with them in the designer. Since the "description" of a property isn't really related to the behavior of the type in a program (at runtime), it doesn't belong in the class. However, it's very handy when you go to edit a control in a visual designer, for example, to see a description (or category, etc) of a property. Attributes are the means by which this is handled.
I think the answer to the following question will provide you some insight to your questions.
How do attribute classes work?
Here is a repost of the answer I provided.
Attributes are essentially meta data that can be attached to various pieces of your code. This meta data can then be interogate and affect the behaviour of certain opperations.
Attributes can be applied to almost every aspect of your code. For example, attributes can be associated at the Assembly level, like the AssemblyVersion and AssemblyFileVersion attributes, which govern the version numbers associated with the assembly.
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Then the Serializable attribute for example can be applied to a type declaration to flag the type as supporting serialization. In fact this attribute has special meaning within the CLR and is actually stored as a special directive directly on the type in the IL, this is optimized to be stored as a bit flag which can be processed much more efficiently, there are a few attributes on this nature, which are known as pseudo custom attributes.
Still other attributes can be applied to methods, properties, fields, enums, return values etc. You can get an idea of the possible targets an attribute can be applied to by looking at this link
http://msdn.microsoft.com/en-us/library/system.attributetargets(VS.90).aspx
Further to this, you can define your own custom attributes which can then be applied to the applicable targets that your attributes are intended for. Then at runtime your code could reflect on the values contained in the custom attributes and take appropriate actions.
For a rather naive example, and this is just for the sake of example :)
You might want to write a persistence engine that will automatically map Classes to tables in your database and map the properties of the Class to table columns. You could start with defining two custom attributes
TableMappingAttribute
ColumnMappingAttribute
Which you can then apply to your classes, as an example we have a Person class
[TableMapping("People")]
public class Person
{
[ColumnMapping("fname")]
public string FirstName {get; set;}
[ColumnMapping("lname")]
public string LastName {get; set;}
}
When this compiles, other than the fact that the compiler emits the additional meta data defined by the custom attributes, little else is impacted. However you can now write a PersistanceManager that can dynamically inspect the attributes of an instance of the Person class and insert the data into the People table, mapping the data in the FirstName property to the fname column and the LastName property to the lname column.
As to your question regarding the instances of the attributes, the instance of the attribute is not created for each instance of your Class. All instances of People will share the same instance of the TableMappingAttribute and ColumnMappingAttributes. In fact, the attribute instances are only created when you actually query for the attributes the first time.
C# provides a mechanism for defining declarative tags, called attributes, which you can place on certain entities in your source code to specify additional information. The information that attributes contain can be retrieved at run time through reflection. You can use predefined attributes or you can define your own custom attributes.
http://msdn.microsoft.com/en-us/library/aa288059%28v=VS.71%29.aspx

Categories