Define warnings for using properties (as attribute?) in C# - c#

I want to raise warnings, if certain properties are used in the code. I could use the obsolete-attribute. But the used properties aren't obsolete, thus it wouldn't be that correct to give an obsolete warning.
How can I define own warnings for some properties that are printed during compilation, when the property is used?

Why not use the obsolete atrribute?
You can use task list with comments. Just use of the keywords defined here

Related

CC Suggesting Redundant Ensures

I have a piece of code which looks a little like this:
public TReturn SubRegion(TParam foo)
{
Contract.Requires(foo!= null);
Contract.Ensures(Contract.Result<TReturn>() != null);
if (!CheckStuff(foo))
foo.Blah();
return OtherStuff(foo);
}
CC is giving me a warning:
Warning 301 CodeContracts: Consider adding the postcondition Contract.Ensures(Contract.Result() != null); to provide extra-documentation to the library clients
Which is obviously completely redundant! I have several such redundant warnings and it's becoming a problem (real warnings getting buried in a torrent of redundant suggestions).
So I have two questions:
1) Am I missing something which means this is not a redundant recommendation? In which case what do I need to do to fix this warning?
2) Alternatively, if this is just a quirk of CCCheck and cannot be fixed how can I hide or suppress this warning?
N.b. Just in case you think my example is missing something important, the full code is the SubRegion method here.
Regarding 2: The documentation is pretty good, take a look at 6.6.10 Filtering Warning Messages:
To instruct the static contract checker not to emit a particular class
of warnings for a method (a type, an assembly), annotate the method
(the type, the assembly) with the attribute:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Contracts", warningFamily)]
where warningFamily is one of: Requires, Ensures, Invariant, NonNull,
ArrayCreation, ArrayLowerBound, ArrayUpperBound, DivByZero,
MinValueNegation.
If necessary, the static contract checker allows filtering a single
warning message (instead of an entire family) as well. To do so you
can annotate a method with the attribute
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Contracts", warningFamily-ILOffset-MethodILOffset)]
where warningFamily is as
above, and ILOffset and MethodILOffset are used by the static
contract checker to determine the program point the warning refers to.
The offsets can be obtained from the static contract checker by
providing the -outputwarnmasks switch in the "Custom Options" entry in
the VS pane. Check the Build Output Window for the necessary
information.

Cannot set a DisplayName on an enum

I used a decompiler to extract all the code from a DLL (SharpSVN -- cannot get my hands on the source code) and I want to modify an enum to give it a DisplayName.
public enum SvnStatus
{
Zero,
None,
[DisplayName("Not Versioned")]
NotVersioned,
//other one-word values that don't need a display name
}
But this gives me the following error:
Attribute 'System.ComponentModel.DisplayNameAttribute' is not valid on this declaration type. It is valid on 'Class, Method, Property, Event' declarations only.
Googled around and found a number of threads where people seem to do this no problem with their enums. Am I missing something? I can't Resolve the error in Visual Studio, the option doesn't even show up (but that might be because I just installed Resharper and am not familiar with it yet?)
Edit: Just found DevExpress has a CustomColumnDisplayText event where I can change the value as desired, so I'm going to go with that instead, since the data is only being displayed in a GridControl.
The reason is given in the error you're getting.
The System.ComponentModel.DisplayNameAttribute has been attributed with a System.AttributeUsageAttribute which constricts the usage to only be applied to classes, methods, properties, or events. Enums are excluded. It looks like this:
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Property|AttributeTargets.Event)]
Perhaps you can write your own attribute instead?

Cannot prevent "Code Analysis" warnings for

I am using T4 to generate some code. The code will be in a class called "MyClass.generated.cs" and typical output will look like this.
//<autogenerated/>
namespace MyNamespace
{
using System;
using System.CodeDom.Compiler;
[GeneratedCode("T4", "1.0.0.0")]
public partial class MyClass: SomeBaseClass
{
private SomeBaseClass myBackingField;
}
}
However, even though the class is decorated with the GeneratedCodeAttribute, I still get a Code Analysis warning as follows:
Field 'MyNamespace.MyClass.myBackingField' is never assigned to, and will always have its default value null
I have ensure that the Project Properties → Code Analysis → "Suppress results from generated code (managed only)" checkbox is checked.
Please note that I understand the meaning of the warning - I just want to know how to suppress it :)
Possible solutions
I could modify my generator to use Suppressions to suppress specific warnings, but this is extra work that I shouldn't have to do (as generated code should be ignored by Code Analysis).
Related Questions
Visual studio code analysis for generated files
EDIT with background context
The actual generated code is essentially a wrapper around SomeBaseClass. There are 100+ types in a namespace, and I want to change the behaviour of a subset of those. There are other warnings being generated as well - I just used this one as an example. Consider for example, if there is a property SomeBaseClass.MyObsoleteProperty, which is decorated with the ObsoleteAttribute. My code generater would still create a MyClass.MyObsoleteProperty which would raise a Code Analysis warning.
Another example would be where the SomeBaseClass (which is from a 3rd-party) would itself raise Code Analysis warnings if they had bothered to check for them (maybe the class is not CLS-compliant, for example). My wrapper will recreate any errors they have (and that would actually be the desired behaviour).
I figured it out - this is not a Code Analysis warning - it's a compiler warning.
Therefore, the only way to disable it is to modify the generator to enclose the class in pragma directives to suppress compiler warnings, e.g
#pragma warning disable warning-list
// Now generate some code
#pragma warning restore warning-list
WARNING
Note that this is a dangerous feature - compiler warnings are there for a reason! Try and limit your use of it to as small a section as possible.
More information can be found at
Suppressing "is never used" and "is never assigned to" warnings in C#
List of compiler warnings and errors here.
I think you mean
#pragma warning disable
// generated code
#pragma warning restore
the "warning-list" is a placeholder in MSDN documentation for something like "c0605,c0403,c3498" etc

Code Contracts Ensures for ReSharper ExternalAnnotations

Does anyone know how to add Code Contracts Ensures in ReSharper ExternalAnnotations? It's not there in the last v7.1.3 nor in the latest v8 EAP, and neither in any of the custom xmls floating around.
Specifically it should detect if a method does not return a null: Contract.Ensures(Contract.Result<T>() != null);
If you're attempting to simply appease the analysis engine, the simplest thing to use is [NotNull] in front of the method declaration. The Contract Annotations to which you posted a link above is a more powerful mechanism for defining relationships between input parameters and the return value, e.g., [ContactAnnotation("null => null")].
However, explicitly analyzing for a Contract.Ensures statement is an entirely different proposition, as no automatic analysis can be defined for this statement via [ContractAnnotation] or any other ReSharper annotation attribute.

what does the bracket represent in P/invoke [dllimport

I am curious to know why when we are doing P/invoke
the dllimport call is in a "["
and not just a class or a function
e.g.:
[DllImport("something.dll",....)]
rather than
DllImport("something.dll,....)
or even
DllImport.import(something.dll...)
I do not want to rewrite it, my questions is what does "[" represent or mean ? what is it called in this instance ? Why is it used ?
In this context, it signifies an "attribute"; DllImportAttribute (MSDN). Simply : it is a syntax already in the language for adding metadata to the code.
The language allows you to define your own attributes, or any from libraries. Attributes can be used on assemblies, types, methods, properties, fields, events, parameters, etc - or restricted to a small subset of that. DllImportAttribute is limited to methods, for example. Most only have meaning when inspected with reflection at runtime, but some re handled directly by the compiler.
DllImport is not a method. It is an attribute. The brackets are just the syntax for applying attributes.
The syntax is specified in appendix B of the C# specification, section B.2.13, Attributes.

Categories

Resources