views:

105

answers:

3

Is there a way to write custom refactorings or code transformations for Visual Studio?

An example: I have a codebase with a billion instances of:

DbConnection conn = null;
conn = new DbConnection();
conn.Open();
...a number of statements using conn...
conn.Close();
conn = null;

I would like to transform this into:

using (DbConnection conn = GetConnection()){
   ...statements...
}

Everywhere the above pattern appears.

Edit: The above is just an example. The point is that I need to do a number of code transformations which are too complex to perform with a text-based search-replace. I wonder if I can hook into the same mechanism underlying the built-in refactorings to write my own code transformations.

A: 

You would need to write a macro to do this.

Andrew Hare
+1  A: 

Strictly speaking, that isn't a pure refactor, since it changes the code in a way that significantly changes the behaviour (in particular, calling Dispose()). I would hope that either "Resharper" or "Refactor! Pro" would have a bulk "introduce using" (or similar). I've checked on "Refactor! Pro" (since that is what I use), and although it detects the undisposed local (at least, it does with DbConnection conn = new SqlConnection();), it doesn't offer an automated fix (trivial to do manually, of course). I would suggest:

  • check Resharper (there is an evaluation period)
  • if not, do it manually
Marc Gravell
+2  A: 

As Marc said, this is more of a 'replace' thing than a refactoring. But in any case, ReSharper is an option, and if you decide to use it, you can check out this guide. Good luck!

Dmitri Nesteruk