FxCop, exclude a rule from an assembly (but use it for the other assemblies) - fxcop

I would like to exclude CA1822:MarkMembersAsStatic from the CoreTest assembly as the NUnit test methods cannot be converted to static methods as NUnit won´t execute them if I do. In the other assemblies I would like to have this rule as I have found it valuable.
If it is possible I do not like to add a SuppressMessage to each test methods, as I have a lot of them and it just clutters up the file.
This is the FxCop rule XML-file:
<?xml version="1.0" encoding="utf-8"?>
<FxCopProject Version="1.35" Name="Foo, Release">
<ProjectOptions>
<SharedProject>True</SharedProject>
<Stylesheet Apply="False">http://www.gotdotnet.com/team/fxcop//xsl/1.35/FxCopReport.xsl</Stylesheet>
<SaveMessages>
<Project Status="None" NewOnly="False" />
<Report Status="Active" NewOnly="False" />
</SaveMessages>
<ProjectFile Compress="True" DefaultTargetCheck="True" DefaultRuleCheck="True" SaveByRuleGroup="" Deterministic="True" />
<EnableMultithreadedLoad>True</EnableMultithreadedLoad>
<EnableMultithreadedAnalysis>True</EnableMultithreadedAnalysis>
<SourceLookup>True</SourceLookup>
<AnalysisExceptionsThreshold>10</AnalysisExceptionsThreshold>
<RuleExceptionsThreshold>1</RuleExceptionsThreshold>
<Spelling Locale="en-us" />
<VersionAware>False</VersionAware>
<OverrideRuleVisibilities>False</OverrideRuleVisibilities>
<CustomDictionaries SearchFxCopDir="True" SearchUserProfile="True" SearchProjectDir="True" />
<SearchGlobalAssemblyCache>False</SearchGlobalAssemblyCache>
<DeadlockDetectionTimeout>120</DeadlockDetectionTimeout>
</ProjectOptions>
<Targets>
<AssemblyReferenceDirectories>
<Directory>$(ProjectDir)/Library/EPiServer CMS/5.2.375.7/</Directory>
<Directory>$(ProjectDir)/Foo.Plugin/bin/Release/</Directory>
</AssemblyReferenceDirectories>
<Target Name="$(ProjectDir)/Foo.Core/bin/Release/Foo.Core.dll" Analyze="True" AnalyzeAllChildren="True" />
<Target Name="$(ProjectDir)/Foo.CoreTest/bin/Release/Foo.CoreTest.dll" Analyze="True" AnalyzeAllChildren="True" />
<Target Name="$(ProjectDir)/Foo.Example/bin/Foo.Example.dll" Analyze="True" AnalyzeAllChildren="True" />
<Target Name="$(ProjectDir)/Foo.Web.WebForms/bin/Release/Foo.Web.WebForms.dll" Analyze="True" AnalyzeAllChildren="True" />
</Targets>
<Rules>
<RuleFiles>
<RuleFile Name="$(FxCopDir)\Rules\DesignRules.dll" Enabled="True" AllRulesEnabled="True" />
<RuleFile Name="$(FxCopDir)\Rules\GlobalizationRules.dll" Enabled="True" AllRulesEnabled="False">
<Rule Name="AvoidDuplicateAccelerators" Enabled="True" />
<Rule Name="DoNotHardcodeLocaleSpecificStrings" Enabled="True" />
<Rule Name="SetLocaleForDataTypes" Enabled="True" />
<Rule Name="SpecifyCultureInfo" Enabled="True" />
<Rule Name="SpecifyIFormatProvider" Enabled="True" />
<Rule Name="SpecifyMessageBoxOptions" Enabled="True" />
</RuleFile>
<RuleFile Name="$(FxCopDir)\Rules\InteroperabilityRules.dll" Enabled="True" AllRulesEnabled="True" />
<RuleFile Name="$(FxCopDir)\Rules\MobilityRules.dll" Enabled="True" AllRulesEnabled="True" />
<RuleFile Name="$(FxCopDir)\Rules\NamingRules.dll" Enabled="True" AllRulesEnabled="True" />
<RuleFile Name="$(FxCopDir)\Rules\PerformanceRules.dll" Enabled="True" AllRulesEnabled="True" />
<RuleFile Name="$(FxCopDir)\Rules\PortabilityRules.dll" Enabled="True" AllRulesEnabled="True" />
<RuleFile Name="$(FxCopDir)\Rules\SecurityRules.dll" Enabled="True" AllRulesEnabled="True" />
<RuleFile Name="$(FxCopDir)\Rules\UsageRules.dll" Enabled="True" AllRulesEnabled="True" />
</RuleFiles>
<Groups />
<Settings />
</Rules>
<FxCopReport Version="1.35" />
</FxCopProject>
Any ideas on how this can be done in the most convenient way?

There's no way to use separate rule sets within a single FxCop run. For dealing with the CA1822 test method issue, I usually create two separate FxCop projects: one that includes CA1822 for normal assemblies, and one that excludes CA1822 for test assemblies.
If you're using the code analysis feature integrated into some of the "developer" team edition of Visual Studio, you can apply a different rule set to each assembly. This is supported because the tool ends up running fxcopcmd.exe seperately for each assembly, not because it uses some more complex configuration to support multiple rule sets within a single run.

Related

.net 6 Blazor Web Assembly standalone not working in local iis

I have already installed .net core 6 hosting bundle & rewrite url for IIS
this is the web config file
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<remove fileExtension=".blat" />
<remove fileExtension=".dat" />
<remove fileExtension=".dll" />
<remove fileExtension=".json" />
<remove fileExtension=".wasm" />
<remove fileExtension=".woff" />
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".blat" mimeType="application/octet-stream" />
<mimeMap fileExtension=".dll" mimeType="application/octet-stream" />
<mimeMap fileExtension=".dat" mimeType="application/octet-stream" />
<mimeMap fileExtension=".json" mimeType="application/json" />
<mimeMap fileExtension=".wasm" mimeType="application/wasm" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
<mimeMap fileExtension=".woff2" mimeType="application/font-woff" />
</staticContent>
<httpCompression>
<dynamicTypes>
<add mimeType="application/octet-stream" enabled="true" />
<add mimeType="application/wasm" enabled="true" />
</dynamicTypes>
</httpCompression>
<rewrite>
<rules>
<rule name="Serve subdir">
<match url=".*" />
<action type="Rewrite" url="wwwroot\{R:0}" />
</rule>
<rule name="SPA fallback routing" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
</conditions>
<action type="Rewrite" url="wwwroot\" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
and here the program.cs Code
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("http://localhost:8888/api/") });
builder.Services.AddScoped<IHttpService, HttpService>();
builder.Services.AddScoped<IToastServices, ToastServices>();
builder.Services.AddScoped<IDialogService, DialogService>();
builder.Services.AddMudServices();
await builder.Build().RunAsync();
If any one faced the same problem please give me any advice

Are rewrite providers supported inside ASP.NET core?

I know you can have rewrite middleware but I have my database where all rewrite rules are set up and I use this code that used to work inside .net framework. Is this supported in .NET core. What is solution?
<rewrite>
<providers>
<provider name="FileMap" type="DbProvider, Microsoft.Web.Iis.Rewrite.Providers, Version=7.1.761.0, Culture=neutral, PublicKeyToken=0545b0627da60a5f">
<settings>
<add key="ConnectionString" value="myconnString" />
<add key="StoredProcedure" value="Search.GetRewriteUrlMvc" />
<add key="CacheMinutesInterval" value="0" />
</settings>
</provider>
</providers>
<!--<rules configSource="rewrite-rules-sol-local.config" />-->
<rewriteMaps configSource="rewritemaps-sol.config" />
</rewrite>

Is there any similar kind of configure to rolingStyle="once" of log4net is available for NLog?

I am using log4net currently and on every hour log file archive is being performed.
Now I am changing log4net to NLog
Is there similar setting available in NLog Like rolingStyle="once"? which was configure setting available in log4net.
For example earlier while using log4net the files created were used to be like:
LogFile.log
LogFile.log.1 <-last archive file
Following is configuration I used in log4net and I want to use the exact configure settings so that archived file naming should remains as it was in log4net:
<appender name="Work" type="RMM.Common.Logger.LogFileRollingAppender, Common">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<dateTimeStrategy type="log4net.Appender.RollingFileAppender+UniversalDateTime" />
<file type="log4net.Util.PatternString" value="%property{EdgeAPILogPath}\WebAPI_Work.log" />
<param name="AppendToFile" value="true"/>
<rollingStyle value="Once" />
<rollingStyle value="Composite" />
<datePattern value=".yyyyMMdd-HH" />
<maxSizeRollBackups value="300" />
<maximumFileSize value="20MB" />
<Encoding value="UTF-8" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%utcdate{yyyy/MM/dd HH:mm:ss,fff} [%-5p] [%3t] %m%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="DEBUG" />
<levelMax value="FATAL" />
</filter>
</appender>
You can:
Use fileName="${basedir}/logs/${cached:${date:format=yyyy-MM-dd HH_mm_ss}}.log" as a way to ensure one log file per application instance.
Use archiveFileName="${archiveLogDirectory}/LogFile.log.{####}" to append numbers at the end (feel free to add or remove # as required, depending on your maxArchiveFiles).
Use archiveNumbering="Sequence" to achieve the order you want (higher numbers = newer logs).
Source: this piece of documentation and some personal experience.
Hopefully this basic example will help you getting closer to your final target:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Error"
internalLogFile="./internal-nlog.txt"
throwExceptions="true">
<variable name="logDirectory" value="./logs"/>
<variable name="archiveLogDirectory" value="./logs/archive"/>
<targets>
<target name="errors"
xsi:type="File"
fileName="${logDirectory}/${cached:${date:format=yyyy-MM-dd HH_mm_ss}}.log"
archiveFileName="${archiveLogDirectory}/LogFile.log.{#}"
maxArchiveFiles="9"
archiveEvery="Hour"
archiveNumbering="Sequence"
/>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="errors"/>
</rules>
</nlog>
Not an expert on log4net, but it sounds like that rolingStyle="once" is the same as NLog FileTarget ArchiveOldFileOnStartup. So maybe something like this:
<nlog>
<variable name="EdgeAPILogPath" layout="${basedir}" />
<targets>
<target xsi:type="file" name="work"
fileName="${EdgeAPILogPath}/WebAPI_Work.log"
encoding="utf-8"
archiveNumbering="DateAndSequence"
archiveFileName="${EdgeAPILogPath}/WebAPI_Work.{#}.log"
archiveDateFormat="yyyyMMdd-HH"
archiveEvery="Hour"
archiveAboveSize="20000000"
archiveOldFileOnStartup="true"
maxArchiveFiles="300" />
</targets>
<rules>
<logger name="*" minLevel="Debug" writeTo="work" />
</rules>
</nlog>
See also: https://github.com/NLog/NLog/wiki/FileTarget-Archive-Examples

Web.config file IIS rules for URL rewrites for Angular hosted inside ASP.NET Core not working as expected

I am trying to get the IIS web.config rule rewrites to work but I have been unsuccessful thus far. Based on my research I need a single web.config file at the root of the main project.
The contents of this web.config file are as follow:
`<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<rewrite>
<rules>
<rule name="SpaRewriteRule" stopProcessing="true">
<match url=".*"/>
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true"/>
</conditions>
<action type="Rewrite" url="index.html"/>
</rule>
</rules>
</rewrite>
<staticContent>
<mimeMap fileExtension=".*" mimeType="application/octet-stream" />
</staticContent>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
<environmentVariable name="COMPLUS_ForceENC" value="1" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>`
I have already installed the IIS Rewrite module. Based on this set up my expectation is that:
Once angular app is initially loaded, I would be able to refresh the page successfully - this is not the case
I have found a work around for this to add the following code in Startup.cs:
.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value) && !context.Request.Path.Value.StartsWith("/api/"))
{
context.Request.Path = "/index.html";
await next();
}
});
This however feels hacky, unless this is the accepted way of doing it now?
What is the right way of handling this?
Thanks
If you want to apply the angular routes rule which is hosted as an application and added this at the root web.config:
<rule name="ARoutes" enabled="true" stopProcessing="true">
<match url="testapi" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="http://localhost:843/testapi/index.html" logRewrittenUrl="true" />
</rule>
in short, you need to provide the full URL of the rewritten page.
and you want to use at the application level than you need to create a web.config file in the angular site dist folder.
and add below code in web.config file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS Routes1" enabled="true" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

HTTP Error 405.0 - Method Not Allowed when call api

i have same api ,when call api in angualr 2 i gat this error
HTTP Error 405.0 - Method Not Allowed
The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used.
my Webconfig
<rewrite>
<!--This directive was not converted because it is not supported by IIS: RewriteBase /.-->
<rules>
<rule name="Imported Rule 1" stopProcessing="true">
<match url="^index\.html" ignoreCase="false" />
<action type="None" />
</rule>
<rule name="Imported Rule 2" stopProcessing="true">
<match url="." ignoreCase="false" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
</conditions>
<action type="Rewrite" url="/index.html" />
</rule>
</rules>
</rewrite>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="OPTIONSVerbHandler" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
if remove rules tag in web config my api is worked but when refresh angular page i get this error
The resource cannot be found.
Whatever your browser of choice, if might be worth getting acquainted with the usual F12 developer tools that usually come with them for a bit of clientside visibility.
It's useful to verify that your client isn't trying to do something that you weren't expecting, you can see the verbs, content types and the urls that might assist you tracking it down.
Also you're using url rewrites in your config, so the server could be adjusting your requests after they're received, possibly in a way you weren't expecting - Suspect I'll need a bit more information on the relative urls that are failing to provide more advice.
An example is that in Chrome, you can check the Network tab.