Saturday, September 8, 2018

Batch job History Log Cleanup code in Axapta till specified date

You can clear log for batch job history in Ax by following code. This code can work in most of ax version .

If you want to clear  log till some date that you can also specify in query . You can just copy and paste below code run or execute.

 BatchJobHistory BatchJobHistory;  
   date startDate;  
   TimeOfDay      startTime;  
   utcDateTime     rangeStart;  
   startDate=mkDate(21,12,2014);  
   startTime  = str2time("6:00:00 am");  
   rangeStart = DateTimeUtil::newDateTime(startDate,startTime);  
   delete_from BatchJobHistory where BatchJobHistory.createdDateTime<rangeStart;  
 //select count(RecId) from BatchJobHistory where BatchJobHistory.createdDateTime<rangeStart ;  
  // info(strFmt("%1 till cleanup done ",BatchJobHistory.RecId));  
    info(strFmt("%1 till cleanup done ",rangeStart));  

Thursday, March 22, 2018

How to get Customer,Vendor VAT Registration Number by code in Axapta


To get Customer,Vendor VAT Registration Number by code in Axapta in 2012 version you can try below code in data method on table label then you can use the method in string control on form .

This code will work perfectly .

 display name Get_TaxRegistration()  
 {  
   TransDate _transDate = systemDateGet();  
   DirPartyLocation            dirPartyLocation;  
   TaxRegistration             taxRegistration;  
   TaxRegistrationTypeApplicabilityRule  taxRegistrationTypeApplicabilityRule;  
   if (_transDate)  
   {  
     dirPartyLocation = DirPartyLocation::findByPartyLocation(  
       this.Party,  
       this.invoiceAddress().Location);  
     if (dirPartyLocation)  
     {  
       select firstonly validTimeState(_transDate) taxRegistration  
         where taxRegistration.DirPartyLocation == dirPartyLocation.RecId  
         join RecId from taxRegistrationTypeApplicabilityRule  
           order by taxRegistrationTypeApplicabilityRule.IsPrimaryAddressRestricted desc  
           where taxRegistration.TaxRegistrationTypeApplicabilityRule == taxRegistrationTypeApplicabilityRule.RecId;  
     }  
   }  
   return taxRegistration.RegistrationNumber;  
 }  

Wednesday, March 14, 2018

Code to Confirm and Post Project Item Requirement for Sales Order in Ax 2012

This is a sample Code to confirm and Post Project Item Requirement for Sales Order in Ax 2012 . You need to pass sales order in salesFormLetter class method update and you can pass transaction date or posting date as per your need it will create or post project sales order item requirement packing slip. Its same functionality as post button on project item requirement form.

 SalesFormLetter salesFormLetter;  
   salesTable Salestablelocal;  
   str 200 msg;  
   salesid salesid;  
   if(salesid)  
   {  
       select Salestablelocal  
         where Salestablelocal.Salesid ==salesid  
           && Salestablelocal.salestype==SalesType::ItemReq  
           && Salestablelocal.SalesStatus==SalesStatus::Backorder;  
       if(Salestablelocal)  
       {  
         ttsBegin;  
           salesFormLetter = SalesFormLetter::construct(DocumentStatus::Confirmation);  
           salesFormLetter.update(Salestablelocal);  
           salesFormLetter = SalesFormLetter::construct(DocumentStatus::ProjectPackingSlip);  
           salesFormLetter.update(Salestablelocal);  
         ttsCommit;  
           msg = "Item Requirement with Sales order id : " + salesid + " Posted ";  
       }  
       else  
       {  
           msg = "Item Requirement with Sales order id: "+ salesid + " already posted";  
       }  
   }  
   else  
   {  
      msg = "Item Requirement with provided Sales order id does not exists";  
   }  

Monday, February 12, 2018

Code to get opening balance for Ledger Main account in Ax 2012

If you want to check opening balance for particular main account then you can check below code to get the same.

This is sample Code to get opening balance for Ledger Main account in Ax 2012.

  LedgerBalanceMainAccountAmounts ledgerBalance;  
   AmountMst  opSum;  
   ;  
   ledgerBalance = LedgerBalanceMainAccountAmounts::construct();  
   ledgerBalance.parmIncludeRegularPeriod(true);  
   ledgerBalance.parmIncludeOpeningPeriod(true);  
   ledgerBalance.parmIncludeClosingPeriod(false);  
   ledgerBalance.parmAccountingDateRange(mkDate(01,01,2000), mkDate(31,12,2017));  
   ledgerBalance.calculateBalance(MainAccount::findByMainAccountId('1123333'));  
   opSum = ledgerBalance.getAccountingCurrencyBalance();  
   info(num2str(opSum,10,2,1,1));  

Code to get Miscellaneous charges of purchase line in Ax 2012

This is Code to get Miscellaneous charges of purchase line in Ax 2012. You can try below code to check in job.

 PurchTable purchTable;  
   PurchLine purchLine;  
   MarkupTrans markupTrans;  
   while select * from purchLine  
   Join purchTable  
   Join markupTrans  
   Where purchTable.PurchId == purchLine.PurchId  
     && markupTrans.TransRecId == purchLine.RecId  
     && purchTable.PurchId=="PO-0000043"  
   {  
     info(strFmt("%1 , %2 , %3",purchLine.PurchId,markupTrans.Txt,markupTrans.Value));  
   }  

Thursday, February 8, 2018

Code to approve bom for product in Ax 2012.

Code to approve bom for product in Ax 2012.If you are creating or uploading bom list by code then auto approval may required,below code will help to approve bom item automatically.

 void God_setBOMActive(BOMId bomid,str 20 approver1)  
 {  
   BOMVersion BOMVersion1;  
   BOMApprove bomApprove = new BOMApprove();  
   RecId approver = HcmWorker::findByPersonnelNumber(approver1).RecId;  
   boolean ret=true;  
   try  
   {  
     select forUpdate BOMVersion1 where BOMVersion1.BOMId==bomid;  
     BOMVersion1.selectForUpdate();  
     BOMVersion1.Approved = true;  
     BOMVersion1.Active = true;  
     BOMVersion1.Approver = approver;  
     ttsBegin;  
     BOMVersion1.write();  
     ttsCommit;  
     bomApprove.init();  
     bomApprove.parmApprover(approver);  
     bomApprove.parmBOMId(bomid);  
     bomApprove.run();  
   }  
   catch  
   {  
     info(strFmt("(%1) approval failed.", bomid));  
   }  
 }  

Saturday, January 13, 2018

Getting Error on AIF Web service enabling for custom class in Ax 2012

Problem
I am Getting below Errors on AIF Web service enabling for custom class in Ax 2012.

1.Application pool 'MicrosoftDynamicsAXAif60' is being automatically disabled due to a series of failures in the process(es) serving that application pool.


2.
There was an error during processing of the managed application service auto-start for configuration path: 'MACHINE/WEBROOT/APPHOST/Default Web Site/MicrosoftDynamicsAXAif60'. The error message returned is: 'An initialization error occurred while trying to preload an application.

Exception: System.Configuration.ConfigurationErrorsException

Message: Duplicate type with name 'Dynamics.Ax.Application.NewItem' in assembly 'Dynamics.Ax.Application, Version=6.3.1000.309, Culture=neutral, PublicKeyToken=null'.

StackTrace:    at System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective)
   at System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory()
   at System.Web.Configuration.AssemblyInfo.get_AssemblyInternal()
   at System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig)
   at System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded)
   at System.Web.Compilation.BuildManager.ExecutePreAppStart()
   at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException)

InnerException: System.BadImageFormatException

Message: Duplicate type with name 'Dynamics.Ax.Application.NewItem' in assembly 'Dynamics.Ax.Application, Version=6.3.1000.309, Culture=neutral, PublicKeyToken=null'.

StackTrace:    at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection)
   at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   at System.Reflection.Assembly.Load(String assemblyString)
   at System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective)'.  The worker process will be marked unhealthy and be shutdown.  The data field contains the error code.


Solution:After struggling a lot I found solution for this which I am sharing here to help you and save your time.

Following steps I did to resolve this issues.

1.Stop AOS, 
2.Truncate table SYSXPPAssembly, 
3.delete folder xppil form Bin folder
C:\Program Files\Microsoft Dynamics AX\60\Server\AX_60_Dynamics_TEST\Bin\
4.Run AOS services, 
5.Axbuild, and full compile full cil
6.the problem cause the dll and net module not refresh delete all file in C:\Program Files\Microsoft Dynamics AX\60\AifWebServices\Bin
7.Enable customized port in ax again 
Now problem resolved enjoy and happy daxing.

Thursday, December 14, 2017

Solved:Getting Error during Full CIL in Ax 2012 R3 CU11

I am Getting Error during Full CIL in Ax 2012 R3 CU11 version.

"The SysWorkflowDictElement.getAttribute() reflection API could not create and return the AifCollectionTypeAttribute object. Please check the parameters."

No any single report executing and giving parameter related error then tried to do full CIL then above error coming.

Solution: Solution of this issue is as below.
1.
first, compile the class mentioned in the error message and see if this solves the problem if not then use compile forward option.
2.Then use incremental compile option if again other class error coming then compile again till incremental compile issue not resolved.

3. Once incremental compile did then do full CIL.

4. Then if the issue still exists then do steps.


1) first stop the aos services and go to the folder of the XPPIL folder and delete all files

2) start the services of aos

3) and do the incremental CIL

4)THEN  Do FULLY CIL, THEN ALL THE SERVICE WILL BE STARTED.

5) If the issue still exists then you need to compile AOT and stop-start service then try to do full CIL.It will take minimum 3 hours.

Friday, November 17, 2017

Import References for SSRS Report user Control in Enterprise portal axapta

Following Import References  are required in using section for Creating SSRS Report user Control in Enterprise portal axapta

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.DataVisualization.Charting;  
 using System.Web.UI.WebControls;  
 using Microsoft.Dynamics.Framework.Portal.UI.WebControls;  
 using Microsoft.Dynamics.Framework.Portal.UI.WebControls.WebParts;  
 using System.Diagnostics;  
 using Microsoft.Dynamics.AX.Framework.Reporting.Shared;  
 using Microsoft.Dynamics.Framework.BusinessConnector.Session;  
 using Microsoft.Dynamics.AX.Framework.Portal.Data;  
 using Microsoft.Dynamics.Framework.Portal.CommonControls;  
 using System.Globalization;  
 using Microsoft.Dynamics.AX.Framework.Services.Client;  
 using Microsoft.Dynamics.Framework.Portal;  
 using Microsoft.Dynamics.Framework.Portal.UI;  
 using Proxy = Microsoft.Dynamics.Framework.BusinessConnector.Proxy;  
 using Microsoft.Dynamics.Framework.BusinessConnector.Adapter;  
 using System.Security.Principal;  

Add Financial dimension Lookup at Enterprise portal in Axapta

To Add Financial dimension Lookup at Enterprise portal in Axapta you can to help with below code.

 protected void BusinessSector_LookUp(object sender, AxLookupEventArgs e)  
     {  
       //Getcurrent user to filter record based on current user   
       String usr = WindowsIdentity.GetCurrent().Name;  
       int pos = usr.IndexOf('\\');  
       usr = pos != -1 ? usr.Substring(pos + 1) : usr;  
       AxLookup lookup = (AxLookup)sender;  
       // Create the lookup data set. The respective table will be used.  
       Proxy.SysDataSetBuilder sysDataSetBuilder;  
       sysDataSetBuilder = Proxy.SysDataSetBuilder.constructLookupDataSet(AxSession.AxaptaAdapter, TableMetadata.TableNum(AxSession, "DimensionFinancialTag"));  
       // Set the generated data set as the lookup data set.  
       lookup.LookupDataSet = new DataSet(AxSession, sysDataSetBuilder.toDataSet());  
       using (Proxy.Query query = lookup.LookupDataSet.DataSetViews[0].MasterDataSource.query())  
       {  
         query.dataSourceNo(1).addRange(TableArrayFieldMetadata.FieldNum(this.AxSession, "DimensionFinancialTag", "FinancialTagCategory")).value = "5637146078";  
       }  
       // Specify the fields for the lookup.  
       lookup.Fields.Add(AxBoundFieldFactory.Create(AxSession, lookup.LookupDataSetViewMetadata.ViewFields["Description"]));  
       lookup.Fields.Add(AxBoundFieldFactory.Create(AxSession, lookup.LookupDataSetViewMetadata.ViewFields["Value"]));  
       lookup.SelectField = "Value";  
 }  

X++ code to print sales invoice on printer directly

Below is the X++ code to print sales invoice on printer directly.

  Args          salesArgs = new Args();  
   SalesInvoiceContract  salesInvoiceContract;  
   SalesInvoiceController controller;  
   SrsReportRunImpl    srsReportRunImpl;  
   str fileName;  
   CustInvoiceJour     custInvoiceJour;// = _args.record();  
     select custInvoiceJour where custInvoiceJour.InvoiceId=="INV_00000009";  
   salesArgs.record(custInvoiceJour);  
   controller       = new SrsReportRunController();  
   salesInvoiceContract  = new SalesInvoiceContract();  
   controller.parmReportName(ssrsReportStr(SalesInvoice,Report));  
   controller.parmShowDialog(false);  
   controller.parmReportContract().parmPrintSettings().printMediumType(SRSPrintMediumType::Printer);  
   // controller.parmReportContract().parmPrintSettings().printerName(@"\\espprn03\Follow Me - MFP");  
   salesInvoiceContract.parmRecordId(custInvoiceJour.RecId); // Record id must be passed otherwise the report will be empty  
   salesInvoiceContract.parmCountryRegionISOCode(SysCountryRegionCode::countryInfo()); // comment this code if tested in pre release  
   controller.parmReportContract().parmRdpContract(salesInvoiceContract);  
   controller.startOperation();  

Thursday, November 16, 2017

Ax 2012 Form Development,User control,Role centers,Citrix lookup issues




Simple form development using multiple tables
How to create role center in Ax 2012


Custom lookup issue On citrix client



How to create User control on EP website