Thursday, January 21, 2016

Batch Mail through VS.. Reports

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
using System.Diagnostics;
namespace epicmail
{
    public partial class Form1 : Form
    {
        List<string> data;
        List<string> cren;
        List<string> subj;
        List<string> body;
        List<string> frm;
        List<string> to;
        List<string> cc;
        List<string> files;
        string sSource;
        string sLog;
        string sEvent;
        int flag = 0;
        private readonly string path = @"c:\config\mailconfig.txt";
        private readonly string mailfile = @"c:\Report\";
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
        }
        protected void loadData()
        {
            string line = string.Empty;
            string header = string.Empty;
            cren = new List<string>();
            subj = new List<string>();
            body = new List<string>();
            frm = new List<string>();
            to = new List<string>();
            cc = new List<string>();
            files = new List<string>();
            if (Directory.Exists(mailfile))
            {
               
                string[] p = Directory.GetFiles(mailfile);
                foreach (string pt in p)
                {
                    flag = 1;
                    files.Add(pt);
                }
            }
            else
            {
                sSource = "Robot Mail Application";
                sLog = "Application";
                sEvent = "Please check the mail or configuration file.\r\n!!!";
                if (!EventLog.SourceExists(sSource))
                    EventLog.CreateEventSource(sSource, sLog);
                EventLog.WriteEntry(sSource, sEvent);
                EventLog.WriteEntry(sSource, sEvent,
                    EventLogEntryType.Error, 234);
                flag = 0;
            }
            if (File.Exists(path) && flag == 1)
            {
                data = new List<string>();
                using (StreamReader sr = new StreamReader(path))
                {
                    if (sr != null)
                    {
                        while ((line = sr.ReadLine()) != null)
                        {
                            data.Add(line);
                            flag = 1;
                        }
                    }
                    else
                    {
                        sSource = "Robot Mail";
                        sLog = "Application";
                        sEvent = "Please check the mail or configuration file.\r\n!!!";
                        if (!EventLog.SourceExists(sSource))
                            EventLog.CreateEventSource(sSource, sLog);
                        EventLog.WriteEntry(sSource, sEvent);
                        EventLog.WriteEntry(sSource, sEvent,
                            EventLogEntryType.Error, 234);
                        flag = 0;
                    }
                }
                if (flag == 1)
                {
                    foreach (string s in data)
                    {
                        if (!s.Contains("="))
                        {
                            if (s.ToUpper() == "SMTP" || s.ToUpper() == "SUBJECT" || s.ToUpper() == "BODY" || s.ToUpper() == "FROM" || s.ToUpper() == "TO" || s.ToUpper() == "CC")
                            {
                                header = s;
                            }
                            if (header.ToUpper() == "SMTP" && s.ToUpper() != "SMTP")
                            {
                                cren.Add(s);
                            }
                            if (header.ToUpper() == "SUBJECT" && s.ToUpper() != "SUBJECT")
                            {
                                subj.Add(s);
                            }
                            if (header.ToUpper() == "BODY" && s.ToUpper() != "BODY")
                            {
                                body.Add(s);
                            }
                            if (header.ToUpper() == "FROM" && s.ToUpper() != "FROM")
                            {
                                frm.Add(s);
                            }
                            if (header.ToUpper() == "TO" && s.ToUpper() != "TO")
                            {
                                to.Add(s);
                            }
                            if (header.ToUpper() == "CC" && s.ToUpper() != "CC")
                            {
                                cc.Add(s);
                            }
                        }

                    }
                }
            }
            else
            {
                sSource = "Robot Mail";
                sLog = "Application";
                sEvent = "Please check the mail or configuration file.\r\n!!!";
                if (!EventLog.SourceExists(sSource))
                    EventLog.CreateEventSource(sSource, sLog);
                EventLog.WriteEntry(sSource, sEvent);
                EventLog.WriteEntry(sSource, sEvent,
                    EventLogEntryType.Error, 234);
            }
        }
        protected void sendMail()
        {
            MailMessage mailMessage = new MailMessage();
            foreach (string t in to)
            {
                mailMessage.To.Add(t);
            }
            foreach (string m in subj)
                mailMessage.Subject = m;
            foreach (string c in cc)
                mailMessage.CC.Add(c);
            string bd = string.Empty;
            foreach (string b in body)
            {
                bd = bd + b;
            }
            mailMessage.Body = bd;
           
            foreach (string f in files)
                mailMessage.Attachments.Add(new Attachment(f));
            mailMessage.From = new MailAddress(frm[0]);
            mailMessage.IsBodyHtml = true;//false;
            SmtpClient sc = new SmtpClient(cren[0]);
            sc.Port = 587;
            sc.Credentials = new NetworkCredential(cren[1], cren[2]);
            sc.EnableSsl = true;//false
            sc.Send(mailMessage);
            mailMessage.Dispose();
            mailMessage = null;
            sc.Dispose();
            sc = null;
        }
        protected void delFile()
        {
            try
            {
               
               
                Directory.CreateDirectory(@"C:\Report");
                String[] f = Directory.GetFiles(@"C:\Report");
                foreach (string f1 in f)
                    File.Delete(f1);
               
            }
            catch (IOException ex)
            {
                sSource = "Robot Mail";
                sLog = "Application";
                sEvent = ex.Message;
                if (!EventLog.SourceExists(sSource))
                    EventLog.CreateEventSource(sSource, sLog);
                EventLog.WriteEntry(sSource, sEvent);
                EventLog.WriteEntry(sSource, sEvent,
                    EventLogEntryType.Error, 234);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                loadData();
                if (flag == 1)
                    sendMail();
                sSource = "Robot Mail Application";
                sLog = "Application";
                sEvent = "Mail send successfully.";
                EventLog.WriteEntry(sSource, sEvent);
                EventLog.WriteEntry(sSource, sEvent,
                    EventLogEntryType.Information, 234);
                delFile();
                this.Close();
                this.Dispose();
            }
            catch (Exception ex)
            {
                sSource = "Robot Mail Application";
                sLog = "Application";
                sEvent = ex.Message;
                if (!EventLog.SourceExists(sSource))
                    EventLog.CreateEventSource(sSource, sLog);
                EventLog.WriteEntry(sSource, sEvent);
                EventLog.WriteEntry(sSource, sEvent,
                    EventLogEntryType.Error, 234);
            }
        }
    }
}

Product Category Update ax 2012


//CSV

static void UpdateInsertProdCatCSV(Args _args)
{
    EcoResProduct                   ecoResProduct;
    EcoResProductCategory           ecoResProductCategory;
    ecoResCategoryHierarchy         ecoResCategoryHierarchy;
    Name                            itemName,CatHrName,CatName;
    CommaTextIO                 csvFile;
    container                   readCon;
    counter                     icount,inserted;
    Dialog                      dialog;
    DialogField                 dfFileName;
    FileName                    fileName;
    ItemId      itemId;
     #File

    dialog = new Dialog("PicK CSV file");
    dfFileName = dialog.addField(extendedTypeStr("FilenameOpen"));
    dialog.filenameLookupFilter(["All files", #AllFiles]);
    info(curext());
    if (dialog.run())
    {
        csvFile = new CommaTextIo(dfFileName.value(), 'r');
        csvFile.inFieldDelimiter(',');
        readCon = csvFile.read();
        ttsBegin;
        while(csvFile.status() == IO_Status::OK)
        {
            readCon = csvFile.read();
            if(readCon)
            {
                icount++;
                itemName  = conpeek(readCon,1);
                CatHrName  = conpeek(readCon,2);
                CatName  = conpeek(readCon,3);
                select forUpdate ecoResProduct
                    where ecoResProduct.DisplayProductNumber ==  itemName;   // Item Number
                select forUpdate ecoResProductCategory
                    where ecoResProductCategory.Product == EcoResProduct::findByDisplayProductNumber(ecoResProduct.DisplayProductNumber).RecId;
                if(ecoResProductCategory)
                {
                    ttsBegin;
                    ecoResProductCategory.Product = EcoResProduct::findByDisplayProductNumber(ecoResProduct.DisplayProductNumber).RecId;
                    ecoResCategoryHierarchy = ecoResCategoryHierarchy::findByName(CatHrName);
                    ecoResProductCategory.CategoryHierarchy = ecoResCategoryHierarchy.RecId;
                        ecoResProductCategory.Category = EcoResCategory::findByName(CatName,ecoResCategoryHierarchy.RecId).RecId;
                        ecoResProductCategory.update();
                    ttsCommit;
                }
                if(!ecoResProductCategory)
                {
                    ecoResProductCategory.Product = EcoResProduct::findByDisplayProductNumber(ecoResProduct.DisplayProductNumber).RecId;
                    ecoResCategoryHierarchy = ecoResCategoryHierarchy::findByName(CatHrName);
                    ecoResProductCategory.CategoryHierarchy = ecoResCategoryHierarchy.RecId;
                    // Category Nam
                    ecoResProductCategory.Category = EcoResCategory::findByName(CatName,ecoResCategoryHierarchy.RecId).RecId;
                    ecoResProductCategory.insert();
                }
            }
        }
        ttsCommit;
    }
}

//Job - One time update

static void UpdateInsertProductCategoryHierarchy(Args _args)
{
    EcoResProduct _EcoResProduct;
    EcoResProductCategory _EcoResProductCategory;
    EcoResCategoryHierarchy EcoResCategoryHierarchy;
    ;
    select forUpdate _EcoResProduct
    where _EcoResProduct.DisplayProductNumber == "AS000000001";   // Item Number
    select forUpdate _EcoResProductCategory
    where _EcoResProductCategory.Product == EcoResProduct::findByDisplayProductNumber(_EcoResProduct.DisplayProductNumber).RecId;
    if(_EcoResProductCategory)
    {
        ttsBegin;
        _EcoResProductCategory.Product = EcoResProduct::findByDisplayProductNumber(_EcoResProduct.DisplayProductNumber).RecId;
        EcoResCategoryHierarchy = EcoResCategoryHierarchy::findByName("PROCUREMENT");
        _EcoResProductCategory.CategoryHierarchy = EcoResCategoryHierarchy.RecId;
          _EcoResProductCategory.Category = EcoResCategory::findByName('ALL',EcoResCategoryHierarchy.RecId).RecId;
           _EcoResProductCategory.update();
        ttsCommit;
    }
    if(!_EcoResProductCategory)
    {
        ttsBegin;
        _EcoResProductCategory.Product = EcoResProduct::findByDisplayProductNumber(_EcoResProduct.DisplayProductNumber).RecId;
        EcoResCategoryHierarchy = EcoResCategoryHierarchy::findByName("PROCUREMENT");//Category Hierarchy Name
        _EcoResProductCategory.CategoryHierarchy = EcoResCategoryHierarchy.RecId;
        // Category Nam
        _EcoResProductCategory.Category = EcoResCategory::findByName('ALL',EcoResCategoryHierarchy.RecId).RecId;
        _EcoResProductCategory.insert();
        ttsCommit;
    }
}

//EXCEL

static void UpdateInsertProductCategoryHierarchy(Args _args)
{
    EcoResProduct                   ecoResProduct;
    EcoResProductCategory           ecoResProductCategory;
    ecoResCategoryHierarchy         ecoResCategoryHierarchy;
    Name                            itemName,CatHrName,CatName;
    SysExcelApplication application;
    SysExcelWorkbooks   workbooks;
    SysExcelWorkbook    workbook;
    SysExcelWorksheets  worksheets;
    SysExcelWorksheet   worksheet;
    SysExcelCells       cells;
    COMVariantType      type;
    int                 row = 1;
    int i=0;
    Dialog              dialog;
    DialogField         dfFileName;
    Filename template;
    #File

    dialog = new Dialog("Select Excel to Import/Update Product Category");
    dfFileName = dialog.addField(extendedTypeStr("FilenameOpen"));
    dialog.filenameLookupFilter(["All files", #AllFiles]);
    if (dialog.run())
    {
        template = dfFileName.value();
        application = SysExcelApplication::construct();
        workbooks = application.workbooks();
        try
        {
            workbooks.open(template);
        }
        catch (Exception::Error)
        {
            throw error("File cannot be opened.");
        }
        workbook = workbooks.item(1);
        worksheets = workbook.worksheets();
        worksheet = worksheets.itemFromNum(1);
        cells = worksheet.cells();
        do
        {
            row++;
            itemName  = cells.item(row,3).value().bStr();
            CatHrName  = "Procurement";
            CatName  = cells.item(row,2).value().bStr();
            select forUpdate ecoResProduct
            where ecoResProduct.DisplayProductNumber ==  itemName;   // Item Number
            select forUpdate ecoResProductCategory
            where ecoResProductCategory.Product == EcoResProduct::findByDisplayProductNumber(ecoResProduct.DisplayProductNumber).RecId;
            if(ecoResProductCategory)
            {
                ttsBegin;
                ecoResProductCategory.Product = EcoResProduct::findByDisplayProductNumber(ecoResProduct.DisplayProductNumber).RecId;
                ecoResCategoryHierarchy = ecoResCategoryHierarchy::findByName(CatHrName);
                ecoResProductCategory.CategoryHierarchy = ecoResCategoryHierarchy.RecId;
                    ecoResProductCategory.Category = EcoResCategory::findByName(CatName,ecoResCategoryHierarchy.RecId).RecId;
                    ecoResProductCategory.update();
                ttsCommit;
            }
            if(!ecoResProductCategory)
            {
                ttsBegin;
                ecoResProductCategory.Product = EcoResProduct::findByDisplayProductNumber(ecoResProduct.DisplayProductNumber).RecId;
                ecoResCategoryHierarchy = ecoResCategoryHierarchy::findByName(CatHrName);
                ecoResProductCategory.CategoryHierarchy = ecoResCategoryHierarchy.RecId;
                // Category Nam
                ecoResProductCategory.Category = EcoResCategory::findByName(CatName,ecoResCategoryHierarchy.RecId).RecId;
                ecoResProductCategory.insert();
                ttsCommit;
            }
            i++;
            type = cells.item(row+1, 1).value().variantType();
        }
        while (type != COMVariantType::VT_EMPTY);
        application.quit();
        info(strFmt("No of Record inserted %1",i));
    }
}

Vendor Address /Contact Person Upload AX 2012

static void UploadVendorAddress(Args _args)
{
         CommaTextIO                             csvFile;
    int                     row = 1;
    int                     i = 0;
     container                               readCon;
     counter                                 icount,inserted;
     Dialog                                  dialog;
     DialogField                             dfFileName;
     DirPartyRecId                           partyRecId,contactPartyRecid;
     VendTable                               vendtable;
     str                                     contactperson;
     DirPartyPostalAddressView               addressView;
     DirPartyContactInfoView                 contactView;
     ContactPerson                           contactpersonTable;
     LogisticsElectronicAddressMethodType    enumType;
     DirContactPersonsService                dirContactPersonsService;
     DirContactPersons                       dirContactPersons;
     DirContactPersons_ContactPerson         dirContactPersons_ContactPerson;
     DirContactPersons_Person                dirContactPersons_Person;
     DirContactPersons_PersonName            dirContactPersons_PersonName;
     AifEntityKeyList                        aifEntityKeyList, aifEntityKeyList_DirContactPerson;
     str                                     fName, mName, lName;
     VendAccount                             vendorAccount;
     DirParty                                dirParty;
     LogisticsPostalAddress                  address;
     LogisticsElectronicAddress              logisticsElectronicAddress;
     BinData                                 binData;
     str                                     stringImage;
     LogisticsAddressStateID                 stateId;
     str                                     accountnum,accountName,vendgroup,currency,dlvmode,paymtermid,countryid,street,city,mobile,fax,email,zipcode,pobox,phone;
     Filename filename;
    SysExcelApplication     application;
    SysExcelWorkbooks       workbooks;
    SysExcelWorkbook        workbook;
    SysExcelWorksheets      worksheets;
    SysExcelWorksheet       worksheet;
    SysExcelCells           cells;
    COMVariantType          type;
    ;
    #File
    dialog     = new Dialog("Select Excel to Import");
    dfFileName = dialog.addField(extendedTypeStr("FilenameOpen"));
    dialog.filenameLookupFilter(["All files", #AllFiles]);
    if (dialog.run())
    {
        filename    = dfFileName.value();
        application = SysExcelApplication::construct();
        workbooks   = application.workbooks();
        try
        {
            workbooks.open(filename);
        }
        catch (Exception::Error)
        {
            throw error("File cannot be opened.");
        }
        workbook    = workbooks.item(1);
        worksheets  = workbook.worksheets();
        worksheet   = worksheets.itemFromNum(1);
        cells = worksheet.cells();
        do
        {
                row++;
                accountnum = cells.item(row,1).value().bStr();
                street = cells.item(row,2).value().bStr();
                countryid = cells.item(row,3).value().bStr();
                fax =cells.item(row,5).value().bStr();
                phone = cells.item(row,6).value().bStr();
                mobile = cells.item(row,7).value().bStr();
                 vendtable = vendtable::find(accountnum);
                address.clear();
                 address.CountryRegionId = strLRTrim(Countryid);
                 address.Street  = strLRTrim(Street);
                addressView.clear();
                 addressView.IsPrimary = NoYes::Yes;
                 addressView.Party = vendtable.Party;
                 addressview.initFromPostalAddress(address);
                 DirParty = DirParty::constructFromPartyRecId(addressView.Party );
                 DirParty.createOrUpdatePostalAddress(addressView);

                    if(mobile)
                    {
                        contactView.clear();
                         contactView.LocationName = "Mobile";
                         contactView.Locator      = strLRTrim(mobile);
                         contactView.Type         = LogisticsElectronicAddressMethodType::Phone;
                         contactView.Party        = vendtable.Party;
                         contactView.IsPrimary    = NoYes::Yes;
                         dirParty.createOrUpdateContactInfo(contactView);
                    }
                    if(Phone)
                    {
                        contactView.clear();
                         contactView.LocationName = "Phone";
                         contactView.Locator      = strLRTrim(Phone);
                         contactView.Type         = LogisticsElectronicAddressMethodType::Phone;
                         contactView.Party        = vendtable.Party;
                         contactView.IsPrimary    = NoYes::Yes;
                         dirParty.createOrUpdateContactInfo(contactView);
                    }
                    if(fax)
                    {
                        contactView.clear();
                         contactView.LocationName = "Fax";
                         contactView.Locator      = strLRTrim(Fax);
                         contactView.Type         = LogisticsElectronicAddressMethodType::Fax;
                         contactView.Party        = vendtable.Party;
                         contactView.IsPrimary    = NoYes::Yes;
                         dirParty.createOrUpdateContactInfo(contactView);
                    }
                 i++;
                type        = cells.item(row+1, 1).value().variantType();
             }
        while (type != COMVariantType::VT_EMPTY);
        application.quit();
        info(strFmt(" No of Records updated is %1",i));
    }
}




static void Job1(Args _args)
{
        //CommaTextIO                             csvFile;
     container                               readCon;
     counter                                 icount,inserted;
     Dialog                                  dialog;
     DialogField                             dfFileName;
     DirPartyRecId                           partyRecId,contactPartyRecid;
     Name                                    name,contactName;
     VendTable                               vendtable;
     str                                     contactperson;
     DirPartyPostalAddressView               addressView;
     DirPartyContactInfoView                 contactView;
     ContactPerson                           contactpersonTable;
     LogisticsElectronicAddressMethodType    enumType;
     DirContactPersonsService                dirContactPersonsService;
     DirContactPersons                       dirContactPersons;
     DirContactPersons_ContactPerson         dirContactPersons_ContactPerson;
     DirContactPersons_Person                dirContactPersons_Person;
     DirContactPersons_PersonName            dirContactPersons_PersonName;
     AifEntityKeyList                        aifEntityKeyList, aifEntityKeyList_DirContactPerson;
     str                                     fName, mName, lName;
     VendAccount                             vendorAccount;
     DirParty                                dirParty;
     LogisticsPostalAddress                  address;
     LogisticsElectronicAddress              logisticsElectronicAddress;
     BinData                                 binData;
     str                                     stringImage;
     LogisticsAddressStateID                 stateId;
     str                                     accountnum,accountName,vendgroup,currency,dlvmode,paymtermid,countryid,street,city,mobile,fax,email,zipcode,pobox,phone;
     ;
     csvFile = new CommaIO(filename, 'r');
     try
     {
         if (csvFile)
         {
             ttsbegin;
             readCon = csvFile.read();
             while (csvFile.status() == IO_Status::OK)
             {
                 readCon = csvFile.read();
                 if(readCon)
                 {
                 icount++;
                 accountnum = conPeek(readCon,1);
                 accountName = conPeek(readCon,2);
                 phone = conPeek(readCon,3);
                 fax = conPeek(readCon,4);
                 vendgroup = conPeek(readCon,5);
                 currency = conPeek(readCon,6);
                 dlvmode = conPeek(readCon,7);
                 paymtermid = conPeek(readCon,8);
                 email = conPeek(readCon,9);
                 mobile = conPeek(readCon,10);
                 contactperson = conPeek(readCon,11);
                 pobox = conPeek(readCon,12);
                 countryid = conPeek(readCon,13);
                 zipcode = conPeek(readCon,14);
                 stateId = conPeek(readCon,15);
                 city = conPeek(readCon,16);
                 street = conPeek(readCon,17);

                 ttsBegin;
                 name = conPeek(readCon,2);
                 if(!name)
                 break;
                 partyRecId = DirPartyTable::createNew( DirPartyType::Organization, name).RecId;
                 vendtable.clear();
                 vendtable.initValue();
                 vendtable.Party = partyRecId;
                 vendtable.AccountNum = accountnum;
                 vendtable.VendGroup  = vendgroup;
                 vendtable.Currency   = currency;
                 //vendtable.Blocked    =
                 vendtable.DlvMode    = dlvmode;
                 vendtable.PaymTermId   = paymtermid;
                 if(contactperson != '')
                 {
                     contactname = ContactPerson;
                     ContactPerson::findOrCreateNameParty(partyRecId,contactname);
                 }
                 vendtable.insert();
                 ttsCommit;
                 stateId = subStr(stateId,1,25);
                 address.PostBox = strLRTrim(PoBox);
                 address.CountryRegionId = strLRTrim(Countryid);
                 address.State = stateId;
                 address.ZipCode = strLRTrim(ZipCode);
                 address.Street  = strLRTrim(Street);
                 //address.county = strLRTrim(conPeek(readCon,17));
                 address.City    = strLRTrim(City);
                 addressView.LocationName = name;
                 addressView.IsPrimary = NoYes::Yes;
                 addressView.Party = partyRecId;
                 addressview.initFromPostalAddress(address);
                 DirParty = DirParty::constructFromPartyRecId(addressView.Party );
                 DirParty.createOrUpdatePostalAddress(addressView);
                 contactView.LocationName = "Email";
                 contactView.Locator      = strLRTrim(email);
                 contactView.Type         = LogisticsElectronicAddressMethodType::Email;
                 contactView.Party        = partyRecId;
                 contactView.IsPrimary    = NoYes::Yes;
                 dirParty.createOrUpdateContactInfo(contactView);
                 contactView.LocationName = "Mobile";
                 contactView.Locator      = strLRTrim(mobile);
                 contactView.Type         = LogisticsElectronicAddressMethodType::Phone;
                 contactView.Party        = partyRecId;
                 contactView.IsPrimary    = NoYes::Yes;
                 dirParty.createOrUpdateContactInfo(contactView);
                 contactView.LocationName = "Phone";
                 contactView.Locator      = strLRTrim(Phone);
                 contactView.Type         = LogisticsElectronicAddressMethodType::Phone;
                 contactView.Party        = partyRecId;
                 contactView.IsPrimary    = NoYes::Yes;
                 dirParty.createOrUpdateContactInfo(contactView);
                 contactView.LocationName = "Fax";
                 contactView.Locator      = strLRTrim(Fax);
                 contactView.Type         = LogisticsElectronicAddressMethodType::Fax;
                 contactView.Party        = partyRecId;
                 contactView.IsPrimary    = NoYes::Yes;
                 dirParty.createOrUpdateContactInfo(contactView);
                 inserted++;
                 }
             }
             ttsCommit;
         }
         icount--;//Remove header recount from total record count
     }
     catch(Exception::Error)
     {
         info(strFmt("%1 %2",Exception::Error,icount));
     }
}

Marked Transaction in Payment Journal Invoice Posted /Not Posted

Markeed Transaction in Payment Journal Invoice
Not posted
:
    ledgerJournalTransLocal = LedgerJournalTrans::findRecId(_ledgerJournalTrans.RecId,false);
    if(_ledgerJournalTrans.AccountType == LedgerJournalACType::Vend)
    {
        custVendFindSettlements = new CustVendFindSettlements(ModuleCustVend::Vend, ledgerJournalTransLocal);
        if (ledgerJournalTransLocal.ledgerJournalTable().JournalType == LedgerJournalType::VendPromissoryNoteRedraw ||
            ledgerJournalTransLocal.ledgerJournalTable().JournalType == LedgerJournalType::BankChequeReversal)
        {
            custVendFindSettlements.findSettledSettlements();
        }
        else
        {
            custVendFindSettlements.findSettlements();
        }
        tmpCustVendTrans.setTmpData(custVendFindSettlements.tmpCustVendTrans());
        while select tmpCustVendTrans
        {
            InvoiceNumber += strFmt("%1,", tmpCustVendTrans.Invoice);
        }
    }
    else if(_ledgerJournalTrans.AccountType == LedgerJournalACType::Cust)
    {
         custVendFindSettlements = new CustVendFindSettlements(ModuleCustVend::Cust, ledgerJournalTransLocal);
        if (ledgerJournalTransLocal.ledgerJournalTable().ProtestSettledBill == NoYes::Yes ||
            ledgerJournalTransLocal.ledgerJournalTable().JournalType == LedgerJournalType::BankChequeReversal ||
            ledgerJournalTransLocal.ledgerJournalTable().JournalType == LedgerJournalType::BankDepositPaymCancel)
        {
            custVendFindSettlements.findSettledSettlements();
        }
        else
        {
            custVendFindSettlements.findSettlements();
        }
        tmpCustVendTrans.setTmpData(custVendFindSettlements.tmpCustVendTrans());
        while select tmpCustVendTrans
        {
            InvoiceNumber += strFmt("%1,", tmpCustVendTrans.Invoice);
        }
    }
Posted :
Public void settlementCustAftPosting(LedgerJournalTrans _ledgerJournalTrans)
{
    CustSettlement  set, set2;
    CustTrans   custTrans, custTrans1;
    boolean _old = true;
     #ISOCountryRegionCodes

     select set
        join custTrans where set.TransCompany ==  custTrans.dataAreaId
        &&  set.TransRecId          ==  custTrans.RecId
        &&  set.AccountNum          ==  custTrans.AccountNum
        &&  custTrans.AccountNum    == _ledgerJournalTrans.accountDisplay()
        &&  custTrans.Voucher       == _ledgerJournalTrans.Voucher
        &&  custTrans.TransDate     == _ledgerJournalTrans.TransDate ;

    while select set2
        where ((set.OffsetCompany   == set2.TransCompany    && set.OffsetRecId  == set2.TransRecId)     &&
               (set.TransCompany    == set2.OffsetCompany   && set.TransRecId   == set2.OffsetRecId))   ||
              ((set.TransCompany    == set2.TransCompany    && set.TransRecId   == set2.TransRecId)     &&
               (set.OffsetCompany   == set2.OffsetCompany   && set.OffsetRecId  == set2.OffsetRecId))   &&
               (set2.CanBeReversed  == true || _old)                                                    &&
               (set2.TransDate      == set.TransDate || ! SysCountryRegionCode::isLegalEntityInCountryRegion([ #isoRU ]))
    join custTrans1
        where set2.TransCompany     ==  custTrans1.dataAreaId
               &&  set2.TransRecId  ==  custTrans1.RecId
               &&  set2.AccountNum  ==  custTrans1.AccountNum
               &&  custTrans1.Invoice != ""
    {
            jvSettleTmp.Name  = "Settlement";
            jvSettleTmp.Invoice = custTrans1.Invoice;
            jvSettleTmp.InvoiceDate = custTrans1.TransDate;
            jvSettleTmp.Txt = custTrans1.txt;
            jvSettleTmp.CurrencyCode = custTrans1.CurrencyCode;
            jvSettleTmp.Amount = custTrans1.SettleAmountCur;
            jvSettleTmp.insert();
    }

}

Public void settlementVendAftPosting(LedgerJournalTrans _ledgerJournalTrans)
{
    VendSettlement  set, set2;
    VendTrans       vendTrans, vendTrans1;
    boolean         _old = true;
    #ISOCountryRegionCodes

     select set
        join vendTrans where set.TransCompany ==  vendTrans.dataAreaId
        &&  set.TransRecId          ==  vendTrans.RecId
        &&  set.AccountNum          ==  vendTrans.AccountNum
        &&  vendTrans.AccountNum    == _ledgerJournalTrans.accountDisplay()
        &&  vendTrans.Voucher       == _ledgerJournalTrans.Voucher
        &&  vendTrans.TransDate     == _ledgerJournalTrans.TransDate ;

    while select set2
        where ((set.OffsetCompany   == set2.TransCompany    && set.OffsetRecId  == set2.TransRecId)     &&
               (set.TransCompany    == set2.OffsetCompany   && set.TransRecId   == set2.OffsetRecId))   ||
              ((set.TransCompany    == set2.TransCompany    && set.TransRecId   == set2.TransRecId)     &&
               (set.OffsetCompany   == set2.OffsetCompany   && set.OffsetRecId  == set2.OffsetRecId))   &&
               (set2.CanBeReversed  == true || _old)                                                    &&
               (set2.TransDate      == set.TransDate || ! SysCountryRegionCode::isLegalEntityInCountryRegion([ #isoRU ]))
    join vendTrans1
        where set2.TransCompany     ==  vendTrans1.dataAreaId
               &&  set2.TransRecId  ==  vendTrans1.RecId
               &&  set2.AccountNum  ==  vendTrans1.AccountNum
               &&  vendTrans1.Invoice != ""
    {
            jvSettleTmp.Name  = "Settlement";
            jvSettleTmp.Invoice = vendTrans1.Invoice;
            jvSettleTmp.InvoiceDate = vendTrans1.TransDate;
            jvSettleTmp.Txt = vendTrans1.txt;
            jvSettleTmp.CurrencyCode = vendTrans1.CurrencyCode;
            jvSettleTmp.Amount = vendTrans1.SettleAmountCur;
            jvSettleTmp.insert();
    }
}

commissions Setup and calculation

https://technet.microsoft.com/en-us/library/aa497145.aspx
http://axtradeandlogistics.blogspot.com/2015/03/commissions-setup-and-calculations-in.html

Number Sequence Creation through Code X++

//Number Sequence Creation through Code X++

static void Fcc_NumberSeqTest(Args _args)
{
     NumberSequenceTable                numberSeqTable;
     NumberSequenceScope                numberSeqScope;
     container                          segments;
     str                                annotatedFormat, format;
     NumberSequence                     sequence;
     Args                               args = new Args();
     ;
     select  numberSeqScope
           where numberSeqScope.DataArea == 'dataAreaId';
     segments += [[0, 'CVT']];
     segments += [[-1,'-']];
     segments += [[-2,'######']];
     annotatedFormat  = NumberSeq::createAnnotatedFormatFromSegments(segments);
     format           = NumberSeq::createAnnotatedFormatFromSegments(segments, false);
     numberSeqTable.clear();
     numberSeqTable.NumberSequence      = 'CVTst';
     numberSeqTable.Txt                 = 'Test Seq';
     numberSeqTable.AnnotatedFormat     = annotatedFormat;
     numberSeqTable.NumberSequenceScope = numberSeqScope.RecId;
     numberSeqTable.Format              = format;
     numberSeqTable.Highest             = 999999;
     numberSeqTable.Lowest              = 1;
     numberSeqTable.NextRec             = 1;
     numberSeqTable.insert();  
   
     args.record(NumberSequenceTable::find(numberSeqTable.RecId));
     new MenuFunction(MenuItemDisplayStr(NumberSequenceDetails),MenuItemType::Display).run(args);
}

Collection Class Ax 2012

Collection Class Ax 2012
https://msdn.microsoft.com/en-us/library/aa608508.aspx
http://www.junctionsolutions.com/dynamicsax/using-dynamics-ax-collection-classes-3/

source:
http://axgenius.blogspot.com/2016/03/collection-classes-in-ax-2012.html

Source blog information:

Collection Classes
We cannot store objects in arrays (x++ class) or containers. The Microsoft Dynamics AX collection classes have been designed for storing objects. 
Below are collection classes: Set , Map , List , Array (Collection class)
A Set is used for the storage and retrieval of data from a collection in which the members are unique. The values of the members serve as the key according to which the data is automatically ordered. Thus, it differs from a List collection class where the members are placed into a specific position, and not ordered Automatically by their value.
static void Set(Args _args)
{
    Set setOne;
    Set setTwo;
    SetEnumerator enumerator;
    Int value;
    setOne = new Set(types::Integer);
    setOne.add(4);
    setOne.add(6);
    setOne.add(3);
  
    enumerator = setOne.getEnumerator();
    while (enumerator.moveNext())
    {
        value = enumerator.current();
        info(strFmt("%1",value));     
    }
}
Output :- 3
                 4
                 6
A List object contains members that are accessed sequentially. Lists are structures that can contain members of any X++ type. All the members in the same list must be of the same type.
static void List(Args _args)
{
    List integerList = new List(Types::Integer);
    ListEnumerator enumerator;
    // Add some elements to the list
    integerList.addEnd(1);
    integerList.addEnd(4);
    integerList.addEnd(3);
    // Set the enumerator
    enumerator = integerList.getEnumerator();
    // Go to beginning of enumerator
    enumerator.reset();
    //Go to the first element in the List
    while(enumerator.moveNext())
    {
        info(strfmt("%1", enumerator.current()));
    }
}
Output :- 1
                 4
                 3
A Map object associates one value (the key) with another value. Both the key and value can be of any valid X++ type, including objects. The types of the key and value are specified in the declaration of the map. The way in which maps are implemented means that access to the values is very fast.
static void Map(Args _args)
{
    Map mapTest;
    MapEnumerator enumerator;
 
    mapTest = new Map(Types::String, Types::Integer);
  
    mapTest.insert("One", 1);
    mapTest.insert("Two", 2);
  
    enumerator = mapTest.getEnumerator();
    while (enumerator.moveNext())
    {
        info(strfmt("Key - %1 , Value  - %2.",enumerator.currentKey(),enumerator.currentValue()));
    }
}
Output:- Key - One , Value  - 1.
                Key - Two , Value  - 2.

Array inserts, sometimes referred to as bulk inserts, are implemented in the kernel. They buffer a group of rows and insert them in a single trip to the SQL backend. This vastly reduces the number of trips, and speeds up inserts. You can use RecordSortedList or RecordInsertList to hold your rows until they are inserted. Both classes have an insertDatabase method that is used to insert the records into the database as efficiently as possible. However, the insertDatabase method does
RecordSortedList
                     
                         Use RecordSortedList when you want a subset of data from a particular table, and you want it sorted in an order that does not currently exist as an index.
A RecordSortedList object holds records from a single table. The list has a unique key that is defined by the fields listed by using the sortOrder method.
Records are automatically sorted as they are inserted, they do not have to be inserted in sort sequence.
There is no limit to the size of a RecordSortedList object, but they are completely memory-based, so there are potential memory consumption problems.
RecordSortedList objects must be server-located before the insertDatabase method can be called. Otherwise, an exception is thrown.
Record level security (RLS) cannot be applied by the RecordSortedList class. RLS is applied by the RecordInsertList class).
Compared to temporary tables, RecordSortedList objects:
are faster
are not disk-based
only have one index
cannot be used in forms
require a call between the client and server per (grouped) read
 Ex:
Student student;
RecordSortedList recordSortedList = new RecordSortedList(tablenum(Student));
recordSortedList .sortOrder(fieldname2id(tablenum(Student),’StudentId’));
student.clear();
student.StudentID=”123?;
student.FirstName=”DOM”;
student.LastName=”FED”;
recordSortedList.ins(student);
student.clear();
student.StudentID=”456?;
student.FirstName=”TOM”;
student.LastName=”GED”;
recordSortedList.ins(student);
 student.clear();
student.StudentID=”789?;
student.FirstName=”ROM”;
student.LastName=”TED”;
recordSortedList.ins(student);
recordSortedList.insertDatabase();
RecordInsertList:
               The RecordInsertList class provides array insert capabilities in the kernel. This allows you to insert more than one record into the database at a time, which reduces communication between the application and the database.
               The array insert operation automatically falls back to classic record-by-record inserts when non-SQL based tables are used (for example, temporary tables), or when the insert method on the table is overridden (unless it is explicitly discarded).
Ex:
FiscalCalendar myTable;
 RecordInsertList insertList = new RecordInsertList(myTable.TableId, True);
  int i;
 for ( i = 1; i <=  100; i++ )
 {
        myTable.CalendarId = "F"+int2str(i);
        insertList.add(myTable);
 }
 insertList.insertDatabase();

Thursday, September 3, 2015

EcoResCategory Category Lookup in Form

// EcoResCategory Lookup in Form

Enable Purch/Sales Category in Customized Table:

TableOne(Customize Table)
1)      Create New Field – Data Type (Int64) ,Extends to Purch Category/Sales Category
2)      Create New Relation for New Field
2.1) Relation Table – EcoResCategory
2.2) Create Normal Relation
        Field – TableOne.fieldName == EcoResCategory.RecId
2.3) Relation Properties Changes to
      2.3.1) RelatedTableCardinality – ZeroOne
       2.3.2) Cardinality – Zero More
       2.3.3) RelationShip Type – Association
     à Form
3)      Form à datasource à tableàField(category Field)
3.1) Add New Method  -- resolveReference
 public Common resolveReference(FormReferenceControl _formReferenceControl)
{
    return EcoResCategory::resolveCategoryHierarchyRole(
        _formReferenceControl,
        EcoResCategoryNamedHierarchyRole::(CategoryType));
}

3.2) Add New Method  -- lookupReference

public Common lookupReference(FormReferenceControl _formReferenceControl)
{

        return EcoResCategory::lookupCategoryHierarchyRole(
            _formReferenceControl,
            EcoResCategoryNamedHierarchyRole:: ::(CategoryType));
}

3.3) Add New Method  -- Modified

public void modified()
{
    <CategoryEDT>               NAmeCategory;
    ItemFreeTxt                 name;
    LedgerDimensionAccount      ledgerDimension;

    name                     = salesQuotationLine.Name;

    NAmeCategory = salesQuotationLine.fieldName;
    salesQuotationTableForm.resetSalesQuotationLine(salesQuotationLine);
    salesQuotationLine. fieldName = NAmeCategory;
    salesQuotationLine_ds.changedInventoriedStatus();
 }



Skip Inventory reservation on Sales order lines in D365FO

[ExtensionOf(classStr(InventUpd_Reservation))] final class InventUpd_ReservationCls_SAN_Extension {     void updateNow()     {         if(mo...