Code reuse in PostSharp's OnMethodBoundaryAspect leads to StackOverflowException - stack-overflow

I have written a custom OnMethodBoundaryAspect called TraceAspect. This aspect checks within the OnEntry, OnExit, and OnException methods whether tracing is enabled or not. I have a central class for reading and writing settings. Both of the two methods Settings.GetLoggingEnabled() and Settings.GetLogLevel() are called from the TraceAspect. They are there, so I reuse them which results in a StackOverflowException.
[assembly: MyCompany.MyProduct.TraceAspect]
[Serializable]
public class TraceAspect : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
if (Settings.GetLogginEnabled() && Settings.GetLogLevel() == LogLevel.Trace)
{
// Log the message
}
}
}
Applying the [TraceAspect(AttributeExclude = true)] attribute to the TraceAspect class leads to the same behaviour.
I could write something like this. But this is code duplication.
[assembly: MyCompany.MyProduct.TraceAspect]
[Serializable]
public class TraceAspect : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
if (this.GetLogginEnabled() && this.GetLogLevel() == LogLevel.Trace)
{
// Log the message
}
}
private bool GetLoggingEnabled()
{
// copy code from Settings.GetLogginEnabled()
}
private bool GetLogLevel()
{
// copy code from Settings.GetLogLevel()
}
}
How can I tell that the Settings.GetLoggingEnabled() and Settings.GetLogTrace() methods should not be traced, when they are called by the aspect?

You can break the recursion during logging by introducing a thread static flag to indicate that you're currently inside the logging call.
[Serializable]
public class TraceAspect : OnMethodBoundaryAspect
{
[ThreadStatic]
private static bool isLogging;
public override void OnEntry(MethodExecutionArgs args)
{
if (isLogging) return;
isLogging = true;
try
{
if (Settings.GetLogginEnabled() && Settings.GetLogLevel() == LogLevel.Trace)
{
// Log the message
}
}
finally
{
isLogging = false;
}
}
}

Related

ImagePicker MainActivity Instance is not defined

Followed the below link in adding the ImagePicker
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/photo-picker
Here, for Android Implementation the issue is Instance is not defined in the MainActivity.cs
[assembly: Dependency(typeof(PicturePickerImplementation))]
namespace DependencyServiceSample.Droid
{
public class PicturePickerImplementation : IPicturePicker
{
public Task<Stream> GetImageStreamAsync()
{
// Define the Intent for getting images
Intent intent = new Intent();
intent.SetType("image/*");
intent.SetAction(Intent.ActionGetContent);
// Start the picture-picker activity (resumes in MainActivity.cs)
MainActivity.Instance.StartActivityForResult(
Intent.CreateChooser(intent, "Select Picture"),
MainActivity.PickImageId);
// Save the TaskCompletionSource object as a MainActivity property
MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource<Stream>();
// Return Task object
return MainActivity.Instance.PickImageTaskCompletionSource.Task;
}
}
}
And the MainActivity doesn't have the Instance Field, Is there an alternate way to get the instance?
public class MainActivity : FormsAppCompatActivity
{
...
// Field, property, and method for Picture Picker
public static readonly int PickImageId = 1000;
public TaskCompletionSource<Stream> PickImageTaskCompletionSource { set; get; }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
base.OnActivityResult(requestCode, resultCode, intent);
if (requestCode == PickImageId)
{
if ((resultCode == Result.Ok) && (intent != null))
{
Android.Net.Uri uri = intent.Data;
Stream stream = ContentResolver.OpenInputStream(uri);
// Set the Stream as the completion of the Task
PickImageTaskCompletionSource.SetResult(stream);
}
else
{
PickImageTaskCompletionSource.SetResult(null);
}
}
}
}
To the MainActivity Class add this:
internal static MainActivity Instance { get; private set; }
protected override void OnResume()
{
Instance = this;
base.OnResume();
}
also thanks to #SushiHangover's answer here for describing how to initialize the Instance object.
The documentation is missing this, most likely.
You are missing a static variable definition and its assignment.
Add a static var named Instance to the MainActivity class:
public static Activity Instance;
and then in the OnResume override assign it:
protected override void OnResume()
{
Instance = this;
base.OnResume();
}

I am getting following error : "The following constructor parameters did not have matching fixture data: AddressValidator addressValidator"

ValidatorTest class having common methods for all the validations.
Test case get passed but after passing I am getting this error.
I can write extension methods which can do this job but I am not getting what is going wrong with xunit. Any help is appreciated.
namespace TestSuite.Validator
{
public abstract class ValidatorTest<TClass,TClassValidator> where TClassValidator: AbstractValidator<TClass>
{
private readonly TClassValidator _tClassValidator;
public ValidatorTest(TClassValidator validator)
{
_tClassValidator = validator;
}
public void Address_Should_ReturnValidationError_When_MandatoryFieldsAreNotPassed(TClass address, List<KeyValuePair<string, string>> expectedErrors)
{
var validationResult = _tClassValidator.Validate(address);
Assert.False(validationResult.IsValid);
foreach (var expectedError in expectedErrors)
{
Assert.Contains(validationResult.Errors, (actualError) => actualError.ErrorMessage.Equals(expectedError.Value) && actualError.ErrorCode.Equals(expectedError.Key));
}
foreach (var actualError in validationResult.Errors)
{
Assert.Contains<KeyValuePair<string, string>>(expectedErrors, expectedError => expectedError.Value.Equals(actualError.ErrorMessage) && expectedError.Key.Equals(actualError.ErrorCode));
}
}
public void Address_Should_Pass_When_MandatoryFieldsArePassed(TClass address)
{
var validationResult = _tClassValidator.Validate(address);
Assert.True(validationResult.IsValid);
Assert.Empty(validationResult.Errors);
}
}
}
namespace TestSuite.Validator
{
public class AddressValidatorTest : ValidatorTest<Address, AddressValidator>
{
public AddressValidatorTest(AddressValidator addressValidator) : base(new AddressValidator())
{
}
[Theory]
[JsonDataReaderAttribute("AddressValidatorData", "Valid")]
public void PositiveTest(Address address)
{
Address_Should_Pass_When_MandatoryFieldsArePassed(address);
}
}
}
I just had a similar error and it was because I forgot to implement IClassFixture on my test class.

PostSharp - args.ReturnValye = default(T) -> T = method return type, how?

My aspect:
[Serializable]
class FlowController : OnMethodBoundaryAspect
{
[ThreadStatic]
private static bool logging;
public override void OnEntry(MethodExecutionArgs args)
{
if (logging)
return;
try
{
logging = true;
if (ProgramState.State() == false)
{
args.ReturnValue = ""; // WHAT DO I SET HERE?
args.FlowBehavior = FlowBehavior.Return;
}
}
finally
{
logging = false;
}
}
}
Basically the ProgramState.State() method checks if the program is running(true),paused(loops while isPaused == true), stopped(false), this should control the if methods can run or not(basically a start pause/resume stop thing)
But sometimes i get nullreferences when returning from the method.
i am interested in knowing how can i set the return type to the default return type of the method.
It is tested with PostSharp 6.0.29
Before use it please check required null controls.
If method is async Task
public override void OnException(MethodExecutionArgs args)
{
var methodReturnType = ((System.Reflection.MethodInfo)args.Method).ReturnType;
var runtime = methodReturnType.GetRuntimeFields().FirstOrDefault(f => f.Name.Equals("m_result"));
//Only if return type has parameterless constructture (should be check before create)
var returnValue = Activator.CreateInstance(runtime.FieldType);
args.ReturnValue = returnValue;
}
And if method is not async
public override void OnException(MethodExecutionArgs args)
{
var methodReturnType = ((System.Reflection.MethodInfo)args.Method).ReturnType;
//Only if return type has parameterless constructture (should be check before create)
var returnValue = Activator.CreateInstance(methodReturnType);
args.ReturnValue = returnValue;
}
You can make your aspect class generic with the generic parameter representing the method return type. Then you need to create a method-level attribute that is also an aspect provider. The attribute will be applied to the user code and in turn it can provide the correct instance of the generic aspect.
[Serializable]
[MulticastAttributeUsage( MulticastTargets.Method )]
public class FlowControllerAttribute : MethodLevelAspect, IAspectProvider
{
public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
{
MethodInfo method = (MethodInfo) targetElement;
Type returnType = method.ReturnType == typeof(void)
? typeof(object)
: method.ReturnType;
IAspect aspect = (IAspect) Activator.CreateInstance(typeof(FlowControllerAspect<>).MakeGenericType(returnType));
yield return new AspectInstance(targetElement, aspect);
}
}
[Serializable]
public class FlowControllerAspect<T> : IOnMethodBoundaryAspect
{
public void RuntimeInitialize(MethodBase method)
{
}
public void OnEntry(MethodExecutionArgs args)
{
args.ReturnValue = default(T);
args.FlowBehavior = FlowBehavior.Return;
}
public void OnExit(MethodExecutionArgs args)
{
}
public void OnSuccess(MethodExecutionArgs args)
{
}
public void OnException(MethodExecutionArgs args)
{
}
}
// Usage:
[FlowController]
public int Method()
{
// ...
}

Delegate in Xamarin.iOS

I have a problem in creating class for xamarin.ios delegate.
In iOS we use protocols to implement the delegate but here I can not implement Interface as a delegate.
Let me clear this concept.
I have an interface in one file like:
public interface SendBackDelegate
{
void sendBackData();
}
public class SelectList
{
}
In other file I have main class like this:
public class ShowList: SendBackDelegate
{
public ShowList()
{
SelectList obj = new SelectList();
obj.delegate = this;
}
void sendBackData()
{
Console.WriteLine("Send Back DATA");
}
}
Now Can you please tell me how this interface be implemented in SelectList class?
Thanks
you can use Interface like protocol, only you have to make reference object of interfaces it can own the class object which already implemented the Interface methods. it will be clear with your example as well.
public interface SendBackDelegate
{
void sendBackData();
}
public class SelectList
{
ShowList showListObj = new ShowList();
SendBackDelegate delegate = showListObj;
delegate.sendBackData();
//this will call the method sendBackData() of class ShowList.
}
public class ShowList: SendBackDelegate
{
public ShowList()
{
SelectList obj = new SelectList();
obj.delegate = this;
}
void sendBackData()
{
Console.WriteLine("Send Back DATA");
}
}
Please let me know if you still have questions.
I am not using delegates anymore on Xamarin.iOS. I prefer to use actions though.
class MainClass
{
public static void Main (string[] args)
{
var x = new ShowList ();
}
}
public interface SendBackDelegate
{
void sendBackData ();
}
public class ShowList : SendBackDelegate
{
public ShowList ()
{
SelectList obj = new SelectList (sendBackData);
}
public void sendBackData ()
{
Console.WriteLine ("Send Back DATA");
}
}
public class SelectList
{
Action _callback;
public SelectList (Action callback)
{
_callback = callback;
Ticker ();
}
private void Ticker ()
{
_callback ();
}
}

dynamically register transaction listener with spring?

I have a springframework application in which I would like to add a transaction listener to a transaction which is currently in progress. The motivation is to trigger a post commit action which notifies downstream systems. I am using #Transactional to wrap a transaction around some service method -- which is where I want to create/register the post transaction listener. I want to do something "like" the following.
public class MyService {
#Transaction
public void doIt() {
modifyObjects();
// something like this
getTransactionManager().registerPostCommitAction(new
TransactionSynchronizationAdapter() {
public void afterCommit() {
notifyDownstream();
}
});
}
}
Spring has a TransactionSynchronization interface and adapter class which seems exactly what I want; however it is not immediately clear how to register one dynamically with either the current transaction, or the transaction manager. I would rather not subclass JtaTransactionManager if I can avoid it.
Q: Has anyone done this before.
Q: what is the simplest way to register my adapter?
Actually it was not as hard as I thought; spring has a static helper class that puts the 'right' stuff into the thread context.
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronizationAdapter() {
#Override
public void afterCommit() {
s_logger.info("TRANSACTION COMPLETE!!!");
}
}
);
you could use an aspect to match transactional methods aspect in your service to accomplish this:
#Aspect
public class AfterReturningExample {
#AfterReturning("execution(* com.mypackage.MyService.*(..))")
public void afterReturning() {
// ...
}
}
Here is a more complete solution I did for a similar problem that with wanting my messages sent after transactions are committed (I could have used RabbitMQ TX but they are rather slow).
public class MessageBusUtils {
public static Optional<MessageBusResourceHolder> getTransactionalResourceHolder(TxMessageBus messageBus) {
if ( ! TransactionSynchronizationManager.isActualTransactionActive()) {
return Optional.absent();
}
MessageBusResourceHolder o = (MessageBusResourceHolder) TransactionSynchronizationManager.getResource(messageBus);
if (o != null) return Optional.of(o);
o = new MessageBusResourceHolder();
TransactionSynchronizationManager.bindResource(messageBus, o);
o.setSynchronizedWithTransaction(true);
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new MessageBusResourceSynchronization(o, messageBus));
}
return Optional.of(o);
}
private static class MessageBusResourceSynchronization extends ResourceHolderSynchronization<MessageBusResourceHolder, TxMessageBus> {
private final TxMessageBus messageBus;
private final MessageBusResourceHolder holder;
public MessageBusResourceSynchronization(MessageBusResourceHolder resourceHolder, TxMessageBus resourceKey) {
super(resourceHolder, resourceKey);
this.messageBus = resourceKey;
this.holder = resourceHolder;
}
#Override
protected void cleanupResource(MessageBusResourceHolder resourceHolder, TxMessageBus resourceKey,
boolean committed) {
resourceHolder.getPendingMessages().clear();
}
#Override
public void afterCompletion(int status) {
if (status == TransactionSynchronization.STATUS_COMMITTED) {
for (Object o : holder.getPendingMessages()) {
messageBus.post(o, false);
}
}
else {
holder.getPendingMessages().clear();
}
super.afterCompletion(status);
}
}
}
public class MessageBusResourceHolder extends ResourceHolderSupport {
private List<Object> pendingMessages = Lists.newArrayList();
public void addMessage(Object message) {
pendingMessages.add(message);
}
protected List<Object> getPendingMessages() {
return pendingMessages;
}
}
Now in your class where you actually send the message you will do
#Override
public void postAfterCommit(Object o) {
Optional<MessageBusResourceHolder> holder = MessageBusTxUtils.getTransactionalResourceHolder(this);
if (holder.isPresent()) {
holder.get().addMessage(o);
}
else {
post(o, false);
}
}
Sorry for the long winded coding samples but hopefully that will show someone how to do something after a commit.
Does it make sense to override the transaction manager on the commit and rollback methods, calling super.commit() right at the beginning.

Resources