visual-stylecop / visual-stylecop Goto Github PK
View Code? Open in Web Editor NEWCopy of StyleCop from stylecop.codeplex.com for visual studio 2015 and C# 6
Home Page: http://visual-stylecop.github.io/Visual-StyleCop
License: Other
Copy of StyleCop from stylecop.codeplex.com for visual studio 2015 and C# 6
Home Page: http://visual-stylecop.github.io/Visual-StyleCop
License: Other
The following line:
XmlNode node = ... ;
var property = node["properties"]?["property"];
incorrectly gives:
SA1011 : CSharp.Spacing : Invalid spacing around the closing square bracket.
Build 4.7.58.3
The following line:
var when = new XElement("someelement");
incorrectly gives:
SA0102 : CSharp.CsParser : A syntax error has been discovered in file ... .
Changing when to another name fixes the issue.
Build 4.7.53
I've made a local version that has by Global Settings or by SourceFile/Global Settings that allows you to completely disable processing.
The use case is that if you have a huge .cs file (such as a large Entity Framework Migrations that inserts lots of data), you can use this setting to ensure that absolutely NO processing happens for a file.
Let me know if you'd like to arrange review and me adding it back into the repository.
Thanks,
Christine Boersen
There seems to be an issue with SA1202 - from StackOverflow - http://stackoverflow.com/questions/34549069/stylecop-sa1202-internal-property-with-private-set
https://stylecop.codeplex.com/discussions/640343
I have installed the extension and work fine except when I use the string interpollation of C# 6.
In this case I have : SA0102 : CSharp.CsParser : A syntax error has been discovered in file ...
Copy from #20
// -- Example 2 (new long?[0])
public long?[] GetSelectedOrgIds()
{
return BulkScheduleEvents == null
? new long?[0]
: BulkScheduleEvents.Where(a => a.IsChecked).Select(a
=> a.OrganizationId).ToArray();
}
return modules?[0] is incorrectly reported as syntax error in the following code snippet (v4.7.55.26)
private static Module AssemblyModule
{
get
{
Module[] modules = Assembly.GetExecutingAssembly().GetModules();
Contract.Assume(modules?.Length > 0);
return modules?[0];
}
}
Thanks for the product !
Hello @ptittof57,
I've been testing the functionality of this project at work, and have found a few C# 6.0 language features that still cause a syntax exception:
Index Initializers:
Dictionary<int, string> myDictionary = new Dictionary<int, string>()
{
[1] = "One"
};
Exception Filters:
try
{
}
catch (Exception) when (true)
{
}
Expression-bodied function members / parameters
public string Test => "Test";
public string Test(string a) => a + "b";
Using static
using static System.Console;
I'm using version 4.7.52 on VS 2015 Enterprise.
Thanks for the work you have done to this project so far!
--Gustave Granroth.
Software Engineer, [email protected]
nameof(Nullable<int>.Value)
StyleCop complains:
Error SA1125 : CSharp.Readability : Use the shorthand of the nullable type
Problem here is that nameof operator doesn't accept shorthand notation for nullables
Hi Christoph,
I think there is a not considered use case with the NullCoalescingSymbol Symbol.
Line 8 of the The following code results in an error in VisualStyleCop in parsing the file
internal class myclass
{
private bool? singleBitValue;
private bool? foo(object obj)
{
this.singleBitValue = obj as bool?;
this.singleBitValue = obj as bool? ?? false;
return true ? true : false;
}
}
I was able to fix it by adding a check for checkNullCondition
In StyleCop.CSharp.CodeLexer.GetOperatorSymbor on line 2056
if (character == '?' && checkNullCondition.Length == 0)
In my opinion this makes sense as there must not be any tokes between the ?? operator.
Do you think it is possible to update the code accordingly?
Kind Regards
Ruedi
I am getting a parser exception with following code in version 4.7.57.0:
var list = new List<string>();
var length = list.FirstOrDefault()?
.Length;
ExcludeFromStyleCop works fine for project's build.
But when using "Run StyleCop (Rescan All)" from the VS extension on a solution level it still raises warnings, e.g.:
SA1633 : CSharp.Documentation : The file has no header, the header Xml is invalid, or the header is not located at the top of the file.
I have installed the extension directly from nuget.
Hi,
I am trying to install the Visual-StyleCop.Build in my solution. But it doesnot work on the build server. The build failed with the message.
error MSB4018: The "StyleCopTask" task failed unexpectedly.
error MSB4018: System.MissingMethodException: Method not found: '!!0[] System.Array.Empty()'
error MSB4018: at StyleCop.StyleCopTask.Execute()
error MSB4018: at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
error MSB4018: at Microsoft.Build.BackEnd.TaskBuilder.d__20.MoveNext()
Can somebody give me some more hints, I have search on the internet but I have not yet found the solution.
Grtz.
I have the following piece of code:
string.Format(Resources.Foo, "bar")
I am getting a SA1127 for this whereas I have no way to use string interpolation here.
Attempting to use in VS 2013 on a computer where VS 2015 is not also installed generates an error:
1553 2015/08/26 19:14:49.273 ErrorCopy from #20
// Example 3 (AlternateNames)
var expected = new InstitutionalInfo
{
AgendaSource = _institutionalInfo.AgendaSource != 0,
AudioSource = _institutionalInfo.AudioSource != 0,
Calendar = _institutionalInfo.Calendar,
IdConferenceFrequency =
_institutionalInfo.IdConferenceFrequency,
ContactDescription = _institutionalInfo.ContactDescription,
ContactEmail = _institutionalInfo.ContactEmail,
ContactName = _institutionalInfo.ContactName,
ContactTelephone = _institutionalInfo.ContactTelephone,
ContactTitle = _institutionalInfo.ContactTitle,
Notes = _institutionalInfo.Notes,
AlternateNames = new List {
_names[0].AlternateName, _names[1].AlternateName } //Here problem
occurs
};
Distributions = new List { reader["Distribution1"].ToString(),
reader["Distribution2"].ToString() },
I propose rule SA1127 be removed for the following reasons:
string.Format
. Calls to string.Format
have the ability to use the standard call syntax with one argument per line to express long formatting operations. These uses should not be required to suppress a warning.Conclusion: the benefits provided by string interpolation are not consistent across a code base, and therefore do not meet the bar for declaring a general readability rule that will apply to whole code bases. Support for string interpolation should be limited to the creation of refactoring operations which can be applied to specific calls to string.Format
if and when developers see readability benefits.
In the target file, only @compile items are analyzed. But in xproj file there are not any of these anymore.
I have succefully tested some changes and it now works fine.
I could not commit my changes on the dev branch, I can post you the fix if you want.
I'm getting this error on a line that contains nameof()
1>D:\Dev\Project\Search.cs(89,1): error : SA0102 : CSharp.CsParser : A syntax error has been discovered in file D:\Dev\Project\Search.cs on line 89.
My line 89 looks like this:
nameof(this.index.SearchAsync),
From VSExtension comment open by ophioscorodon
First let me start off by saying thanks, if you are ever in Providence RI, I'll buy you dinner for doing this.
Have a slight problem,
var handler = this.OpenEditorAndFileEvent;
// Raise the PropertyChanged event.
handler?.Invoke(this, filename);
produces a
SA1126 : CSharp.Readability : The call to Invoke must begin with the 'this.', 'base.', 'object.' or 'MevWpfUserControl.' or 'UserControl.' prefix to indicate the intended method call.
Something weird is going on
Thanks
-jam
Strings containing new lines and created by verbatim string literal causes SA0102.
Example:
const string Query = @"delete from [dbo].[OrganizationEventEntry] where [idOrganization] = 104
insert into [dbo].[OrganizationEventEntry](idOrganization, idTimezone (...)
When running StyleCop from the right-click context menu on a Solution Explorer item or on the file itself, I get a model dialog with the following message:
Method not found: 'Void StyleCop.CodeProject.ctor(Int32, System.String, StyleCop.Configuration, Double).
Version is 4.7.55.26 in VS2015 Enterprise
Comment from Visual Studio Gallery:
Hi,
First, thanks for this great Tool we are using on a daily basis.
Then talking about C#6, I have found a string interpolation syntax that seems not to be recognized by the parser (v 4.7.54) while correctly compiled and run in VS2015 :
WriteLine($"{argumentName}[{argIndex}] = "{arguments[argIndex]}"");
where argumentName is a const string (local auto)
where argIndex is an int
where arguments is an array of string
Thanks for fixing.
The first line of the following statement seems to cause the above error:
string sql = @"
SELECT *
FROM SomeTable";
It appears the verbatim string literal is not been recognised.
Hi,
When I replaced v4.7.49 with Visual-StyleCop.MSBuild 4.7.58.3 from https://www.nuget.org/packages/Visual-StyleCop.MSBuild
I started to have following exception on some specific file:
...cs(1,1): error : SA0001 : CoreParser : An exception occurred while parsing the file: System.FormatException, Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
.cs(1,1): error : at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
.cs(1,1): error : at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
.cs(1,1): error : at System.String.Format(IFormatProvider provider, String format, Object[] args)
.cs(1,1): error : at StyleCop.StyleCopThread.RunAnalyzers(CodeDocument document, SourceParser parser, IEnumerable1 analyzers) .cs(1,1): error : at StyleCop.StyleCopThread.TestAndRunAnalyzers(CodeDocument document, SourceParser parser, IEnumerable
1 analyzers, Int32 passNumber)
.cs(1,1): error : at StyleCop.StyleCopThread.ParseAndAnalyzeDocument(SourceCode sourceCode, DocumentAnalysisStatus documentStatus)
.cs(1,1): error : at StyleCop.StyleCopThread.DoWork(Object sender).
Same with Visual-StyleCop... 4.7.54
I get the following error
Warning SA0102 : CSharp.CsParser : A syntax error has been discovered in file ... on line 16
from the code:
public void test()
{
string[] strings = null;
var l = new List<string>
{
strings[9], // line 16
strings[8],
strings[0],
strings[1],
strings[2],
strings[3],
strings[4],
strings[5],
strings[6],
};
}
First appeared in version 4.7.53, altso present in 4.7.54
// Index initializers
Dictionary<int, string> primaryNumbers = new Dictionary<int, string>()
{
[1] = "one",
[3] = "three",
[5] = "five",
[7] = "seven",
[11] = "eleven"
}; <= SA0102 : CSharp.CsParser : A syntax error has been discovered
I use nameof in switch statement like this code
...
switch (typeof(O).Name)
{
case nameof(CompanyFolderModel):
result = this.GetCompanyFolderModel(name) as O;
break;
...
compiler accept this. StyleCop fails with syntax error.
Regards
Ralf
We've integrated visual-stylecop into our csproj and we've started using the C# 6.0 syntax throughout the files. We are using VS 2015.
We are finding that Visual-StyleCop is giving warnings for the "first appearance" of C# 6.0 syntax for a file:
"SA0102 : CSharp.CsParser : A syntax error has been discovered in **\fileA.cs on line 59."
"SA0102 : CSharp.CsParser : A syntax error has been discovered in file **\fileB.cs on line 67.
etc.
In fileA's case, we have multiple usages of C# 6.0 syntax particularly string interpolation and null propagation (ie. on line 59, 143, etc.) but the only warning being flagged is the first appearance of it (on line 59 but not line 143). This similar behavior is seen in fileB.cs as well.
It would be nice if this had a better way of dealing with custom extensions. In order to get a custom extension to work you have to drop the extension dll in the install folder. With VS extensions it's difficult to identify the location and it changes with every update. It would be nice if StyleCop extensions could be placed in a more general location.
OK:
public static string Property { get; } = string.Empty;
ERROR:
public static string Property { get; }
= string.Empty;
Source : https://stylecop.codeplex.com/discussions/640343
Hi ptit_tof57
I tried using the nugget package however the target files didn't get automatically added to the projects.
If I change the target from StyleCop.MSBuild.targets to Visual-StyleCop.MSBuild.targets then it will work.
Regards
Gary
Trying to install the extension in a VS2015 that is not run by an administrator causes the installer to use up all available memory and crash.
Running StyleCop over ASP.NET 5 (.xproj) projects does not work. It produces no output. This is probably because these project files do not include a list of all files within them.
Hi, I've already checked issue #7 where it says this has been resolved, however I just intalled Visual-Stylecop.MSBuild from nuget, version 4.7.58.3 and I am getting the SA0102 error on all the C#6 features that I tried out, like:
try
{
}
catch (Exception) when (true)
{
}
or
public virtual ICollection<CostType> CostTypes { get; protected set; } = new List<CostType>();
Am I doing anything wrong or there is a regression?
Thanks.
This rule has two major drawbacks:
String interpolation requires the Roslyn compiler, but it does not require .NET 4.6. The newer framework is only required for the specific case where an interpolated string is assigned to a variable with the static type IFormattable
. In other cases, including but not limited to assignments to string
, object
, and variables declared with var
, string interpolation works at least going back to .NET 3.5 (we use it extensively for this where it improves code clarity; it may work going back to .NET 2.0 but we haven't been using it like this).
The compiler and project system already have a feature specifically designed to restrict the use of newer language features in projects that still need to target older versions of .NET. For teams where some but not all developers are using Visual Studio 2015, the LangVersion property in the project file keeps everyone on the same page. This property is configured in the following location:
See this comment
#42 (comment)
Could confirm that it fails on latest release (4.7.59)
Since I have a problem with string interpolation, I'll post it right here and won't open a new issue.
My code is
var message = $"ConnectionString missing: {ConfigurationManager.AppSettings["ConnectionStringName"]}";
The code analyzer gives a warning SA0102.
I guess it's a problem with the quotation marks inside of the curly brackets
#37
The following valid C# snippet is reported as a syntax error.
workArea.Leave(x => HandleWorkAreaLogoutLeave(wa, x, obj as bool? ?? true));
Name: SyntaxException
Namespace: StyleCop.CSharp.CsParser
Description:
The following code:
Func<object> x = () => null;
decimal t = x() as decimal? ?? 0;
incorrectly gives:
SA0102 : CSharp.CsParser : A syntax error has been discovered in file ....
Build 4.7.58.3
The following line:
var x = y ? z?.Invoke() : w?.Invoke();
incorrectly gives:
SA0102 : CSharp.CsParser : A syntax error has been discovered in file ....
Upon further investigation, it is the first use of the null conditional operator
z?.Invoke()
which appears to causes the SA0102 error.
Build 4.7.58.3
We recently switched to C# 6 with VS2015 at work and after using ReSharper's kind suggestions to start going to C# 6 features like properties to expression body, I got an SA0102 issue with both the lines below.
public IEnumerable SelectableShiftHours => CreateSelectableShiftHours();
public OptimisationDayOfWeekEnum SelectedDay => selectedDay; (just a standard backing field to see if it was the method that did it)
Build 4.7.58.3
Source CodePlex : https://stylecop.codeplex.com/workitem/7709
public class Test1
{
public struct Rect2
{
public float x,y,w,h;
}
public class TestClass
{
public Rect2 TrackPosition = new Rect2();
public TestClass() {}
}
public void TestFunc(TestClass group, bool hidden)
{
if ((int)42.0f == (int)group.TrackPosition.y)
{
}
}
}
The following snippet:
var posts = new List<string>() { "abc", "123" };
posts.First()?.Replace('a', 'z');
incorrectly gives:
SA1009 : CSharp.Spacing : Invalid spacing around the closing parenthesis.
for the second line.
Build 4.7.53 and previous build 23/08/2015.
Sample code:
using System.Collections.Generic;
class Bug
{
private static IDictionary<string, string[]> _bug = new Dictionary<string, string[]>()
{
["bug"] = new string[]
{
},
["gub"] = new string[]
{
}
};
}
The new Null Conditional Operator in C# version 6 causes SA1000 to trigger in some circumstances.
I have this code:
internal static class AssemblyInfo
{
internal static T Attribute() where T : Attribute
{
return typeof(AssemblyInfo).Assembly.GetCustomAttribute();
}
}
And this call:
string company = AssemblyInfo.Attribute()?.Company;
The call causes SA1009 CSharp.Spacing : Invalid spacing around the closing parenthesis
However in this case, a ? here is properly spaced.
Hi @ptittof57,
I'd like to invite you to join the DotNetAnalyzers/StyleCopAnalyzers project. Over the past 9 months, more than 20 community members have joined together to build a faithful reproduction of StyleCop using the .NET Compiler Platform (Roslyn). The project implements the nearly all of the original StyleCop rules and even includes code fixes for most of them, all without requiring any special tools or Visual Studio extensions. We have over 5000 unit tests (including coverage of C# 6 features), a live status page, and an active discussion room on Gitter.
If you don't join us, please consider at least joining our chat room to discuss ways to make sure our diagnostic IDs stay in sync over time. ๐
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.