Is it possible to sort code via Resharper? - c#

CodeRush has this nifty plugin called cr_ClassCleaner that allows me to sort the elements in the class (e.g. methods, private variables, etc...).
Can Resharper 5.x do this, either via the product or plugins?

Yes - ReSharper, Tools, Cleanup Code.
They recently blogged about customising the type layout this generates.

There is an option in code cleanup to reorder type members. This would be done as part of a full cleanup. If you wanted to only reorder, you could create a cleanup profile that only included that step. You can have multiple cleanup profile.

Ctrl+Alt+F (if you're using the IDEA profile) will take you to the cleanup code menu where you can achieve that.

Related

Is it bad to create and use custom Deprecated and NeedsWork C# attributes?

I want to mark many of my C# functions as "deprecated" or "needs work". My plan is to create customer attributes that I use to tag the functions. I saw this question which seems to indicate that information only attributes will not effect performance:
Is this use of attributes in .Net (C#) expensive?
My question is whether this is a bad use for attributes. Is there better way to mark code so that I can come back in phase 2 and either eliminate the code or rework it in some way?
P.S. I realize that there is an Obsolete attribute, but it results in far too many compiler warnings. I want to be able to see the "real" compiler warnings.
This feels like you want to create some sort of Project Management attributes for your classes.
I see project management as different than your code. If a feature is not 'done' right the first time, chances are it will be burried under other priorities and 'good enough' will cut it.
Of course there is always the Task list comments just add // TODO: and you will get it in your task list editor in visual studio if you do need reminders in your code.
I wouldn't go so far as to decorate classes with 'needfixing' attributes. If it's done it's done, if it's not it's not, if you need a reminder a todo should be enough.
I won't say that it's "bad" to mark code that needs work with attributes, but it may be overkill. Have you considered XML comments?

Change each c# file in solution

Is there a tool or set of tools to go through a c# solution and automatically perform certain changes such as enforcing naming schemes and change for/foreach to linq if possible.
I have used Resharper to do some basic solution wide changes, but I would really like it to do more like global renaming.
Specifically, I would like a tool to rename method parameters to proper c# naming schemes. For instance, MethodA(string Field) should become MethodA(string field) and so on.
Resharper has some pretty cool features, including "Cleanup Code", which can be run on multiple files at once.
It will automatically refactor your files based on the settings you've supplied it.
They have a demo version, so you can test to see if it helps with your problem.
http://www.jetbrains.com/resharper/
Resharper`s "Clean Up Code" tool can be run from context menu of any item in Solution Explorer. There are a few built in clean up configurations. You can configure your own. For example, you can set up order of fields\properties\methods\nested types in you class and reordering their before commit by executing clean up tool. It also can wrap its into region and so on.
Also you can force Resharper to use any of refactorings when cleaning up.(Optimize imports, remove unused methods or properties or use linq instead of loops, etc)
You can start looking from there
UPD You can use stylecop plugin to make your code correspond with the style conventions you want. It is open source and compatible with R#

Detecting if a class/type is defined prior to compiling

This is similar to a few other threads i have found, but I haven't found the answer I need yet. I would appreciate a direct answer, even if it is "no, you can't do that".
Is there a way to use one block of code if a class/type exists and another if it doesn't. The result would be the same as using preprocessor directives but without the need to #define and manually comment or un-comment something in a file.
This may be a special use-case. I'm not sure. I'm working in an environment where sets of files can be installed, or not, before anything is compiled. So someone could buy a plugin which gets "installed" (files added to the project) which makes classes/types available for use (like extending an API). I need to provide a workaround if someone doesn't have one of our other plugin packages. I hope that makes sense.
It just wouldn't be user-friendly to ask someone to open up one of our files, if they have another plug-in, to un-comment a preprocessor directive, unless we have to.
e.g. I know this doesn't work because it only tests boolean if #define is used, but it illustrates what I am trying to do...
#if SomeType
SomeType.DoSomething();
#else
DefaultWay.DoSomething();
EDIT: I added this as a C# feature suggestion. Please vote here:
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2297494-add-type-testing-as-preprocessor-directive
I don't see how reflection would be able to do this, but I am new to C#, so examples using relection, if it is possible, would be great.
Instead of using pre-compiler statements (which I don't know if they would work anyway if the client didn't have to recompile after installing your plug-in), I would suggest querying the assembly and trying to instantiate an instance of the class by string as seen here:
C# - Correct Way to Load Assembly, Find Class and Call Run() Method
Assembly assembly = Assembly.LoadFile(#"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
if (type != null)
//Do Something
Editing to show Activator call
if type is not null then use this to create an instance of the type you want.
var obj = Activator.CreateInstance(type);
You could define interfaces for your types/services that your evaluation-provided code supports, but doesn't provide. Then you could use a plugin framework like MEF, which is built into the .Net Framework (v4.0).
MEF will do the reflection and assembly enumeration for you. You just have to define simple extension points in your code.
Here is some basic documentation for MEF. It might be specific to the Codeplex version of the code (not sure) but it shouldn't be too old, and should give you a good idea of how it works:
http://mef.codeplex.com/wikipage?title=Guide&referringTitle=Documentation
Alternative ideas
You might want to solve this with licensing rather than distribution.
You're going to have to solve the licensing problem anyhow, so you can collect money from users, and so you can sue people who grievously violate your copyright.
If your code is worth distributing, you won't be able to prevent distribution. Piracy is not preventable.
And most licensed code I've used recently have full-featured but timed trials, and phone home. They install all the code, but simply disable parts of it if they aren't licensed. It is hard for someone to know if they want to pay for your advanced features if they can't try them out :)
Do you really care what is present at compile-time, or at run-time? You might be able to use a Factory pattern to encapsulate the logic for which class to instantiate assuming that polymorphism is possible (they both share an interface or base class).

Finding unused classes in C# app

I'm a C#/.net/Visual Studio noob. I inherited a half-completed C# application for a mobile phone. In the course of debugging, I came across several half-finished classes that don't seem to be used anywhere else in the code. Is there a way to get determine if a class definition is instantiated anywhere?
The quickest way (in Visual Studio) is to right-click the type name and select Find all references from the context menu. This will show you all places where that type is referenced in the current solution.
You should get Resharper - it will show "dead" code in grey and make refactoring a lot easier! You may also prefer CodeRush.
Without ReSharper or a similar tool, you can always do a file search for "new ClassName(" in the entire solution.
I usually start with Shift-F12 (or right-click on class name and select "Find All References")
Unless you know the code, and the modules that may use it., CodeRush or Resharper are your better choices.
None of the other answers mentioned the modifiers which can be applied to classes/functions. You certainly want to take scope into consideration before deleting code. You may have other assemblies which use classes/functions.
Remove them from the project and let your unit tests (ahem, you have those right?) and your QA team (you have that right?) identify the problems.
Jokes aside, if it's SO obvious that it's not complete, why not simply remove the code and recompile?
The next steps I would take would be to use a tool like "Find All References" or Resharper (does it even have a feature to do that?)
You can list all the classes (searching for class [a-zA-Z0-9_]+), and then search for new <classname>. The ones not found at the second search are not used. Of course, a simple script in your favourite script language would help.
You'll need however to filter out the classes that are used as base classes of used classes.
Note that this way you'll not find the classes which are used only from unused classes, so several iterations might be needed. Moreover, if some two classes are using each other (but not used from outside), removing them might need additional effort.
Edit:
A better approach would be building dependency tree: for each of the classes you define which class is used by that class, and which class is a base class for that class. This way you find which classes are required for every single class. Then, you can define which classes are required (directly or indirectly) from the class containing Main. All other classes are "unreachable" and therefore not used.
This approach will however remove the classes instantiated by reflection. Well, there is no way to find out at compile time, which classes are going to be instantiated by reflection anyway.
Maybe using the ready tools (like others proposed) is a simpler alternative.

Prevent other developers using base methods within a class

I have a class that uses filesystem entities to manipulate data. We have several methods specifically designed to (attempt to) cope with some of the issues we face with this approach (file locking, non-existent files, etc.). Ideally I'd like to be able to issue a warning if another developer attempts access the filesystem directly via System.IO rather than using the helper methods.
Is this possible? The behaviour I'm looking for is to effectively mark methods such as File.ReadAllText() as if they were obsolete, but only within this project (NOT solution-wide).
I've done some digging around, and it looks like my only option is "tell them to make sure they use your methods". I'm hoping someone can give me a different, and more helpful answer. :)
--EDIT--
The suggestions of a custom StyleCop or FxCop rule are good, but unfortunately impractical in this scenario (not every developer in the department uses these excellent tools), and the legitimate methods that do the file access do use System.IO. Adding "ignore" attributes to the legit methods is a dangerous idea, too. If someone sees how I've "broken" my own rule, they'll likely copy the attribute to their own method.
Use a static analysis tool (such as StyleCop or FxCop) with a rule that captures "Do not use System.IO directly." Then integrate it as part of your automated build process and throw up if someone does try to use System.IO directly. No one likes to break the build.
You can write custom analysis rule for FxCop/Visual Studio Code Analysis and run these as part of your automated build.
Hmm. Not tried this myself, but how about forcing people to use your custom file handling classes, by using a namespace alias that "hides" the genuine System.IO. If I remember rightly these are applied at a project level.
Not sure if either of these suggestions are valid as I've never done them, but some food for thought:
Isn't this what "Enterprise Templates" are designed for? Don't they allow you to craft a policy file that restricts the allowed project references?
Alternatively, while not foolproof, could you add a pre-build event to the project that throws a warning if System.IO is referenced?
Can you add some custom functionality to a source-control commit hook? It won't find existing violations (if there are any) unless those files are changed but should detect new uses?
Any good?

Categories

Resources