Tuesday, 1 March 2016

Event handlers and Pre/Post methods AX7

In legacy X++, it was possible to prescribe in metadata that certain methods were to be executed prior to and after the execution of a method. The information about what subscribes call was recorded on the publisher, which isn’t useful in the Dynamics AX environment. It’s now possible to provide Pre and Post handlers through code, by providing the SubscribesTo attribute on the subscribers.

Example

[PreHandlerFor(classStr(MyClass2), methodstr(MyClass2, publisher))]
  public static void PreHandler(XppPrePostArgs arguments)
  {
    int arg = arguments.getArg("i");
  }

  [PostHandlerFor(classStr(MyClass2), methodstr(MyClass2, publisher))]
  public static void PostHandler(XppPrePostArgs arguments)
  {
    int arg = arguments.getArg("i");
    int retvalFromMethod = arguments.getReturnValue();
  }

  public int Publisher(int i)
  {
    return 1;
  }
This example shows a publishing method called Publisher. Two subscribers are enlisted with the PreHandlerFor and PostHandlerFor. The code shows how to access the variables, and the return values.

Note: This feature is provided for backward compatibility and, because the application code doesn’t have many delegates, to publish important application events. Pre and Post handlers can easily break as the result of added or removed parameters, changed parameter types, or because methods are no longer called, or called under different circumstances.
Attributes are also used for binding event handlers to delegates:

  [SubscribesTo(
    classstr(FMRentalCheckoutProcessor),  
    delegatestr(FMRentalCheckoutProcessor, RentalTransactionAboutTobeFinalizedEvent))]
  public static void RentalFinalizedEventHandler(
    FMRental rentalrecord, Struct rentalConfirmation)
  {
  }

  delegate void RentalTransactionAboutTobeFinalizedEvent(
    FMRental fmrentalrecord, struct RentalConfirmation)
  {
  }
In this case, the SubscribesTo attribute specifies that the method RentalFinalizedEventHandler should be called when the FmRentalCheckoutProcessor.RentalTransactionAboutToBeFinalizedEvent delegate is called.
Since the binding between the publisher and subscribers is done through attributes, there’s no way of specifying the sequence in which subscribers are called.

No comments:

Post a Comment