Why can I not find a custom attribute on this MethodInfo - c#

I have a method with the following signature
[Specification]
public void slide_serialization() {
From a point in my code I need to move up the stacktrace to find the closest method with the SpecificationAttribute (performance is not an issue here). I find this method but I cannot find any custom attributes on it.
I don't think I've ever seen this happen. What might be the reason?
This is a unit testing assembly with Optimization disabled in Build.

The code snippet is not much to go by. But the stack trace makes it pretty clear what happened. Note the <>c_DisplayClass5 type name in the trace. This is an auto-generated class, produced by the C# compiler when it rewrites your code to compile a lambda expression with a closure. The subject of this Q+A.
The slide_serialization() method was rewritten as well, now acquiring the unspeakable <slide_serialization>_b40 method name. Use of angle brackets is intentional, it ensures that the members in the auto-generated code can never collide with identifier names in your program.
And you discovered a restriction in the code rewriting logic in the compiler. It does not transfer [attributes] on the original code to the rewritten code. Whether Microsoft did not think it was important enough to invest the effort or they could not do this correctly for every possible code rewriting rule is unclear. I strongly suspect the latter, the limitation is pretty painful. Usually discovered with much chagrin by programmers that need [SuppressMessage] attribute to get through code analysis without warnings.
There is no simple workaround for this, you have to deal with the limitation.

Related

Is CodeContract similar to FxCop?

Please clarify, is the Code Contracts is similar to FxCop and StyleCop?
As per the online references, we need to add Codes for implementing the code contract conditions inside the function of existing code.
public void Initialize(string name, int id)
{
Contract.Requires(!string.IsNullOrEmpty(name));
Contract.Requires(id > 0);
Contract.Ensures(Name == name);
//Do some work
}
Usually in FxCop, the code we want to check will be in separate Dll and the Class library which includes the rules to check will be in separate dll.
Likewise whether we can create separate class library for Code contract to rule the existing code?
Please confirm..
disclaimer: you'd better take their current docs and read them through, write down the features and then compare them. What I wrote below is some facts I remembered long time ago about their core functionalities and I can't guarantee you that they are not outdated and now-wrong. For example, someone could write some complex&heavy rules for FxCop that behave as Contracts do. This is why I'm marking it as community-wiki. Please correct me if I'm wrong anywhere.
No they are not similar, although they share common target: help you find bugs.
FxCop is a "static analyzer", which inspects your code and tries to find "bad patterns". You will not see any FxCop rules/effects during runtime. FxCop has a set of "rules" that will be used during inspection and it reports to you whenever it finds a rule to be broken. Rules can be very easy and nitpicking like you must initialize every variable or you must name classes with uppercase or complex ones like you shouldn't have more than one loop in a method. Some rules are available by the standard installation, and you can expand the ruleset with your own rules.
CodeContracts is two-sided. At the most basic level, it is a set of helper methods, like throw if argument 'foo' is null. At runtime, when someone passes a null, it will throw. Just that simple. However, if you use those helper methods correctly and widely in your code, you will be able to run an additional static analyzer. It will scan your code, find all usages of those helper methods, and will try to automatically detect any places where their contracts are not satisfied. So, with the "argument is null" example, it will try to find all usages of that function, check who calls it with what args, it will try to deduce (prove) if that arg can be null at all anytime, and will warn you if it finds such case. There are more types of such validators other than just not-null, but you can't add/write your own. I mean, you could add more such helper validators, but the static analyzer wouldn't pick them up (it's too hard to write a general theorem prover for any rule).
CodeContracts is more powerful in its analyses than FxCop, but limited in diversity and scope. CodeContracts cannot check the structure of the code: it will not check the number of loops, code complexity, names of methods, code hierarchy, etc. It can only attempt to prove/disprove some contracts (runtime requirements) of some methods/interfaces. FxCop on the other hand can inspect your code, style, structure, etc, but it will not "prove" or "deduce" anything - it will just check for some bad patterns defined by rules.
While FxCop is used to verify some code-style or typical perfomance issues,
Code Contracts influences your code design, so it aims to achieve higher level goals. It's a .NET implementation attempt of contract programming methodology used in Eiffel language. Methodology says, that every type will behave correctly (performing its postconditions and invariants), only if it will have input according to required preconditions.
You should describe your types preconditions, invariants and postconditions with use of library helper methods and attributes (Contract.Requires, etc.) and Code Contracts static analizer will be able to detect their failures during compilation.
(Last time I looked at it, tool was rather slow and hard to use. Seems, that it haven't been completed by microsoft research team. Fortunately, few days ago a new version of it have been released with bug-fixes for async-await as well as VS2015 support.)

Extending Intellisense on specific language constructs (namely Attribute constructors)

I've written a custom attribute for decorating methods. The attributes help add non-critical but very helpful contextual data to the method. Currently, this helps with debugging, but eventually it will help with static analysis.
Because the Master of the data specified in the attributes is on a server and queriable, I figured I'd write a Visual Studio Intellisense extention to help my developers. The extension would kick in when typing in parameters in my Attribute's constructor. The completion suggestions would essentially be query results.
I've read and implemented a Statement Completion example on MSDN with relative success.
The example is for Completion on PlainText. I've changed it to work on Code instead. I'm one step closer. The problem I'm having, however, is that I can't seem to find how to make it aware of its context. The Completion kicks an whenever I type any code. I'd like it to be a bit more discriminating than this.
Question: Is it possible to make a custom Visual Studio Statement Completion extension aware of the language constructs around it?
I'd like to be able to only trigger Statement Completion when I'm typing into an Attribute's constructor. And, if possible, preferably only on Attributes derived from a given base class.
Is this kind of thing possible?
No. This is why we're building Roslyn, but until then you might be able to use a third-party parser, or your own hacked up parser or heuristics to make it work.

If attributes are only constructed when they are reflected into, why are attribute constructors so limited?

As shown here, attribute constructors are not called until you reflect to get the attribute values. However, as you may also know, you can only pass compile-time constant values to attribute constructors. Why is this? I think many people would much prefer to do something like this:
[MyAttribute(new MyClass(foo, bar, baz, jQuery)]
than passing a string (causing stringly typed code too!) with those values, turned into strings, and then relying on Regex to try and get the value instead of just using the actual value, and instead of using compile-time warnings/errors depending on exceptions that might be thrown somewhere that has nothing to do with the class except that a method that it called uses some attributes that were typed wrong.
What limitation caused this?
Attributes are part of metadata. You need to be able to reflect on metadata in an assembly without running code in that assembly.
Imagine for example that you are writing a compiler that needs to read attributes from an assembly in order to compile some source code. Do you really want the code in the referenced assembly to be loaded and executed? Do you want to put a requirement on compiler writers that they write compilers that can run arbitrary code in referenced assemblies during the compilation? Code that might crash, or go into infinite loops, or contact databases that the developer doesn't have permission to talk to? The number of awful scenarios is huge and we eliminate all of them by requiring that attributes be dead simple.
The issue is with the constructor arguments. They need to come from somewhere, they are not supplied by code that consumes the attribute. They must be supplied by the Reflection plumbing when it creates the attribute object by calling its constructor. For which it needs the constructor argument values.
This starts at compile time with the compiler parsing the attribute and recording the constructor arguments. It stores those argument values in the assembly metadata in a binary format. At issue then is that the runtime needs a highly standardized way to deserialize those values, one that preferably doesn't depend on any of the .NET classes that you'd normally use the de/serialize data. Because there's no guarantee that such classes are actually available at runtime, they won't be in a very trimmed version of .NET like the Micro Framework.
Even something as common as binary serialization with the BinaryFormatter class is troublesome, note how it requires the [Serializable] attribute on the class to allow it to do its job. Versioning would also be an enormous problem, clearly such a serializer class could never change for the risk of breaking attributes in old assemblies.
This is a rock and a hard place, solved by the CLS designers by heavily restricting the allowed types for an attribute constructor. They didn't leave much, just the simple values types, string, a simple one-dimensional array of them and Type. Never a problem deserializing them since their binary representation is simple and unambiguous. Quite a restriction but attributes can still be pretty expressive. The ultimate fallback is to use a string and decode that string in the constructor at runtime. Creating an object of MyClass isn't an issue, you can do so in the attribute constructor. You'll have to encode the arguments that this constructor needs however as properties of the attribute.
The probably most correct answer as to why you can only use constants for attributes is because the C#/BCL design team did not judge supporting anything else important enough to be added (i.e. not worth the effort).
When you build, the C# compiler will instantiate the attributes you have placed in your code and serialize them, so that they can be stored in the generated assembly. It was probably more important to ensure that attributes can be retrieved quickly and reliably than it was to support more complex scenarios.
Also, code that fails because some attribute property value is wrong is much easier to debug than some framework-internal deserialization error. Consider what would happen if the class definition for MyClass was defined in an external assembly - you compile and embed one version, then update the class definition for MyClass and run your application: boom!
On the other hand, it's seriously frustrating that DateTime instances are not constants.
What limitation caused this?
The reason it isn't possible to do what you describe is probably not caused by any limitation, but it's purely a language design decision. Basically, when designing the language they said "this should be possible but not this". If they really wanted this to be possible, the "limitations" would have been dealt with and this would be possible. I don't know the specific reasoning behind this decision though.
/.../ passing a string (causing stringly typed code too!) with those values, turned into strings, and then relying on Regex to try and get the value instead of just using the actual value /.../
I have been in similar situations. I sometimes wanted to use attributes with lambda expressions to implement something in a functional way. But after all, c# is not a functional language, and if I wrote the code in a non-functional way I haven't had the need for such attributes.
In short, I think like this: If I want to develop this in a functional way, I should use a functional language like f#. Now I use c# and I do it in a non-functional way, and then I don't need such attributes.
Perhaps you should simply reconsider your design and not use the attributes like you currently do.
UPDATE 1:
I claimed c# is not a functional language, but that is a subjective view and there is no rigourous definition of "Functional Language". I agree with the Adam Wright, "/.../ As such, I wouldn't class C# as functional in general discussion - it is, at best, multi-paradigm, with some functional flavour." at Why is C# a functional programmming language?
UPDATE 2:
I found this post by Jon Skeet: https://stackoverflow.com/a/294259/1105687 It regards not allowing generic attribute types, but the reasoning could be similar in this case:
Answer from Eric Lippert (paraphrased): no particular reason, except
to avoid complexity in both the language and compiler for a use case
which doesn't add much value.

ILogger _logger.Debug("Something") - Any way for the compiler to remove it?

I got a pretty common scenario, namely a self implemented ILogger interface. It contains several methods like _logger.Debug("Some stuff") and so on. The implementation is provided by a LoggingService, and used in classes the normal way.
Now I have a question regarding performance, I am writing for Windows Phone 7, and because of the limited power of these devices, little things may matter.
I do not want to:
Include a precompiler directive on each line, like #IF DEBUG
Use a condition like log4net e.g. _logger.DebugEnabled
The way I see it, in the release version, I just return NullLoggers, which contain an empty implementation of the interface, doing nothing.
The question is: Does the compiler recognize such things (may be hard, he can't know on compile time which logger I assign). Is there any way to give .NET a hint for that?
The reason for my question, I know entering an empty function will not cause a big delay, no problem there. But there are a lot of strings in the source code of my application, and if they are never used, they do not really need to be part of my application...
Or am I overthinking a tiny problem (perhaps the "string - code" ratio just looks awful in my code editor, and its no big deal anyway)..
Thanks for tips,
Chris
Use the Conditional attribute:
[Conditional("DEBUG")]
public void Debug(string message) { /* ... */ }
The compiler will remove all calls to this method for any build configurations that don't match the string in the conditional attribute. Note that this attribute is applied to the method not the call site. Also note that it is the call site instruction that is removed, not the method itself.
It is probably a very small concern to have logging code in your application that does not "run". The overhead of the "null" logger or conditionals is likely to be very small in the scheme of things. The strings will incur memory overhead which could be worrying for a constrained device, but as it is WP7 the minimum specs are not that constrained in reality.
I understand that logging code looks fugly though. :)
If you really want to strip that logging code out...
In .Net you can use the ConditionalAttribute to mark methods for conditional compilation. You could leverage this feature to ensure that all logging calls are removed from compilation for specified build configurations. As long as methods that you have decorated with the conditional attributes follows a few rules, the compiler will literally strip the call chain out.
However, if you wanted to use this approach then you would have to forgo your interface design as the conditional attribute cannot be applied to interface members, and you cannot implement interfaces with conditional members.

Why does StyleCop recommend prefixing method or property calls with "this"?

I have been trying to follow StyleCop's guidelines on a project, to see if the resulting code was better in the end. Most rules are reasonable or a matter of opinion on coding standard, but there is one rule which puzzles me, because I haven't seen anyone else recommend it, and because I don't see a clear benefit to it:
SA1101: The call to {method or property name} must begin with the 'this.' prefix to indicate that the item is a member of the class.
On the downside, the code is clearly more verbose that way, so what are the benefits of following that rule? Does anyone here follow that rule?
I don't really follow this guidance unless I'm in the scenarios you need it:
there is an actual ambiguity - mainly this impacts either constructors (this.name = name;) or things like Equals (return this.id == other.id;)
you want to pass a reference to the current instance
you want to call an extension method on the current instance
Other than that I consider this clutter. So I turn the rule off.
It can make code clearer at a glance. When you use this, it's easier to:
Tell static and instance members apart. (And distinguish instance methods from delegates.)
Distinguish instance members from local variables and parameters (without using a naming convention).
I think this article explains it a little
http://blogs.msdn.microsoft.com/sourceanalysis/archive/2008/05/25/a-difference-of-style.aspx
...a brilliant young developer at Microsoft (ok, it was me) decided to take it upon himself to write a little tool which could detect variances from the C# style used within his team. StyleCop was born. Over the next few years, we gathered up all of the C# style guidelines we could find from the various teams within Microsoft, and picked out all of best practices which were common to these styles. These formed the first set of StyleCop rules. One of the earliest rules that came out of this effort was the use of the this prefix to call out class members, and the removal of any underscore prefixes from field names. C# style had officially grown apart from its old C++ tribe.
this.This
this.Does
this.Not
this.Add
this.Clarity
this.Nor
this.Does
this.This
this.Add
this.Maintainability
this.To
this.Code
The usage of "this.", when used excessively or a forced style requirement, is nothing more then a contrivance used under the guise that there is < 1% of developers that really do not understand code or what they are doing, and makes it painful for 99% who want to write easily readable and maintainable code.
As soon as you start typing, Intellisence will list the content available in the scope of where you are typing, "this." is not necessary to expose class members, and unless you are completely clueless to what you are coding for you should be able to easily find the item you need.
Even if you are completely clueless, use "this." to hint what is available, but don't leave it in code. There are also a slew of add-ons like Resharper that help to bring clarity to the scope and expose the contents of objects more efficiently. It is better to learn how to use the tools provided to you then to develop a bad habit that is hated by a large number of your co-workers.
Any developer that does not inherently understand the scope of static, local, class or global content should not rely on "hints" to indicate the scope. "this." is worse then Hungarian notation as at least Hungarian notation provided an idea about the type the variable is referencing and serves some benefit. I would rather see "_" or "m" used to denote class field members then to see "this." everywhere.
I have never had an issue, nor seen an issue with a fellow developer that repeatedly fights with code scope or writes code that is always buggy because of not using "this." explicitly. It is an unwarranted fear that "this." prevents future code bugs and is often the argument used where ignorance is valued.
Coders grow with experience, "this." is like asking someone to put training wheels on their bike as an adult because it is what they first had to use to learn how to ride a bike. And adult might fall off a bike 1 in 1,000 times they get on it, but that is no reason to force them to use training wheels.
"this." should be banned from the language definition for C#, unfortunately there is only one reason for using it, and that is to resolve ambiguity, which could also be easily resolved through better code practices.
A few basic reasons for using this (and I coincidentally always prefix class values with the name of the class of which they are a part as well - even within the class itself).
1) Clarity. You know right this instant which variables you declared in the class definition and which you declared as locals, parameters and whatnot. In two years, you won't know that and you'll go on a wondrous voyage of re-discovery that is absolutely pointless and not required if you specifically state the parent up front. Somebody else working on your code has no idea from the get-go and thus benefits instantly.
2) Intellisense. If you type 'this.' you get all instance-specific members and properties in the help. It makes finding things a lot easier, especially if you're maintaining somebody else's code or code you haven't looked at in a couple of years. It also helps you avoid errors caused by misconceptions of what variables and methods are declared where and how. It can help you discover errors that otherwise wouldn't show up until the compiler choked on your code.
3) Granted you can achieve the same effect by using prefixes and other techniques, but this begs the question of why you would invent a mechanism to handle a problem when there is a mechanism to do so built into the language that is actually supported by the IDE? If you touch-type, even in part, it will ultimately reduce your error rate, too, by not forcing you to take your fingers out of the home position to get to the underscore key.
I see lots of young programmers who make a big deal out of the time they will save by not typing a character or two. Most of your time will be spent debugging, not coding. Don't worry so much about your typing speed. Worry more about how quickly you can understand what is going on in the code. If you save a total of five minutes coding and win up spending an extra ten minutes debugging, you've slowed yourself down, no matter how fast you look like you're going.
Note that the compiler doesn't care whether you prefix references with this or not (unless there's a name collision with a local variable and a field or you want to call an extension method on the current instance.)
It's up to your style. Personally I remove this. from code as I think it decreases the signal to noise ratio.
Just because Microsoft uses this style internally doesn't mean you have to. StyleCop seems to be a MS-internal tool gone public. I'm all for adhering to the Microsoft conventions around public things, such as:
type names are in PascalCase
parameter names are in camelCase
interfaces should be prefixed with the letter I
use singular names for enums, except for when they're [Flags]
...but what happens in the private realms of your code is, well, private. Do whatever your team agrees upon.
Consistency is also important. It reduces cognitive load when reading code, especially if the code style is as you expect it. But even when dealing with a foreign coding style, if it's consistent then it won't take long to become used to it. Use tools like ReSharper and StyleCop to ensure consistency where you think it's important.
Using .NET Reflector suggests that Microsoft isn't that great at adhering to the StyleCop coding standards in the BCL anyway.
I do follow it, because I think it's really convenient to be able to tell apart access to static and instance members at first glance.
And of course I have to use it in my constructors, because I normally give the constructor parameters the same names as the field their values get assigned to. So I need "this" to access the fields.
In addition it is possible to duplicate variable names in a function so using 'this' can make it clearer.
class foo {
private string aString;
public void SetString(string aString){
//this.aString refers to the class field
//aString refers to the method parameter
this.aString = aString;
}
}
I follow it mainly for intellisense reasons. It is so nice typing this. and getting a consise list of properties, methods, etc.

Categories

Resources