Can please someone explain, in a very easy/simple way, how to handle an exception via attributes?
For example if I have simple code like this:
class Test{
static void Main(string[] args){
try {
Console.WriteLine("div= "+ Division(0));
}
catch (DivideByZeroException e)
{
Console.WriteLine("Attempted divide by zero -->" + e.Message);
}
Console.ReadLine();
}
public static int Division(int i){ return 10 / i; }
}
How can I change this code using attributes?
This cannot be done with .NET out of the box.
tl;dr - There is no "very easy/simple way (...) to handle an exception via attributes"
You're trying to handle exceptions in a AOP way (aspect oriented programming), where you attach aspects to methods - using attributes, for example.
PostSharp allows you to do this:
Without postsharp:
public class OrderFulfillmentService
{
public void Fulfill( Order order )
{
try
{
// Do stuff.
}
catch ( Exception e )
{
if ( ExceptionHandler.Handle(e) )
throw;
}
}
}
With postsharp:
public class OrderFulfillmentService
{
[HandleException]
public void Fulfill( Order order )
{
// Do stuff.
}
}
Beware of the downsides of using AOP though: the code might become less readable (as it isn't written sequentially) and less maintainable.
Instead of using attributes, you could also use Castle Interceptor/DynamicProxy
You will need to create an interceptor that wraps around your object and intercepts calls to it. At runtime, Castle will make this interceptor either extend your concrete class or implement a common interface - this means you'll be able to inject the interceptor into any piece of code that targets the intercepted class. Your code would look something like this:
public class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
try{
invocation.Proceed();
} catch(Exception ex) {
//add your "post execution" calls on the invocation's target
}
}
}
Introduction to AOP with Castle: http://docs.castleproject.org/Windsor.Introduction-to-AOP-With-Castle.ashx
Related
Is there a way in C# or .NET in general to create an attribute on a method which triggers an event when the method is invoked? Ideally, I would be able to run custom actions before and after the invocation of the method.
I mean something like this:
[TriggersMyCustomAction()]
public void DoSomeStuff()
{
}
I am totally clueless how to do it or if it possible at all, but System.Diagnostic.ConditionalAttribute might do a similar thing in the background. I am not sure though.
EDIT: I forgot to mention that due to the circumstances of my specific case, performance is not really an issue.
This concept is used in MVC web applications.
The .NET Framework 4.x provides several attributes which trigger actions, e.g.: ExceptionFilterAttribute (handling exceptions), AuthorizeAttribute (handling authorization). Both are defined in System.Web.Http.Filters.
You could for instance define your own authorization attribute as follows:
public class myAuthorizationAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
// do any stuff here
// it will be invoked when the decorated method is called
if (CheckAuthorization(actionContext))
return true; // authorized
else
return false; // not authorized
}
}
Then, in your controller class you decorate the methods which are supposed to use your authorization as follows:
[myAuthorization]
public HttpResponseMessage Post(string id)
{
// ... your code goes here
response = new HttpResponseMessage(HttpStatusCode.OK); // return OK status
return response;
}
Whenever the Post method is invoked, it will call the IsAuthorized method inside the myAuthorization Attribute before the code inside the Post method is executed.
If you return false in the IsAuthorized method, you signal that authorization is not granted and the execution of the method Post aborts.
To understand how this works, let's look into a different example: The ExceptionFilter, which allows filtering exceptions by using attributes, the usage is similar as shown above for the AuthorizeAttribute (you can find a more detailed description about its usage here).
To use it, derive the DivideByZeroExceptionFilter class from the ExceptionFilterAttribute as shown here, and override the method OnException:
public class DivideByZeroExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception is DivideByZeroException)
{
actionExecutedContext.Response = new HttpResponseMessage() {
Content = new StringContent("A DIV error occured within the application.",
System.Text.Encoding.UTF8, "text/plain"),
StatusCode = System.Net.HttpStatusCode.InternalServerError
};
}
}
}
Then use the following demo code to trigger it:
[DivideByZeroExceptionFilter]
public void Delete(int id)
{
// Just for demonstration purpose, it
// causes the DivideByZeroExceptionFilter attribute to be triggered:
throw new DivideByZeroException();
// (normally, you would have some code here that might throw
// this exception if something goes wrong, and you want to make
// sure it aborts properly in this case)
}
Now that we know how it is used, we're mainly interested in the implementation. The following code is from the .NET Framework. It uses the interface IExceptionFilter internally as a contract:
namespace System.Web.Http.Filters
{
public interface IExceptionFilter : IFilter
{
// Executes an asynchronous exception filter.
// Returns: An asynchronous exception filter.
Task ExecuteExceptionFilterAsync(
HttpActionExecutedContext actionExecutedContext,
CancellationToken cancellationToken);
}
}
The ExceptionFilterAttribute itself is defined as follows:
namespace System.Web.Http.Filters
{
// Represents the attributes for the exception filter.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
Inherited = true, AllowMultiple = true)]
public abstract class ExceptionFilterAttribute : FilterAttribute,
IExceptionFilter, IFilter
{
// Raises the exception event.
// actionExecutedContext: The context for the action.
public virtual void OnException(
HttpActionExecutedContext actionExecutedContext)
{
}
// Asynchronously executes the exception filter.
// Returns: The result of the execution.
Task IExceptionFilter.ExecuteExceptionFilterAsync(
HttpActionExecutedContext actionExecutedContext,
CancellationToken cancellationToken)
{
if (actionExecutedContext == null)
{
throw Error.ArgumentNull("actionExecutedContext");
}
this.OnException(actionExecutedContext);
return TaskHelpers.Completed();
}
}
}
Inside ExecuteExceptionFilterAsync, the method OnException is called. Because you have overridden it as shown earlier, the error can now be handled by your own code.
There is also a commercial product available as mentioned in OwenP's answer, PostSharp, which allows you to do that easily. Here is an example how you can do that with PostSharp. Note that there is an Express edition available which you can use for free even for commercial projects.
PostSharp Example (see the link above for full description):
public class CustomerService
{
[RetryOnException(MaxRetries = 5)]
public void Save(Customer customer)
{
// Database or web-service call.
}
}
Here the attribute specifies that the Save method is called up to 5 times if an exception occurs. The following code defines this custom attribute:
[PSerializable]
public class RetryOnExceptionAttribute : MethodInterceptionAspect
{
public RetryOnExceptionAttribute()
{
this.MaxRetries = 3;
}
public int MaxRetries { get; set; }
public override void OnInvoke(MethodInterceptionArgs args)
{
int retriesCounter = 0;
while (true)
{
try
{
args.Proceed();
return;
}
catch (Exception e)
{
retriesCounter++;
if (retriesCounter > this.MaxRetries) throw;
Console.WriteLine(
"Exception during attempt {0} of calling method {1}.{2}: {3}",
retriesCounter, args.Method.DeclaringType, args.Method.Name, e.Message);
}
}
}
}
The only way I know how to do this is with PostSharp. It post-processes your IL and can do things like what you asked for.
You need some sort of Aspect oriented framework. PostSharp will do it, as will Windsor.
Basically, they subclass your object and override this method...
then it becomes:
//proxy
public override void DoSomeStuff()
{
if(MethodHasTriggerAttribute)
Trigger();
_innerClass.DoSomeStuff();
}
of course all this is hidden to you. All you have to do is ask Windsor for the type, and it will do the proxying for you. The attribute becomes a (custom) facility I think in Windsor.
You can use ContextBoundObject and IMessageSink. See http://msdn.microsoft.com/nb-no/magazine/cc301356(en-us).aspx
Be warned that this approach has a severe performance impact compared with a direct method call.
I don't think there is a way to do it with just an attribute, but using proxy classes and reflection you could have a class that knows to intercept instantiations of the classes in which you have attributed methods.
Then the proxy class can trigger an event whenever the attributed methods are called.
An attribute gives information, they are metadata. I don't know of a way to do this offhand, someone might.
You could look at partial methods in .NET which allow you to do some lightweight event handling. You provide the hooks and let someone else handle the implementation. If the method isn't implemented the compiler just ignores it.
http://msdn.microsoft.com/en-us/library/wa80x488.aspx
You might take a look at the poor man's solution: see the decorator pattern.
I am writing a method in c# class as shown below:
using(sftpClient)
{
sftpClient.Connect();
try{
//Do some process
}
catch(Exception ex)
{
}
sftpClient.Disconnect();
}
I need to create some more methods similar to the above but the logic changes only inside the try{} catch{} block. Can anyone suggest some best way to achieve this using some design pattern?
You could create an abstract base class:
abstract class MyBaseClass {
protected abstract void DoSomething();
public void DoSmtpStuff() {
smtpClient.Connect();
try {
DoSomething();
} catch (Exception ex) {
}
smtpClient.Disconnect();
}
}
and then just create inheritances of that class, which implement only the DoSomething method.
Take a look at the Strategy Pattern (emphasis my own):
In computer programming, the strategy pattern (also known as the
policy pattern) is a software design pattern that enables an
algorithm's behavior to be selected at runtime.
So basically, you would declare an interface, say, IBehaviour and define some method:
public interface IBehaviour
{
void Process();
}
Then have a different class implement IBehaviour for each piece of logic you want to have.
The class where you need to consume the logic would then allow passing an IBehaviour object and in your try block just do behaviour.Process().
This will allow you to set up the behaviour from outside the class and then simply pass it along to the class in which you want to actually do something with it.
Alternative to classes is just take Action as argument:
TResult WithSftpClient<TResult>(Func<TResult, SftpClient> operation)
{
TResult result = default(TResult);
// Note that one may need to re-create "client" here
// as it is disposed on every WithSftpClient call -
// make sure it is re-initialized in some way.
using(sftpClient)
{
sftpClient.Connect();
try
{
result = operation(sftpClient);
}
catch(Exception ex)
{
// log/retrhow exception as appropriate
}
// hack if given class does not close connection on Dispose
// for properly designed IDisposable class similar line not needed
sftpClient.Disconnect();
}
return result;
}
And use it:
var file = WithSftpClient(client => client.GetSomeFile("file.name"));
You can use this pattern:
abstract class ProcedureBase<T>
{
public T Work()
{
using(sftpClient)
{
sftpClient.Connect();
try{
ProtectedWork();
}
catch(Exception ex)
{
}
sftpClient.Disconnect();
}
}
protected abstract T ProtectedWork();
}
class Procedure1 : ProcedureBase<TypeToReturn>
{
protected override TypeToReturn ProtectedWork()
{
//Do something
}
}
class Procedure2 : ProcedureBase<AnotherTypeToReturn>
{
protected override AnotherTypeToReturn ProtectedWork()
{
//Do something
}
}
Usage:
static void Main(string[] args)
{
Procedure1 proc = new Procedure1();
proc.Work();
}
Is there a way in C# or .NET in general to create an attribute on a method which triggers an event when the method is invoked? Ideally, I would be able to run custom actions before and after the invocation of the method.
I mean something like this:
[TriggersMyCustomAction()]
public void DoSomeStuff()
{
}
I am totally clueless how to do it or if it possible at all, but System.Diagnostic.ConditionalAttribute might do a similar thing in the background. I am not sure though.
EDIT: I forgot to mention that due to the circumstances of my specific case, performance is not really an issue.
This concept is used in MVC web applications.
The .NET Framework 4.x provides several attributes which trigger actions, e.g.: ExceptionFilterAttribute (handling exceptions), AuthorizeAttribute (handling authorization). Both are defined in System.Web.Http.Filters.
You could for instance define your own authorization attribute as follows:
public class myAuthorizationAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
// do any stuff here
// it will be invoked when the decorated method is called
if (CheckAuthorization(actionContext))
return true; // authorized
else
return false; // not authorized
}
}
Then, in your controller class you decorate the methods which are supposed to use your authorization as follows:
[myAuthorization]
public HttpResponseMessage Post(string id)
{
// ... your code goes here
response = new HttpResponseMessage(HttpStatusCode.OK); // return OK status
return response;
}
Whenever the Post method is invoked, it will call the IsAuthorized method inside the myAuthorization Attribute before the code inside the Post method is executed.
If you return false in the IsAuthorized method, you signal that authorization is not granted and the execution of the method Post aborts.
To understand how this works, let's look into a different example: The ExceptionFilter, which allows filtering exceptions by using attributes, the usage is similar as shown above for the AuthorizeAttribute (you can find a more detailed description about its usage here).
To use it, derive the DivideByZeroExceptionFilter class from the ExceptionFilterAttribute as shown here, and override the method OnException:
public class DivideByZeroExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception is DivideByZeroException)
{
actionExecutedContext.Response = new HttpResponseMessage() {
Content = new StringContent("A DIV error occured within the application.",
System.Text.Encoding.UTF8, "text/plain"),
StatusCode = System.Net.HttpStatusCode.InternalServerError
};
}
}
}
Then use the following demo code to trigger it:
[DivideByZeroExceptionFilter]
public void Delete(int id)
{
// Just for demonstration purpose, it
// causes the DivideByZeroExceptionFilter attribute to be triggered:
throw new DivideByZeroException();
// (normally, you would have some code here that might throw
// this exception if something goes wrong, and you want to make
// sure it aborts properly in this case)
}
Now that we know how it is used, we're mainly interested in the implementation. The following code is from the .NET Framework. It uses the interface IExceptionFilter internally as a contract:
namespace System.Web.Http.Filters
{
public interface IExceptionFilter : IFilter
{
// Executes an asynchronous exception filter.
// Returns: An asynchronous exception filter.
Task ExecuteExceptionFilterAsync(
HttpActionExecutedContext actionExecutedContext,
CancellationToken cancellationToken);
}
}
The ExceptionFilterAttribute itself is defined as follows:
namespace System.Web.Http.Filters
{
// Represents the attributes for the exception filter.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
Inherited = true, AllowMultiple = true)]
public abstract class ExceptionFilterAttribute : FilterAttribute,
IExceptionFilter, IFilter
{
// Raises the exception event.
// actionExecutedContext: The context for the action.
public virtual void OnException(
HttpActionExecutedContext actionExecutedContext)
{
}
// Asynchronously executes the exception filter.
// Returns: The result of the execution.
Task IExceptionFilter.ExecuteExceptionFilterAsync(
HttpActionExecutedContext actionExecutedContext,
CancellationToken cancellationToken)
{
if (actionExecutedContext == null)
{
throw Error.ArgumentNull("actionExecutedContext");
}
this.OnException(actionExecutedContext);
return TaskHelpers.Completed();
}
}
}
Inside ExecuteExceptionFilterAsync, the method OnException is called. Because you have overridden it as shown earlier, the error can now be handled by your own code.
There is also a commercial product available as mentioned in OwenP's answer, PostSharp, which allows you to do that easily. Here is an example how you can do that with PostSharp. Note that there is an Express edition available which you can use for free even for commercial projects.
PostSharp Example (see the link above for full description):
public class CustomerService
{
[RetryOnException(MaxRetries = 5)]
public void Save(Customer customer)
{
// Database or web-service call.
}
}
Here the attribute specifies that the Save method is called up to 5 times if an exception occurs. The following code defines this custom attribute:
[PSerializable]
public class RetryOnExceptionAttribute : MethodInterceptionAspect
{
public RetryOnExceptionAttribute()
{
this.MaxRetries = 3;
}
public int MaxRetries { get; set; }
public override void OnInvoke(MethodInterceptionArgs args)
{
int retriesCounter = 0;
while (true)
{
try
{
args.Proceed();
return;
}
catch (Exception e)
{
retriesCounter++;
if (retriesCounter > this.MaxRetries) throw;
Console.WriteLine(
"Exception during attempt {0} of calling method {1}.{2}: {3}",
retriesCounter, args.Method.DeclaringType, args.Method.Name, e.Message);
}
}
}
}
The only way I know how to do this is with PostSharp. It post-processes your IL and can do things like what you asked for.
You need some sort of Aspect oriented framework. PostSharp will do it, as will Windsor.
Basically, they subclass your object and override this method...
then it becomes:
//proxy
public override void DoSomeStuff()
{
if(MethodHasTriggerAttribute)
Trigger();
_innerClass.DoSomeStuff();
}
of course all this is hidden to you. All you have to do is ask Windsor for the type, and it will do the proxying for you. The attribute becomes a (custom) facility I think in Windsor.
You can use ContextBoundObject and IMessageSink. See http://msdn.microsoft.com/nb-no/magazine/cc301356(en-us).aspx
Be warned that this approach has a severe performance impact compared with a direct method call.
I don't think there is a way to do it with just an attribute, but using proxy classes and reflection you could have a class that knows to intercept instantiations of the classes in which you have attributed methods.
Then the proxy class can trigger an event whenever the attributed methods are called.
An attribute gives information, they are metadata. I don't know of a way to do this offhand, someone might.
You could look at partial methods in .NET which allow you to do some lightweight event handling. You provide the hooks and let someone else handle the implementation. If the method isn't implemented the compiler just ignores it.
http://msdn.microsoft.com/en-us/library/wa80x488.aspx
You might take a look at the poor man's solution: see the decorator pattern.
I want to have an attribute like this for Cross Cutting Concerns like Logging , Exception , ...
public class MyService
{
[Log] // Interception (AOP)
[ExceptionHandler] // Interception (AOP)
public void DoSomething()
{
}
}
I know that I can write these codes with postsharp but I want to write these interceptions with free libraries like Castle Core and ...
Can anyone help me and write a sample for these purpose ???
I need a very simple sample for learning concepts
Autofac is a free IoC container. I use Autofac with Autofac.Extras.DynamicProxy2 nuget, docs.
Assuming you know why and when to (and not to) use interceptors, and you want to intercept some functionality:
public class FooService : IFooService
{
public void MoreFoo()
{
DoSomething();
}
public void LessFoo()
{
DoSomethingElse();
}
}
It needs to be "wired". I like attributes as you don't need to explicitly specify the interceptor at IoC container wiring. You just specify an attribute to watch out for:
[Intercept(typeof(Logger)]
public class FooService : IFooService { ... }
and wire it:
var builder = new ContainerBuilder();
builder.RegisterType<FooService>()
.EnableClassInterceptors();
Then create your Logger interceptor in another file:
class Logger : IInterceptor
{
public void Intercept(IInvocation invocation) // implements the IInterceptor interface
{
_loggerService.Log("calling " + invocation.Method.Name);
invocation.Proceed();
_loggerService.Log("finished " + invocation.Method.Name);
}
}
As you can see, you can create timers, try-catch blocks, and much more. Database context and other disposable resources is an interesting one:
class Logger : IInterceptor
{
public void Intercept(IInvocation invocation) // implements the IInterceptor interface
{
using (var someThing = new SomeResource())
{
invocation.Proceed();
}
}
}
Usually with such a resource you need to use someThing inside your method. That's a topic for another question! (see invocation.SetArgumentValue or invocation.TargetType.GetProperties() to communicate to the enclosing class. I'm not 100% comfortable with this, so some comments from others would be helpful)
Then, take a logging as an example:
void ManageFoo()
{
// sorry for the messy code, what else can I do?!
_logger("more foo please");
_fooService.MoreFoo();
_logger("less foo please");
_fooService.LessFoo();
_logger("enough foo");
}
The actual concern of the ManageFoo method is lost in all the mess of logging (add security and other concerns and you can end up with a big mess).
Now you can rewrite it like this:
void ManageFoo()
{
_fooService.MoreFoo();
_fooService.LessFoo();
}
Java has AOP with aspectJ and weaving (LTW load time with a proxy, and complile time CTW)
C# (Castle) has intersceptors, that use a (dynamic) proxy as well. You can see it as the LTW variant.
I used this setup in c#.
It is no big magic, and quite limited code.
Autofac 5.1.0
Autofac.Extras.DynamicProxy 5.0.0
Castle.Core 4.4.0
The trick is to
define some attibute, that you use as intersceptor attribute
define a intersceptor, that checks for the attribute on the method called
define a interface with a method and the attribute on the interface method
define implementation class of the interface
register the whole setup with autofac
test/run/go
1) define some attibute
using System;
[AttributeUsage(
AttributeTargets.Method,
AllowMultiple = true)]
public class SomeAttribute : Attribute
{
public long Id { get; set; }
}
2) Define a Castle dynamic intersceptor (aka proxy)
using Castle.DynamicProxy;
using System;
public class SomeInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (Attribute.IsDefined(invocation.Method, typeof(SomeAttribute)))
{
Console.Write("Method called: " + invocation.Method.Name);
}
invocation.Proceed();
}
}
Now, create a object with a interface (dont forget, put the attribute on the interface, not on the impl!)
3) define a interface
public interface AOPTest
{
[Some(Id = 10)]
void DoSomething();
}
4) define implementation :
public class AOPTestImpl : AOPTest
{
public void DoSomething()
{
}
}
5) register the whole setup with autofac
builder.RegisterType<AOPTestImpl>()
.As<AOPTest>()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(SomeInterceptor));
builder.RegisterType<SomeInterceptor>().AsSelf();
6) test/run/go : run the whole setup:
using Autofac;
using Autofac.Extras.DynamicProxy;
using (var scope = bootstrap.BootStrap.Container.BeginLifetimeScope())
{
var aOPTest = scope.Resolve<AOPTest>();
aOPTest.DoSomething();
}
I dont know how it excactly works but the idea is:
interface -> proxy -> implementation
So if you call the implementation over the interface, the proxy/intersceptor is in between.
Note: If you call other code inside the doSomething() method that needs intersception as well, you probably need a autofac class intersceptor EnableClassInterceptors
Note: it is not the fastest solution in the world. Probably some filtering intersceptor is faster, and compile time weaving like Fody or PostSharp are probably faster. But this will do a lot of times.
Note: if you need something done #Before start of the method, code it before the invocation.Proceed(); If you need something done at the end, code it if #After the invocation.Proceed() call:
#Before
DoSomething(){...}
#After
This lib does what you need https://github.com/pamidur/aspect-injector
[LogCall]
public void Calculate()
{
Console.WriteLine("Calculated");
}
ps. shameless self-ad
if you want to use runtime aop , you can try https://fs7744.github.io/Norns.Urd/index.html
it is very simple, a Interceptor like:
public class ConsoleInterceptor : AbstractInterceptor
{
public override async Task InvokeAsync(AspectContext context, AsyncAspectDelegate next)
{
Console.WriteLine($"{context.Service.GetType().GetReflector().FullDisplayName}.{context.Method.GetReflector().DisplayName}");
await next(context);
}
}
I would like to automagically add the following code around the body of some methods:
try
{
// method body
}
catch (Exception e)
{
throw new MyException("Some appropriate message", e);
}
I am working with PostSharp 1.0 and this is what I've done at the moment:
public override void OnException(MethodExecutionEventArgs eventArgs)
{
throw new MyException("Some appropriate message", eventArgs.Exception);
}
My problem is that I can see the PostSharp OnException call in the stack.
What would be the good practice to avoid this and get the same call stack as implementing by hand the exception handler?
There is no way to hide "OnException" from the call stack.
Two things working in tandem will allow you to do this:
The fact that Exception.StackTrace is virtual
The use of the skipFrames parameter to the StackFrame constructor. This is not required, but makes things easier
The below example demonstrates how to customize the stack trace. Note that I know of no way to customize the Exception.TargetSite property, which still gives the details of the method from which the exception originated.
using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// exception is reported at method A, even though it is thrown by method B
MethodA();
}
private static void MethodA()
{
MethodB();
}
private static void MethodB()
{
throw new MyException();
}
}
public class MyException : Exception
{
private readonly string _stackTrace;
public MyException()
{
// skip the top two frames, which would be this constructor and whoever called us
_stackTrace = new StackTrace(2).ToString();
}
public override string StackTrace
{
get { return _stackTrace; }
}
}
}