I am using Resharper for refactoring. What is this type of feature called when you have the same code in around 5 different events being called but you want to replace them with a method call? And place that code in that method.
All done automatically.
Thanks
I've been working on a Resharper plugin that does what you are asking. That is, it scans your code, searching for sections that can be replaced by an existing method call. A section can be a whole method or just a part of a method. When it finds one, the lightbulb pops up and offers to replace said section with a call to the existing method.
(source: landofjosh.com)
I call it AgentRalph. At this point it's not ready for production use, but I've been making a lot of progress and hope to make a release soon.
Extract Method.
See our C# CloneDR. While it doesn't replace redundant code with function calls, it does tell you where they are across very large system, and forms the essential abstraction (procedure body and parameters). The web link has example clone analyses for the C# equivalent of Hibernate (NHibernate).
Related
Is it possible to write an Attribute that can track methods to detect if those methods are never called?
[Track]
void MyMethod(){
}
output:
warning: method "MyMethod" in "MyClass" has no references in code.
It is not strictly necessary to have it run at compile time, but it should work when the application is initialized (better at compile time anyway).
This tag will be putted to track methods on Audio Library, since audio is refactored very frequently and we usually search for audio methods with 0 references in code we want to mark these methods so we can detect quickly and remove unused audio assets.
Basically each time we add a new sound effect, we may later no longer trigger it (calling its method), and the audio file/playback code can remain in the application for a long time.
Maybe this is the answer you're looking for?
Finding all references to a method with Roslyn
you can use the code there to automate something of your own with Reflection I'd say
A partial answer is found here:
C# reflection and finding all references
I can use that info to get references to methods marked with a particular attribute, however that is a run-time script (But better than nothing).
A little late, but better than never: I use WinGrep by Gnu to search all folders and files for the name of the method:
`C:\>grep -irw "method_name" * --include=*.cs --include=*.sql --include=*.txt`
You can include as many, or as few, file name extensions as makes sense for you. In the example above, I show the top directory as C:, but you can start the search at any directory that makes sense.
The huge advantage of using grep over IDE based searches is that it will search across multiple projects and solutions.
I've written a custom attribute for decorating methods. The attributes help add non-critical but very helpful contextual data to the method. Currently, this helps with debugging, but eventually it will help with static analysis.
Because the Master of the data specified in the attributes is on a server and queriable, I figured I'd write a Visual Studio Intellisense extention to help my developers. The extension would kick in when typing in parameters in my Attribute's constructor. The completion suggestions would essentially be query results.
I've read and implemented a Statement Completion example on MSDN with relative success.
The example is for Completion on PlainText. I've changed it to work on Code instead. I'm one step closer. The problem I'm having, however, is that I can't seem to find how to make it aware of its context. The Completion kicks an whenever I type any code. I'd like it to be a bit more discriminating than this.
Question: Is it possible to make a custom Visual Studio Statement Completion extension aware of the language constructs around it?
I'd like to be able to only trigger Statement Completion when I'm typing into an Attribute's constructor. And, if possible, preferably only on Attributes derived from a given base class.
Is this kind of thing possible?
No. This is why we're building Roslyn, but until then you might be able to use a third-party parser, or your own hacked up parser or heuristics to make it work.
I want to log the entry of methods. In entry log I would have inputs\parameters received by the method. This has to be done for thousands of methods.
I thought of doing this logging of input parameters using C# ATTRIBUTES, since they fired before method call. (Something similar to ActionFilters in MVC)
Is that possible to read method parameters through attributes?
The concept you are looking for is called aspect oriented programming (AOP). It is a technique that allows you to "weave" in blocks of boilerplate code across your application code. Logging is a perfect example for that. You can either go the hard way and implement logging before and after each method call manually (which is on the one hand not feasible in large projects and on the other hand error prone).
Or you can use an AOP Framework that allows you to define these cross cutting functions in one place and apply it declaratively to your application code. There are several approaches to achieve this; one is to create IL after the build of the application logic and therefore integrating the aspects at compile time. A well known example for this is PostSharp. There also is a free edition that is good for the start.
BTW: PostSharp heavily relies on attributes, so you're on the right track.
Another option is to integrate the aspects at run time (keyword is interception). Most IoC Frameworks offer this. This approach is easy to use but has some downsides IMHO (weaker runtime Performance, only virtual methods can be intercepted).
Attributes are not 'fired before method call', the code that invokes a method that is decorated with an Attribute may (or may not) do something based on the presence of the Attribute.
The Attribute doesn't know the member it is applied on, nor can access it in any (straight forward) way.
HI all,
I am not sure whether this is possible in C# or in any other language for that matter. Below is my requirement
It is a service application which will get some commands to execute. Those commands are predefined (methods in classes). When user calls these methods, the application framework must call another method (a default method) and complete the execution then execute teh called method. I understand there is a possibility of performance but i am in need of this type of architecture.
To explain better below is an example
Step 1: User A calls a webservice method GetData (string dataid, string dataLocation).
step 2: webservice recieves this call as http get method and it must first execute a default method CheckData(GetData).
Step 3: CheckData will now check the data which was sent to GetData Method and then it executes the GetData Method.
This way i can perform some operations like authentication, cleanup works and also other various system activities. Will it be possible for this kind of model.
My requirement is
User calls Webservice method employee.GetQualification.
In webservices, the call stack must be
Validater.CheckData (GetQualification)
Employee.GetQualification()
Validator.CheckOutput(output)
I am not looking for something like below (method stack)
Employee.GetQualification()
Validater.CheckData (getQualification parameters)
execute actual execution
Validator.CheckOutput(output)
Return
Some links/ thoughts would be beneficial for me to start on
Thanks.
Sounds like you are looking for a weaver like PostSharp (unfortunately not free any more).
Edit: Just remembered another aspect-oriented programming (AOP) library: LOOM.NET.
At the method level, there is no way to do exactly what you want, but if you're using WCF, you can create a custom behavior that does this for you.
See this article for examples, particularly the bit about IParameterInspector.
Personally, I don't think I would use this approach though, unless you need it to be configurable behavior. Hard coding a call to a single private method to do some validation at the start of some operation isn't so bad.
This seems to be a typical scenario for an AOP framework, e.g. have a look at the logging sample in the PostSharp tutorial
In web apps or in a WCF environment, there are certainly other approaches (e.g. HttModules), but by an AOP-based approach will work in any environment.
Note: there is a free community edition of PostSharp and the older version 1.5 is also free. And of course there are other AOP frameworks, such as Spring.NET.
You could write a sink for yourself which hooks in before and after your method executes. I had written a sink sometime back, check it out : http://technologyandme.blogspot.com/2009/05/putting-c-attributes-to-use.html
I've been searching for this for quite a while with no luck so far. Is there an equivalent to Java's ClassFileTransformer in .NET? Basically, I want to create a class CustomClassFileTransformer (which in Java would implement the interface ClassFileTransformer) that gets called whenever a class is loaded, and is allowed to tweak it and replace it with the tweaked version.
I know there are frameworks that do similar things, but I was looking for something more straightforward, like implementing my own ClassFileTransformer. Is it possible?
EDIT #1. More details about why I need this:
Basically, I have a C# application and I need to monitor the instructions it wants to run in order to detect read or write operations to fields (operations Ldfld and Stfld) and insert some instructions before the read/write takes place.
I know how to do this (except for the part where I need to be invoked to replace the class): for every method whose code I want to monitor, I must:
Get the method's MethodBody using MethodBase.GetMethodBody()
Transform it to byte array with MethodBody.GetILAsByteArray(). The byte[] it returns contains the bytecode.
Analyse the bytecode as explained here, possibly inserting new instructions or deleting/modifying existing ones by changing the contents of the array.
Create a new method and use the new bytecode to create its body, with MethodBuilder.CreateMethodBody(byte[] il, int count), where il is the array with the bytecode.
I put all these tweaked methods in a new class and use the new class to replace the one that was originally going to be loaded.
An alternative to replacing classes would be somehow getting notified whenever a method is invoked. Then I'd replace the call to that method with a call to my own tweaked method, which I would tweak only the first time is invoked and then I'd put it in a dictionary for future uses, to reduce overhead (for future calls I'll just look up the method and invoke it; I won't need to analyse the bytecode again). I'm currently investigating ways to do this and LinFu looks pretty interesting, but if there was something like a ClassFileTransformer it would be much simpler: I just rewrite the class, replace it, and let the code run without monitoring anything.
An additional note: the classes may be sealed. I want to be able to replace any kind of class, I cannot impose restrictions on their attributes.
EDIT #2. Why I need to do this at runtime.
I need to monitor everything that is going on so that I can detect every access to data. This applies to the code of library classes as well. However, I cannot know in advance which classes are going to be used, and even if I knew every possible class that may get loaded it would be a huge performance hit to tweak all of them instead of waiting to see whether they actually get invoked or not.
POSSIBLE (BUT PRETTY HARDCORE) SOLUTION. In case anyone is interested (and I see the question has been faved, so I guess someone is), this is what I'm looking at right now. Basically I'd have to implement the profiling API and I'll register for the events that I'm interested in, in my case whenever a JIT compilation starts. An extract of the blogpost:
In your ICorProfilerCallback2::ModuleLoadFinished callback, you call ICorProfilerInfo2::GetModuleMetadata to get a pointer to a metadata interface on that module.
QI for the metadata interface you want. Search MSDN for "IMetaDataImport", and grope through the table of contents to find topics on the metadata interfaces.
Once you're in metadata-land, you have access to all the types in the module, including their fields and function prototypes. You may need to parse metadata signatures and this signature parser may be of use to you.
In your ICorProfilerCallback2::JITCompilationStarted callback, you may use ICorProfilerInfo2::GetILFunctionBody to inspect the original IL, and ICorProfilerInfo2::GetILFunctionBodyAllocator and then ICorProfilerInfo2::SetILFunctionBody to replace that IL with your own.
The great news: I get notified when a JIT compilation starts and I can replace the bytecode right there, without having to worry about replacing the class, etc. The not-so-great news: you cannot invoke managed code from the API's callback methods, which makes sense but means I'm on my own parsing the IL code, etc, as opposed to be able to use Cecil, which would've been a breeze.
I don't think there's a simpler way to do this without using AOP frameworks (such as PostSharp). If anyone has any other idea please let me know. I'm not marking the question as answered yet.
I don't know of a direct equivalent in .NET for this.
However, there are some ways to implement similar functionality, such as using Reflection.Emit to generate assemblies and types on demand, uing RealProxy to create proxy objects for interfaces and MarshalByRefObject objects. However, to advise what to use, it would be important to know more about the actual use case.
After quite some research I'm answering my own question: there isn't an equivalent to the ClassFileTransformer in .NET, or any straightforward way to replace classes.
It's possible to gain control over the class-loading process by hosting the CLR, but this is pretty low-level, you have to be careful with it, and it's not possible in every scenario. For example if you're running on a server you may not have the rights to host the CLR. Also if you're running an ASP.NET application you cannot do this because ASP.NET already provides a CLR host.
It's a pity .NET doesn't support this; it would be so easy for them to do this, they just have to notify you before a class is loaded and give you the chance to modify the class before passing it on the CLR to load it.