Friday, June 15, 2012

AX 2012 Eventing

Hello Dear Friends,

Today, I am going to talk on the event handling new mechanism introduced in AX 2012. You could do event handling in earlier versions too but in AX 2012, event handling is better than previous version. Now it uses the concepts of delegates, event handlers etc...

Everybody must have seen that there are very few customers that use out of the box AX without any customizations. I would say not even a single customer. All customers are required to customize AX to fulfill their business needs. Sometimes, customizations become so large that it becomes difficult to upgrade when Microsoft does make changes in the lower layer. Finally, it becomes cost/budget issue so event handling mechanism in AX 2012 will help to lower the cost of developing customizations and then upgrading these customizations.

Events are simple and powerful concept. In daily life, we encounter with so many events. Events can be used to support these programming paradigms.

  • Observation: Generate alerts to see exceptional behavior.
  • Information dissemination: To convey information to right people at right time.
  • Decoupling: Consumer doesn’t need to know about producer. Producer and Consumer can be sitting in totally different applications.
Terminology
AX 2012 events are based on .NET eventing concepts.

Producer: Object to trigger the event.
Consumer: Object to consume the event and process logic based on the event triggered.
Event: An action that needs to be triggered
Event Payload: Information that can go along with event.
Delegate: Definition that is passed to trigger an event. Basically, communicator between producer and consumer

Things to remember while using Events in AX2012
  • Delegate keyword to use in delegate method.
  • Public or any other accessibility specifier is not allowed in a delegate method.
  • Delegate Method return type must be void.
  • Delegate Method body must be empty.
  • A delegate declaration can have the same type of parameters as a method.
  • Event handlers can run only on the same tier as the publisher class of the delegate runs on.
  • Handler can be implemented either in X++ or in managed code.
  • Only static methods are allowed to be event handlers.
  • Delegate method can’t be called outside class. Basically, events can’t be raised outside class in which event is defined.
  • Event handlers for host methods can use one of two parameter signatures:
    • One parameter of the type XppPrePostArgs. Go through all the methods available in XppPrePostArgs.
    • The same parameters that are on the host method that the event handler subscribes to.

Now, let me show you how to use events in AX 2012.

1. Let’s create a class Consumer to create EventHandler (sendEmailToCustomer). This will be called once order is shipped so that email can be sent to customer to notify. It has to be static method.

2. Now let’s create Producer class where this event (sendEmailToCustomer) is called using Delegates. Add delegate by right clicking on Producer class > New > Delegate.
 

3. Change its name to delegateEmail (you can have any name). Parameter should be same as event handler method (sendEmailToCustomer) i.e. of type Email. Notice it has no body and is a blank method.

4. Now drag and drop sendEmailToCustomer method from Consumer class to delegateEmail.

5. Look at properties of EventHandler. You will notice it is pointing to Class Consumer and method sendEmailToCustomer

6. If order is not shipped, I am creating another event handler (errorLog) in Consumer class to log error into error log.

7. Create another delegate method (delegateErrorLog) in Producer class to call this event handler (errorLog)

8. Drag and drop event handler (errorLog) in delegate method (delegateErrorLog) similar to step 4.
9. Now let’s create main method in Producer class to ship order and let’s see how delegates can be used to trigger event handlers.

10. Suppose shipOrder method returns true. Now, if I run this main method, it should go into delegateEmail method and should trigger method sendEmailToCustomer. Let’s run and see the result. 11. Here is the result and it is as expected so it did trigger method sendEmailToCustomer.

12. Let’s suppose shipOrder method returns false. Now, if I run this main method, it should go into delegateErrorLog method and should trigger method errorLog. Let’s run and see the result.

13. Here is the result and it is as expected so it did trigger method errorLog.

14. Handlers can also be added/removed in x++.

Add Handler: It uses += sign.



Remove Handler: It uses -= sign.


15. Now, let’s  use addStaticHandler in main method. If you see the code, it is calling addStaticHandler before calling delegate method. If we run it and see the result, it should send 2 emails.


16. Here is the result as expected.


17. Similarly if we use removeStaticHandler method instead of addStaticHandler before calling delegate method then it will remove handler and will not send any email.

So, you can see that with the use of delegates and event handlers, it is so easy to trigger events. Also, it will be easy and less time consuming to upgrade it. Suppose if delegates are called from standard methods while doing customizations then it will be so easy to upgrade if standard methods are changed in next release because only 1 liner code of calling delegate method needs to be rearranged and no changes will be required in event handler methods.

Use of Pre and Post event handlers
In AX 2012, any event handler method can dropped in other method. If the property “CalledWhen” is set to “Pre” then it becomes pre event handler. If it is set to “Post” then it becomes post event handler. Pre event handler is called before the method under which it is dropped and Post event handler is called after method ends. These are so powerful that event handler method can be created in new class and can be dropped in any standard or any other method without changing a single line of code and can be set as pre or post event handler as per business need. Suppose, before creating a customer in AX, business need is to do some business logic then logic can be written in pre event handler and can be dropped in insert method of CustTable. Similarly, if there is post logic to be written after customer is created then post event handler can be created and dropped in insert method of CustTable.

Let’s see how pre and post event handler methods can be created and used.

1. Let’s take same example. I added 2 event handler methods in Consumer class.



2. Drag and drop both these event handlers in method sendEmailToCustomer


3. Set property “CalledWhen” to Pre for EventHandler1 and Post for EventHandler2.


 4. Now let’s run main method of Producer class again and see the results. It should call EventHandler1 and then sendEmailToCustomer and then EventHandler2.

5. Here is the result as expected.

With use of events, it has opened so many doors and possibilities. Model architecture and events can be integrated which can help if multiple vendors are doing customizations in different models so that it doesn’t impact customizations of other models/vendors. Use of pre and post handlers is so powerful that it can be used without changing a single line of code in original method. Pre or Post handlers can be just dropped in the original method and will be called automatically before (pre handler method) or after (post handler method) original method.

Stay tuned for more on events. I am still exploring the possibilities using events in AX 2012. 

Thursday, October 29, 2009

AX: HTTP Web Request to URL

//This method makes HTTP web request to the given url and returns the response


Static XML HttpWebRequest(XML _url, XML _parameter = "")

{

System.Net.WebRequest webrequest;

System.Net.HttpWebResponse httpresponse;

System.IO.Stream stream;

System.IO.StreamReader streamReader;

xml responseXML;

System.Byte[] arrayOfBytes;

System.Text.Encoding encoding;

;

try

{

new InteropPermission(InteropKind::ClrInterop).assert();

//Use .Net framework reflections to make HttpRequest and get the response back

encoding = System.Text.Encoding::get_UTF8();

arrayOfBytes = encoding.GetBytes(_parameter);

webrequest = System.Net.WebRequest::Create(_url);

webrequest.set_Method("POST");

webrequest.set_ContentType("application/x-www-form-urlencoded");

webrequest.set_ContentLength(arrayOfBytes.get_Length());

stream = webrequest.GetRequestStream();

stream.Write(arrayOfBytes,0,arrayOfBytes.get_Length());

stream.Close ();



httpresponse = webrequest.GetResponse();

stream = httpresponse.GetResponseStream ();

streamReader = new System.IO.StreamReader (stream);

responseXML = streamReader.ReadToEnd ();

streamReader.Close ();

stream.Close ();

httpResponse.Close ();



codeAccessPermission::revertAssert();

}

catch

{

throw error(strfmt("Exception occured during payment process. Url: %1", _url));

}

return responseXML;

}

Tuesday, July 14, 2009

AX: Join Query from .NET to AX

Axapta AxConn = new Axapta();

AxaptaRecord tInventsum = AxConn.CreateAxaptaRecord("Inventsum");
AxaptaRecord tInventDim = AxConn.CreateAxaptaRecord("InventDim");

String sqlString = "Select %1 join %2 where %2.InventDimId == %1.InventDimId";
AxConn.ExecuteStmt(sqlString, tInventSum, tInventDim);

while (tInventsum.found)
{
String ColorId = tInventDim.getField("ColorId") as String;
tInventsum.next();
}

Thursday, July 9, 2009

AX: Rename Primary Key

Here is an example to rename existing item number by reading csv. RenameItems.CSV contains 2 columns. Column 1 contains old item number and Column 2 contains new item number. This job can be used to rename any primary key just by modifying few code lines.

static void renamePrimaryKey(Args _args)
{
#define.read('r')

Container line;
str oldValue;
str newValue;
fieldId fieldId;
Common common;
CommaIO fileIO;
FileName file = @'F:\ImportData\RenameItems.csv';
;
ttsbegin;
//Asserting rights
new FileIOPermission(file,#read).assert();

// BP Deviation Documented
fileIO = new CommaIO(file,#read);

if(!fileIO fileIO.status() != IO_Status::Ok)
{
throw error(strfmt("@SYS76826",file));
}
while(fileIO.status() == IO_Status::Ok)
{
line = fileIO.read();
oldValue = conpeek(line,1);
newValue = conpeek(line,2);
if(!InventTable::exist(newValue))
{
common = InventTable::find(oldValue);
fieldId = fieldnum(InventTable,ItemId);
//SIG - start
if (isConfigurationkeyEnabled(configurationkeynum(SIG)))
{
SIGBaseDocument::checkAndCacheRename(common,fieldId,newValue);
}
//SIG -end

// CC Start
CCPrimaryKey::renamePrimaryKey(common, newValue, fieldId);
// CC End
common.(fieldId) = newValue;common.renamePrimaryKey();
}
}
ttscommit;
}

AX: Import Items

To import items in AX 2009 using Excel template. Just import InventTable using Excel template feature and then run the following job.

static void importItems(Args _args)
{
InventTableModule inventTableModule;
InventItemLocation inventItemLocation;
InventTable inventTable;
InventItemInventSetup inventItemInventSetup;
InventItemPurchSetup inventItemPurchSetup;
InventItemSalesSetup inventItemSalesSetup;
int i;
;
while select inventTable
notexists join inventTableModule
where inventTable.ItemId == inventTableModule.ItemId

{
inventTableModule.ItemId = inventTable.ItemId;
inventTableModule.initValue();
inventTableModule.ModuleType = ModuleInventPurchSales::Invent; inventTableModule.insert();
inventTableModule.ModuleType = ModuleInventPurchSales::Purch; inventTableModule.insert();
inventTableModule.ModuleType = ModuleInventPurchSales::Sales; inventTableModule.insert();
inventItemInventSetup.ItemId = inventTable.ItemId;
inventItemInventSetup.initValue();
inventItemInventSetup.InventDimId = 'AllBlank'; inventItemInventSetup.InventDimIdDefault = 'AllBlank';
inventItemInventSetup.insert();
inventItemPurchSetup.ItemId = inventTable.ItemId;
inventItemPurchSetup.initValue();
inventItemPurchSetup.InventDimId = 'AllBlank'; inventItemPurchSetup.InventDimIdDefault = 'AllBlank';
inventItemPurchSetup.insert();
inventItemSalesSetup.ItemId = inventTable.ItemId;
inventItemSalesSetup.initValue();
inventItemSalesSetup.InventDimId = 'AllBlank'; inventItemSalesSetup.InventDimIdDefault = 'AllBlank';
inventItemSalesSetup.insert();
inventItemLocation.ItemId = inventTable.ItemId;
inventItemLocation.initValue();
inventItemLocation.inventDimId = 'AllBlank';
inventItemLocation.insert();
i++;
}
print i;
pause;
}

AX: Display Method Caching

To increase the performance of the form or report wherever display methods are in use. Use caching method to cache the display method as follows:
DataSourceName_DS.cacheAddMethod(tablemethodstr(TableName, DisplayMethodName));

It increase huge performance.

Thursday, July 2, 2009

AX: Example using "intertable" relations

Query q = new Query();
QueryBuildDataSource qbr1, qbr2, qbr3;
;
qbr1 = q.addDataSource(tablenum(ProjCategory));
qbr1.orderMode(OrderMode::GroupBy);
qbr1.addSortField(fieldNum(ProjCategory,CategoryId));
...
qbr2 = qbr1.addDataSource(tableNum(ProjValEmplCategorySetUp),
'ProjValEmplCategorySetUp1');
qbr2.addRange(fieldNum(ProjValEmplCategorySetUp,CategoryId)).value(
strFmt('(%1) (%2)',fieldStr(ProjValEmplCategorySetUp,CategoryId),
fieldStr(ProjValEmplCategorySetUp,groupId)));
qbr3 = qbr2.addDataSource(tableNum(ProjValEmplCategorySetUp),
'ProjValEmplCategorySetUp2');
qbr3.addRange(fieldNum(ProjValEmplCategorySetUp,CategoryId)).value(
strFmt('(%1 == %4.%3) && (((%1 == %5.%1) && (%1)) ((%2 == %5.%2) && (%2)))',
fieldStr(ProjValEmplCategorySetUp,CategoryId),
fieldStr(ProjValEmplCategorySetUp,GroupId),
fieldStr(ProjCategory,CategoryId),
qbr1.name(),
qbr2.name()));