Does StyleCop.Analyzers support C# records? - c#

Problem description:
When adding a C# record in a project with StyleCop.Analyzers, it shows the warning:
Warning AD0001 Analyzer 'StyleCop.Analyzers.DocumentationRules.SA1649FileNameMustMatchTypeName' threw an exception of type 'System.ArgumentException' with message 'Unhandled declaration kind: RecordDeclaration'.
System.ArgumentException: Unhandled declaration kind: RecordDeclaration
at StyleCop.Analyzers.Helpers.NamedTypeHelpers.GetNameOrIdentifier(MemberDeclarationSyntax member)
at StyleCop.Analyzers.Helpers.FileNameHelpers.GetConventionalFileName(MemberDeclarationSyntax declaration, FileNamingConvention convention)
at StyleCop.Analyzers.DocumentationRules.SA1649FileNameMustMatchTypeName.Analyzer.HandleSyntaxTree(SyntaxTreeAnalysisContext context, StyleCopSettings settings)
at StyleCop.Analyzers.AnalyzerExtensions.<>c__DisplayClass0_0.<RegisterSyntaxTreeAction>b__0(SyntaxTreeAnalysisContext c)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.<>c.<ExecuteSyntaxTreeActionsCore>b__59_1(ValueTuple`2 data)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info)
Is it a bug in StyleCop.Analyzers?
Steps to reproduce:
Create a new .Net6 console project (or even .Net5).
Add a C# record in it: public record Member(string FirstName, string LastName);
Install the package StyleCop.Analyzers v1.1.118
Look in the Visual Studio Error List, and you will see the warning.

Thank you #stuartd you pointed me to the right direction.
It is indeed a bug in Stylecop 1.1.X
It was corrected in the StyleCop.Analyzers.Unstable v1.2.0-beta.161. but unfortunately, it is not included in the stable version yet. So the workaround I see for now is to use the unstable version

Related

Unit Testing Using Sitecore.FakeDb Throws Sitecore.Nexus instantiation error on GetItem

I'm a sitecore developer and I want to use Sitecore.FakeDb in my unit testing. I have the following code:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void Test_ArticleController_With_SitecoreItem()
{
Sitecore.Data.ID about_us_itemId = Sitecore.Data.ID.NewID;
Sitecore.Data.ID careers_itemId = Sitecore.Data.ID.NewID;
using (var db = new Sitecore.FakeDb.Db
{
new Sitecore.FakeDb.DbItem("about-us", about_us_itemId)
{
new Sitecore.FakeDb.DbField(SitecoreFieldIds.WTW_REDIRECT_TO) { Value = "/WTW-Home/about-us/overview" }
},
new Sitecore.FakeDb.DbItem("careers", careers_itemId)
{
new Sitecore.FakeDb.DbField(SitecoreFieldIds.WTW_REDIRECT_TO) { Value = "http://careers.willistowerswatson.com" }
}
})
{
Sitecore.Data.Items.Item sampleItem3 = db.GetItem(about_us_itemId); // throws error
Sitecore.Data.Items.Item sampleItem2 = db.GetItem("/sitecore/content/careers"); //throws error
//Assert
Assert.AreEqual("abc", "abc");
};
}
}
I get the following error when I try either of the two above .GetItem(...) lines:
System.TypeInitializationException: 'The type initializer for 'Sitecore.SecurityModel.License.LicenseManager' threw an exception.'
InvalidOperationException: Could not instantiate the type 'Sitecore.Nexus.Licensing.NexusLicenseApi, Sitecore.Nexus'
I have included the following relevant references (amongst others) in my unit testing project: Sitecore.FakeDb, Sitecore.Kernel, Sitecore.Mvc, Moq, Glass.Mapper, Glass.Mapper.Sc, Glass.Mapper.Sc.Mvc, Castle.Core. Do I need Sitecore.Nexus? If yes, where can I get it from?
I have an App_Config/Include/Sitecore.FakeDb.config file, as well as an App_Config/app.config file, which has this setting in it:
<sitecore>
<settings>
<setting name="LicenseFile" value="..\..\license.xml" />
</settings>
</sitecore>
Any idea on why this error is occuring and how to exactly fix it?
Here is the full stacktrace, if that helps:
System.TypeInitializationException occurred
HResult=0x80131534
Message=The type initializer for 'Sitecore.SecurityModel.License.LicenseManager' threw an exception.
Source=Sitecore.Kernel
StackTrace:
at Sitecore.SecurityModel.License.LicenseManager.DemandRuntime(Boolean acceptExpress)
at Sitecore.Data.Managers.DefaultItemManager.get_FallbackProvider()
at Sitecore.Data.Managers.DefaultItemManager.<>c__DisplayClass2f.<GetItem>b__2e()
at Sitecore.Data.Managers.DefaultItemManager.ExecuteAndReturnResult[TArgs,TResult](String pipelineName, String pipelineDomain, Func`1 pipelineArgsCreator, Func`1 fallbackResult)
at Sitecore.Data.Managers.DefaultItemManager.GetItem(ID itemId, Language language, Version version, Database database, SecurityCheck securityCheck)
at Sitecore.Data.Managers.DefaultItemManager.GetItem(ID itemId, Language language, Version version, Database database)
at Sitecore.Data.Managers.ItemManager.GetItem(ID itemId, Language language, Version version, Database database)
at Sitecore.Data.DefaultDatabase.GetItem(ID itemId)
at Sitecore.FakeDb.Db.GetItem(ID id)
at WTW.Feature.HomeBottomContent.Tests.UnitTest1.Test_ArticleController_With_SitecoreItem() in C:\dev\TowersWatson\DEV\Maintenance\Source\Feature\HomeBottomContent\Tests\UnitTest1.cs:line 76
Inner Exception 1:
InvalidOperationException: Could not instantiate the type 'Sitecore.Nexus.Licensing.NexusLicenseApi, Sitecore.Nexus'
You need to have a reference to Sitecore.nexus.dll
In Visual Studio: Tools->Options
In Options window find 'Nuget Package Manager'->'Package Sources'
Then click green plus and fill Name and Source text fields.
Name one - whatever you want.
Source text field fill with 'https://sitecore.myget.org/F/sc-packages/api/v3/index.json'
After that go to Tools->Nuget Package Manager->Manage Nuget Packages for Solution...
In 'Package source' dropdown in right-top corner choose just add source. In my case it is 'Sitecore'. In search field type 'Sitecore.Nexus.Noreferences':
Choose a project you want to install package and click Install button.
The Sitecore.Nexus assembly is in the Bin folder of your Sitecore website. Add a reference to this assembly from your test project.

Method not found SetDataTypeProperties in custom SSIS component

I'm trying to build a simple custom SSIS component which looks at a single input column and validates it, creating an output column of type bool depending on the value of each row.
I've successfully built an even simpler component that takes a value and transforms it: that doesn't require fiddling with the output columns. In this instance I need to take in a string and output a boolean and the component needs to know that it outputs a boolean so I can feed the value into a conditional split.
I'm struggling to add the output columns. Based on code samples from Microsoft, I have done this:
public override DTSValidationStatus Validate()
{
IDTSOutput100 output = ComponentMetaData.OutputCollection[0];
IDTSOutputColumn100 outputcol = output.OutputColumnCollection.New();
outputcol.Name = "IsValid";
outputcol.SetDataTypeProperties(DataType.DT_BOOL, 0, 0, 0, 0);
return DTSValidationStatus.VS_ISVALID;
}
And then I attempt to populate it during the ProcessInput step:
public override void ProcessInput(int inputID, PipelineBuffer buffer)
{
while (buffer.NextRow())
{
string str = buffer.GetString(0);
buffer.SetBoolean(0, IsValid(str)); // validation code not relevant
}
}
When I try to use this component in the package, I get this error:
The component has detected potential metadata corruption during validation.
Error at Data Flow Task [Uppercase [24]]: System.MissingMethodException: Method not found: 'Void Microsoft.SqlServer.Dts.Pipeline.Wrapper.IDTSOutputColumn100.SetDataTypeProperties(Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType, Int32, Int32, Int32, Int32)'.
at EmailValidation.Uppercase.Validate()
at Microsoft.SqlServer.Dts.Pipeline.ManagedComponentHost.HostValidate(IDTSManagedComponentWrapper100 wrapper)
Searching on this error message has yielded nothing of value.
In the original sample - and some other tutorials online - adding output columns is done by looping through the input column and adding an additional output for each. I have tried this and get the same error.
I have also tried moving the output column code from Validate to OnInputPathAttached which still yields the same error.
What am I doing wrong?
On investigation this appears to be a bug in SQL Server Data Tools for Visual Studio 2015. I have built, deployed and used a custom component with customised output columns in an Integration Services package in Visual Studio 2013. However, the same tool deployed in a package in 2015 causes the error described.
In case it's still relevant, I encountered a similar issue (With the ComponentMetaData property rather than SetDataTypeProperties), and the solution that worked for me was setting the Embed Interop Types property of the Microsoft.SqlServer.DTSPipelineWrap and Microsoft.SQLServer.DTSRuntimeWrap references to false.
I found this solution here. It's listed as a solution for getting an InvalidCastException, but it seems relevant for whenever you're referencing the DTSPipelineWrap or the DTSRuntimeWrap assemblies in custom components.

Cake -Experimental Switch Compile Error

I am trying to use the Cake-Plist addin and received an error that dynamic is not yet implemented in the version of Roslyn that was being used. Then from advise for someone else I was told to try the -Experimental switch. When using the switch I am receiving the following error when it is trying to compile the build script.
Error: Microsoft.CodeAnalysis.Scripting.CompilationErrorException: (2,1): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
at Microsoft.CodeAnalysis.Scripting.Script.CompilationError(DiagnosticBag diagnostics)
at Microsoft.CodeAnalysis.Scripting.Script.GetExecutor(CancellationToken cancellationToken)
at Microsoft.CodeAnalysis.Scripting.Script.Run(Object globals)
at Microsoft.CodeAnalysis.Scripting.Script.Run(Object globals)
at Cake.Scripting.Roslyn.Nightly.DefaultRoslynNightlyScriptSession.Execute(Script script)
at Cake.Core.Scripting.ScriptRunner.Run(IScriptHost host, FilePath scriptPath, IDictionary`2 arguments)
at Cake.Commands.BuildCommand.Execute(CakeOptions options)
at Cake.CakeApplication.Run(CakeOptions options)
at Cake.Program.Main()
Does anyone know what is causing this error?
A reference needs to be added to Microsoft.CSharp.dll.
#reference "Microsoft.CSharp.dll"
https://gitter.im/cake-build/cake?at=57add5a3364ad7fc5acdb660
I had a similar issue when running it on a Mac (OSX El Capitan).
I couldn't find the Microsoft.CSharp.dll anywhere on the Mac (other than in my MS Windows installation), and didn't want to add it as a dependency into one of my projects just for the sake of getting it to build like this on a mac.
I noticed, however, that Mono.CSharp.dll was being downloaded into the ./tools/Cake folder. This serves roughly the same purpose, so I tried to reference it with
#r "Mono.CSharp.dll"
That didn't work either. But when I changed it to
#r "./tools/Cake/Mono.CSharp.dll"
It worked perfectly.
Now all I need to do is determine which platform it's running on and use the correct
#r "xxx.CSharp.dll"...
You can use reflection instead of dynamic. A little less elegant but avoids issues referencing Microsoft.CSharp.dll and Mono.CSharp.dll.
The example would be written as follows.
#addin "Cake.Plist"
Task("update-ios-version")
.Does(() =>
{
var plist = File("./src/Demo/Info.plist");
var data = DeserializePlist(plist);
var itemPropertyInfo = data.GetType().GetProperty("Item");
itemPropertyInfo.SetValue(data, gitVersion.AssemblySemVer, new[] { "CFBundleShortVersionString" });
itemPropertyInfo.SetValue(data, gitVersion.FullSemVer, new[] { "CFBundleVersion" });
SerializePlist(plist, data);
});

Method not found: 'Nancy.ErrorPipeline Nancy.ErrorPipeline.op_Addition

We updated Nancy from v1.2.0 to 1.3.0 via NuGet. According to the changelog there appear to be no breaking changes relevant to our application. However we are now getting the runtime error
Method not found: 'Nancy.ErrorPipeline
Nancy.ErrorPipeline.op_Addition(Nancy.ErrorPipeline,
System.Func`3)'.
in
base.ApplicationStartup(container, pipelines);
in our CustomBootstrapper. We are using Nancy.Bootstrappers.Autofac and have a custom IStatusCodeHandler.
I have cleaned out the packages folder, as well as bin/obj folders, and verified that there is only one version of Nancy after package restore.
How can I resolve or troubleshoot this?
(Caveat: I've never used Nancy. This is just a matter of looking at the history in Github.)
It looks like the + operator signature you're using changed from this in 1.2.0:
public static ErrorPipeline operator +
(ErrorPipeline pipeline, Func<NancyContext, Exception, Response> func)
to this in 1.3.0:
public static ErrorPipeline operator +
(ErrorPipeline pipeline, Func<NancyContext, Exception, dynamic> func)
That's not a backwardly-compatible change, at the very least at the binary level. As far as the CLR is concerned, that signature will be
public static ErrorPipeline operator +
(ErrorPipeline pipeline, Func<NancyContext, Exception, object> func)
... so any binary with a reference to the earlier signature won't find what it's looking for.
Do any of your dependencies also depend on Nancy, possibly at v1.2.0? Basically, you need to find out which piece of code is expecting the old signature, so you can rebuild that code against 1.3.0.

'Expected Global Line.' exception while loading solution using Roslyn

I'm learning Roslyn and trying it out for the first time. I've written a small code snippet to load a solution and get a reference to a workspace.
IWorkspace workspace = Workspace.LoadSolution(solutionPath);
foreach (IProject project in workspace.CurrentSolution.Projects)
{
CommonCompilation objCompilation = project.GetCompilation();
}
return workspace;
But I'm getting an exception in the first line. The exception details are given below.
Message : Expected Global Line.
stack trace : at
Roslyn.Services.Host.SolutionFile.ParseGlobal(TextReader reader)
at Roslyn.Services.Host.SolutionFile.Parse(TextReader reader) at
Roslyn.Services.Host.LoadedWorkspace.LoadSolution(SolutionId
solutionId, String filePath) at
Roslyn.Services.Host.LoadedWorkspace.OpenSolution(String fileName)
at Roslyn.Services.Host.LoadedWorkspace.LoadSolution(String
solutionFileName, String configuration, String platform, Boolean
enableFileTracking) at
Roslyn.Services.Workspace.LoadSolution(String solutionFileName, String
configuration, String platform, Boolean enableFileTracking) at
Ros2.Program.GetWorkspace(String solutionPath) in
c:\users\amnatu\documents\visual studio
2015\Projects\Ros2\Ros2\Program.cs:line 30
I referred to this link which shows the same issue that I faced. However, the solution of removing the space between EndProject and Global isn't really applicable in my case as my solution file doesn't have any space between them.
Am I missing anything here?Any suggestions on how to resolve this issue?
Apologies for the delayed response. The comment by #JoshVarty helped me understand the issue.
I was indeed using the out dated version and had to use the latest Microsoft.CodeAnalysis library. After I made these changes and updated all classes accordingly, everything worked perfectly.
Thanks JoshVarty.!

Categories