Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
In my work I deal mostly with C# code nowadays, with a sprinkle of java from time to time. What I absolutely love about Eclipse (and I know people using it daily love it even more) is a sophisticated code formatter, able to mould code into any coding standard one might imagine. Is there such a tool for C#? Visual Studio code formatting (Crtl+K, Crtl+D) is subpar and StyleCop only checks the source without fixing it.
My dream tool would run from console (for easy inclusion in automated builds or pre-commit hooks and for execution on Linux + Mono), have text-file based configuration easy to store in a project repository and a graphical rule editor with preview - just like the Eclipse Code Formatter does.
For Visual Studio, take a look at ReSharper. It's an awesome tool and a definite must-have. Versions after 4.0 have the code formatting and clean-up feature that you are looking for. There's also plugin integration with StyleCop, including formatting settings file.
You'll probably want Agent Smith plugin as well, for spell-checking the identifiers and comments. ReSharper supports per-solution formatting setting files, which can be checked into version control system and shared by the whole team. The keyboard shortcut for code cleanup is Ctrl + E, C.
In 'vanilla' Visual Studio, the current file can be automatically formatted with Ctrl + K, Ctrl + D, and Ctrl + K, Ctrl + F formats the selected text.
As for a runs-everywhere command line tool to be used with commit hooks, try NArrange. It's free, can process whole directories at once and runs on Mono as well as on Microsoft .NET.
Some people also use the Artistic Style command line tool, although it requires Perl and works better with C/C++ code than with C#.
The .NET Foundation just released their code formatting tool on GitHub
https://github.com/dotnet/codeformatter
It uses the Roslyn compiler services to parse project documents and convert them to their expected formatting conventions. They're applying this to some of the very old CLR code in order to make all the projects consistent.
Further to #Chris Karcher's answer - you can also automatically format the whole document by hitting Ctrl+K, Ctrl+D.
These formatting features work on a variety of file formats - it works wonders on ugly HTML.
Another option: NArrange;
free
console based (so good for commit hooks etc, but can still be used as an "External Tool" in VS)
flexible config file
For me, Ctrl + Shift + F maps to Find in Files. When I need to format code, I highlight it and hit Ctrl + K, Ctrl + F.
I understand this doesn't really address automated formatting. I just wanted to clarify for those who may not know this feature even exists in Visual Studio.
I've heard only good things about ReSharper. It's on my to-learn list.
http://www.sourceformat.com/
This tool is around (~30$). I tried it and it works nice (with multiple languages).
I like this tool the best because it doesn't check code file for correctness. I can post code snippets from the Internet and it will translate them correctly no matter if they are in missing parts of the code. Other tools I try complain in that cases. The tool can also be integrated easily into editors as it allows command line driving.
Other tools:
http://www.polystyle.com/index.jsp
http://astyle.sourceforge.net/ (open source)
Not directly, but I use the Agent Smith plugin for R# to do this. Unfortunately, R# isn't free.
Also take a look at Microsoft StyleCop
See this previous question:
Is there any tool for reformatting C# code?
Searching for [c#] astyle shows up some more previous questions too.
I haven't tried this (found it through Google). It might work. http://www.semdesigns.com/Products/Formatters/CSharpFormatter.html. It's fairly cheap at USD50, but a trial is not available.
Maybe you could be interested in this free Addin for Visual Studio 2010/2012.
Here is an open source code formatting tool which has amazing features
CodeMaid
If you want to do it online, have a freecodeformat.
Related
I have Resharper 9 installed and StyleCop as I'm trialling then to see if my work should get the tools installed for all developers (So I'm very new to using both tools).
StyleCop has a number of rules that affect line formatting, such as: SA1116. Resharper then picks up when these rules are violated and it offers the option to have it automatically fixed (as you can see below).
The only problem is when I actually hit enter nothing happens. Well nothing happens 80% of the time for this rule violation as well as for a bunch of the other formatting issues such as a space between a cast and a variable (e.g. (double) myDouble;)
It seems so erratic, does anybody know how to improve this or is it simply credit to StyleCop not completely integrating with Resharper? (In which case should I stop looking at recharper/stylecop combo as a "press button to fix" tool and more like "here's a warning, your welcome. Now if there's a button, press it you're lucky")
Cheers,
It might be worth raising this as an issue with the StyleCop project on CodePlex. However, the CodePlex project seems to be a bit abandoned - the current ReSharper 9 plugin is provided by a community member. There's a GitHub repo (although it doesn't have source) that you could use to try and file an issue.
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
I'm looking for extensions that can show code metrics (especially cyclomatic complexity) beside method bodies or in a tool window as I type (without additional interactions).
So far I know:
Code Metrices by Elisha: free and simple. I don't know what metric it calculates, but read somewhere that it's not cyclomatic complexity. It doesn't support any other metrics.
CodeMetricAdornment by Carpslayer: only supports lines of code, comments, and whitespaces within a code file.
CodeRush: Not free. Exactly what I want (metric is selectable), unfortunately I'm already using ReSharper, and I'm thinking that it would be an overkill to have / buy both.
Are there others? What metrics do they provide?
Installing CodeRush (and turning off all the options you don't need) is certainly the easiest. It is possible to get CodeRush and Resharper to work together, see some of the answers here. There's a free trial if you just want to give it a go.
(There is also a free lite version of CodeRush called CodeRush Xpress, but I just checked and it does NOT include code metrics.)
If you're really opposed to installing the whole of CodeRush, DevExpress also provides its Visual Studio plugin technology on which it's built, DXCore, for free. So, you could create your own plugin (without installing CodeRush). There is a tutorial here which continues here and there are some (work in progress) docs here and another tutorial here.
Those tutorials are about creating your own metric, but you should be able to just replace the custom code with:
public partial class PlugIn1 : StandardPlugIn
{
private void codeMetricProvider1_GetMetricValue(object sender, GetMetricValueEventArgs e)
{
e.Value = e.LanguageElement.GetCyclomaticComplexity();
}
}
However, I don't think the display of the resulting value (e.g., next to the method) is covered by the tutorial so you might have to dig further (but DXCore can handle that too).
Here is the tool which can meets your requirements i.e. implementing code metrics using api while coding an application. This helps you generate or suggest the code metrics programmatically and instantly. And it generates the metrics far more than you have specified here.
Here is the link for the tool.
http://www.ndepend.com/ConstraintsExtractedFromCode.aspx
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have to refactor a large C# application, and I found a lot of functions that are never used. How can I check for unused code, so I can remove all the unused functions?
Yes, ReSharper does this. Right click on your solution and selection "Find Code Issues". One of the results is "Unused Symbols". This will show you classes, methods, etc., that aren't used.
It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.
One great tool come to mind:
NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most developers just say "Screw it!" and delete the app. Once you get a good feel for NDepend, it gives you amazing insight to how your apps are coupled. Check it out: http://www.ndepend.com/. Most importantly, this tool will allow you to view methods which do not have any direct callers. It will also show you the inverse, a complete call tree for any method in the assembly (or even between assemblies).
Whatever tool you choose, it's not a task to take lightly. Especially if you're dealing with public methods on library type assemblies, as you may never know when an app is referencing them.
Resharper is good for this like others have stated. Be careful though, these tools don't find you code that is used by reflection, e.g. cannot know if some code is NOT used by reflection.
As pointed Jeff the tool NDepend can help to find unused methods, fields and types.
To elaborate a bit, NDepend proposes to write Code Rule over LINQ Query (CQLinq). Around 200 default code rules are proposed, 3 of them being dedicated to unused/dead code detection
Basically such a rule to detect unused method for example looks like:
// <Name>Dead Methods</Name>
warnif count > 0
from m in Application.Methods where !m.MethodsCallingMe.Any()
select m
But this rule is naive and will return trivial false positives. There are many situations where a method is never called yet it is not unused (entry point, class constructor, finaliser...) this is why the 3 default rules are more elaborated:
Potentially dead Types (hence detect unused class, struct, interface, delegate...)
Potentially dead Methods
Potentially dead Fields
NDepend integrates in Visual Studio 2022, 2019, 2017,2015, 2013, 2012, 2010, thus these rules can be checked/browsed/edited right inside the IDE. The tool can also be integrated into your CI process and it can build reports that will show rules violated and culprit code elements. NDepend has also a VS Team Services extension.
If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used only by unused dead types and methods (recursive).
This is static analysis, hence the prefix Potentially in the rule names. If a code element is used only through reflection, these rules might consider it as unused which is not the case.
In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually unused/dead code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not.
Disclaimer: I work for NDepend.
I would also mention that using IOC aka Unity may make these assessments misleading. I may have erred but several very important classes that are instantiated via Unity appear to have no instantiation as far as ReSharper can tell. If I followed the ReSharper recommendations I would get hosed!
ReSharper does a great job of finding unused code.
In the VS IDE, you can right click on the definition and choose 'Find All
References', although this only works at the solution level.
The truth is that the tool can never give you a 100% certain answer, but coverage tool can give you a pretty good run for the money.
If you count with comprehensive unit test suite, than you can use test coverage tool to see exactly what lines of code were not executed during the test run. You will still need to analyze the code manually: either eliminate what you consider dead code or write test to improve test coverage.
One such tool is NCover, with open source precursor on Sourceforge. Another alternative is PartCover.
Check out this answer on stackoverflow.
I have come across AXTools CODESMART..Try that once.
Use code analyzer in reviews section.It will list dead local and global functions along with
other issues.
FXCop is a code analyzer... It does much more than find unused code. I used FXCop for a while, and was so lost in its recommendations that I uninstalled it.
I think NDepend looks like a more likely candidate.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
Which parsers are available for parsing C# code?
I'm looking for a C# parser that can be used in C# and give me access to line and file informations about each artefact of the analysed code.
Works on source code:
CSParser:
From C# 1.0 to 2.0, open-source
Metaspec C# Parser:
From C# 1.0 to 3.0, commercial product (about 5000$)
#recognize!:
From C# 1.0 to 3.0, commercial product (about 900€) (answer by SharpRecognize)
SharpDevelop Parser (answer by Akselsson)
NRefactory:
From C# 1.0 to 4.0 (+async), open-source, parser used in SharpDevelop. Includes semantic analysis.
C# Parser and CodeDOM:
A complete C# 4.0 Parser, already support the C# 5.0 async feature. Commercial product (49$ to 299$) (answer by Ken Beckett)
Microsoft Roslyn CTP:
Compiler as a service.
Works on assembly:
System.Reflection
Microsoft Common Compiler Infrastructure:
From C# 1.0 to 3.0, Microsoft Public License. Used by Fxcop and Spec#
Mono.Cecil:
From C# 1.0 to 3.0, open-source
The problem with assembly "parsing" is that we have less informations about line and file (the informations is based on .pdb file, and Pdb contains lines informations only for methods)
I personnaly recommend Mono.Cecil and NRefactory.
Mono (open source) includes C# compiler (and of course parser)
If you are going to compile C# v3.5 to .net assemblies:
var cp = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx
If you're familiar with ANTLR, you can use Antlr C# grammar.
I've implemented just what you are asking (AST Parsing of C# code) at the OWASP O2 Platform project using SharpDevelop AST APIs.
In order to make it easier to consume I wrote a quick API that exposes a number of key source code elements (using statements, types, methods, properties, fields, comments) and is able to rewrite the original C# code into C# and into VBNET.
You can see this API in action on this O2 XRule script file: ascx_View_SourceCode_AST.cs.o2 .
For example this is how you process a C# source code text and populate a number of TreeViews & TextBoxes:
public void updateView(string sourceCode)
{
var ast = new Ast_CSharp(sourceCode);
ast_TreeView.show_Ast(ast);
types_TreeView.show_List(ast.astDetails.Types, "Text");
usingDeclarations_TreeView.show_List(ast.astDetails.UsingDeclarations,"Text");
methods_TreeView.show_List(ast.astDetails.Methods,"Text");
fields_TreeView.show_List(ast.astDetails.Fields,"Text");
properties_TreeView.show_List(ast.astDetails.Properties,"Text");
comments_TreeView.show_List(ast.astDetails.Comments,"Text");
rewritenCSharpCode_SourceCodeEditor.setDocumentContents(ast.astDetails.CSharpCode, ".cs");
rewritenVBNet_SourceCodeEditor.setDocumentContents(ast.astDetails.VBNetCode, ".vb");
}
The example on ascx_View_SourceCode_AST.cs.o2 also shows how you can then use the information gathered from the AST to select on the source code a type, method, comment, etc..
For reference here is the API code that wrote (note that this is my first pass at using SharpDevelop's C# AST parser, and I am still getting my head around how it works):
AstDetails.cs
AstTreeView.cs
AstValue.cs
Ast_CSharp.cs
We have recently released a C# parser that handles all C# 4.0 features plus the new async feature: C# Parser and CodeDOM
This library generates a semantic object model which retains comments and formatting information and can be modified and saved. It also supports the use of LINQ queries to analyze source code.
You should definitely check out Roslyn since MS just opened (or will soon open) the code with an Apache 2 license here. You can also check out a way to parse this info with this code from GitHub.
http://www.codeplex.com/csparser
SharpDevelop, an open source IDE, comes with a visitor-based code parser which works really well. It can be used independently of the IDE.
Consider to use reflection on a built binary instead of parsing the C# code directly. The reflection API is really easy to use and perhaps you can get all the information you need?
Have a look at Gold Parser. It has a very intuitive IU that lets you interactively test your grammar and generate C# code. There are plenty of examples available with it and it is completely free.
Maybe you could try with Irony on irony.codeplex.com.
It's very fast and a c# grammar already exists.
The grammar itself is written directly in c# in a BNF like way (acheived with some operators overloads)
The best thing with it is that the "grammar" produces the AST directly.
Something that is gaining momentum and very appropriate for the job is Nemerle
you can see how it could solve it in these videos from NDC :
Igor Tkachev - Metaprogramming with Nemerle
Igor Tkachev - Nemerle Programming Language
Not in C#, but a full C# 2/3/4 parser that builds full ASTs is available with our DMS Software Reengineering Toolkit.
DMS provides a vast infrastructure for parsing, tree building, construction of symbol tables and flow analyses, source-to-source transformation, and regeneration of source code from the (modified) ASTs. (It also handles many other languages than just C#.)
EDIT (September) 2013: This answer hasn't been updated recently. DMS has long handled C# 5.0
GPPG might be of use, if you are willing to write your own parser (which is fun).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
While searching the interweb for a solution for my VB.net problems I often find helpful articles on a specific topic, but the code is C#. That is no big problem but it cost some time to convert it to VB manually.
There are some sites that offer code converters from C# to VB and vice versa, but to fix all the flaws after the code-conversion is nearly as time-consuming as doing it by myself in the first place.
Till now I am using http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx
Do you know something better?
Telerik has a good converter that is based on SharpDevelop that has worked pretty well over the years, though it has not been updated in years (due to it being based on SharpDevelop).
I've recently come across a roslyn based converter as well. I don't know how well it works or how well maintained it is, but as it's open source you can always fork it and update it as needed.
If you cannot find a good converter, you could always compile the c# code and use the dissasembler in Reflector to see Visual Basic code. Some of the variable names will change.
I currently use these two most often:
http://converter.telerik.com/
http://www.carlosag.net/tools/codetranslator/
But have also had some success with these others:
http://converter.atomproject.net/
http://www.dotnetspider.com/convert/Csharp-To-Vb.aspx
http://www.developerfusion.com/tools/convert/csharp-to-vb/
SharpDevelop has a built-in translator between C# and VB.NET. Is not perfect thought (e.g. the optional values in VB.NET doesn't have an equivalent in C#, so the signature of the converter method must be edited), but you can save some time, as you are making all operations inside an IDE and not a webpage (copy C# code, paste, hit button, copy VB.NET code, paste on IDE :P )
I think the best thing to do is learn enough of the other language so that you can rewrite by hand, there's some quite difficult differences in certain aspects that I'm not sure a converter would handle very well. For example, compare my translation from C# to VB of the following:
public class FileSystemEventSubscription : EventSubscription
{
private FileSystemWatcher fileSystemWatcher;
public FileSystemEventSubscription(IComparable queueName,
Guid workflowInstanceId, FileSystemWatcher fileSystemWatcher) : base(queueName, workflowInstanceId)
{
this.fileSystemWatcher = fileSystemWatcher;
}
becomes
Public Class FileSystemEventSubscription
Inherits EventSubscription
Private myFileSystemWatcher As FileSystemWatcher
Public Sub New(ByVal QueueName As IComparable, ByVal WorkflowInstanceID As Guid, ByVal Watcher As FileSystemWatcher)
MyBase.New(QueueName, WorkflowInstanceID)
Me.myFileSystemWatcher = Watcher
End Sub
The C# is from the Custom Activity Framework sample, and I'm afraid I've lost the link to it. But it contains some nasty looking inheritance (from a VB point of view).
I am using a free Visual Studio 2012 plug-in named Language Convert
It works perfectly on 2010/2012, unfortunately isn't working at VS 2013 yet.
The conversion is not 100% accurate, but it is definitely very helpful, to launch for the first time it is a bit tricky, check before the image below :
Last I checked, SharpDevelop has one and it is open source too.
You can load your DLL or EXE into Redgate's (formerly Lutz Roeder's) .Net Reflector, select your method and then the desired language from the language combo. The code of the selected method will be displayed in the selected language.
I hope this helps.
You can try this one converter. There is functionality for C# to VB and VB to C#.
Hope this helps.
Carlos Aguilar Mares has had an online converter for about 40 forevers - Code Translator but I would agree that Reflector is the better answer.
While not answering your question, I will say that I have been in a similar position.
I realised that code samples in C# were awkward when I was really starting out in .NET, but a few weeks into my first project (after I grown more familiar with the .NET framework and VB.NET itself), I found that it was interesting and sometimes beneficial to have to reverse-engineer the C# code. Not just in terms of syntax, but also learning about the subtle differences in approach - it's useful to be open-minded in this respect.
I'm sticking with VB.NET as I learn more and more about the framework, but before long I'll dip my to into C# with the intention of becoming 'multi-lingual'.
Currently I use a plugin for VS2005 that I found on CodeProject (http://www.codeproject.com/KB/cs/Code_convert_add-in.aspx); it use an external service (http://www.carlosag.net/Tools/CodeTranslator/) to perform translation.
Occasionally, when I'm offline, I use a converter tool (http://www.kamalpatel.net/ConvertCSharp2VB.aspx).
The one at http://www.developerfusion.com/tools/convert/csharp-to-vb/ (new url) now supports .NET 3.5 syntax (thanks to the #develop guys once again), and will automatically copy the results to your clipboard :)