Showing posts with label ax2012. Show all posts
Showing posts with label ax2012. Show all posts

Wednesday, April 4, 2018

Delete AUC for all users

Hey Guys!

Today I have got a small but interesting thing in Ax. We had a situation wherein space of C drive was reaching the alarming level of the Ax-client server (from where all users access Ax). I ran the tool WizTree which displays the analysis of a drive as per the space occupancy. It showed that the maximum amount of space was taken by the AppData folder and I knew what needs to be done next.

The problem was auc files had accumulated for all the users which were summed up to almost 30Gb. So, I decided to delete them but the challenge was how to delete it for all the users at once. So I took help from my master (yes, it's Google) and created a batch which will traverse through all the users AppData folder and delete the auc/kti files.

1. Open Notepad.
2. Paste the below commands there:

for /D %D in ("C:\USERS\*") do del "%~fD\AppData\Local\*.auc"
for /D %D in ("C:\USERS\*") do del "%~fD\AppData\Local\*.kti"
pause

3. Save the notepad as .bat file.


4. Run the batch file and it will delete all the auc/kti files for all the users.

Credits: http://blog.bhsolutions.com/index.php/2014/05/dynamics-ax-2012-spring-cleaning-app-data/
https://stackoverflow.com/questions/34019989/batch-file-copy-all-users-profile-app-data

Tuesday, January 9, 2018

Filter AOT objects using X++ in Ax2012

Hey guys,

Let's discuss a very interesting code for the simple purpose of filtering objects in a project. I hope we all know about the standard of Ax to filter and import AOT objects in a project. So now we will see how to do it using x++ code:

static void alle_aks_ImportObjectsToProjects(Args _args)
{
    sysprojectfilterrunbase varProject;
    utilelements            aotElements;

    varProject = new sysprojectfilterrunbase();
    varProject.parmProjectNode(systreenode::createProject('Alle_GST_TaxObejcts'));
    varProject.grouping(sysprojectgrouping::AOT);

    while select name, utilLevel, RecordType, ParentId from aotElements
        where aotElements.utilLevel == UtilEntryLevel::var
        && aotElements.name like 'Tax*'
    {
        try
        {
            aotElements.reread();
            varProject.doUtilElements(aotElements);
        }
        catch (exception::Error)
        {
            throw error('Error');
        }
    }
    varProject.write();
    info('Done');
}

Here you can modify the while select query to suit your need i.e. to change the layer or the name filter.


Source: https://mydynamicsax.wordpress.com/2015/03/19/how-to-filter-aot-objects-to-a-project/

Wednesday, June 7, 2017

"No elements are found in AOD files in the old directory" error in Ax2012

Hi guys,

Today while applying GST patch for one of our clients I faced an error in Code Upgrade. I had installed the hotfix and run the "Detect Code Upgrade Conflicts" and I received an error which said "No elements are found in AOD files in the old directory. The layer conflict project will not be created.". So of course after googling a bit I got a solution to this:

Modify the detectConflictsRun method on SysUpgradeDetectConflicts class like below:
Comment the code that checks for a record on utilElementsOld Table and sets layerDetectorRequirementsOk variable to True.

   // check if the Old directory exists
   /*select firstonly RecId from utilElementsOld;
   if (utilElementsOld.RecId)
   {
       layerDetectorRequirementsOk = true;
   }
   else
   {
       layerDetectorRequirementsOk = false;
       // Inform user that the layer project will not be created
       info("@SYS106623");
   }*/
   layerDetectorRequirementsOk = true;

And that works like a charm and you will get a project with code conflicts. :)

Credits: https://community.dynamics.com/ax/f/33/t/123783

Friday, May 26, 2017

The state of the source document or source document line could not be updated Ax2012

Hi Guys,

Today we faced this in our production environment. A particular PO had developed this issue wherein whenever a user clicks the Invoice button system would throw the error "The state of the source document or source document line could not be updated.".

While debugging, I came to know that this had something to do with Source Document Line records. So I tried looking for a solution on the web and got the below job which works perfectly in deleting the orphan records from SourceDocumentLine:

static void aks_fixOrphanedSourceDocumentsHeader(Args _args)
{
    SourceDocumentLine sline;
    SysDictTable table;
    PurchTable header;
    PurchLine purchline;
    PurchId purchId = "WPFO1617-0001218";
    boolean fix;
    Common rec;
    int fieldId, found, notfound;

    if (purchId)
    {
        while select purchLine where purchLine.PurchId == purchId
        {
            while select forUpdate sline where sline.ParentSourceDocumentLine == purchLine.SourceDocumentLine
            {
                table = new SysDictTable(sline.SourceRelationType);
                rec = table.makeRecord();
                fieldId = fieldName2id(sline.SourceRelationType, "SourceDocumentLine");
                select rec where rec.(fieldId) == sline.RecId;

                if (rec.RecId)
                {
                    info(strFmt("Record Match Found %1 %2", table.name(),rec.caption()));
                    found++;
                }
                else
                {
                    ttsBegin;
                    sline.doDelete();
                    ttsCommit;

                    info(strFmt("Orphan Found %1", table.name()));
                    notfound++;
                }
            }
            info(strFmt("Found %1", found));
            info(strFmt("Orphans found and deleted %1",notfound));

            found = 0;
            notfound = 0;
        }
    }
}


Credit: https://community.dynamics.com/ax/f/33/t/144316

Friday, March 24, 2017

Copy data from a table to another Ax2012

Hi guys,

Another short code for copying data from one table to another (backupTable). This is useful when you have to take backup of the data while you want to perform some operations of the production data (original table) or maybe to resolve some DB sync issues.

static void AKS_CopyTableData(Args _args)
{
    EcomInboundInventoryUpdate          origTable;
    Backup_EcomInboundInventoryUpdate   copyTable;

    ttsBegin;
    delete_from copyTable;

    while select origTable
    {
        buf2Buf(origTable, copyTable);
        copyTable.insert();
    }

    ttsCommit;
}

Delete duplicate records of a table AX2012

Hi Guys,

A code snippet to delete duplicate records of a table and keeping just one of the duplicate set.

static void AKS_DeleteDuplicates(Args _args)
{
    EcomInboundInventoryUpdate      table, tableSelect, tableDelete;

    while select table group by wmsreferencenum
        where table.EcomProcessStatus == EcomProcessStatus::Waiting
    {

        select firstOnly RecId from tableSelect
            where tableselect.WMSReferenceNum == table.WMSReferenceNum;


        delete_from tableDelete
            where tableDelete.WMSReferenceNum == table.WMSReferenceNum &&
                  tableDelete.RecId != tableSelect.RecId;
    }
}

Sunday, October 9, 2016

buf2buf to buf2bufByName in Ax2012

Hi Guys,

I would like to share an interesting blog post regarding buf2buf wherein you can also copy table buffer to another table in which field names are same as the same i.e table structure should be similar of both the tables.

We can create below method in the Global class:

//Modified method, copy data from one table to another table with similar structure

static void buf2BufByName(Common  _from, Common  _to)
{
    DictTable   dictTableFrom   = new DictTable(_from.TableId);
    DictTable   dictTableTo     = new DictTable(_to.TableId);
    DictField   dictFieldFrom;
    FieldId     fieldIdFrom     = dictTableFrom.fieldNext(0);
    FieldId     fieldIdTo
    ;


    while (fieldIdFrom && ! isSysId(fieldIdFrom))
    {
        dictFieldFrom   = new DictField(_from.TableId, fieldIdFrom);


        if(dictFieldFrom)
        {
            fieldIdTo = dictTableTo.fieldName2Id(dictFieldFrom.name());


            if(fieldIdTo)
                _to.(fieldIdTo) = _from.(fieldIdFrom);
        }


        fieldIdFrom = dictTableFrom.fieldNext(fieldIdFrom);
    }
}

Source: http://mybhat.blogspot.in/2012/07/dynamics-ax-buf2buf-and-buf2bufbyname.html

Friday, September 23, 2016

Redirect WMS page to Login Screen AX2012

Hi Guys,

We had a requirement with a client wherein they wanted to see the WMS login screen rather than the WMS Homepage to save that 1 extra click ;)

So to achieve this I had to make a small change in the "Index.aspx" file located at "C:\Program Files (x86)\Microsoft Dynamics AX\60\Warehouse Mobile Devices Portal\00\Views\Home".

The change was a small script to redirect the page:

<script type="text/javascript">
setTimeout('Redirect()',10);
function Redirect()
{
  location.href = 'http://wmsServerName:port/Execute/Display';
}
</script>

So this script will take you directly from 








To this screen:


Friday, July 8, 2016

Checklist can't be skipped Ax2012

Today I faced an issue where I had installed a Hotfix and completed the checklist but even after that the checklist kept popping up.

Then I came to know about the table which controls it. It's named "ReleaseUpdateConfiguration" and there is a field "MinorUpgrade" which will be checked. So in this case we need to uncheck it and the magic happens!

Source: http://yetanotherdynamicsaxblog.blogspot.in/2014/03/skip-modelstore-has-been-modified-dialog.html

Wednesday, April 27, 2016

Filter on display method using context method

You may find a lot of codes for the same purpose but the one which worked flawlessly for me is written below:

Write the below code in the executeQuery method of the root DS:

public void executeQuery()
{
super();

if(!queryObj)
{
queryObj = true;
existQuery = new Query(this.query());
existQuery.saved();
remFilQuery = new Query();
remFilQuery = existQuery;
remFilQuery = existQuery.makeCopy();
}
}

Now the context method in the display method control:
public void context()
{
int selectedMenu;
formrun fr;
Args ag;
Name strtext;
str filSel = ”;
querybuilddataSource qb1, qb2, qb3;
queryrun qr;
query q, q2;
PopupMenu menu = new PopupMenu(element.hWnd());
int a = menu.insertItem(‘Filter by field’);
int b = menu.insertItem(‘Filter by selection’);
int c = menu.insertItem(‘Clear’);
;

selectedMenu = menu.draw();
switch (selectedMenu)
{
case a: //Filter by field
ag = new args(‘SysformSearch’);
fr = new formrun(ag);
fr.run();
fr.wait();

//Reading User entered value for filter process
strtext = fr.design().controlName(‘FindEdit’).valueStr();
//strtext = ‘”‘ + fr.design().controlName(‘FindEdit’).valueStr() + ‘”‘;
if(strtext)
{
//Creating a query for filter
q = new Query(InventSerial_ds.query());
// existQuery = InventJournalTrans_ds.query();

qb1 = q.dataSourceTable(tablenum(InventSerial));

qb2 = qb1.addDataSource(TableNum(EcoResProduct));
qb2.addLink(FieldNum(InventSerial,ItemId),FieldNum(EcoResProduct,DisplayProductNumber));

qb3 = qb2.addDataSource(tableNum(EcoResProductTranslation));
qb3.relations(true);

qb3.addRange(fieldNum(EcoResProductTranslation, Name)).value(strtext);
qb3.addRange(fieldNum(EcoResProductTranslation, LanguageId)).value(infolog.language());

InventSerial_ds.query(q);
InventSerial_ds.executeQuery();

}

break;

case b: // Filter By Selection3

q = new Query(InventSerial_ds.query());

qb1 = q.dataSourceTable(tablenum(InventSerial));

qb2 = qb1.addDataSource(TableNum(EcoResProduct));
qb2.addLink(FieldNum(InventSerial,ItemId),FieldNum(EcoResProduct,DisplayProductNumber));

qb3 = qb2.addDataSource(tableNum(EcoResProductTranslation));
qb3.relations(true);

filSel = ‘”‘ + ItemDesc.valueStr() + ‘”‘;

qb3.addRange(fieldNum(EcoResProductTranslation, Name)).value(filSel);
qb3.addRange(fieldNum(EcoResProductTranslation, LanguageId)).value(infolog.language());

InventSerial_ds.query(q);
InventSerial_ds.executeQuery();

break;

case c : // Remove Filter

InventSerial_ds.query(remFilQuery);
InventSerial_ds.executeQuery();

break;

Default:
break;
}
}

Credits: https://msddax.wordpress.com/2014/11/29/filter-on-the-display-method-using-context-method/

Tuesday, March 22, 2016

Repeat table header SSRS

Sounds easy going by the usual way of Tablix properties and check the "Repeat header rows on each page". Strangely this didn't work for me today so I found out a new way for same.

Under Design Pane - > at the bottom Column Groups - > click on drop down (down arrow) - > Advanced Mode.



Once we selected Advanced Mode, we will be able to notice (static) in Row Groups and Column Groups at the bottom of Design pane .



Under Design Pane - > Row Groups - > click on (static) - > Press F4 - > Properties window will pop-up.

In the Properties window - >Set KeepWithGroup = After and RepeatOnNewPage = True.

If you want the header to be frozen while scrolling down the report, set FixedData = True.




Credit: http://social.technet.microsoft.com/wiki/contents/articles/19398.ssrs-how-to-repeat-headers-on-each-page.aspx

Thursday, September 10, 2015

Add KPI to Role Center AX2012

It's easy to add KPI/Indicators to the Role Centers but it's a time consuming & tiring task to add multiple KPI/Indicators to the role center. But today I have found out a quick way to do so.

Firstly just add a KPI web part to the role center page.
Go to the Page Definition in AOT, right click on it and click "View Code". Then add a small piece of code just after the ending line of KPI webpart code:

&lt;ArrayOfIndicator xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;

After the above line add the below given code and change the Cube name & Indicator Name or other required properties of the KPI accordingly. Most importantly change the Id for every KPI.

&lt;Indicator&gt;
    &lt;Id&gt;ae413b36-9f55-40d5-ae21-a8d3ceaa83cc&lt;/Id&gt;
    &lt;CubeName&gt;General ledger cube&lt;/CubeName&gt;
    &lt;MeasureName&gt;Accounts receivable turnover&lt;/MeasureName&gt;
    &lt;DisplayTitle /&gt;
    &lt;SliceDimensionAttribute /&gt;
    &lt;TimePeriodsName /&gt;
    &lt;RolePlayingTimeDimension /&gt;
    &lt;ReportPath /&gt;
    &lt;ValueType&gt;Amount&lt;/ValueType&gt;
    &lt;IsDecreasingBetter&gt;false&lt;/IsDecreasingBetter&gt;
    &lt;Visible&gt;true&lt;/Visible&gt;
    &lt;IsValid&gt;true&lt;/IsValid&gt;
    &lt;EnableFilters&gt;false&lt;/EnableFilters&gt;
    &lt;DateFilters&gt;
      &lt;DateFilterItem&gt;
        &lt;DateTimeDimension&gt;Acknowledgement date&lt;/DateTimeDimension&gt;
        &lt;TimePeriod&gt;Current_KPI&lt;/TimePeriod&gt;
      &lt;/DateFilterItem&gt;
    &lt;/DateFilters&gt;
    &lt;NonDateFilters /&gt;
    &lt;ReportClientMenuItem /&gt;
    &lt;ReportWebMenuItem /&gt;
    &lt;CompareMeasureName /&gt;
    &lt;CompareMeasureCaption /&gt;
    &lt;SplitOrder&gt;Top&lt;/SplitOrder&gt;
    &lt;NonEmpty&gt;true&lt;/NonEmpty&gt;
    &lt;SplitCount&gt;10&lt;/SplitCount&gt;
  &lt;/Indicator&gt;

Wednesday, September 9, 2015

Ax2012 Number Sequence with year

Source:

http://dev.goshoom.net/en/2013/10/year-in-number-sequence/

Reset Number sequence Ax2012

Whenever you need to reset the number sequence in AX2012 you can use the below job code. You just need to pass the company name for which you want to reset.

static void resetNumSeq(Args _args)
{
    NumberSequenceTable numseqtab;
    info(curext());
    changecompany ('test')
    {
        ttsbegin;
        while select forupdate numseqtab
        {
            numseqtab.NextRec = numseqtab.Lowest;
            numseqtab.update();
        }
        ttscommit;
    }
}

Monday, August 31, 2015

Delete all transactions Ax2012

There is a class named "SysDatabaseTransDelete" in Axapta which can be used to delete all the transactions from your Ax Db but will not delete the base setups. In that case we can use the same DB as Production Db.
NOTE: It works perfectly with Ax2012 CU3 and above as it is now updated for new DB structure. Otherwise you may face issues with General Journal/Trial balance data.
It deletes all data from tables in the Transaction, WorksheetHeader and WorksheetLine table groups plus the following tables...
       SalesTable
       PurchTable
       WMSPallet
       CustInterestJour
       CustCollectionLetterJour
       ProjControlPeriodTable
       ProjInvoiceJour
       ProjJournalTable
       PdsRebateTable
       PdsBatchAttributes
You can run it from the AOT by right clicking on the SysDatabaseTransDelete class node and selecting "open" - this isn't the sort of thing you would want to put on a menu anywhere.
Here is a job for the same:
static void deleteTransactions(Args _args)
{
SysDatabaseTransDelete delete;
;
delete = new SysDatabaseTransDelete();
delete.run();
}

Friday, August 21, 2015

AX2012 R3: DIXF Could not load assembly error

While working on DIXF there can be scenario where you may face errors where assemblies are not able to load properly. Like below:

"Could not load file or assembly 'microsoft.dynamics.ax.framework.tools.dmf.previewgrid.dll'"

In this case you can use 2 options:

1. You can reinstall DIXF Client.
2. You can copy the dll file mentioned in the error from one AOS where it's working properly and paste it to the AOS where the error is coming. The file location is "C:\Program Files (x86)\Microsoft Dynamics AX\60\Client\Bin".

Delete company in AX2012 using SQL

Sometimes we are not able to delete company from AX due to existing transactions then SQL comes to the rescue and does the job beautifully.

There is a Stored Procedure in "master" database named "sp_MSforeachtable". Use the below commands:


This will delete all the transactions from all the tables related to that particular company:


EXEC sp_MSforeachtable 'delete from ? where ?.DataAreaID = "CEU"'


This will delete the company name from the company list in AX:


DELETE FROM DATAAREA WHERE DATAAREA.ID 'CEU'