Partial posting of purchase order in AX 2012

In my previous post
we created code to post product receipt via x++. 
Now this code would post the lines of the PO appropriately as per the quantity specified on the line , provided the ReceiveNow quantity on the purchParmLine is set appropriately. The inventory transfer would work fine for a normal item,with the deduction of the partial quantity alone from the ordered quantity. Yet when you have a serial number tracked or lot item , while creation of receipt say you do not enter the sl no or lot id , yet during posting if you have your lot ID /sl no (inserted through some process via an interfacing application)  you may face problems as the transactions would not have the batch number or serial number specified on them and in 2012 Axapta does all posting on the basis of transactions. (This may lead to negative inventory(ordered qty) against the particular sl no or lot ID.

So to make the whole thing work, you would need to split the transactions via some logic through code by calling the InventTrans.updateSplit method and then register the inventory with the transaction that you created via the split. The registering of inventory would make use of code from class InventTransWMS_Register, method updateInvent which would encompass this piece of code in particular:
 registered = InventUpd_Registered::newParameters(movement,inventDim,inventDimParm,inventDim,inventDimParm,_tmpInventTransWMS.InventQty, _tmpInventTransWMS.PdsCWQty);
      registered.parmSkipQualityOrderCreation(true);  // We handle quality order creation later in this method
      registered.parmInventReceiptForTestRegistrator(inventReceiptForTestRegistrator);

       if (movement.mustBeQuarantineControlled())
            {
                    registered.parmInventDimQuarantine(inventDimQuarantine);
            }

        if (_tmpInventTransWMS.InventTrans)
            {
                    inventTransPrefered = InventTrans::findRecId(_tmpInventTransWMS.InventTrans);
                    if (inventTransPrefered.RecId)
                    { // Only use if sign/direction matches specified quantity.
                        if ((_tmpInventTransWMS.InventQty > 0 && inventTransPrefered.StatusReceipt == StatusReceipt::Ordered)
                         || (_tmpInventTransWMS.InventQty < 0 && inventTransPrefered.StatusReceipt == StatusReceipt::Registered))
                        {
                            registered.parmPreferedInventTransRecId(_tmpInventTransWMS.InventTrans);
                        }
                    }
             }
        movement.parmPDSBaseValue(_tmpInventTransWMS.pdsBaseValue);

        if (inventDim.InventBatchId)
        {
                    registered.pdsSetBatchAttributeValue(inventDim.InventBatchId);
        }

        registered.updateNow();
        inventReceiptForTestRegistrator = registered.parmInventReceiptForTestRegistrator();
        if (inventDim.InventBatchId)
        {
                    inventBatch = InventBatch::find(inventDim.InventBatchId, _tmpInventTransWMS.ItemId, true);
                    inventBatch.pdsInitFromVendBatchDetails(_tmpInventTransWMS.bufferPdsVendBatchInfo());
                    inventBatch.update();
         }
         inventQtySumCW += _tmpInventTransWMS.PdsCWQty;

         inventQtySum += _tmpInventTransWMS.InventQty;

         if (inventReceiptForTestRegistrator)
         {
                InventQualityManagementCreateHandler::createInventoryRegistration(
                    inventTransOriginId,
                    inventReceiptForTestRegistrator);
         }


        if (inventTransWMSRegistrationObserver
            && inventQtySum)
        {
            inventTransWMSRegistrationObserver.notifyArrivalRegistered(inventQtySum, inventQtySumCW, inventDim);
        }

        _tmpInventTransWMS.ttscommit();



Posting of product receipt via code in AX 2012.

The posting of product receipt/packing slip for purchase order is primarily done by using the class: PurchFormLetter. The functions of PurchFormLetter class of 2009 AX are done by the code of two classes in 2012 : One is PurchFormLetter and the other: purchFormLetterParmData.
The class purchFormLetterParmData is responsible for creation of data which would be used by PurchFormLetter.

We could use the PurchFormLetter update method for posting packing slip in most cases, a typical code snippet will look like:

static void Dev_CreatePO_and_Invoice(Args _args)
{
NumberSeq numberSeq;
Purchtable Purchtable;
PurchLine PurchLine;
PurchFormLetter purchFormLetter;

;

ttsbegin;
numberSeq = NumberSeq::newGetNumFromCode(purchParameters::numRefPurchaseOrderId().NumberSequence,true);

// Initialize Purchase order values
Purchtable.initValue();
Purchtable.PurchId = numberSeq.num();
Purchtable.OrderAccount = '3000';
Purchtable.initFromVendTable();

if (!Purchtable.validateWrite())
{
throw Exception::Error;
}
Purchtable.insert();

// Initialize Purchase Line items
PurchLine.PurchId = Purchtable.PurchId;
PurchLine.ItemId = 'B-R14';
PurchLine.createLine(true, true, true, true, true, false);
ttscommit;

purchFormLetter = purchFormLetter::construct(DocumentStatus::PackingSlip);
purchFormLetter.update(purchtable, // Purchase record Buffer
"PO_"+purchTable.PurchId, // Invoice Number
systemdateget()); // Transaction date


if (PurchTable::find(purchTable.PurchId).DocumentStatus == DocumentStatus:: PackingSlip)
{
info(strfmt("Posted invoiced journal for purchase order %1",purchTable.PurchId));
}
}


However in case you would be using run, the code structure would look similar to the one in the PurchFormLetter.update method. To create parmData we would use

purchFormLetterParmData = PurchFormletterParmData::newData(DocumentStatus::PackingSlip,VersioningUpdateType::Initial);
            purchFormLetterParmData.createData_IN(CustomsImportOrderType_IN::PurchaseOrder,false);

The piece of code would look like:
         //create our purchParmTable record to post against
         purchFormLetter = PurchFormLetter::construct(DocumentStatus::PackingSlip);
         //insert data into table PurchParamUpdate
purchFormLetterParmData = PurchFormletterParmData::newData(DocumentStatus::PackingSlip,VersioningUpdateType::Initial);
        purchFormLetterParmData.createData_IN(CustomsImportOrderType_IN::PurchaseOrder,false);
        purchParmTable.clear();
        purchParmTable.TransDate = SystemDateGet();
        purchParmTable.Ordering = DocumentStatus::PackingSlip;
        purchParmTable.ParmJobStatus = ParmJobStatus::Waiting;
        purchParmTable.Num = strfmt('%1', ILSGatewayQueue.RecId);
        purchParmUpdate = purchFormLetterParmData.parmParmUpdate();
        purchParmTable.ParmId = purchParmUpdate.ParmId;
        // fill in fields from PurchTable
        purchParmTable.PurchId = purchTable.PurchId;
        purchParmTable.PurchName = purchTable.PurchName;
        purchParmTable.DeliveryName= purchTable.DeliveryName;
        purchParmTable.DeliveryPostalAddress  = purchTable.DeliveryPostalAddress;
        purchParmTable.OrderAccount = purchTable.OrderAccount;
        purchParmTable.CurrencyCode = purchTable.CurrencyCode;
        purchParmTable.InvoiceAccount = purchTable.InvoiceAccount;
        purchParmTable.insert();

// here we would insert lines into purchParmLine add some logic etc
         purchFormLetter.transDate(systemDateGet());
        purchFormLetter.proforma(false);
        purchFormLetter.specQty(PurchUpdate::All);

        purchFormLetter.purchTable(purchTable);
        purchFormLetter.parmParmTableNum(purchParmTable.ParmId);// this is the ID we hard code as the product receipt ID, if we do the posting via UI,
                                                                    // user would have the option to manually enter this value
        purchFormLetter.parmId(purchParmTable.ParmId);
        purchFormLetter.purchParmUpdate(purchFormLetterParmData.parmParmUpdate());

        purchFormLetter.run();






Lookup issue in AX and EDT relationships

Recently I came across an issue with populating the datagrid for a  combobox in AX.  (during migration of our project from 2009 to 2012). The lookup grid was empty though the view details opened up a form with two detail records.
So I added the following code by overriding the lookup method :
public void lookup()
{
    SysTableLookup          sysTableLookup;
    Query                   query;
    QueryBuildDataSource    queryBuildDataSource;
    ;

    sysTableLookup = SysTableLookup::newParameters(tablenum(tableName), this);
    query = new Query();
    queryBuildDataSource = query.addDataSource(tablenum(tableName));
    sysTableLookup.addLookupfield(fieldnum(tableName, NameOfColumnThatYouWantToSeeInTheLookup));
    sysTableLookup.parmQuery(query);
    sysTableLookup.performFormLookup();
}

The lookup then displayed the list of details , yet when I selected a particular value I got the following error: “Table ‘table name’ does not contain an index with id ’65535′
This was because of the relationship on the EDT because the value selected disobeyed it. EDT migration was the step missed out in the whole process, when I ran the EDT migration tool the problem was resolved- I was able to see the lookup without even writing code in the overridden method ‘lookup.’




Temporary tables, CTEs, TVPs and Views in SQL

Say I have the following tables:
Department Table
Dept ID
Dept Name
1
Java
2
DotNet

Employee Table
Emp ID
Employee Name
Dept ID
Gender
12
A
2
F
13
B
2
M
14
C
1
F

And I want a table that gives me the department in which total number of employees >=2 i.e. Dotnet :
Alternative 1: via Views
One way to accomplish this is via Views as

Create View Dep_Emp As
(Select DeptName, Count(*) As TotalEmpCount from Employee join
Department on Employee.DeptID= Department.DeptID
group by DeptName)

 
 






Dep_Emp View would be created as follows:
DeptName
TotalEmpCount
Java
1
DotNet
2

Then when we run the query:
Select DeptName from Dep_Emp where TotalEmpCount >= 2

We would get the result DotNet, and the view would be created SQL Server under System Databases > tempdb >Views

If we are not going to use the view in multiple places we will have to drop the View as the view will be of no great use in the future.

Alternative 2: Insert into new Tables(Temporary)
I can run the following query with Select into, and then drop the table

Select DeptName, Count(*) As TotalEmpCount
 into #tblEmp
 from Employee join Department on
 Employee.DeptID= Department.DeptID group by DeptName

Select DeptName from #tblEmp where TotalEmpCount >= 2
Drop table #tblEmp

 
 


Select DeptName, Count(*) As TotalEmpCount
 into #tblEmp
 from Employee join Department on Employee.DeptID= Department.DeptID group by DeptName

Select DeptName from #tblEmp where TotalEmpCount >= 2
Drop table #tblEmp

Here #tblEmp is a temporary table and it exists as long as the current session of the user exists.
 The temporary table denoted with a single # symbol is stored in SQL Server under System Databases > tempdb >Temporary Tables and is deleted when the last connection to the db referencing the #tblEmp table is closed.
Alternative 3: Using Table Variable Parameters
We could create a TVP as shown below by declaring the type of table as:

Declare @tblEmp table (DeptName nvarchar(20), empCount int(19,5))
Insert into @tblEmp
Select DeptName, Count(*) As TotalEmpCount from
 Employee join Department on Employee.DeptID= Department.DeptID
group by DeptName

Select DeptName from @tblEmp where TotalEmpCount >= 2

 
 



This would create a TVP under tempDb of SQL Server
The beauty of TVPs is that
i)                    We do not have to drop TVPs , their scope exists in the statement block, stored procedure or batch in which the TVP is declared
ii)                   We can pass these as parameters to functions


Alternative 4: Using Common Table Expressions/CTEs





Note:
i)                    The scope of the CTE exists as long as the statement following the CTE is executed (over here it is the statement “Select DeptName from Employee_Count where TotalEmpCount >= 2 “)
ii)                   This statement that follows the CTE can be an Insert, update or select statement.
iii)                 There can be multiple CTEs inside the With and all those CTEs together have the scope until the statement that follows the CTE creation ie duration of the query.



Sub queries vs Derived Tables in SQL

Sub queries are best defined as query within a query. An example of a sub query is as follows:
select employee_name
from employee
where employee_salary >
-- this is a subquery:
(select avg(employee_salary)
        from employee)

Here, the subquery is within the where clause. It could be put in the in clause as well as:
Select * from employee where employee in(Select employee from employee_details where salary > avg(salary)

Now consider the following set of queries:
Create view view1 as Select salary from employee (this is for the query in the from clause)

Select max(salary) from view1

Drop view1

This set of queries using view involves writing values to the system catalog tables and three statements have to be written. Instead we could use a derived table.
Derived table is a table which is temporary , and created when you write a query within the From Clause as in:
Select max(salary) from (select salary from employee) As Max_salary

The point to be noted here is that the use of As clause is a must , without which we would get the error : “Every derived TABLE must have its own alias”.

Benefit of Derived table over using views:
i)                    No entry is made to the system catalog table.
ii)                   The temporary table made for the query within the from clause exists until the query is executed i.e the duration of the query

iii)                 It is faster than queries with views.

Using statement vs Using Directive

Recently in a quiz, I came across a question about the “using” statement in relation with garbage collection. I was sure that using had nothing to do beyond specifying the namespace that a class used.
All I could think of was this
For eg : using System.Text;

However, a few days later, when I did a quick walkthrough of some code that was in front of me, I remembered that we use “using” within the code we write as in
using (Font font1 = new Font("Arial", 10.0f))
{
//some code related to font1
}
So I did some probing into MSDN and code project and here are the results:
What exactly do both the using’s do?
1. Using directive
First of all the using used with the namespace is called “using directive” (Many of you may know this, but I was not aware of this even after 3 yrs of coding in .NET). It does nothing more than suggesting which namespace (both user defined and system defined) is going to be used by the class.

2. Using statement
This can be a powerful tool to help in releasing memory – it specifies when the objects using the resources (for e.g. the object that uses font1 in the example above) should release them.
Have a look at this fragment of code:
 using (Font font1 = new Font("Arial", 10.0f))
{
               Console.WriteLine(font1.Name);
}
 
How does this block of code work?
Internally using statement calls a try and a finally block without catch. It uses IDisposable interface to free the memory allocated. The sequence is as follows:
1)      The constructor of Font1 is called i.e. (new Font("Arial", 10.0f)))
                                    |
            2) A try block with Console.WriteLine stmt is executed i.e. (Console.WriteLine(font1.Name);)
                                    |
3)The finally block disposes the memory allocated to the object font1 i.e. (font1.Dispose())
So the code essentially (that goes on within) would look like this:
private static void Main(string[] args)
{
      Font font1 = new Font ("Arial", 10.0f));
      try
      {
            Console.WriteLine(font1.Name);
      }
      finally
      {
            if (font1 != null)
            {
                  font1.Dispose();
            }
      }
 }

Hence, the using statement leaves it in the hands of the programmer to decide when memory should be freed. This would be otherwise done by the CLR.

First thing to be noted to use using statement : The class must implement IDisposable interface.

Another thing to be noted is that if any exception is thrown in step 1, then step 2 and 3 will be bypassed.

Why do we use Factory design pattern, and Spring Framework?


 Say there are three objects in real world :
  •     A showroom that does some value added services(eg like adding license plate and give the finishing touch by adding varnish) for cars and scooters and uses both for sale after doing the value add.
  •  Car 
  • Scooter 


Now if the showroom has to do finishing for the scooter(without using either Factory Pattern or IOC) as the customer wants, it should know what kind of scooter it is going to do Value added services for i.e. the specifications of the scooter and car(like color,length and the showroom would provide the specifications and get it from the scooter factory and the car factory. So the details of the car/ scooter have to be known to the showroom. Hence, there is a strong dependency/ coupling on showroom for the both of these objects. 

If you look at it programmatically 

to create car object and scooter object from the Car class(ie the Car factory in real world) and Scooter class, the  showroom will have to know about the constructor arguments of car and scooter.

Class Showroom
{
            //say the customer feeds in the choice of vehicle for which he wants to perform value added service
            Public createObjectBasedOnDemand(string choice){
                        If(choice.Equals(“Scooter”))
                                    {Scooter s = new Scooter(length,breadth,ht,color);}
                        Else if(choice.Equals(“Car”))
                                    Car c = new Car(color,height,weight,length);
            }
}

Now firstly, we do not want the showroom to necessarily know all the details of the scooter and car as it is only going to do value added services like adding license plate and give the finishing shine by adding varnish. But in this approach the Showroom knows all the intricate details about the car like height, weight and color.
Secondly (programmatic issue), the “new” keyword is used too many times. This would mean in case another type of vehicle is added eg lorry, a new line of code will have to be added for choice lorry inside the method createObjectBasedOnDemand. This would mean that the whole code will have to be recompiled.
To do away with these 2 problems we use factory method pattern in conjunction with spring.
To solve the first problem 1(showroom knows everything about individual vehicles) we use Factory method pattern:
Step 1: We introduce an interface called Vehicle which the classes Car, Scooter, Lorry implement. The benefit of this is that we will be able to introduce any number of new vehicles that implement this interface (like motorboat, bike etc) and the showroom will not have to know about either them or the specifications of theirs. The showroom will point to the interface alone and will not know anything more than the choice of the customer i.e. the name of the vehicle the customer needs.
Public interface IVehicle{ public doSomeValueAdd();}
Public class car implements IVehicle{ public Car(string color,int ht,int wt,int len){ //some code; }
Public doSomeValueAdd(){//some code;}}
// and similar code for the other classes
Step 2: We introduce a factory class that knows what the concrete classes available. This factory class however will return only thetype Vehicle back to the customer as:
Public class Factory
{
           
            Public static IVehicle getVehicleBasedOnChoice(string choice)
            {
            IVehicle vehicle;
            If(choice.Equals(“Scooter”))
                        {vehicle = new Scooter(len,br,ht,color);}
            ElseIf(choice.Equals(“Car”))
                        {vehicle = new Car(color,ht,wt,len);}
            //some more conditions
            Return vehicle;
            }
}
Step 3: We change the code of the showroom class to reference only the factory and obtain the object of interface and do the value add
Public class Showroom
{
            Console.Writeline(“Enter the choice”);
            string choice = Console.Readline();
            IVehicle vehicle = Factory. getVehicleBasedOnChoice(choice);
            Vehicle.DoVaueAdd();
}

Using this approach the showroom is totally oblivious about what kind of vehicles are present and the specifications of the vehicle.

Solving issue 2( Enormous number of new keywords) Spring Injection
As the new keyword problem is not solved by using Factory method alone, we use the Spring framework to do the work of the factory class by means of xml files. If you have read my first article on Inversion of Control at : http://dotnetnhibernateconcepts.blogspot.in/2013/05/inversion-of-control-in-laymans-terms.html
We have spoken about a container/dealer that does work of the factory class in our example. Spring accomplishes this by xml files which contain data for example:
<objects xmlns="http://www.springframework.net">
  <object id="IVehicle" type="vehicle, someNamespace, Version=9.0.0.0, Culture=neutral, PublicKeyToken=a978a715ccadf176" singleton="true" autowire="constructor" singleton="true" />
We would then instantiate the object of type via a customized factory class that would
obtain the details of the class it is instantiating from this xml file.
More about spring and the xml files etc will be discussed in the articles yet to come J




Thanks for reading.

Inversion Of Control in layman's terms

This is a question oft asked by beginners, when they are inquisitive about why we use inversion of control and what bearing IOC has in the real world. So here I have attempted to explain the IOC with my own example:

Say there are three objects in real world :
1. A showroom that  does some value added services(eg like adding license plate and give the finishing touch by adding varnish) for cars and scooters and uses both for sale after doing the value add.
2. Scooter( which is the finish good created by Scooter Factory)
3. Car(which is the finished good created by the car factory)

Now if the showroom has to do finishing for the scooter(without using IOC), it should know what kind of scooter it is going to do Value added services for i.e. the specifications of the scooter and car(like color,length and the showroom would provide the specifications and get it from the scooter factory and the car factory. So the details of the car/ scooter have to be known to the showroom. Hence, there is a strong dependency/ coupling on showroom for the both of these objects. 

If you look at it programmatically 
to create car object and scooter object from the Car class(ie the Car factory in real world) and Scooter class, the  showroom will have to know about the constructor arguments of car and scooter.

Class Showroom{
Scooter s;
Car c;
/* See how scooter and car are instantiated by calling constructor of class Scooter and Car.
    That means, Class Showroom needs knowledge about Scooter and Car like
    ‘Which are the possible constructors of Scooter and Car?
     What should be the constructor parameters?’
     This is termed as Tight coupling between Showroom and Scooter/showroom and Car/Showroom.
*/
Public Showroom(){
s = new Scooter(color, length, width);
car = new Car(color, length, width);
}
}

Now we do not want the showroom to necessarily know all the details of the scooter and car as it is only going to do value added services like adding license plate and give the finishing shine by adding varnish. So we would rely on some other entity , say Dealer,to get the scooter and the car from the Scooter factory and Car factory and pass the goods to the showroom to do the finishing. So the control of getting the car and scooter lies in the hands of the Dealer and the showroom knows nothing about the specifications of the car and the scooter it is going to do the finishing for until the car and scooter come to it. 
In the programming world this dealer (who passes on the goods to the showroom) would be called "Container". So all the details of the scooter and car are known only to the Container/dealer who has now become the Controller, previously the showroom was the controller. Hence the name inversion of control.

If you look at this programmatically,

Class Showroom{
Scooter s;
Car c;
/* Look Object of Scooter and Car will be created by Container and provided as Constructor argument.
So, Class Showroom doesn’t need to know class Scooter and Car constructors and all.
It is loose coupling between Showroom  and Scooter/Showroom  and Car.
*/
Public Showroom(Scooter s1, Car c1){
this.s = s1;
this.c = c1;
}
}

Thus, in the above example
the classes Showroom , Car and Scooter are less coupled. This method of passing the objects through a construtor is called constructor injection.

(I originally published this answer at https://www.quora.com/Computer-Programming/How-will-you-explain-Inversion-of-Control-in-laymans-terms)