Replace method call to another - visual-studio

I need to replace all the ocurances of obj.Method1() to obj.Method2() where obj is an instances of the same class. Does ReSharper or VS2010 allow this?

You could write a ReSharper Replace Pattern (ReSharper->Tools->Pattern Catalog, Add Pattern) like so:
where the type of expression obj needs to be changed to your class (that contains Method1).
Then press Save and thereafter press Search now to get all Method1() calls:
Then click Replace and all Method1 calls are type-safely replaced to Method2.

I'd cheat - Do a 3-point symbolic rename (Right-click->Rename on a method name)
Method1 -> Temp
Method2 -> Method1
Temp -> Method2
None of this will change code functionality but will update all your code to use the correct name, except the methods themselves are now named incorrectly - simply rename the methods to by hand and voila - A little bit hacky but fast and effective.
This does rely on all method calls being in managed code (so that VS knows how/what to rename). If you have XML comments, C# rename handles this well but VB doesn't - I assume since you mention ReSharper, you're using C#?
This also assumes the method signatures are identical (if not, get ready for a lot of copy/pasting)

Make body of Method1 like this
public void Method1(...) { return Method2(...); }
And invoke refactoring "Inline method" on Method1.

Related

How to check where a who calls this method?

I have a custom method in an ABAP class.
I used the 'Where used' tool to show where the class is called from but, as it turns out, it's called from somewhere else I didn't expect.
So what's the best way of showing a complete list of everything that calls the method?
Due to the wonders of object-oriented programming, an instance of a class can hide behind a reference to one of its base classes or interfaces it implements. For example:
DATA foo TYPE REF TO z_my_interface.
CREATE OBJECT foo TYPE z_my_class.
" lots of more code
foo->bar( ).
You can not find this reference to z_my_class->foo with its "Where Used" list, because at that code location foo could also be a reference to an instance of any other class which implements z_my_interface. But you might be able to find this if you don't just look at the where-used list of the method but at the where-used list of the whole class or the interface / base class which declares the method.
And then there are evil dynamic programming tricks like this which determine methods and classes at runtime:
DATA foo TYPE REF TO object.
CONSTANTS: classname TYPE string VALUE 'Z_MY_CLASS',
methodname TYPE string VALUE 'BAR'.
CREATE OBJECT foo TYPE (classname).
CALL METHOD foo->(methodname).
There is no chance to find this with the where-used tool. But if the class- and/or method name does actually appear in the code (it might not, for example if they are read from a customizing table) then you can use the report RS_ABAP_SOURCE_SCAN. This handy little tool allows you to select a set of ABAP programs and search for strings (and even regular expressions) within their sourcecodes.
However, if you know the method gets called when you do something specific as a user and just want to know where, then it can be easier to just set a debugger breakpoint in the method, run into it and check the call stack.
Sorted using the code_scanner transaction.

Caching the result of all methods

I have a class which is essentially a collection of methods for some data transformations. In another words I have some data in my files and I use a few different code snippets to transform the textual data into something that I can easily query.
Now the methods often reuse each-other and as the core data is changing I'd like to simply cache the results of each method, for the speed reasons.
I don't want to change each method by adding:
^ methodsCache ifNil: [ methodsCache := "compute" ]
I want to use the power of Pharo reflection to accomplish my task without touching much of code.
One idea that I had is if I can run some code before each method, thing I can either return a cached value or continue the execution of the method and cache it's result
You could use the Reflectivity framework to add pre and post meta links to your methods. A link could check a cache before execution transparently.
link := MetaLink new
metaObject: self;
selector: #cachedExecute:;
arguments: #(selector);
control: #before.
(MyClass>>#myMethodSelector) ast link: link.
This code will install a meta link that sends #cachedExecute: to a MyClass object with the argument #myMethodSelector. The link is installed on the first AST node of the compiled method (of that same method selector, but could be on another method). The #control: message ensures that the link will be executed before the AST node is executed.
You can of course install multiple meta links that influence each other.
Note that in the above example you must not send the same message (#myMethodSelector) again inside of the #cachedExecute: method since you'd end up in a loop.
Update
There's actually an error in the code above (now fixed). The #arguments: message takes a list of symbols that define the parameters of the method specified via #selector:. Those arguments will be reified from the context. To pass the method selector you's use the #selector reification, for the method context the #context reification and for method arguments #arguments. To see which reifications are available, look at the #key on the class side of the subclasses of RFReification.
One idea that I had is to define
doesNotUnderstand: aMessage
aMessage selector beginsWith: 'cached' ifFalse: [ ^ super doesNotUnderstand: aMessage ].
^ cache at: aMessage selector ifAbsentPut: [
self perform: aMessage selector allButFirst: 6 ]
This way the only thing you have to do is to replace all message sends like self methodName with self cachedmethodName (or self cachedMethodName but then you have to do additional lowercase workaround in doesNotUnderstand:)
Another well-known option would be to replace your new and return a caching proxy, delegating to the actual object

How can I quickly create a class in the right place when following TDD using Visual Studio/ReSharper?

Suppose I'm following TDD and using VS/ReSharper. I start out writing a test like this:
[TestFixture]
class FooFixture
{
[Test]
public void ShouldDoSomething()
{
var foo = new Foo();
}
}
At this point, Foo doesn't exist. ReSharper suggests the option of creating the class, but it puts it right next to my test class in my test project, not in my real project. So I have it create the class, then move it to a new file, then move the file to the right place, and finally fix the namespace. This seems like a lot of work.
Is there a more efficient way to quickly create the Foo class and put it in the right place? It seems like the 'right place' could be guessed from the namespace of my test project.
Move types into matching class refactoring is used for this purpose.
You're expected to generate a number of business logic types in the current test class and then move them to matching files/namespaces in one go.
Note that this refactoring is available in the text editor and on Solution Explorer nodes, meaning that you can batch-apply it to a heck lot of files.

How do I implement AssemblyInitialize/AssemblyCleanup in my CodedUITest in MSVS 2010?

I am trying to implement AssemblyInitialize/AssemblyCleanup attributes in my Microsoft Visual Studio 2010 for the exact purpose as stated here. That link even describes the process which I need to follow to implement the code.
A quick summary of that purpose is to create an initial block of code which will run right before any test no matter which of the codedUITests I run in the solution and then a block of code which will run after the last codedUITest is completed. Example: I need to open up a specific application, then run a series of codedUITests which all start at that application and which are executed in any order, then close the application after everything is finished; this is more efficient than opening/closing the application for each codedUITest.
What I don't understand is where I need to place the code laid out at the bottom of that page (also shown below). I stuck all that code right under my 'public partial class UIMap' and the code runs except it runs the 'OpenApplication' and 'CloseApplication' commands before/after each CodedUITest instead of sandwiching the entire group of CodedUITests.
How do I implement the code correctly?
Update:
I discovered AssemblyI/C last night and I spent 3 hours trying to
figure out where to put the code so it works. If I put the
AssemblyInitialize at the beginning of a specific test method then:
1) It still wouldn't run - it was giving me some error saying that
UIMap.OpenWindow() and UIMap.CloseWindow() methods need to be static
and I couldn't figure out how to make them static.
2) Wouldn't the specific [TestMethod] which has the AssemblyI/C on it
need to be in the test set? In my situation I have a dozen
CodedUITests which need to run either individually or in a larger
group and I need to get the AssemblyI/C to Open/Close the window I am
testing.
You've added the methods to the wrong class. By putting then into the UIMap partial class, you are telling the runtime to run those methods every time you create a new UIMap instance, which it sounds like you're doing every test.
The point of the ClassInitialize/ClassCleanup methods is to add them to the class with your test methods in it. You should have at least one class decorated with the TestClass attribute, which has at least one method decorated with a TestMethod attribute. This is the class that needs the ClassInitialize and ClassCleanup attributes applied to it. Those methods will run one time for each separate TestClass you have in your project.
You could also use the AssemblyInitialize and AssemblyCleanup attributes instead. There can only be one of these methods in any given assembly, and they will run first and last, respectively, before and after any test methods in any classes.
UPDATE:
AssemblyInitialize/Cleanup need to be in a class that has the TestClass attribute, but it doesn't matter which one. The single method with each attribute will get run before or after any tests in the assembly run. It can't be a test method, though; it has to be a static method and will not count as a "test".

Is there a way to make a region of code "read only" in visual studio?

Every so often, I'm done modifying a piece of code and I would like to "lock" or make a region of code "read only". That way, the only way I can modify the code is if I unlock it first. Is there any way to do this?
The easiest way which would work in many cases is to make it a partial type - i.e. a single class whose source code is spread across multiple files. You could then make one file read-only and the other writable.
To declare a partial type, you just use the partial contextual keyword in the declaration:
// MyClass.First.cs:
public partial class MyClass
{
void Foo()
{
Bar();
}
void Baz()
{
}
}
// MyClass.Second.cs:
public partial class MyClass
{
void Bar()
{
Baz();
}
}
As you can see, it ends up as if the source was all in the same file - you can call methods declared in one file from the other with no problems.
Compile it into into a library dll and make it available for reference in other projects.
Split up the code into separate files and then check into a source control system?
Given your rebuttal to partial classes... there is no way that I know of in a single file, short of documentation. Other options?
inheritance; but the protected code in the base-class (in an assembly you control); inheritors can only call the public/protected members
postsharp - stick the protected logic in attributes declared externally
However, both of these still require multiple files (and probably multiple assemblies).
I thought about this, but I would prefer to keep the class in one file. – danmine
Sorry, mac. A bit of voodoo as a SVN pre-commit might catch it but otherwise no solution other than // if you change this code you are fired
This is totally unnecessary if you're using a version control system. Because once you've checked it in, it doesn't matter what part of the code you edit, you can always diff or roll back. Heck, you could accidentally wipe out all the source code and still get it back.
I'm getting a really bad "code smell" from the fact that you want to lock certain parts of the code. I'm guessing that maybe you're doing too much in one class, in which case, refactor it to a proper set of classes. The fact that, after the 10+ years visual studio has existed, this feature isn't available, should suggest that perhaps your desire to do this is a result of poor design.

Resources