How to replace boiler-plate code with attributes? - c#

We have this pattern everywhere in our code:
using (ServiceAccess ws = new ServiceAccess())
{
//...
//code here to talk to webservice ws
//...
}
How can I replace this boiler plate code with an attribute on the functions that need to talk to the web service? (I'm thinking back to when I did some stuff with Hibernate in Java a long time ago and there was an some "Transation" annotation you could use that would auto-insert some try...catch boiler-plate code into the function.) The using {} is pretty good already but it would be nice to not have it at all... Having an attribute would also help document the function as one that talks the web service as opposed to one that does.
Edit: Would AOP do the trick?

Take a look at aspects in spring.net.

You can also take a look at PostSharp.
I't will let you use attributes to implement aspects, you can use it to achieve what you want.

I think the best you can do is create a shortcut for inserting that code as a snippet. You can't shoehorn a variable declaration into a method via an attribute. Or put another way, attributes can only tell you things about the code. They can't change the code itself.

"Aspect" type things...this is a way to decorate a given method with code of your choice. If you wanted to dispose e.g. after invocation of your method, the aspect as well as the code would have to have access to the Service. It would also mean that you have little control of the lifetime of the service class.
In some code lately I provide a context to my class through which service instances can be obtained. They are provided to a delegate you may pass. Any disposal can then be made after your closure is left...
DateTime serverTime;
context.UseService<IInfoService>(s=>serverTime = s.GetTime());

Related

Custom attribute with access to input/output parameters of method it is decorating

I was wondering how to go about writing a custom attribute which can access both the input and output parameters of a function.
Below is an example of what I wish to achieve
[CustomAttribute("Creating Foo")]
public Foo CreateFoo(Foo newFoo)
{
//do logic
return newlyCreatedFoo;
}
From this, the CustomAttribute will create an entry in a DB with the "Creating Foo" tag, which is easy enough to do, but I want to be able to access both newFoo and newlyCreatedFoo as well. Is this possible?
Custom attributes can't do that in general: their purpose is to add metadata to a method to view during reflection.
That being said, there are some cases where attributes are leveraged to do that. For example, ASP.Net MVC uses custom attributes that implement IAuthorizationFilter to provide security for some web pages. This works because ASP is using reflection to launch the methods in the first place. Once it gets the method it checks to see if any attributes are IAuthorizationFilters, and does some extra work when they are. See this link for some more info.
Another way to think about this is to consider aspect-oriented programming. I think AOP frameworks for c# tend to make compile time decorations to methods based on attributes that implement a certain interface, but I have not used one.
My favorite way to deal with this is the good old Proxy pattern. Create a logging proxy.
I am afraid that this is not possible with custom attributes.
This could be achieved with post compilation processing. Tools like PostSharp would allow you to achieve this functionality.
Perhaps you should rephrase your question to "How can I intercept calls to specific methods and log the arguments"?
A custom attribute is just a decoration on a method. It does not intercept or in any way affect the execution of a method. It doesn't even know what member it is attached to.
If you want to intercept the calls you can use a dependency injection framework, or any other AOP framework for .NET to do just that. Some of them actually use attributes to mark their targets, but that isn't a requirement.
PostSharp is just one AOP framework for .NET.
Another option, is to use an IoC/Dependency Injection library like MEF to wrap your class in a proxy object that will intercept all calls and only log the values of the methods decorated with a special attribute.

How to intercept method calls in C#

I'd like to intercept and inject custom code when calling 3rd party code in C#. I am using an external library (AutoIt) for GUI automation. The AutoIt dll is provided without source code.
All actions done with this framework are performed from a single class (AutoItClass) providing access to all the methods. I'd like to be able to inject custom code when calling methods on this class, is this possible? For example:
Log some information from within the called method.
Perform any other action from within the method (wait for X seconds).
This would be possible very simply by inheriting from this class and overriding all its methods (which is a must since this is a COM object), but this is not the preferred way. Any comments will be helpful!
I wouldn't use inheritance - you can use composition here. Create your own class which has the same methods - or in fact only the ones you're interested in - and delegate through that. That way you can be sure you won't "miss" any methods accidentally, because anything you don't implement won't be callable through the rest of your codebase... so long as you make sure the rest of your code doesn't refer to the original library class, of course.
You can investigate PostSharp, which is a commercial product that can inject IL into compiled assemblies to perform aspect oriented programming. You can define different kind of behaviour that should happen before and after a method gets executed, for example, which seems to be what you want. This way, as PostSharp handles this in a post-compilation step, you don't need to create any inherited classes from the classes that you want to intercept.
Otherwise if you want a more "pure" solution I would follow Jon's advice about creating a new class that wraps the functionality of the one that you want to intercept. (see Decorator pattern) .

Be notified of method calls in .NET

I want to be notified whenever a specific method has been called. I was hoping I could accomplish this using Reflection, but my attempts haven't gotten me anywhere. How can I be notified?
I figured using MethodInfo was the way to go, but like I said, I found nothing there that could help me accomplish what I wanted to do.
I cannot change the method or decorate it with attributes or anything. If I could do something like that, I wouldn't need to do this, I could just change the method itself.
Have you considered AOP (aspect-oriented programming)? Something like PostSharp.
I believe the only way to do this is either rewrite the method body so that it notifies you when the method has been called or use CLR Profiling Api.
The first way can be accomplished by using AOP framework. You can use Postsharp (which was turned into a commercial product) to achieve it with OnMethodBoundaryAspect. Here is an example: Derive the class from OnMethodBoundaryAspect
Reflection is half the solution. You need to wrapperize the objects being observed in order to intercept the method calls. Usually thi is done via remoting proxy objects.
Enterprise Library has the Unity Interception block which does exactly what you want. Also you may want to look into Castle framework's DynamicProxy, which gives you extremely thorough control of this interception process.
Googling for Aspect Oriented Programming will give you more information.
you can use extension methods
so you can use different attributes and modify everything before or after the actual method

How can I write clean code for a class that uses modular extension methods?

I'm trying to do something rather... unique, and maybe there's a far better way to do it but... I'm doing an inversion of control(ish) system that uses extension methods to enable/disable components of the class, so before I get into more detail and confuse you, lets look at some code!
using TestComponents.CommunicationProtocols.RS232;
//this brings in the
//ConnectRS232 extension method
namespace TestMeNamespace
{
public class Test //Although this class is defined here, we extend it above
{
public void Start()
{
this.ConnectRS232(1, 9600); //calls the ConnectRS232 extension method
}
}
}
So in short, the using declaration extends Test in the same file that we DEFINE test.
(inheritance would be fine as well) However there are some problems with this! first of all, the ugly requisite "this". blech. secondly it's a messy co-dependant system.
Here's what I'm attempting to achieve:
I want a way to easily extend static methods to a class (using declarations are fine)
I want to make statements simple: ConnectRS232();
I want to not have to futz with partial classes if I don't have to.
I'd be fine with using interface inheritance.
Feel free to ask me additional questions via comments but please don't post an answer unless you have an ANSWER!
Edit: In lieu of questions raised, I'm doing some JIT compilation of C#script (www.cs-script.com) in my system, and also these scripts will be mostly written by non-programmers who have been using a really "special" proprietary language for scripting for years. I want to keep things simple as hell, and a whole bunch of "this" calls look like clutter.
I'm not sure I see the point in this...
Your "extensions" will be compile time only. The extension methods only work as static methods, and since you're building this on importing of namespaces, it's more of a compile time construct than any form of IoC. (Extension methods are just a compile time thing - they don't really do anything at runtime.)
Also, given the above statement, having this.Method() doesn't seem onerous (it's good practice to use normally, which is why tools such as StyleCop enforce that you do that on EVERY method call).
Can you give us a better example of how this would be used? Right now, it just seems like a way to put code in two places instead of one, with no real benefit...

Is this a design pattern?

All over our codebase we have this repeated pattern where there's an interface with one method. Is this a real design pattern? If so what is it and what would the benefits be?
Here are a few examples:
public interface IRunnable
{
void Run();
}
public interface IAction
{
void Perform();
}
public interface ICommand
{
void Execute(ActionArgs _actionargs);
}
I've seen this referenced as the Command pattern.
I first learned about it reading Uncle Bob's Agile Principles, Patterns, and Practices in C#.
I believe its elegance is its simplicity. I've used it when I wrote a file processing service. The service performed all of the administration of reading / deleting files. When a file needed to be processed, it's respective plugin was loaded. Each plugin implemented a Process method, and did whatever was needed to process that type of file. (Mainly, parse the contents and insert into a database.)
Everytime I had to process a new file type with a new layout, all I had to do was create a new Plugin that implemented Process.
This worked for me because I needed a simple solution. If you need to take in more than one parameter, this probably is not the pattern to use.
Any of these could very well be specific cases of the Command Pattern, depending on how it's being used and the context. Part of this would depend on why and how you're setting this up.
The command pattern also normally includes a concept of state and of various objects. Typically, this type of interface would suggest that, so I'm guessing this is what you are thinking of as a design pattern here, but without the caller or multiple targets it's difficult to tell if this is a classic example of it or not...
However, this, in and of itself, is just basic interface abstraction to me, and not something I'd classify as a design pattern.
As It was said it is a Command Design Pattern. But it is ( as for me ) more like Java way of achieving the result. In C# you can use delegates and in the C++ function pointers and functors.
There is no big sense to create more and more classes if you already have some implementation of the reaction in a some Class method. Which you can bind in the C++ or set to delegate in the C#. In Java I suppose you have no choice but to write the code you have found.
I'm not sure whether you could call it a design pattern as the interfaces you provided does not provide solutions to commonly experienced problems but rather solution to very specific problems in the project that you're developing.
The reason you're properly using interfaces is due to the fact that you cannot have all your classes that needs these methods extend a base class that contains these, yet you need to know that specific classes promise to implement these.
Might be, as some of the previous posters suggested: http://en.wikipedia.org/wiki/Command_pattern
You can remove this repetition (or prevent it for future code) by using lambda expressions. Lambda expressions are exactly for this situation.
If anything, then it's a functor. It's used in languages without first class function( pointer)s for the sort of things function( pointer)s are used for, such as the main function for a thread.
There are applications for Interfaces with only one method. I mean, in .NET there are plenty - INotifyPropertyChanged, for one (the PropertyChanged event). It just guarantees that an object has a certain method (regardless of what type of object it actually is), so you can call it (again, regardless of type).
Dim runnableObjects As List(Of Object)
runnableObjects.Add(New MyRunnableObject1)
runnableObjects.Add(New MyRunnableObject2)
For Each o As IRunnable In runnableObjects
o.Run()
Next
Maybe I'm missing something, but the first two look like they could be part of the strategy pattern. Basically, an object has a member of type IAction, and that member is assigned/reassigned at runtime based on the needs of the system to perform a task in a particular way (ie using a particular strategy).

Categories