GithubHelp home page GithubHelp logo

icsharpcode / refactoringessentials Goto Github PK

View Code? Open in Web Editor NEW
641.0 46.0 120.0 7.81 MB

Refactoring Essentials for Visual Studio

License: MIT License

C# 99.18% HTML 0.65% PowerShell 0.12% Visual Basic 0.05%

refactoringessentials's Introduction

Refactoring Essentials for Visual Studio

Development of the Visual Studio extension and NuGet package has wound down.

Refactorings Essentials sports the following features:

  • Refactorings for C# and Visual Basic
  • Analyzers and code fixes for C# and Visual Basic
  • Code Converters to convert C# to Visual Basic and vice versa (VB to C#) - now available separately via https://github.com/icsharpcode/CodeConverter/

Refactoring Essentials comes in the following flavors:

  • VSIX: built for Visual Studio - supports analyzers and refactorings
  • Nuget: packaged for build servers / IDEs that support analyzers via Nuget packages
  • RefactoringEssentials assembly: usable in any IDE (-like environment), base assembly with all features

The latter means it is x-platform and not tied to Windows / Visual Studio.

History: Refactoring Essentials started out as NR6Pack, and was part of the NRefactory 6 repository. In the course of
joint development, we made architectural tweaks that resulted in the two projects now being separate - which makes them easier to maintain and contribute to.

refactoringessentials's People

Contributors

bradwilson avatar ceddlyburge avatar christophwille avatar cstick avatar danbrad avatar dgrunwald avatar ehasis avatar gitter-badger avatar grahamthecoder avatar kavignon avatar mhutch avatar mihailik avatar nosami avatar novakov avatar olathunberg avatar patrickhuber avatar remcovandenberg avatar rpinski avatar samjudson avatar siegfriedpammer avatar suchiman avatar therzok avatar tintoy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

refactoringessentials's Issues

Feature Request: Extract Method when nesting depth exceeds limit

Hey,

could you add a feature which offers to extract part of a method if the nesting depth of the current method exceeds a certain limit? I have a on going struggle with some of my developers who fail to keep their methods short and concise and this way, they would at least get a warning as well as a proposal on how to fix their method.

Thank you for your great extension! I have downloaded it last week and really liked it so far.

Arne

RECS0143 in this[string key] when trying to throw ArgumentNullException for 'key'

I have the following code:

public string this[string key]
{
   set
   {
       if (key == null) throw new ArgumentNullException("key");
   }
}

This gives the following warning:

RECS0143 - The parameter 'key' can't be resolved

I'm pretty sure that this warning is incorrect. The Microsoft docs for Dictionary.Item property state that ArgumentNullException is thrown if key is null, so the above should be valid code. https://msdn.microsoft.com/en-us/library/9tee9ht2(v=vs.100).aspx

Anyone any ideas?

Do not treat redundant syntax as warning

Green wavy underline indicating redundant syntax is too intrusive. These cases should not count as warnings, only possibilities for simplification of the source code at syntax level. Remove underline and keep only dimming like built-in analyzers do.

Some fixes are even contradictory with the Microsoft coding guidelines. For example, one of the rules states: always write access modifiers explicitly even if it is 'private' or 'internal'.
intrusive redundant syntax

Or another case, initialization of an array should not be treated as a warning:
intrusive array

Please decrease the diagnostic severity from warning but keep the 'unnecessary' custom tag in the redundant syntax analyzers.

RECS0014 proposal on empty class

Hi,

i think this proposal is not correct.
Example:

public class UserClaimDbModel : IdentityUserClaim
{
}

This class should not be static! It seems that the check for this does not check if the class is empty (does not contain anything member wise).

StringMethodIsCultureSpecificCodeFixProvider encountered an error and has been disabled

with NR0061, (really NR0060-NR0064 warns of culture aware), I get a yellow box in between text editor and tabs telling me the Provider has encountered an error and has been disabled. I can't find the stack trace like I could with the warnings. The line of code that is failing is like this

            return _fileHelper.GetFileInfos(new DirectoryInfo(_path))
                              .Where(fileInfo => fileInfo.Name.EndsWith(extension))
                              .Select(fileInfo => _triggerFileFactory.Create(fileInfo.FullName))
                              .ToList();

Not sure what the exception is or where to look, so if I can help out more please advise.

A number of refactorings failing

I'm getting these when working on the DasBlog source code. I'm in SharedBasePage.cs. It's lousy code, but it's still interesting I'm getting errors.

image

InvertIfCodeRefactoringProvider: InvalidOperationException on nested "if ... if ... else"

The code

    class TestClass
    {
        int TestMethod(int a)
        {
            if (a > 0)
                if (a < 5)
                {
                    return 1;
                }
                else
                {
                    return 2;
                }

            return 0;
        }
    }

and Ctrl+. at if (a < 5) makes InvertIfCodeRefactoringProvider crash with

An exception of type 'System.InvalidOperationException' occurred in Microsoft.CodeAnalysis.CSharp.dll but was not handled in user code

Additional information: The item specified is not the element of a list.

at
https://github.com/icsharpcode/RefactoringEssentials/blob/master/RefactoringEssentials/CSharp/CodeRefactorings/Synced/InvertIfCodeRefactoringProvider.cs#L44

Error when trying to access Quick Actions

When I press Ctrl + . to access the Quick Actions menu, an error is thrown. Sometimes generic, and other times with a note to reference the Visual Studio reference log. If I click on the light-bulb glyph, Visual Studio just crashes and closes.

I'm using Visual Studio 2015 RC, and RefactoringEssentials 1.1.0.0 (problem started after upgrade yesterday). I'm coding in C#.

The stack trace in the activity log is:
System.MissingMethodException: Method not found: 'Microsoft.CodeAnalysis.SyntaxAnnotation Microsoft.CodeAnalysis.Formatting.Formatter.get_Annotation()'. at RefactoringEssentials.CSharp.CodeRefactorings.GenerateSwitchLabelsCodeRefactoringProvider.d__0.MoveNext() at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine) at RefactoringEssentials.CSharp.CodeRefactorings.GenerateSwitchLabelsCodeRefactoringProvider.ComputeRefactoringsAsync(CodeRefactoringContext context) at Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringService.d__7.MoveNext()

RECS0022 Empty general catch clause

This warning show some weird behavior (at least IMHO).

public bool DoSomething()
{
    try
    {
        // ...
        return true;
    }
    catch
    {
        return false;
    }
}

In the above code sample, I get a warning that the empty general catch clause will suppress any errors, but this is not true, since the catch clause is not empty and errors won't be suppressed because of the return value. The suggested fix inserts (Exception e) behind the catch, but in the next line, so the code looks like this:

    catch
(Exception e)
    {
        return false;
    }

Surprisingly, the warning disappears although this doesn't change the behavior of my code, even if I remove the unnecessarily introduced variable e.

Duplication of Analyzers in IntelliSense Window with VSIX and NuGet Installed

VS 2015 RTM, the following example code in a C# console project:

class Program
{
    static void Main(string[] args)
    {
        if (0 == 0)
        {
            Console.WriteLine("done");
        }
    }
}

This produces the following IntelliSense popup (when Refactoring Essentials VSIX is installed):

dup_vsixonly

If, however, you go to Manage NuGet Packages, and install the Refactoring Essentials NuGet, you are now presented with a duplication of the analyzer suggestions:

dup_withvsixandnuget

Fun fact is that the error window in both cases shows the analyzers only once (even with NuGet and VSIX both installed):

dup_noduplicatesinerrorwindow

Bootnote: we discussed that a long time ago in a SO thread, but the problem persists to this day

http://stackoverflow.com/questions/28053514/vs2015-diagnostic-with-code-fix-nuget-or-vsix-or-both

"To expression body" refactoring doesn't preserve comments inside replaced method body

Using v1.2 of Refactoring Essentials on VS 2015 Community

It would be nice if the "To expression body" refactoring preserved any comments found in the (to be converted) method/property body

For example, this method

    public string Foo()
    {
        return _bar.Foo(); //This is a very important comment I don't want to lose
    }

Should be converted to this

    public string Foo() => _bar.Foo(); //This is a very important comment I don't want to lose

VS 2015 RTM - Initialize field/property from ctor parameter is failing

  1. I've got simple class like this: https://gist.github.com/Novakov/cea09c31c3b4b568e3f7
  2. Place caret on ctor parameter param
  3. Press Ctrl+. (quick actions)
  4. Error bar appears: InitializeFieldFromConstructorParameterCodeRefactoringProvider encountered an error and has been disabled

After some debugging I've found that

is throwing exception System.ArgumentException with message Node to track is not a descendant of the root.

More debugging showed that lambda passed to CodeActionFactory.Create is called twice. First invocation works fine than, the second one, throws the exception. As an experiment I changed lambda to direct value (https://gist.github.com/Novakov/bf6e521506a4511e3401) and it worked.

I'm using VS 2015 RTM (14.0.23107.0 D14REL). I'm able to reproduce this issue with release from VS Gallery, VSIX Gallery and manually built version (76a6b95).

Argument Null Exception AD0001

System.ArgumentNullException: Value cannot be null.
Parameter name: node
at Microsoft.CodeAnalysis.CSharp.CSharpSemanticModel.GetConstantValueCore(SyntaxNode node, CancellationToken cancellationToken)
at ICSharpCode.NRefactory6.CSharp.Diagnostics.ConstantConditionAnalyzer.Check(SyntaxNodeAnalysisContext nodeContext, ExpressionSyntax condition)
at ICSharpCode.NRefactory6.CSharp.Diagnostics.ConstantConditionAnalyzer.b__3_4(SyntaxNodeAnalysisContext nodeContext)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.<>c__DisplayClass35_0`1.b__1()
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock(DiagnosticAnalyzer analyzer, Action analyze)'.

C# - MergeNestedIfAction

MergeNestedIfAction looks like not implemented and not provided by Roslyn, so I'll try to implement this one.

C# - GeneratePropertyAction

I'm going to try port GeneratePropertyAction. I see that there are some ignored test for that action, so I'll treat them as starting point.

It lags out my VS installation

I got to a point where this extension would keep my CPU @ 25-50% not doing anything with my VS, and also lagging it out. Is it a known bug, or not?
After disabling the extension, everything work well again (it's a pure 2015 installation, without any extension or whatnot).

RECS0033 Suggestion produces bad code in Fix

The code:

if(args.TargetNode != null)
{
    args.TargetNode.Expanded = true;
}

produces a suggestion RECS0033 Replace with '|='.

Doing the fix produces:

args.TargetNode.Expanded |= args.TargetNode != null;

as you can see, the original intent of only expanding a non-null args.TargetNode now produces a NullReferenceException if args.TargetNode is null instead of just not setting the Expanded property.

I don't know if you can expand the suggestion template to account for this or whether it is just something the user needs to be wary of, but I thought I would share.

Up for grabs: missing.md for C#

NRefactory 5 had a myriad of C# refactorings / analyzers, and some haven't been ported yet. We keep track of those in missing.md at

https://github.com/icsharpcode/RefactoringEssentials/blob/master/RefactoringEssentials/missing.md

Those are up for grabs; to avoid duplication of work, please create an issue, assign it to yourself by mentioning "I am working on it" in the issue description (as you are not a GH team member, assignee isn't available to you), and then start working (and provide the pull request linking to the work item).

Note that some might be in-flight already by @Kavignon (Google Summer of Code student mentored by @mkrueger), you can see the list of current pull requests via

https://github.com/icsharpcode/RefactoringEssentials/pulls/Kavignon

'standard' nuget package

Hi!

Having the nightly VSIX build is great for VS users, but OmniSharp can't use this because it's a DNX app and it can't reference the assembly in the /tools folder.

For this reason, OmniSharp still uses nrefactory-alpha3. Please can you consider making a 'standard' nuget package that has the assemblies in the /lib/framework folder?

Running into a couple of "Object reference not set to an instance of an object" errors.

First set were this:
Message AD0001 The User Diagnostic Analyzer 'RefactoringEssentials.CSharp.Diagnostics.ConvertClosureToMethodGroupAnalyzer' threw an exception with message 'Object reference not set to an instance of an object.'

Also:

Message AD0001 The User Diagnostic Analyzer 'RefactoringEssentials.CSharp.Diagnostics.ConvertClosureToMethodGroupAnalyzer' threw an exception with message 'Object reference not set to an instance of an object.'.

I'm running it against Craig's Utility Library, version 4.0 branch. Happens when I open up the solution.

RECS0002 - Incorrectly identifies Lambda Simplifications

There was some weirdness going on here, but the analyser suggested the following line as an RECS0002 candidate:

https://github.com/smudge202/compose/blob/dev/tests/Compose.Tests/TransitionTests.cs#L248

The resulting refactor was not compilable, but that was because the simplification changed the delegate signature from Action to Func<T1, T2>, which in turn switched to a different overload in xUnit which was deprecated. Point being though, the refactor changed the signature, which should not happen.

Split Local Variable Declaration refactoring crashes on VS2015 RTM

Running current master branch at 0aed864 against VS2015 RTM.
Given the following sample code:

        public void T()
        {
            ArgumentNullException npe = new ArgumentNullException();
        }
  1. Pressing Ctrl+. shortcut in VS while cursor is blinking at npe expression.
  2. Mouse-over / select Split declaration and assignment option.
  3. Watch RE crash.

With debugger attached, exception is thrown from SplitLocalVariableDeclarationAndAssignmentCodeRefactoringProvider.cs

line 73:

root = root.TrackNodes(new SyntaxNode[] { declaration.Parent, declaration.Type, node });

Exception:

System.ArgumentException
Node to track is not a descendant of the root.
   at Microsoft.CodeAnalysis.SyntaxNodeExtensions.TrackNodes[TRoot](TRoot root, IEnumerable`1 nodes)
   at Microsoft.CodeAnalysis.SyntaxNodeExtensions.TrackNodes[TRoot](TRoot root, SyntaxNode[] nodes)
   at RefactoringEssentials.CSharp.CodeRefactorings.SplitLocalVariableDeclarationAndAssignmentCodeRefactoringProvider.<>c__DisplayClass0_0.<GetActions>b__1(CancellationToken t2)
   at RefactoringEssentials.DocumentChangeAction.GetChangedDocumentAsync(CancellationToken cancellationToken)
   at Microsoft.CodeAnalysis.CodeActions.CodeAction.<GetChangedSolutionAsync>d__9.MoveNext()

Open Release Notes on Installation / Upgrade

Up for discussion / input whether we should do that. But given the new detailed change logs in the wiki, it might be a good idea.

https://msdn.microsoft.com/en-us/library/hh696828.aspx

Either ReleaseNotes or GettingStartedGuide (the latter indicates to auto-launch and might be the ticket).

See also: https://github.com/madskristensen/WebEssentials2015/blob/master/EditorExtensions/Source.extension.vsixmanifest

Further discussion needed whether we link directly to the wiki article or use a redirect on the Web site (ie vsrefactoring.com/mrc)

"To expression body" refactoring not being offered in several cases

I'm using v1.2 of Refactoring Essentials with VS 2015 Community

The "To expression body" refactoring is not available in the following cases

  1. One-line class methods that return void
    public void Foo()
    {
        _bar.Foo(); //public void Foo() => _bar.Foo();
    }
  1. Read-only class indexers
    public string this[int index]
    {
        get
        {
            return _list[index]; //public string this[int index] => _list[index];
        }
    }

The opposite of RECS0129, RECS0145, ...

These rules suggest to remove unnecessary access modifiers, which sounds reasonable and I don't want to start a discussion about having them or not.

But, coding styles like the one of .NET Core, just to name a prominent project, often require to include them, which sounds reasonable too -- it seems to be solely opinion based.

Thus, it would be nice to have both options including some kind of configuration, ideally at global and project level.

RFC - Usage Tracking / Automatic Crash Data Collection

When a refactoring or analyzer crashes in VS you get error info panels like these:

crashinfoinvs

Aside: given this error message, how would the user know to report to us and not some other vendor?

For a user to be able to provide us with useful data to track down the root cause of the issue, she would have to go through the procedure outlined in Collecting Activity Log Data. This is a hassle and probably a lot of users won't care to do that to help us improve (providing a code sample could be enough in many cases though).

What other data might be interesting to collect aside from crashes:

  • How often is a refactoring being used
  • How often is an analyzer being suppressed
  • How often does an analyzer fire?
  • How often does a user apply a fix?
  • How often is a fix applied locally only, document or project level?

Suppressions provide a additional problem - this is done by VS, our analyzers are none the wiser about this actually happening.

Crashes - we would need to wrap all methods in a try/catch because there is no "global" exception handler in our case (base class?).

Consent - how do we ask users for consent to the data collection? How do we allow users to later opt out? Is this a solution setting, a per-user setting, ...? What about the NuGet package running on a build server?

Sending of collected data - when? There is no "application" that can send on startup or such.

Platform support - we would need to be able to disable the entire collection code (not being compiled), especially important for downstream projects.

RECS0092 - Convert field to readonly - static field and non-sattic constructor

In this example the RECS0092 suggests to add readonly to StaticField. This will however break the build as static readonly fields can be written from static constructors only. The analyzer should consider if the field/constructor is static/instance

class SomeClass
{
    static int StaticField;
    public SomeClass()
    {
        StaticField = 1;
    }
}

Global suppression for namespace is ignored

We use EF migrations on one of our projects and there are a lot of auto generated files (one per migration) that result in lots of RECS0070 warnings.

I've attempted to suppress them in GlobalSuppressions.cs using the following line of code but the warnings remain in the Error List window even after a rebuild.

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Redundancies in Code", "RECS0070:Redundant explicit argument name specification", Justification = "Auto-generated code by Entity Framework Migrations", Scope = "namespace", Target = "Portal.Data.Returns.Migrations")]

CONTRIBUTING.md

Technical FAQ for contributors will go to the wiki (easier to maintain, don't pollute repo with screenshots et al). Those wiki articles should contain links to getting started guides, conference videos, samples, SO posts, blog posts, MSDN articles, as well as a ramp up from simple to more complicated in our own codebase.

https://github.com/icsharpcode/RefactoringEssentials/wiki/Contributing-to-Analyzers-and-Code-Fixes
https://github.com/icsharpcode/RefactoringEssentials/wiki/Contributing-to-Refactorings

The .md: a welcome to everyone, from users to bug reporter to devs writing new analyzers/refactorings.

Maybe http://contributor-covenant.org/

Disable analysis of auto generated files

I am getting warnings for auto generated files, e.g.

  • Resources.Designer.cs
  • .NETFramework,Version=v4.5.2.Assembly.Attributes.cs

Is it possible to provide a way to ignore certain files by name, I don't really want to add a global suppression file for every project in my solution

ContainsKey refactoring is repetitive, slow, and presumptuous

Scott Hanselman highlighted the ContainsKey refactoring. There are three issues with this refactoring:

  1. The result isn't DRY. The key is repeated in the ContainsKey call and the call to the dictionary indexer. This opens the door to bugs if one instance of the key is changed but not the other. Additionally, the cost of evaluating the key is doubled, which may be significant if not a simple literal.
  2. Two dictionary lookup are required. Instead, the refactoring should generate TryGetValue.
  3. The refactored code assumes that the proper response to a missing key is to do nothing. Somethings this is correct, but often not. Just as generated code for methods includes throw new NotImplementedException(), this refactoring should include code to throw an exception, which the user can replace with the appropriate handling logic or remove as appropriate.

Add null check for parameter must be changed

Checks for null must be done always with ReferenceEquals(object x, object y) because overrides of operators is not a runtime operation but a compile time.

Current: if(obj == null) throw new ArgumentNullException(nameof(obj));
Should be if(ReferenceEquals(null, obj)) throw new ArgumentNullException(nameof(obj));

https://msdn.microsoft.com/en-us/library/system.object.referenceequals(v=vs.110).aspx

https://github.com/icsharpcode/RefactoringEssentials/blob/bb25d62f8610d863a3bc639dc1924585bf4373c9/RefactoringEssentials/CSharp/CodeRefactorings/Synced/CheckIfParameterIsNullCodeRefactoringProvider.cs

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.