I've included a 3rd party .cs file in my code. It doesn't comply with StyleCop's rules but I desperately need to be able to exclude it from StyleCop's checks but none of the methods I've found so far will work.
Three methods are documented here: http://sethflowers.com/blog/force-stylecop-to-ignore-a-file/ .. but none of these methods seems to work in StyleCop 4.7
The most useful of which looks to be this method in .csproj:
<Compile Include="AViolatingFile.cs">
<ExcludeFromStyleCop>true</ExcludeFromStyleCop>
</Compile>
But despite having added the files, StyleCop still causes a compilation error when parsing this file.
// <auto-generated/>
Put this at the top of the class
Style cop ignores auto generated code
I used stylecop a while back as well and I believe you have to use the following line in your csproj file:
<Import Project="$(MSBuildExtensionsPath)\StyleCop\v4.6\StyleCop.targets" Condition="Exists('$(MSBuildExtensionsPath)\StyleCop\v4.6\StyleCop.targets')" />
You will also need to change the version number in the xml declaration to whatever you have installed.
Hope this helps.
Atm, I'm running StyleCop 4.7.49 from Xamarin Studio, and I have some hideous autogenerated file outside of my control (looking at you ¬¬ netfx-System.StringFormatWith)...
The solution for me was to disable all rules for only that file... how to do that?
You have to modify the file Settings.StyleCop and insert inside the StyleCopSettings tag the following
<SourceFileList>
<SourceFile>HideousClass.cs</SourceFile>
<Settings>
<GlobalSettings>
<BooleanProperty Name="RulesEnabledByDefault">False</BooleanProperty>
</GlobalSettings>
</Settings>
</SourceFileList>
Change HideousClass.cs with the file you want. you can also have multiple SourceFile tags if you want to set the rules for various files at once.
Taken from Using File Lists at StyleCop at CodePlex.com (see "Disable all rules for a subset of files" under "Examples").
Similar approach to the one seen above can be used if you want to enable or disable some rules for only some files.
Anyone that is still pulling your hair out on this one, I did the following:
.editorconfig
Example:
[SpecFlow.Plus.Runner.AssemblyHooks.cs]
dotnet_diagnostic.SA1633.severity = none
dotnet_diagnostic.CS1591.severity = none
// <auto-generated/>
put this on top of namespace and that should be good.
Related
I'm converting my project to .NET 6 and I want to use filescoped namespaces everywhere. But the conversion tool exists only in the editor.
Has anyone found out if there's a way to run this editor function across all files in solution at once? (Looks like Rider has that function)
Adding a rule to use file scoped namespaces in .editorconfig worked for me:
create an .editorconfig file in the solution directory
add following line/content below (docs, code - IDE0161)
Example .editorconfig file content:
[*.cs]
csharp_style_namespace_declarations = file_scoped:warning
After that the preview changes dialog had an option to apply the fix to the whole project/solution:
I always have problems finding files that are supposed to be updated (.editorconfig in this case). I don't even know if I should search for it in the project's, Visual Studio installation's or any folder on the PC. So I like the answer in the link below because it says where in the interface to change the setting.
Best answer in my opinion is here:
https://www.ilkayilknur.com/how-to-convert-block-scoped-namespacees-to-file-scoped-namespaces
It says that you can change the code-style preference (and enable the display of the option to apply this preference in a document / project / solution) by going to Tools => Options => Text Editor => C#=> Code Style and then changing the related preference.
EditorConfig syntax
csharp_style_namespace_declarations = file_scoped:error
dotnet_diagnostic.IDE0161.severity = error
Note
Syntax option = rule:severity will be deprecated, sooner or later.
I strongly recommend to read this article before you start build .editorconfig for your project.
After you have configured the .editorconfig, you can configure a 'Code Cleanup' setting to automatically convert all files to use file-scoped namespace. Go to Tools -> Options -> Text Editor -> Code Cleanup -> Configure Code Cleanup. Then add the 'Apply namespace preferences'. Then go to Analyze -> Code Cleanup (or just search for 'Code cleanup') and run the Code Cleanup to automatically change the namespaces to file-scoped.
I work frequently in multiple EF Core projects across multiple solutions. It's getting very frustrating seeing IDE0058 analysis hints everywhere whenever I'm saving a DbContext:
From what I can gather, suppressing this code style violation requires modifying at least one file:
Adding a local discard for every call to database.SaveChangesAsync (looks terrible)
Adding a System.Diagnostics.CodeAnalysis.SuppressMessage annotation on a per-method basis (again not ideal)
Adding a GlobalSuppressions.cs file to each project in the solution (really not ideal either)
Adding a .editorconfig file to each project to configure this violation. None of the projects I work with use editorconfig files.
For code review reasons, I can't just keep adding irrelevant files/changes like this whenever I work on a different project.
The thing that gets me is that I swear this is a recent issue. I've been working in EF Core for years up until now and this has not been an issue.
Further to this, a Roslyn team member commented on GitHub saying it has "no UI impact" and "is hidden by default" (clearly not the case here). There appears to be no way of "resetting" this to the default value, as the linked comment suggests, either.
Is there anyway to suppress this violation, once and for all, across every project and solution that I work on?
Yes, you can create a global Analyzers.ruleset file and add the rule ids you wish to ignore.
In the .csproj file of each project, you will have to add in the PropertyGroup section the <CodeAnalysisRuleSet> and specify the path to the ruleset file.
The ruleset file is an XML file and this is an example of what you can do:
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Rules for Core Application" Description="Custom Rules" ToolsVersion="16.0">
<Rules AnalyzerId="Microsoft.CodeAnalysis.CSharp.Features" RuleNamespace="Microsoft.CodeAnalysis.CSharp.Features">
<Rule Id="IDE0058" Action="None" />
</Rules>
</RuleSet>
This is how the file looks:
You can decide for each one if it is a warning/message/error/hidden/info/none.
Update:
One more way would be to add a .editorconfig file and ignore the warning there.
dotnet_style_readonly_field = false:none
I've worked out that in my C#/F# code I can load information about any .NET project using
collection.LoadProject(path_to_my_proj_file)
where collection is of type ProjectCollection. I can then get the access to all the properties and items defined in the project and all of its dependencies. As an example I can get an access to all the files included via Compile in the following way
project.GetItems "Compile"
Let's assume I want to define a custom ItemGroup in my fsproj file:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
...
<ItemGroup>
<MyGroup Include="Test.txt" />
<MyGroup Include="TestFiles\**\*" />
</ItemGroup>
</Project>
Some comments:
MyGroup is my custom collection identifier. I've found out things like this are allowed
The "TestFiles" folder contains 4 files all together that exist in some subfolders, but they all match the pattern "TestFiles\**\*"
When I load the project using the method I had mentioned at the beginning and run
project.GetItems "MyGroup"
I get only one item, that is "Test.txt". The other files don't get discovered, unless I define them explicitly (i.e. without the wildcard) in the fsproj.
Is there a way for me to discover the files included using wildcards as well ? I'm even happy to get them in the unresolved form. So getting "TestFiles\**\*" instead of specific files that match the pattern is fine as well.
Found the solution.
First, let me say that the problem was on my side. In fact in general when you try to load a project, it DOES load also all the files. Even those defined with a wildcard, as long as the ofc match the pattern.
And here's the deal: in my application I don't use the plain collection.LoadProject, but rather a more sophisticated library. And yes - the library does some magic stuff that caused the problem.
In this situation the problem was simple: all the *.[cs|fs]proj files were copied to C:\temp\<random_folder_name>. Only *.[cs|fs]proj files - nothing less, nothing more. As a result, when the project loader attempted to evaluate the solution, there were simply no files to pattern-match, resulting in zero elements.
The lesson here is: writing a proper MCVE is important - would save me (and probably you as well) some time. Apologies for problems, guys!
My Obfuscar configuration does not seem to skip types the way I expected. I'm trying the alternative approach to obfuscate only what is marked.
I enabled marking with the configuration element <Var name="MarkedOnly" value="true" />
In front of C# object definitions I am trying to mark for obfuscation using the [Obfuscate] attribute. The instructions at http://obfuscar.codeplex.com/wikipage?title=Configuration&referringTitle=Documentation
are to "reference Obfuscar.exe". Neither the xxx_bin.zip nor the xxx_src.zip downloads contain such file. I tried to reference Obfuscar.Console.exe and Obfuscar.dll in Visual Studio. In both cases the [Obfuscate] attribute is not recognized.
How can I setup to get this attribute to be recognized?
That attribute is obsolete and you should use System.Reflection.ObfuscationAttribute instead. Forgot to update the wiki page to reflect the changes.
If you add reference to Obfuscar.dll with copy local = true and add using Obfuscar; to the class in question, you will be able to use attributes.
Also, you don't add the .exe as a reference, instead copy to release folder. You can do this by adding as a link and Copy to Output directory or xcopy pre-build event etc.
I have a solution which is built for several customers, and I need to be able to specify different xml files for each customer. How can I do this automatically. I was thinking it might be done with different configurations, but can't seem to figure out how.
Any suggestions?
EDIT:
This is the code used for declaring the xml file right now:
protected readonly static string XML_PATH = #"Resources/xml/Description.xml";
And the way it is solved now is to manually copy the correct file to the Description.xml before building. This is of course error prone, and I would like to automate it, preferentially based on the configuration. I'm looking for a quick fix right now, as we unfortunately haven't got the time to refactor the code.
Build Configuration dependent config files are a tricky issue and there are multiple ways to solve it.
If you want to down the road you outlined, you would need to manually edit the *.csproj File and add a Conditional ItemGroup to include the correct xml file. The syntax below hasn't been checked, but something like this should do
<ItemGroup Condition="'${Configuration}' == 'DEBUG'">
<Content Include="blablabl.xml"/>
</ItemGroup>
I don't remember if Content was the right ItemGroup, but simply check what ItemGroup your current .xmls are in and use that.
Based on your reformulated question:
You could use conditional compilation (caveat: It's messy and not the right way to manage config files!):
protected readonly static string XML_PATH =
#if DEBUG
#"Resources/xml/Description.xml";
#else
#"Resources/xml/Description2.xml";
#endif
If you want to read up on better techniques for managing config files, this is worth a read.
Now, I now self-promotion is frowned upon, but in this case I hope it's ok as it sounds relevant to the question, and I don't gain anything from this.
Recently I wrote a couple of blog posts on how to target multiple environments/machines:
Targeting multiple environments and machines - part 1/2
Targeting multiple environments and machines – part 2/2
As I understand it, the problem in this case, is how do you automatically build the correct set of files without having to manually figure out which files belong to which customer/environment. The solution I propose in the blog posts, suggests the use of nAnt along with some extensions built on top. nAnt is the .NET versions of Ant, a build tool, which lets you generate e.g. xml files given a specific set of input files, allowing you for example to generate a customer specific web.config file.
In the following appSetting section of the web.config file, say you want to specify a different value for the CustomerName key for each customer:
<appSettings>
<add key="CustomerName" value="${CustomerName}"/>
</appSettings>
Instead of specifying a value for the CustomerName key, you define a property called CustomerName. Now, assuming we are using nAnt, you create another customer specific file with the following content:
<?xml version="1.0" encoding="utf-8"?>
<target xmlns="http://nant.sf.net/release/0.86-beta1/nant.xsd">
<property name="CustomerName" value="Acme Incorporated"/>
</target>
nAnt can then merge these two files and automatically build customer/environment specific files for you.
The solution I go through, allow you to automatically build environment and machine specific files, such as the web.config file, but also allow you to output static files such as license files or libraries, all depending on which environment/machine you are targeting. I also supply a sample Visual Studio 2010 solution that shows a very basic example on how to do it, which you can download here.
You can of course just go ahead and take a look at nAnt, but I thought I'd provide you with the option to use my solution.