How to add SqlAzure retry logic to OrmLite operations? - c#

I would like to make the retry logic transparent, ideally utilizing Microsoft's Transient Fault Handling Application Block, instead of wrapping every database-accessing piece of my code into a function that retries.
What I can do is creating a custom IDbConnectionFactory
that produces custom IDbConnection objects of type MySqlAzureConnection:
MySqlAzureConnection dbConn = myConnFactory.OpenDbConnection();
dbConn.Insert(new Employee { ... });
I have two choices:
Add an .Insert() method to MySqlAzureConnection to hide
the same extension method of OrmLite, to provide my retry logic.
Actually my .Insert() will contain exactly the same source code
as in OrmLite: call dbConn.Exec(), but that .Exec() will be
my implementation that provides the retry logic.
The problem is that (in order to be sure that queries and writes
in my program always use the retry logic) this way I will end up
with copy&pasting all the 120+ methods in the
[OrmLite][Read|Write]ConnectionExtensions static classes,
just to extend the behaviour of the very single dbConn.Exec().
Not sounds too good.
Omit using ServiceStack.OrmLite; to make sure that the non-retrying
implementations of OrmLite won't get called. In this case how can I use
OrmLite? I'll have to write full namespace-qualified names all the time.
Sounds terrible, too.
EDIT:
I realized that there's a third choice: giving up the requirement of
the retry logic being 'transparent'. In other words, admit the explicit use
of a wrapper function at every piece of code that uses OrmLite, and
implement the retry logic in that wrapper function. In fact, the Transient Fault Handling Application Block
does the very same thing: introduces ExecuteCommand(), a new method
(non-standard in an IDbConnection) and makes the developer responsible
for using it as a high-level wrapper around any database-accessing code.
Whilst this solution sounds better than the first two, I'm still not
satisfied with it. The Entity Framework (6.0) has managed to make
this resiliency transparent, and I'm looking forward to a similiar
solution here. (It would be easy to wire into OrmLite's
ReadConnectionExtensions.Exec() method – if it weren't a static extension
method. Even better is an injectable module, as done in the Entity Framework)
.

Did some further research on this and it turns out that transient error handling is now built into SqlConnection under the hood from .Net 4.6.1 onwards. Therefore as a raw Ado.net SqlConnection underpins Ormlite any custom approach should be rendered unnecessary.
Dan

Related

Good practice for making service calls

I'm working on a project that relies extensively on Exchange Web Services. As of now I'm wrapping all of my service calls on try/catch. While this isn't a problem per say it does clutter code quite a bit by having one line turn into 10~.
Here are the options I see:
Create a function such as bool TryExecute(Action action, Action failCallback)
Interface all of my service calls and use an interceptor to wrap my calls
Are these any alternatives that I'm missing?
that depends on your implementation. I would place the try/catch as near to the point where failure is expected (and can be gracefully handeled) as possible.
For example wrapping those calls into a interface (for testing) and using only a common exception-type otherwise (for example handle EndpointNotFound and wrap any unexpected failure into a ExchangeCommunication-Exception you created yourself).
Both of your options seems to handle every kind of error, and I would not advise this but aside from that it's surely better than going against DRY

Untestable Braintree API: Should I alter the source code or individually wrap every class? [duplicate]

This question already has answers here:
Instancing a class with an internal constructor
(9 answers)
Closed 8 years ago.
I am working with the Braintree API for .NET to take care of processing payments. Their business does a fine job of processing payments and the API wrapper works for straightforward use. However, the provided API wrapper begins to fail quickly upon closer investigation or more strenuous use; for example, it contains hand-rolled enums. My problem comes with unit testing my code that uses this wrapper.
In order to do this, I essentially need to mock up my own 'fake' Braintree gateway that will have some known values in it, generate errors when requested, etc. My plan of attack was to override the functionality of the Braintree API wrapper and reroute the requests to a local in-memory endpoint. Then I could use dependency injection to link up the proper gateway/wrapper at runtime.
Initially, it seemed to be going swimmingly: despite the sins against software engineering that had been committed in the API wrapper, every method that I would need to override was miraculously marked virtual. However, that came to a screeching halt: almost constructor in the API wrapper is marked internal. As such, I can neither inherit off of these classes nor create them at whim to store for testing.
An aside: I grok internal constructors, and the reasons that one would legitimately want to use them. However, I have looked at the source code for this, and every internal constructor performs only trivial property assignments. As such, I am comfortable in claiming that a different coding practice should have been followed.
So, I'm essentially left with three options:
Write my own API wrapper from scratch. This is obviously doable, and holds the advantage that it would yield a well-engineered infrastructure. The disadvantages, however, are too numerous to list briefly.
Pull the source code from the API down and include it in my solution. I could change all of the internal constructors to be whatever I need to make them work. The disadvantage is that I would have to re-update all of these changes upon every subsequent API wrapper release.
Write wrapper classes for every single object that I need to use in the whole API wrapper. This holds the advantage of not altering the provided source code; the disadvantages are large, though: essentially rewriting every class in the wrapper three times (an interface, a Braintree API wrapper adapter, and a testable version).
Unfortunately, all of those suck. I feel like option 2 may be the least bad of the options, but it makes me feel dirty. Has anyone solved this problem already/written a better, more testable wrapper? If not, have I missed a possible course of action? If not, which of those three options seems least distasteful?
Perhaps this stackoverflow entry could help
Also, A random blog entry on the subject
Since you're not testing their API, I would use a Facade pattern. You don't need to wrap everything they provide, just encapsulate the functionality that you're using. This also gives you an advantage: If you decide to ditch that API in the future, you just need to reimplement your wrapper.

How to programmatically insert code into assembly

I have an .net assembly at C#. I have both: binary and source which has no logger, for example.
All I need is to insert property which will be initialised specific logger. Then I need to introduce logger invoker in all methods. The first way - is manually write property and their invokes. And the second way - is to write another class\method (I suppose in the same assembly) which will do it automatically.
Is it possible? Any suggestions?
I think it is possible, cause it was one of the questions at the interview. But there is no proof that this is possible, and they wanted to hear "no, do this manually".
This is what we call in architectural terms a 'cross cutting concern'. Logging is something that straddles many aspects of an application.
There are features to take care of it in the Microsoft Enterprise Library. The part you want is the Policy Injection library. You can then specify, in the config, methods to match (based on method name/structure) and a function to be called. In this way you can include logging as a proper cross-cutting concern of your app, rather than something which must be manually coded into every method.
It is not possible to alter the execution of a method without altering the source code and recompiling. You could write a wrapper class that would expose all classes and methods which would first call your logger and then the methods, but that's not what they asked.
So the answer to their question is 1. is possible, 2. isn't possible, and if you would have to add logging support, you would need to add it to each method manually.

Tool to create mock from a real execution

I'm working on this ,let's call it legacy, code that makes calls to another component using an interface (IFjuk).
I realize that mocking is generally intended for unit testing, but I thought it might be useful for a form of "system test". My primary goal is to get rid of a dependency on a piece of external hardware.
The execution makes many calls to IFjuk, which would make it cumbersome to manually write and maintain code that defines the mock expectations.
One idea I have is to use Castle Dynamic Proxy to record calls (including return values from the real component) and generate C# code from that which defines RhinoMock mocks, but I suspect someone must have built something similar already...
Is there a tool that can record calls and responses to IFjuk against the actual component, so that I can use that data to generate mocks?
No there is no any builtin "call tracer" available, but I think this is one of the place where AOP http://www.c-sharpcorner.com/uploadfile/shivprasadk/aspect-oriented-programming-in-C-Sharp-net-part-i/ can become very useful.

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) .

Categories