Thursday, 21 March 2019

Run Base Batch My Reference


Framework in Microsoft Dynamics AX 2012

Overview

RunBase framework provides a common software platform for data manipulation in Microsoft Dynamics AX. It provides a standardized pathway to create batch jobs and periodic processes.
RunBase framework can be used to run a process periodically or to manipulate some data over a period of time.
Using RunBase framework has the following advantages:
  1. All future updates are integrated automatically
  2. Common layout of dialog
  3. Remembering the user selections from the last run
  4. Easy to implement
To implement RunBase framework, extend a class with RunBaseBatch.

Pre-requisites

  1. Microsoft Dynamics AX 2012
  2. Batch server must be configured

Important Methods

  1. Run

    Run is the central method of the RunBase framework and is where all business logic is written. All data manipulation statements are placed in this method.
  2. Description

    Description is a static method that returns a descriptive name of a batch job. This name is then shown as a caption on the batch job dialog to identify the specific job in batch queue.
  3. Main

    Main is a static method which provides the entry point for a batch job. This method calls the prompt method, which calls the RunBase dialog, and run method which processes the batch job.

Scenario

As part of this tutorial, the RunBase class will mark all customers on-hold who have exceeded their credit limit.

Steps

  1. First create a new class. Open AOT àClasses

  2. Right click on Classes, select New Class, and create a new RunBaseDemo class

  3. Open the class declaration by right clicking on the RunBaseDemo class and selecting View Code

  4. Write the following code:
  5. class RunBaseDemo extendsRunBaseBatch
    {
    }
  6. Add a new method and name it as description. Write the following code in the method:
    client server static ClassDescription description()
    {
        return “Mark customers on-hold”;
    }

  7. Add a new method and name it as main. Write the following code in the method:
    static void main(Args _args)
    {
        RunBaseDemo objClass = new RunBaseDemo();
        //prompt for runbase framework dialog
        if (objClass.prompt())
        {
           //run the process
           objClass.run();
        }
    }

  8. Override the run method and write the following code:
    public void run()
    {
        CustTable custTable;
        //start transaction
        ttsbegin;
        try
        {
            //select all customers
            while select forUpdate * from custTable
            {
                //if credit limit is reached, placed on-hold
                if(custTable.CreditMax && custTable.balanceMST() > custTable.CreditMax)
                {
                    custTable.Blocked = CustVendorBlocked::Invoice;
                    custTable.update();
                }
            }
            //end transaction
            ttsCommit;
        }
        catch
        {
            //throw error of failure
            error(“Process failed”);
        }
    }

  9. Run the job by right clicking on the RunBaseDemo class and select Open. Alternatively, the job can also be called from a menu item

  10. The RunBase framework dialog will open

  11. There are two ways to run the batch job, only once and periodically
    1. If once, click OK. Use this option if you want to run the job just this time
    2. If periodically, schedule the batch job. Use this option if you want to run the job periodically. Follow the following steps to schedule the batch job
      • Check the Batch processing box
      • Select the respective batch group from the Batch group drop down
      • Click on the Recurrence button

      • In the Recurrence dialog, set an appropriate schedule and click OK

      • Click OK to schedule. It will now run the job according to the inputted schedule

      • Batch job history can be viewed from System administration à Inquiries à Batch jobs à Batch job history

Custom Workflow from scratch, Dynamics Ax 2012 my Reference


Let start work on fake requirement. Suppose we are working in HR module and client wants that worker will add their expense and send for Approval.

For this requirement, first we create a custom table and create its relation with Worker table. And then develop a custom workflow on it.
So this post contains tasks
  • Table creation and relation with worker
  • Create a simple entry form and list page.
  • Workflow



So first we create a new table and generate its relation with Worker ID.

If we open HCMworker table we will find that its primary key is “PersonnelNumber”.

We add new enum type which has expected values, medical, Certification, Food expense and others. We use Tst as extension for our example’s artifacts.
Expense

Now create a new table set its Name as tstWorkerExpenseTable.
Expand table node and right click on relation node. Create a new and set table as HCMWorker.

Rightlick on it new => foreignKey=>Primarykey.
HcmWorker
You will find new and new field added, you can rename it, if you check the properties you will the  which will int64 bit.

Now drag and drop enum created in previous step
Rename it to Expense type.


Now add one more field name It Amount of real type and set its label as Amount
Save It. Also create a field group with overview and drag all fields in that group.
Table final structure will be as follow.
Table Final stage


Form create simple form with Name tstWorkerExpense and set its data source as
Now create a simple form and set its datasource as TstWorkerExpense. And set data source properties  “Edit” and “insert if empty” to no.

Add grid on form and drag and drop fields from data source to grid. Save it.  Form structure will be look like.
WorkerListPage

Run the form you will find something like. You can improve from. It is enough for our current example
Also insert command buttons on action table for new, Edit and delete.
CreateForm


You can improve but for current example it is enough.

Now create a new enum  for which will used as approval status for table.
WorkFlowStatus
Drag and drop in fields of tstWorkerExpense. Save table, compile and synchronize, so this will be reflect at SQL Server level.

Now Its time to write some code that will work for state change in workflow steps.
Right click on Method node on tstWorkerExpense and click on CanSubmitToWorkFlow
CanWorkflow




Update it as follow.

publicboolean canSubmitToWorkflow(str _workflowType = ”)
{
boolean ret;

if (this.ExpenseStatus ==tstExpenseStatus::NotSubmit)
{

ret = boolean::true;
}
else
{
ret =boolean::false;
}

return ret;
}

New add a new static method with Name “updateworkFlow” and update it as follow

publicstaticvoid updateWorkFlowState(RefRecId _id, tstExpenseStatus _status)
{
tstWorkerExpense _Expense;

selectforUpdate _Expense where _Expense.RecId ==_id;
if (_Expense !=null)
{
ttsBegin;
_Expense.ExpenseStatus = _status;
_Expense.update();
ttsCommit;
}
}



Now create a Query and This query will later used when we build Workflow type on it.
Query
Add TstWorkerExpense table in it and set field  dynamic to yes.

WorkflowQuery
Now expand AOT and expand workflow right click on new Workflow Category
Custom Cateogry
Set its name tstWorkFlowCategory and set Module as HumanResource.
CategoryDetail
Save it. Now add a new me display menu Item With name “tstExpenseTable” and set its form tstWorkerExpenseTable.
Menu Item



Now expand workflow and then expand workflow Type right click and run the wizard.
WorkFlowType Wizard
Wizard1


From next window set following properties all based on artifacts we create in pervious steps.
ExpenseWizard
Ie.  Query, workflow category and menu item.  AS we test this workflow only on Ax client so check on rich client
TypeWizardFinished
Click on next.


In result a new Ax Project is created
TypeProject
  • Workflow Type
  • Classes
    • Document class which extends WorkflowDocument.
    • EventHandler class which gives implementation to handle different workflow events.
    • SubmitManager class.
  • Action menu items:
    • SubmitMenuItem pointing to SubmitManager class.
    • CancelMenuItem pointing to WorkflowCancelManager class.


Now expand the form (We created this in one above step) and expand its design, and set following properties  to it will workflow enable
WorkflowEnabled =yes
WorkflowDataSorce =tstWorkFlowExpense
WorkflowType = tstWorkerEpense (We created this in previous step).
WorkFlowSettings

Now expand submit manager class in workflow type project and update logic as follow.
And Create a new method with following logic.

public void submit(Args _args)
{
CustTable                           CustTable;
   CustAprWorkflowTypeSubmitManager    submitManger;   
   recId _recId =                      _args.record().RecId;
   WorkflowCorrelationId               _workflowCorrelationId;

   workflowTypeName                    _workflowTypeName = workFlowTypeStr(“CustAprWorkflowType”);
   WorkflowComment                     note = “”;
   WorkflowSubmitDialog                workflowSubmitDialog;
   submitManger =                      new CustAprWorkflowTypeSubmitManager();
   
   
   

   //Opens the submit to workflow dialog.
   workflowSubmitDialog = WorkflowSubmitDialog::construct(_args.caller().getActiveWorkflowConfiguration());
   workflowSubmitDialog.run();

   if (workflowSubmitDialog.parmIsClosedOK())
   {
       CustTable = _args.record();
       // Get comments from the submit to workflow dialog.
       note = workflowSubmitDialog.parmWorkflowComment();

       try
       {
           ttsbegin;
           // Activate the workflow.
           _workflowCorrelationId = Workflow::activateFromWorkflowType(_workflowTypeName, CustTable.RecId, note, NoYes::No);

           CustTable.WorkflowApprovalStatus = CustWFApprovalStatus::Submitted;
           CustTable.update();
           ttscommit;

           // Send an Infolog message.
           info(“Submitted to workflow.”);
       }
       catch (Exception::Error)
       {
           error(“Error on workflow activation.”);
       }
   }

   _args.caller().updateWorkFlowControls();
}



Now Create a we create workflow approval.
Expand Workflow node in AOT and then again expand Workflow approval.
Approval


Now you have to use the following artifacts we created in previous steps.

Document, which we created through workflow type wizard and tables field group. And
ApprovalWithDocument


Again new project created.
New Approval Project is created

Now expand TsWorkerExpenseAppEventHandler and update following methods.
public void returned(WorkflowElementEventArgs _workflowElementEventArgs)
{
tstWorkerExpense::updateWorkFlowState(_workflowElementEventArgs.parmWorkflowContext().parmRecId(), tstExpenseStatus::ChangeRequest);
}


public void changeRequested(WorkflowElementEventArgs _workflowElementEventArgs)
{
tstWorkerExpense::updateWorkFlowState(_workflowElementEventArgs.parmWorkflowContext().parmRecId(), tstExpenseStatus::ChangeRequest);
}

public void denied(WorkflowElementEventArgs _workflowElementEventArgs)
{
tstWorkerExpense::updateWorkFlowState(_workflowElementEventArgs.parmWorkflowContext().parmRecId(), tstExpenseStatus::Reject);
}


public void completed(WorkflowElementEventArgs _workflowElementEventArgs)
{
tstWorkerExpense::updateWorkFlowState(_workflowElementEventArgs.parmWorkflowContext().parmRecId(), tstExpenseStatus::Approve);
}

public void canceled(WorkflowElementEventArgs _workflowElementEventArgs)
{
tstWorkerExpense::updateWorkFlowState(_workflowElementEventArgs.parmWorkflowContext().parmRecId(), tstExpenseStatus::Cancel);
}

public void started(WorkflowElementEventArgs _workflowElementEventArgs)
{
tstWorkerExpense::updateWorkFlowState(_workflowElementEventArgs.parmWorkflowContext().parmRecId(), tstExpenseStatus::Submit);
}


Now expand the workflow and in sub node Supported Elements, drag and drop approval artifact.
Support



Drag
WorkFlowElement



Now create a new menu item and set its form and set its following properties.
WorkFlowMenuItem
  • Form WorkflowTableListPage
  • EnumTypeParameter to ModuleAxapta
  • EnumParameter to Basic.


Now generate increment CIL. It is necessary step.


Click on this and open the workflow design.


Navigate to the menu item to open WorkflowTableListPage to design the workflow.
Click on new button.
WorkFlowScreen

Drag and drop approval on designer screen and. Link the start to shape and from shape to end .

WorkFlow