Code analysis warnings in generated code (like migrations) - Visual Studio (C#) - c#

Most of the warnings that currently I have at my project comes from code that was autogenerated. In most cases, it is (CA1062: Validate arguments of public methods). I noticed that even console hello word app generated by Visual Studio display warning (S1118: Utility classes should not have public constructors).
How I can disable warnings for autogenerated code? (migrations mostly)

As crgolden says, you can add // <auto-generated/> tag at the start of file. BUT I would be cautious with doing that to files where the generator tools chose to not add it. You specifically mention migrations - you are supposed to review them before commit, EF sometimes does surprising things (*). That review is also a good time to fix any warnings that bother you. If you care enough about the warning to leave it enabled, silencing it in migrations sets a bad precedent. And if you don't care about it, you can disable it globally.
My view of the auto-generated comment is that it belongs in files that are regenerated outside of your control, or frequently, or both. Since we use EF as example, ModelSnapshot is a good candidate, and the migration tools DO include it. <Migration>.Designer.cs files are also generated with it. And it should almost never be added by hand (**)
(*) delete one column and add another, you may find migration with rename action if they have similar types. Or your coleague did some change to code and forgot to generate migration for it - your migration will now include changes from both and his part will be untested.
(**) since every rule needs an exception, recently I was considering breaking this rule for a thirdparty library we imported into project as source files. In the end I decided to just set the whole project to warning level 0.

You can just add this comment to the top of the file:
// <auto-generated/>

Related

C# class backward compatibility

I have a NuGet package that is been used by some projects internally. Now, while refactoring the project, I found several classes that were named inappropriately. I want to know if there is any way in C# change the class names and not break anything.
There is no way to rename identifiers without breaking other people code. The best thing you can do is to leave clAssNaME identifier, provide new ClassName and mark clAssNaME as deprecated. Publish new release with documented and highlighted changelog.
When you're confident enough that most people managed to fix their code, delete the clAssNaME.
What you do depends on the extent of the changes. If the types with the changed names are not simple types (ie. have a lot of behavior) or are used throughout your package it can be very difficult to create a copy of the type because you also have to ensure the code can use either type (for a while anyways).
A simpler solution might be to branch your package and increment the major version number in the new branch. In the "new" branch: Update the type names, document the breaking changes, and push a release as a new version. You can then maintain both branches until you see fit to stop work on the "older" branch. In the "older" branch you can also mark types as deprecated with a warning that in the future version they will have a changed name.

Three gray dots under variable names in Visual Studio

What do these three gray dots mean? I recently updated to Visual Studio 2017, and I haven't ever seen them in other versions of VS.
They indicate suggestion from Visual Studio to refactor your code to be simpler, more readable and efficient.
See Quick Actions and Refactorings section of the Visual Studio 2017 (version 15.0) Release Notes.
Just to make doubly clear for newish programmers, these are not in any sense error messages. They are merely suggestions for more "readable and efficient" code as #Oleksander states.
Some may not be the best advice for your application, unlike warning or error messages, which almost 100% are in my case at least.
I had suggestion in a Unity game engine C# application to make a variable "readonly". I'm not sure in my case it makes practical difference whether this is readonly or not, as in this case I think fairly obvious in the context: a private variable which is serialized and can be set in game's editor program, nobody likely to create new method in this game scene manager class to alter/assign this variable. Likewise it gave a suggestion to create property for a class private field, which I think extra code overkill.
At the least these are low priority messages to action.
Suppressing 3 Dot Symbols in Visual Studio
If you right click and read through one of these suggestions, you can find there is option to suppress these messages in global project file, with various optional parameters. So eg in my case, now I don't want any readonly message suggestions for whole project (welcome correct me anyone more experienced if this is bad idea!), so in the root of project, same level as .sln solution file, .csproj files, .git file in my case for C# project, it saves file called "GlobalSuppressions.cs". Root location and this exact file name is presumably crucial.
I guess if you want stop future coders / future you from fretting or spending time on these 3 dot messages when you think waste of time, could be useful.
In my case, to get rid of all "readonly" keyword suggestions in this project, code is (comments are VS auto comments):
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier")]

Ignoring files from checkin with certain pattern of change

Since having started using JetBrains Annotations, for my own benefit I've decorated all methods with [CanBeNull] or [NotNull]
For example, the following line:
public AccountController(IAccountService accountService)
Would be changed to:
public AccountController([CanBeNull] IAccountService accountService)
Another example would be:
public Account CreateAccountEntity(Account accountEnttity)
would be changed to:
[CanBeNull]
public Account CreateAccountEntity([NotNull] Account accountEnttity)
How can I bypass pending changes for annotations, specifically "[CanBeNull]", and have TFS completely ignore this change?
You cannot make TFS "ignore" the change. That is the purpose of TFS - to track all changes.
The way I interpret your question, you are wanting to avoid the noise of potentially many small but innocuous checkins due to your annotations. If this is correct then there is a way to use TFS that will minimize the noise:
create a branch from where you are currently working (let's call it "BranchA"), then make all the annotation changes in that new branch ("BranchB"), checking them in regularly
if this is going to take some time (days, weeks) to complete then ensure you do regular merges from BranchA to BranchB
when you think you've finished do a final merge from BranchA to BranchB. If you've pulled across any new methods then ensure you annotate them. Repeat this step if you made changes.
merge all changes from BranchB back to BranchA. This will have the effect of aggregating all your smaller changes into a single large checkin/changeset in BranchA. Provided you have been doing regular merges from BranchA to BranchB this should be problem free even if considerable time has passed since you started the decoration work.
In short, you shouldn't, the closest feature is the tfignore, but this will ignore all file.
On the other hand, if you really want this, you could create a tool using the TFS API, and you would have to run this before check-ins and it would verify all the pending files in your solution and looking for this small changes and excluding the files, but this could cause the problem that at some point you may make a change to an excluded file and it won't get checked in and cause problems. You would need to add extra code to verify what files should be included from the excluded list.
External tool used inside VS Here you can see how to add tools to the Tools menu and send arguments to it.
TFS API Example
This example shows how to use the TFS API. There is a 'workspace.AddIgnoreFileExclusion()', but I don't have TFS here, so I'll verify how to ignore the files later.
Now in my experience, the only reason I wouldn't want to check in those changes would be to avoid conflicts with the team.
If I see a lot of value in some practice like using the annotations, I would talk with the team to get them to buy in into the idea of using annotations, that way everyone would be using it and soon every file will have the annotations and there won't be any conflicts.
You can't selectively ignore changes within files, in TFVC or in any other SCM I've ever encountered.
I agree with other answers that such kind of feature isn’t officially supported by Microsoft.
But you can also overwrite TFVC in a few ways if it is really needed. You can write your own Visual Studio plug-in or Source Control VSPackage .
If your main goal is to write better code with the help of ReSharper telling you whether you should expect nulls or not or produce other warnings and you don't want to disturb other team members with it I would suggest you to consider using External Annotations instead of annotation attributes in code.
You can then decide whether you want to commit those files or keep them locally. And even if you commit your code will still be clean without those extra attributes.
At least I would give it a try.

How to ignore reference to jetbrains.annotations.dll in NodaTime nuget package xml documentation file

I lean quite heavily on Resharper context actions to generate boilerplate code. The Check parameter for null context action had, up until recently, generated code that performs the null check and throws accordingly. However, now it is adding a Resharper specific [NotNull] annotation to the parameter as part of the method signature.
Looking at this related question Stop ReSharper from Adding Annotations, I've checked across my solution codebase for jetbrains.annotations.dll references but not found any.
However, searching across all files I've found references to jetbrains.annotations.dll in the xml documentation file for NodaTime (NodaTime.xml).
Specifically, entries like this:
<member name="T:JetBrains.Annotations.NotNullAttribute">.
Im not categorically stating that this is the root cause. However, NodaTime is the most recent nuget package I have added since the issue began, and a grep across the solution shows this to be the single point of reference.
Should xml documentation files be including these references, and if so, is there a way for me to configure Resharper to ignore them?
UPDATE
I've decompiled the NodaTime assembly and although it doesn't have any binary references to jetbrains.annotations.dll it does appear to (re)declare the offending JetBrains.Annotations namespaces and annotations within itself.
As per citizenmatts suggestion, Ive used the Resharper take me to definition tool for the [NotNull] attribute and this goes to the NodaTime.dll
I've also just noticed that the NotNull attributes Resharper is including do not compile and complain of Cannot reference internal class NotNullAttribute. Hence I obviously don't have the jetbrains.annotations.dll included anyway.
UPDATE 2
Just done the obvious thing of creating a new blank project in VS2013 and checking the null check context action in Resharper works. Then added NodaTime nuget package and rechecked - and indeed it adds the [NotNull] attribute and the project wont compile.
UPDATE 3
As suggested by Jon Skeet I've tried "turning off" data annotations using Resharper-->Code Inspection-->Code Annotations-->Unticking JetBrains.Annotations. However, this has no affect and the NotNull attribute continues to be included.
Looks like I may just have to return to System.DateTime.
Noda Time deliberately ships with an internal copy of the R# annotations, so that those who do want them can benefit from them - it will know which methods are pure, etc.
It sounds like you don't actually want to use annotations at all, so it's just worth disabling them. That's easy from the R# options - under Code Inspection / Code Annotations, uncheck the JetBrains.Annotations option.
We can certainly consider moving the annotations into a specific namespace for Noda Time in the future, so that it's more opt-in than opt-out, but this is probably a good solution if you don't want to use annotations, as it makes it absolutely clear to R# that you really don't want to use them, even if other libraries include annotations.
EDIT: Just to promote Matt's comment into this answer:
Sadly, this is a bug in ReSharper - it doesn't take visibility of the NotNullAttribute into account before applying it. Here's the ticket to track and vote on: http://youtrack.jetbrains.com/issue/RSRP-413425
NodaTime.dll ships with the JetBrains annotations compiled in as internal symbols, which means they're used internally to NodaTime and not visible for anyone else to use. However, ReSharper can see these annotations that have been applied to the NodaTime classes and methods.
NodaTime doesn't have any binary references to JetBrains.Annotations.dll, and neither ReSharper nor Visual Studio should be adding a reference to a dll based on xml documentation. If ReSharper is able to add a [NotNull] annotation to your code, the dll must be being referenced from somewhere. I'd suggest invoking ReSharper's "go to definition" on the [NotNull] and see where it takes you - it should show you where the annotations dll is being referenced from, and you should be able to remove it easily from there.
Update: As noted above, and in the other answers, the issue is a bug in ReSharper that doesn't check the accessibility of the attribute before applying it. Here's the YouTrack ticket to track and vote on: http://youtrack.jetbrains.com/issue/RSRP-413425

Change each c# file in solution

Is there a tool or set of tools to go through a c# solution and automatically perform certain changes such as enforcing naming schemes and change for/foreach to linq if possible.
I have used Resharper to do some basic solution wide changes, but I would really like it to do more like global renaming.
Specifically, I would like a tool to rename method parameters to proper c# naming schemes. For instance, MethodA(string Field) should become MethodA(string field) and so on.
Resharper has some pretty cool features, including "Cleanup Code", which can be run on multiple files at once.
It will automatically refactor your files based on the settings you've supplied it.
They have a demo version, so you can test to see if it helps with your problem.
http://www.jetbrains.com/resharper/
Resharper`s "Clean Up Code" tool can be run from context menu of any item in Solution Explorer. There are a few built in clean up configurations. You can configure your own. For example, you can set up order of fields\properties\methods\nested types in you class and reordering their before commit by executing clean up tool. It also can wrap its into region and so on.
Also you can force Resharper to use any of refactorings when cleaning up.(Optimize imports, remove unused methods or properties or use linq instead of loops, etc)
You can start looking from there
UPD You can use stylecop plugin to make your code correspond with the style conventions you want. It is open source and compatible with R#

Categories

Resources