Database Controller API with AOP Try Catch - c#

I am in the process of creating an api for database operations where I have to wrap every function call in the api with a try catch. I am basically trying to get the same functionality as decorators in python.
I read a bunch of articles and this one seemed like the best example to follow: http://ayende.com/blog/3474/logging-the-aop-way. A problem I have with it is that after resolving the container with the interface of functions that need to be wrapped, you have to make a call on the resolved container to call one of those functions.
I would like the user of my controller to be able to just make a call to my class which implements the above interface and know nothing about what I have done internally as far as the try catch business.
Is this possible?
I apologize if the solution is simple, I haven't had much experience with C#.
Thanks.

If you can spend a few bucks on PostSharp, here is one way to accomplish this:
[Serializable]
public class PrintAndIgnoreExceptionAttribute : OnExceptionAspect
{
public override void OnException(MethodExecutionArgs args)
{
Console.WriteLine(args.Exception.Message);
args.FlowBehavior = FlowBehavior.Return;
}
}
Then you use [PrintAndIgnoreException] to decorate your methods which need to be covered. PostSharp is also the best performing of all AOP frameworks, because the extra code is weaved in post-compilation, so there is no run-time penalty. I don't work for them, I just use it in pretty much everything I do these days.

Related

Inheritance with functions?

I'm aware of inheritance with classes (obviously) but I want to know if the behaviour can be replicated within functions?
I have a situation where all methods need to implement some logic before being called, and rather than duplicate the code across all functions, I want to know if there's some way to inherit a base function or something similar that executes before the rest of the function processes?
Is this possible with C#?
For example, I have the following methods:
public void MyFunction1 {
if(debug)
return;
MyProductionApi.DoSomething();
}
public void MyFunction2 {
if(debug)
return;
MyProductionApi.DoSomethingElse();
}
As you see from above, my scenario basically involves checking whether I'm in development so I can avoid expensive 3rd party API calls. I just want to skip over them if I'm testing, but want to avoid writing a check for each method as there are a large number of functions.
Ideally I could create some base functionality that executes the check that I can inherit from, but I don't know if this is possible?
I want to know if there's some way to inherit a base function or
something similar that executes before the rest of the function
processes?
You don't need necessarily inheritance to solve the problem of repeating the code. You could also pass the function as parameter to an other function, doing some basic jobs before calling it. You can do it like
public void MyFunction(Action a)
{
if(debug)
return;
a();
}
and call it like
MyFunction(MyProductionApi.DoSomething);
This solves your scenario of
I just want to skip over them if I'm testing
in a very simple way without complicated structures or inheritance.

Better way to add logging or a method that needs to occur in every function?

Is there a better way to log or add a method calls to a series of functions without explicitly adding in the function calls?
For example I have a class like:
public class MyClass
{
public void DoStuff()
{
doSomethingEnter();
//MyCode
doSomethingExit();
}
public void DoStuff_2()
{
doSomethingEnter();
//MyCode
doSomethingExit();
}
}
doSomethingEnter() and doSomethingExit() can be logging calls or events calling other things that need to occur on function start and end.
I have read on Aspect Oriented Programming that allows me to do something like this:
public class MyClass
{
[DoSomethingEnterExit]
public void DoStuff()
{
//MyCode
}
}
But is there a pattern or framework that allows me to do something similar without having to buy an AOP framework like PostSharp?
Thanks.
EDIT
I have also looked into doing sort of a facade to make sure stuff always gets called with a master method that has the entry and exit functions.
public class MyFacade
{
public void MasterMethod(string methodName)
{
doSomethingEnter();
if(methodName == "DoStuff")
{
MyClass.DoStuff();
}
else
{
MyClass.DoStuff_2();
}
doSomethingExit();
}
}
Use AOP (Aspect Oriented Programming) to inject logging into your code transparently at compile time.
PostSharp is an AOP library for .Net and it uses reflection Attributes to allow you to put markers (aspects) in your code, then a pre-compiler locates those markers and replaces them with the actual code.
Disclosure: I'm not affiliated with PostSharp, but have used it before in some of my projects.
Edit:
As far as I remember, there is still a free and open source version of PostSharp that will work for the logging scenario.
I haven't heard of other AOP libraries in .Net ecosystem.
Castle Windsor offers interceptors that will do this for you. If you don't want to use an entire IoC framework just for this, you could go straight to DynamicProxy to achieve the same thing. However, having an IoC container handle the wiring is nice and neat.
You could also consider using the Decorator pattern. However, this often results in significant proliferation of code if the concerns are many.
A drawback to consider when using interception or decoration is that the additional concerns each pattern adds are transparent. This is great for reducing the noise but can be difficult to debug or enhance if those supporting the code are unaware or unfamiliar with the concepts.
An additional drawback, as highlighted by #Bishoy in the comments below, is that these are run-time solutions that may have an impact on performance that the 'static' approaches do not.

How do I remove dependencies to 3rd party code when unit testing?

I've got some code that performs some legacy 'database' operation and then processes the result. I want to write a unit test that checks the method that calls the legacy code without interacting with the 'database'.
My code looks something like this:
public static bool CallRoutine(LegacySession session, /* routine params*/)
{
try
{
LegacyRoutine routine = session.CreateRoutine(/* routine params */);
routine.Call();
// Process result
}
catch (LegacyException ex)
{
// Perform error handling
}
}
Were this all my code, I would create interfaces that the LegacySession and LegacyRoutine implement and then write unit tests that use mock implementations of those interfaces using MOQ or something similar. The problem is that I don't have access to the code for LegacyRoutine or LegacySession so I can't make them implement an interface.
Any ideas about how I could do this without changing the production code too much?
If you can't access LegacyRoutine (i'm guessing it's in a referenced DLL), why not just create a wrapper for it, then flick on/off different implementations:
public interface ILegacyWrapper
{
ILegacyRoutine CreateRoutine();
// etc etc
}
public interface ILegacyRoutine
{
// put members of LegacyRoutine
}
Know what i mean? Just mock everything out into wrappers/interfaces.
Then you could go:
ILegacyRoutine routine = session.CreateRoutine(/* routine params */)
Where session would be declared as an ILegacyWrapper, but implemented with a mock concrete.
Also, it goes without saying (but i'll say it anyway), you should consider a DI framework to make your life simpler. Otherwise you'll end with IFoo foo = new Foo() (hard-coded injection) all over the place.
StructureMap is my DI poison of choice.
HTH
You could write a thin wrapper over their API for which you did have an interface. Whether that's a practical thing to do or not rather depends on the size of the API.
Search for C# mock concrete types. Sorry, I have to run, but here's a link to the first thing I found that will solve your problem (there may be better solutions, but this looks OK):
http://docs.typemock.com/isolator/##typemock.chm/Documentation/CreatingFakesWithAAA.html
Also, check out Moq, which I've had great success with in the past
I would advise you to use a depedency injection framework. It helps you to make your classes more loosely copuled by breaking out external class dependencies into objects which are injected into your classes. These objects are often represented by an interface, which helps you to use different implementations in production and when testing. That way you won't have to actually call the external database when testing. I can recommend Ninject. It's makes dependency injection a lot easier than doing it manually.

C#: using type of "self" as generic parameter?

This may seem a bit odd, but I really need to create a workaround for the very complicated duplex - communication - handling in C#, especially to force other developers to observe the DRY - principle.
So what I'm doing is to have a type based multiton that looks like this:
internal sealed class SessionManager<T> where T : DuplexServiceBase
which is no problem at all - so far.
However, as soon as I want to have the services (I'm going with one instance per session) register themselves with the SessionManager, the hassle starts:
internal abstract class DuplexServiceBase : MessageDispatcherBase<Action>
(MessageDispatcherBase being a class of mine that creates a thread and asynchronously sends messages).
I want to have a method that looks like this:
protected void ProcessInboundMessage()
{
// Connect
SessionManager<self>.Current.Connect(this);
}
...but the problem is - how would I get to the "self"?
I really NEED separate session managers for each service class, because they all have their own notifications (basically it's the very annoying "NotifyAllClients" - method that makes we want to pull my own hair out for the last hours) and need to be treated separately.
Do you have ANY ideas?
I don't want to use "AsyncPattern = true", btw... this would require me to give up type safety, enforced contract compliance (this would lead to very bad abuse of the communication system I'm setting up here) and would require abandoning the DRY - principle, there would be a lot of repetitive code all over the place, and this is something I seriously frown upon.
Edit:
I have found the best possible solution, thanks to the answers here - it's an EXTENSION METHOD, hehe...
public static SessionManager<T> GetSessionManager<T>(this T sessionObject)
where T : DuplexServiceBase
{
return SessionManager<T>.Current;
}
I can use this like this:
GetSessionManager().Connect(this);
Mission accomplished. :-D
This method (belongs to DuplexServiceBase) gives me the session manager I want to work with. Perfect! :-)
I'd write a helper method:
static class SessionManager { // non-generic!
static void Connect<T>(T item) where T : DuplexServiceBase {
SessionManager<T>.Current.Connect(item);
}
}
and use SessionManager.Connect(this) which will figure it out automatically via generic type inference.
You could wrap the call in a generic method, thereby taking advantage of the compiler's type inference:
private static void ConnectSessionManager<T>(T service)
{
SessionManager<T>.Current.Connect(service)
}
protected void ProcessInboundMessage()
{
// Connect
ConnectSessionManager(this);
}

Use Attributes To Check Whether to Access a Method

I have a method that is only accessible if a certain criteria is fulfilled, if it's not, then the method won't be executed. Currently, this is how I code the thing:
public void CanAccessDatabase()
{
if(StaticClass.IsEligible())
{
return;
}
// do the logic
}
Now, this code is ugly because out of no where there is this if(StaticClass.IsEligible()) condition that is not relevant to the concern of the method.
So I am thinking about putting the IsEligible method in the attribute, so that my code will look like this. If the condition is not fulfilled, then this method will just return without executing the logic below.
[IsEligibleCheck]
public void CanAccessDatabase()
{
// do the logic
}
Eligibility is a runtime decision, of course.
Any idea on how to code up the logic for IsEligibleCheck ? Thanks
Edit: I know PostSharp can do this, but I am looking at something that works out of box, not depending on any third party library.
Any idea on how to code up the logic for IsEligibleCheck?
This is a perfect spot for AOP.
Edit: I know PostSharp can do this, but I am looking at something that works out of box, not depending on any third-party library.
Is Microsoft considered third-party? If not, you could look at Unity from their Patterns & Practices team. Look at the Interceptor mechanism in Unity.
Otherwise, you effectively have to roll your own implementation using reflection. Effectively what you have to do is wrap your objects in a proxy wherein the proxy uses reflection to check the attributes and interpret them appropriately. If IsEligibleCheck succeeds then the proxy invokes the method on the wrapped object. Really, it's easier to just reuse an already existing implementation.
My advice is just use Unity (or another AOP solution).
Unfortunately, attributes doesn't get executed at runtime. A handful of built-in attributes modify the code that gets compiled, like the MethodImpl attributes and similar, but all custom attributes are just metadata. If no code goes looking for the metadata, it will sit there and not impact the execution of your program at all.
In other words, you need that if-statement somewhere.
Unless you can use a tool like PostSharp, then you cannot get this done in out-of-the box .NET, without explicit checks for the attributes.
This looks like a perfect candidate for AOP. In a nutshell, this means that the CanAccessDatabase logic will live in an "aspect" or "interceptor", that is, separate from the business logic, thus achieving separation of concerns (the aspect is only responsible for security, business code is only responsible for business things).
In C#, two popular options for doing AOP are Castle.DynamicProxy and PostSharp. Each has its pros and cons. This question sums up their differences.
Here are other options for doing AOP in .Net, some of them can be done without 3rd-party libraries. I still recommend using either DynamicProxy, PostSharp, LinFu, Spring.AOP or Unity, other solutions are not nearly as flexible.
Custom attributes go hand in hand with Reflection.
You will need to create another class that is responsible for calling the methods in your CanAccessDatabase() class.
Using reflection, this new class will determine the attributes on each method. If the IsEligibleCheck attribute is found, it will perform the StatiClass.IsEligible() check and only call CanAccessDatabase() if the check passes.
Heres an introduction to doing this at MSDN. It revolves around using the MemberInfo.GetCustomAttributes() method.
Heres the pseudocode:
Get the Type of the CanAccessDatabase() class
Using this type, get all methods in this class (optionally filtering public, private etc).
Loop through the list of methods
Call GetCustomAttributes() on the current method.
Loop through the list of custom attributes
If the IsEligibleCheck attribute is found
If StaticClass.IsEligible is true
Call the current method (using MethodInfo.Invoke())
End If
End If
End Loop
End Loop
I know this is an old thread...
You can use the Conditional Attribute: http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx
"Indicates to compilers that a method call or attribute should be ignored unless a specified conditional compilation symbol is defined."
#define IsEligibleCheck // or define elsewhere
[Conditional("IsEligibleCheck")]
public void CanAccessDatabase()
{
// do the logic
}
check AOP that will help you a lot in this, one of the powerful components in the market is PostSharp

Categories

Resources