I have a class like this one:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Io")]
public void ParaQueFalleCalidadCodigoUnoIo_ReglaCA1709()
{
}
public void ParaQueFalleCalidadCodigoDosIo_ReglaCA1709()
{
}
I use a custom Ruleset file CustomRules.ruleset
<RuleSet Name="RulesNet" ToolsVersion="10.0">
<RuleHintPaths>
<Path>C:\Fxcop10.0\Rules</Path>
</RuleHintPaths>
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
<Rule Id="CA1709" Action="Warning" />
</Rules>
</RuleSet>
When I run VS2010 built in Code Analysis tool, I get this warning:
CA1709 : Microsoft.Naming : Correct the casing of 'Io' in member name
'_Default.ParaQueFalleCalidadCodigoDosIo_ReglaCA1709()' by changing it
to 'IO'.
Now, I can use this same rule set file CustomRules.ruleset in FxCopCmd.exe:
FxCopCmd.exe /gac /d:"C:\CompanyFramework\4.0.0.0" /f:"D:\TFS\Tests\WebApplication1\bin\WebApplication1.dll" /o:"resultsFxCop.xml" /ruleset:"=CustomRules.ruleset" /v
I get 2 errors (FixCategory Breaking, and Level Error)
CA1709 - Correct the casing of 'Io' in member name
'_Default.ParaQueFalleCalidadCodigoUnoIo_ReglaCA1709()' by changing it
to 'IO'.
CA1709 - Correct the casing of 'Io' in member name
'_Default.ParaQueFalleCalidadCodigoDosIo_ReglaCA1709()' by changing it
to 'IO'.
<Message Id="Io" TypeName="IdentifiersShouldBeCasedCorrectly" Category="Microsoft.Naming" CheckId="CA1709" Status="Active" Created="2013-02-05 10:24:01Z" FixCategory="Breaking">
<Issue Name="Member" Certainty="85" Level="Error" Path="D:\TFS\Tests\WebApplication1" File="Default.aspx.cs" Line="21">Correct the casing of 'Io' in member name '_Default.ParaQueFalleCalidadCodigoUnoIo_ReglaCA1709()' by changing it to 'IO'.</Issue>
</Message>
<Message Id="Io" TypeName="IdentifiersShouldBeCasedCorrectly" Category="Microsoft.Naming" CheckId="CA1709" Status="Active" Created="2013-02-05 10:24:01Z" FixCategory="Breaking">
<Issue Name="Member" Certainty="85" Level="Error" Path="D:\TFS\Tests\WebApplication1" File="Default.aspx.cs" Line="26">Correct the casing of 'Io' in member name '_Default.ParaQueFalleCalidadCodigoDosIo_ReglaCA1709()' by changing it to 'IO'.</Issue>
</Message>
In resultsFxcop.xml, I have seen CA1709: IdentifiersShouldBeCasedCorrectly rule:
<Rule TypeName="IdentifiersShouldBeCasedCorrectly" Category="Microsoft.Naming" CheckId="CA1709">
<Name>Identifiers should be cased correctly</Name>
<Description>Type, namespace, and... OMITED.</Description>
<Resolution Name="Member">Correct the casing of '{0}' in member name {1} by changing it to '{2}'.</Resolution>
<Owner />
<Url>http://msdn.microsoft.com/library/ms182240(VS.100).aspx</Url>
<Email>[none]</Email>
<MessageLevel Certainty="85">Error</MessageLevel>
<File Name="namingrules.dll" Version="10.0.0.0" />
</Rule>
MessageLevel for CA1709 rule:
<MessageLevel Certainty="85">Error</MessageLevel>
Two issues:
I get Errors but CA1709 rule Action is Warning
SuppressMessage is ignored using FxCopcmd.exe
Now, I modify CustomRules.ruleset and I execute FxCopcmd.exe again
<Rule Id="CA1709" Action="None" />
I get NO errors.
I modify CustomRules.ruleset and I execute FxCopcmd.exe again
<Rule Id="CA1709" Action="Ignore" />
I get the same 2 errors.
I need use FxCopCmd.exe and a custom ruleset.
Does SuppressMessage works for FxCopcmd.exe?
Why do I get errors if Action is Warning, using Fxcopcmd.exe?
What does MessageLevel Error for CA1709 rule mean? More priority than Rule Action "Warning"?
Any suggestions?
Update
http://social.msdn.microsoft.com/Forums/en/vstscode/thread/3f8931da-9a4d-47a6-b331-8b6b07aea8d6
http://social.msdn.microsoft.com/forums/en-US/vstscode/thread/3cb6c50c-7095-4551-a4e3-a3cbc7cb85be
For the default FxCop rules, there is no easy way to modify the message level,
MessageLevel is the importance of the message, e.g. if you had thousands of messages, it probably would be a good idea to start addressing the Critical (the exclamation mark) Errors first.
Certainty is the number the Rule writer assigns to each rule, it is the likelihood that a message leads to a code change. This number is built up based on feedback from domain experts & customers and how well the heuristic used in the rule is able to avoid false positives.
Fix Category: This indicates if the fix for a violation would be a binary breaking change if the code has previously shipped. e.g you have a library with a misspelling in it that you have already shipped to customers. You now start running FxCop on it and see the misspelling. FxCop will tell you this is a breaking change. If you fix the misspelling and ship a new version of your library to customers, they can't use the library without changing and recompiling their code. So you probably want to ignore the FxCop violation on this API. On the other hand, if you never shipped, it would be totally fine to fix the FxCop violation.
Does SuppressMessage works for FxCopcmd.exe?
Yes. You will need to compile with the CODE_ANALYSIS compilation symbol defined in order for your SuppressMessage attributes to be included in your assembly. Once they're in there, the FxCop engine will recognize them, regardless of the mechanism used to run the analysis.
Why I get errors if Action is Warning, using Fxcopcmd.exe?
The issue level written to the FxCop-produced report always uses the level specified by the rule author. When you run from within Visual Studio, the Visual Studio integration plug-in overrides this level with the one specified in the ruleset. When you run fxcopcmd.exe, the only difference between a configuring a rule as a warning vs an error is that detection of an error-level rule violation will cause fxcopcmd.exe to return a non-zero exit code, thereby allowing you to break an automated build.
If you would prefer that fxcopcmd.exe use your level overrides when generating its report, you may want to consider making a suggestion at http://visualstudio.uservoice.com/.
Related
I'm using StyleCop and want to suppress some warning which does not suit my style. I prefer to have solution for
1) in-line code suppressing
2) global setting suppressing
I've searched the internet but still not sure how to do the suppressing.
For method 1), They said to add the lines:
[assembly: SuppressMessage("Microsoft.Design",
"SA1202:All private methods must be placed after all public methods",
Scope = "namespace", Target = "Consus.Client.ClientVaultModule.Services.OnlineDetection")]
But they do not say where and which namespace to be used.
For method 2), they said to use GlobalSuppress file but it seems not easy to search for a how-to do it at the moment.
Please help.
[Edited]
In my case, I have the warning about SA1202: All private methods must be placed after all public methods which is bothering since I group my related codes into regions. I want to suppress those warning for just some certain methods.
Here's what you need:
[SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess")]
An example of inline suppression would be similar to this - examine the namespaces in the code compared to the suppression
namespace Soapi
{
///<summary>
///</summary>
///<param name = "message"></param>
///<param name = "statusCode"></param>
///<param name = "innerException"></param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)")]
public ApiException(string message, ErrorCode statusCode, Exception innerException)
: base(String.Format("{0}\r\nStatusCode:{1}", message, statusCode), innerException)
{
this.statusCode = statusCode;
}
A global supression file is a file in the root of your project named GlobalSuppressions.cs and might look like this:
// 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.
//
// To add a suppression to this file, right-click the message in the
// Error List, point to "Suppress Message(s)", and click
// "In Project Suppression File".
// You do not need to add suppressions to this file manually.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object,System.Object)", Scope = "member", Target = "Soapi.ApiException.#.ctor(System.String,Soapi.ErrorCode,System.String,System.Exception)")]
And you can generate this code automatically by right-clicking on the warning.
Starting with StyleCop 4.3.2, it is possible to suppress the reporting of rule violations by adding suppression attributes within the source code.
Rule Suppressions
http://stylecop.soyuz5.com/Suppressions.html
but it says -
Global Suppressions
StyleCop does not support the notion of global suppressions or
file-level suppressions. Suppressions must be placed on a code
element.
If you've installed StyleCop, you can right-click your project and there will be a StyleCop option. Click this and you'll see you can prevent certain rules from even running against your project. Moreover, you can create a separate rules file to share between different projects. This means you can configure the rules once the way you want them and then share that configuration between all your projects.
For individual overrides, SuppressMessage is the way to go.
Go to Solution Explorer
Go to your project
Expand references
Expand Analyzers
Expand StyleCop.Analyzers
Right click on a particular rule which you want to disable at a global (project) level
Set Rule Set severity -> Select None
Read the admonition from Style Cop, looking for the alphanumeric code. In your case 'SA1202'. Then browse to the corresponding page on the Style Cop website. Change the URL as appropriate https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1202.md
Copy the line labelled 'How to Suppress Violations'. Paste the attribute above the class about which Style Cop moans
[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess", Justification = "Reviewed.")]
Cant you just remove the rule instead of soiling your code?
Same goes for FxCop...
1.
In your case, correct SuppressMessage attribute should like like the following:
[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess")]
private void SomeMethod()
{
}
Note that you can place it on any other element (e.g, on the class - then all similar violations in the entire class will be supressed).
I also agree that it's quite unobvious what to write in these fields.
Actually, the first one should be the fully qualified name of StyleCop analyser class and could be found from the source code (e.g. from here).
The second one should start with rule code, then colon and the name of the rule enumeration (luckily, it always looks like the rule name displayed in the Settings Editor, but with no whitespaces).
2.
Regarding suppressing rules "globally" - why don't just turn them off via Settings Editor? Settings files are inherited through the file system, so you could easily have one "main" settings file at the "top" of your folder structure, and some other files (holding the "difference" from main) with exceptions made for some projects, if you want so (like described here).
Good luck!
You can disable the rules you don't want in Settings.StyleCop file, which is in the project root folder.
You will need the namespace that contains the rule, which can be found here:
http://stylecop.soyuz5.com/StyleCop%20Rules.html
Settings.stylecop file code for your reference:
<StyleCopSettings Version="105">
<Analyzers>
<Analyzer AnalyzerId="StyleCop.CSharp.LayoutRules">
<Rules>
<Rule Name="ElementsMustBeSeparatedByBlankLine">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
</Analyzers>
</StyleCopSettings>
Alternatively you could move the code in regions into partial classes. Then the issue with the stylecop rule will go away.
In addition to the helpful answers already in place:
If you suppress a warning in the suppression file GlobalSuppressions.cs,
you can edit that [assembly: SuppressMessage(StyleCop...blabla line and entirely remove the Scope=... and Target=... tags. That makes the suppression global in the project.
The README.md for the StyleCop.Analyzers NuGet package used by Visual Studio 2015+ contains a link to the documentation for the rules. The documentation for each rule contains a "How to suppress violations" section. For the SA1202 rule, the options are:
[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess", Justification = "Reviewed.")]
and
#pragma warning disable SA1202 // ElementsMustBeOrderedByAccess
#pragma warning restore SA1202 // ElementsMustBeOrderedByAccess
in my uwp app I am using dynamic variables at many places, because the data is coming from the server backend api, so we want to keep it dynamic. it runs fine in Debug mode but I wanted to upload to store so I tried it on Release mode and it fails with following exception
system.reflection.missingmetadataexception
obviously this exception occurs, in one of my pages called "LoginPage.xaml.cs" at the first line where I am trying to use the dynamic data. following is the line which causes the exception.
ViewModel.backgroundURL = AppConfig.Login.background;
AppConfig here is a static object in a constants class. and its type is dynamic, I am succesfully get it from server API, but exception only occurs when I try to consume it in my app as you can see in the code line above.
after some research I found that using the following line in Default.rd.xml can solve this error I put the following line there.
<Namespace Name="bluebook.ViewModels" Seralize="All" />
as you can see I am putting this line in my directives tag as shown below.
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
<Application>
<!--
An Assembly element with Name="*Application*" applies to all assemblies in
the application package. The asterisks are not wildcards.
-->
<Assembly Name="*Application*" Dynamic="Required All" />
<!-- Add your application specific runtime directives here. -->
<Namespace Name="bluebook.ViewModels" Serialize="All" />
</Application>
</Directives>
I am trying to do the directives on ViewModels because the fields I am assigning to are in the ViewModel class. I also tried to do it on Views name space which has all the view classes like LoginPage and others, but in both cases the exception is still occuring, exactly at the same line.
Update 1
Exception Details
System.Reflection.MissingMetadataException: 'Reflection_InsufficientMetadata_NoHelpAvailable: EETypeRva:0x000a8990.
StackTrace : null
Source : null
Is "Serialize" misspelled in your directive file?
Try adding <Type Name="Microsoft.CSharp.RuntimeBinder.CSharpGetMemberBinder" Dynamic="Required All"/> to your Default.rd.xml.
(This answer may be relevant to you - answered by someone who works on .Net Native - Building with .NET Native tool chain causes error with missing property in dynamic object )
Trying to update my resharper extension to work for 9.0, before I was just moving the dll into the plugins directory but now I need to figure out how to get nuget to work... I've been able to package the files, dll gets included in the nupkg but I think I have some namespace\id something something issues(not very familiar with .net) and it doesn't seem as if my actions.xml is even being read by resharper when I import the nuget package. The menu item isn't being added. Anwyays if anyone can give me any sort of advice on how to debug a nuget package or what might be going wrong would really really appreciate as I've been stuck on this for a few days now.
Actions.xml
<?xml version="1.0" encoding="utf-8" ?>
<actions>
<action id="yuval" text="L10N"></action>
<insert group-id="ReSharper" position="last">
<action-ref id="yuval" text="About Localization Helper"/>
</insert>
</actions>
AboutAction.cs
namespace JetBrains.Resharper.L10N
{
[Action(Id)]
public class AboutAction : IExecutableAction
{
public const string Id = "yuval";
public bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate)
{
return true;
}
public void Execute(IDataContext context, DelegateExecute nextExecute)
{
MessageBox.ShowMessageBox(
"Localization Helper\nYuval\n\nHelps Localize",
"About Localization Helper",
MbButton.MB_OK,
MbIcon.MB_ICONASTERISK);
}
}
}
nuget spec
<?xml version="1.0"?>
<package >
<metadata>
<id>JetBrains.Resharper.L10N</id>
<version>1.0.0.7</version>
<title>L10N</title>
<authors>Yuval</authors>
<owners>UW</owners>
<licenseUrl>https://myurl.com</licenseUrl>
<projectUrl>https://myurl.com</projectUrl>
<iconUrl>https://myurl.com/logo.png</iconUrl>
<requireLicenseAcceptance>true</requireLicenseAcceptance>
<description>Tool to help localize</description>
<releaseNotes>Summary of changes made in this release of the package.</releaseNotes>
<copyright>Copyright 2015</copyright>
<tags></tags>
<dependencies>
<dependency id="Wave" version="[1.0]" />
</dependencies>
</metadata>
<files>
<file src="..\bin\Debug\JetBrains.Resharper.L10N.dll"
target="dotFiles\"/>
</files>
</package>
The way actions are registered has changed in ReSharper 9. It's no longer done with actions.xml, but with interfaces on your action class. For example, to add an action to the ReSharper → Tools menu, you would do:
[Action(ActionId, Id = 1)]
public class AboutAction : IExecutableAction, IInsertLast<ToolsMenu>
{
public const string ActionId = "yuval";
// …
}
You also need to specify a unique value for Id. As of 9.1, this needs to be unique within your own extension (9.0 required it to be unique across the whole installation, including ReSharper itself and any other extensions).
Whenever you change the attributes or interfaces of an action, the extension needs to be reinstalled via nupkg (the actions are statically registered with Visual Studio, in the same way as a standard VS extension), but if just the implementation has changed, you can copy the dlls to the install folder, either manually, or via a small change to the .csproj.
You also need to make sure you've defined a ZoneMarker class. This declares that your action belongs to a zone, which is used to enable/disable functionality based on installed features and the current host (e.g. so Visual Studio specific extensions only work in VS and don't get loaded into dotPeek, etc.). You can find out more about Zones in the devguide, with this page providing useful info for defining a zone marker.
This thread should help, too.
Also, it's probably a good idea to name you dll and nupkg something other than JetBrains.ReSharper.(Whatever) to prevent any potential clashes with official dlls, and to prevent confusion as to where the dll comes from. The first part of the name is supposed to be your company's name (or personal name).
I am getting many of the following warning messages. Is this something I should be concerned with?
Warning 1 The element 'PropertyGroup' in namespace
'http://schemas.microsoft.com/developer/msbuild/2003' has invalid
child element 'ImportByWildcardBeforeMicrosoftCommonTargets' in
namespace 'http://schemas.microsoft.com/developer/msbuild/2003'. List
of possible elements expected: 'Property, AllowUnsafeBlocks,
AppConfigForCompiler, ApplicationIcon, ApplicationRevision,
ApplicationVersion, AppDesignerFolder, AspNetConfiguration,
AssemblyKeyContainerName, AssemblyKeyProviderName, AssemblyName,
AssemblyOriginatorKeyFile, AssemblyOriginatorKeyFileType,
AssemblyOriginatorKeyMode, AssemblyType, AutorunEnabled, BaseAddress,
BootstrapperComponentsLocation, BootstrapperComponentsUrl,
BootstrapperEnabled, CharacterSet, CheckForOverflowUnderflow,
CLRSupport, CodePage, Configuration, ConfigurationName,
ConfigurationOverrideFile, CreateDesktopShortcut,
CreateWebPageOnPublish, CurrentSolutionConfigurationContents,
DebugSecurityZoneURL, DebugSymbols, DebugType, DefaultClientScript,
DefaultHTMLPageLayout, DefaultTargetSchema, DefineConstants,
DefineDebug, DefineTrace, DelaySign, DisableLangXtns,
DisallowUrlActivation, CodeAnalysisAdditionalOptions,
CodeAnalysisApplyLogFileXsl, CodeAnalysisConsoleXsl,
CodeAnalysisCulture, CodeAnalysisFailOnMissingRules,
CodeAnalysisForceOutput,
CodeAnalysisGenerateS.... C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets 20 9 Miscellaneous
Files
You can ignore this warning, see this link for an explanation:
When you apply the schema attribute to your Project element, Visual
Studio reads in the schema and uses the information indide to provide
Intellisense during your editing. As an offshoot of this, it also
warns you when it finds that you have used elements or attributes that
are not part of the schema. The custom property and item elements are
not part of the MSBuild schema.
Let's say i have 3 smtp appenders in same log4net file whose names are:
<appender name = "emailDevelopment".. />
<appender name = "emailBeta".. />
<appender name = "emailProduction".. />
Let's say i have 3 different servers(Dev, Beta, Production). Depending upon the server, i want to fire the log. In case of Development server, it would fire log from "emailDevelopment". I have a system variable in each server named "ApplicationEnvironment" whose value is Development, Beta, Production based on the server names. Now is there anyway i can setup root in log4net so that it fires email depending upon the server name.
<root>
<priority value="ALL" />
<appender-ref ref="email<environment name from whose appender should be used>" />
</root>
This doesn't directly answer your question, but another approach is to simply have multiple log4net configuration files and call XmlConfigurator.Configure() on the right one. For example, you might have Logging.Development.Config, Logging.Beta.Config and so on.
Somewhere in code, you determine the "environment" and configure using the file you want.
I've even gone so far as to have multiple config files and pull different parts of them out into a single XML representing the "true" config, and then calling the Configure() method on that. For example, Logging.Appenders.Config which has all the appenders, and takes all of them and combines it with one of your environment-specific config files above; the environment-specific ones simply reference what they need, and the rest are effectively inactive/unreferenced for that environment.
Even after having written the only XSD file for log4net configuration I'm still not aware of an easy way to achieve this.
You might be able to do something like:
log4net.GlobalContext.Properties["host"] = new ClassThatToStringsHost();
class ClassThatToStringsHost
{ public override string ToString() { return "whatever"; } }
Now you can reference this value from the Log format with: "%property{host}"
To perform the filtering you will need to use a filter configuration in the adapter(s):
<appender name="file" type="log4net.Appender.RollingFileAppender">
<filter type="log4net.Filter.PropertyFilter">
<Key value="host" />
<StringToMatch value="whatever" />
</filter>
<!-- Anything not accepted by the above should be excluded -->
<filter type="log4net.Filter.DenyAllFilter" />
</appender>
There may even be a built-in property you could leverage and this should work. See also this post: http://geekswithblogs.net/rgupta/archive/2009/03/03/dynamic-log-filenames-with-log4net.aspx
For me, myself, and I... I would approach it another way all together. I would derive my own SMTP appender from the default and in the ActivateOptions() method I'd configure the values according to the environment. This would allow you to use one SMTP appender with consistent rules and yet provide three public properties for each of the email addresses you want to send from. It's not hard, give it a try!