Saturday, September 9, 2017

How to run a Report through X++ code and save to PDF format

static void autoSave_PDF_SSRSSalesInoive(Args _args)
{
    Dialog                                    dialog;
    DialogField                          fromDate, toDate, invoiceId, folderPath;
    CustInvoiceJour                  custInvoiceJourLocal;
    FilePath                              filePath, slash = @"\";
    Filename                            fileName;
    Args                                   args = new Args();
    boolean                             folderexists,fileExists;
    str                                      idstr;
    int                 poss;
    SrsReportRunController              ssrsController = new SrsReportRunController();
    InvoiceContract                           salesConfirmContract = new InvoiceContract();
    SRSPrintDestinationSettings      printerSettings;  
    ;
    dialog = new Dialog("Sales Invoices save to PDF");
    fromDate = dialog.addField(extendedTypeStr(TransDate), "Select From Date");
    toDate = dialog.addField(extendedTypeStr(TransDate), "Select To Date");
    if(dialog.run())
    {
        if(curUserId() == "userid")
            filePath = @"C:\Users\userid\Desktop\Invoices\" + strFmt("%1%2%3",fromDate.value(), " To ", toDate.value()) + slash;
        else
            filePath = @"C:\JB\" + strFmt("%1%2%3",fromDate.value(), " To ", toDate.value()) + slash;
        while(poss < strLen(filePath))
        {
            poss = strFind(filePath, "/", poss, strLen(filePath));
            filePath = strPoke(filePath, "-", poss);
            if(!poss)
                break;
        }
        folderexists = WinAPI::folderExists(filePath);
        if(!folderexists)
            WinAPI::createDirectoryPath(filePath);
         while select custInvoiceJourLocal where custInvoiceJourLocal.InvoiceDate >=     fromDate.value() && custInvoiceJourLocal.InvoiceDate <= toDate.value()
              {
            fileName = filePath + strFmt("%1%2%3%4%5",custInvoiceJourLocal.PrintMgmtSiteId + "_",custInvoiceJourLocal.InvoiceId, "_" , custInvoiceJourLocal.InvoiceDate, ".pdf");
            while(poss < strLen(fileName))
            {
                poss = strFind(fileName, "/", poss, strLen(fileName));
                fileName = strPoke(fileName, "-", poss);
                if(!poss)
                    break;
            }
            fileExists = System.IO.File::Exists(fileName);
            if(!fileExists)
            {
                ssrsController.parmReportName(ssrsReportStr(SalesInvoice, Report));
                   //define how we want to execute the report (right now or batch style)
                ssrsController.parmExecutionMode(SysOperationExecutionMode::Synchronous);
                //hide the report dialog
                ssrsController.parmShowDialog(false);

                //we need to populate the required parms for the current sales order controller
                salesConfirmContract.parmInvoiceId(custInvoiceJourLocal.InvoiceId);
                salesConfirmContract.parmInvoiceDate(custInvoiceJourLocal.InvoiceDate);
                salesConfirmContract.parmSalesId(custInvoiceJourLocal.SalesId);
 
                //link the contract to the controller so we know how to run the dp
                ssrsController.parmReportContract().parmRdpContract(salesConfirmContract);

                //link the printer settings to the controller
                printerSettings = ssrsController.parmReportContract().parmPrintSettings();
                //print to pdf and always overwrite if the file exists
                printerSettings.printMediumType(SRSPrintMediumType::File);
                printerSettings.fileFormat(SRSReportFileFormat::PDF);
                printerSettings.overwriteFile(true);
                printerSettings.fileName(fileName);

                //run & save the report
                ssrsController.startOperation();
               info(strFmt("File Saved at %1", fileName));
            }
        }
    }
}

Tuesday, August 22, 2017

How to delete Duplicate Records through X++ in Dynamics Ax

static void DupDeleteRecords(Args _args)
{
VendTable       vendTable ;
int                   c1,c2;
Set fieldset = new set(types::Integer);
// create dictindex from unique index
DictIndex dictIndex = new dictIndex (tablenum(VendTable  ), indexnum(VendTable  ,AccountNumIdx));
;
select count(RecId) from vendTable  ;
c1=vendTable .RecId;
// these are fields from index add them to set
fieldset.add(fieldnum(VendTable  ,AccountNum));

ReleaseUpdateDB::indexAllowDup(dictIndex);
// set allow duplicates
ReleaseUpdateDB::deleteDuplicatesUsingIds(tablenum(VendTable  ),0,fieldset);
//re enable duplicates
ReleaseUpdateDB::indexAllowDup(dictIndex);
select count(RecId) from vendTable ;
c2=vendTable .RecId;
if(c1!=c2)
info(“Duplicate Deletion done”);
else
info(“No Duplicates found”);
}
force DB Synchronize :

static void forceDbSynchronize1(Args _args)
{
Dictionary dict;
int idx, lastIdx, totalTables;
TableId tableId;
Application application;
SysOperationProgress progress;
StackBase errorStack;
ErrorTxt errorTxt;
;
application = new Application();
dict = new Dictionary();
totalTables = dict.tableCnt();
progress = new SysOperationProgress();
progress.setTotal(totalTables);
progress.setCaption(“@SYS90206″);
errorStack = new StackBase(Types::String);
lastIdx = 0;
try
{
for (idx = lastIdx+1; idx <= totalTables; idx++)
{
tableId = dict.tableCnt2Id(idx);
progress.setText(dict.tableName(tableId));
lastIdx = idx;
application.dbSynchronize(tableId, false, true, false);
progress.incCount();
}
}
catch (Exception::Error)
{
errorTxt = strFmt("Error in table '%1' (%2)", tableId, dict.tableName(tableId));
errorStack.push(errorTxt);
retry;
}
setPrefix("@SYS86407");
errorTxt = errorStack.pop();
while (errorTxt)
{
error(errorTxt);
errorTxt = errorStack.pop();
}
}

Wednesday, June 14, 2017

Create a Product and Release through X++ Code

void clicked()
{
    EcoResProductMaster                 ecoResProductMaster;
    EcoResProductIdentifier             ecoResProductIdentifier;
    EcoResProductDimensionGroupProduct  ecoResProductDimensionGroupProduct;
    EcoResProductMasterModelingPolicy   ecoResProductMasterModelingPolicy;

    EcoResStorageDimensionGroupProduct  ecoResStorageDimensionGroupProduct;
    EcoResTrackingDimensionGroupProduct ecoResTrackingDimensionGroupProduct;

    EcoResConfiguration                           ecoResConfiguration;
    EcoResProductMasterConfiguration    ecoResProductMasterConfiguration;

    EcoResColor                                   ecoResColor;
    EcoResProductMasterColor            ecoResProductMasterColor;

    EcoResSize                                     ecoResSize;
    EcoResProductMasterSize             ecoResProductMasterSize;

    EcoResStyle                                   ecoResStyle;
    EcoResProductMasterStyle            ecoResProductMasterStyle;

    EcoResDistinctProductVariant        ecoResDistinctProductVariant;
    EcoResProductVariantConfiguration   ecoResProductVariantConfiguration;
    EcoResProductVariantColor           ecoResProductVariantColor;
    EcoResProductVariantSize            ecoResProductVariantSize;
    EcoResProductVariantStyle           ecoResProductVariantStyle;

    InventTable                                      inventTable;
    InventTableModule                          inventTableModule;
    InventItemSetupSupplyType           inventItemSetupSupplyType;

    EcoResStorageDimensionGroupItem     ecoResStorageDimensionGroupItem;
    EcoResTrackingDimensionGroupItem    ecoResTrackingDimensionGroupItem;

    InventModelGroupItem                inventModelGroupItem;
    InventItemGroupItem                 inventItemGroupItem;

    InventDim                                     inventDim;
    InventDimCombination                inventDimCombination;
    NumberSequenceTable                 numberSequenceTable;
    EcoResProductDisplayProductNumber   displayProductNumber;
    MerchandisingTable               merchant;
    merchant = MerchandisingTable_ds.getFirst(1);

    try
    {
        while(merchant.RecId != 0)
        {
        //ProductMaster
        ecoResProductMaster.clear();
        ecoResProductMaster.initValue();
        numberSequenceTable = EcoResProductParameters::numRefProductNumber().numberSequenceTable();
        displayProductNumber = NumberSeq::newGetNumFromId(numberSequenceTable.RecId).num();
        ecoResProductMaster.ProductType = EcoResProductType::Item;
        ecoResProductMaster.DisplayProductNumber = displayProductNumber;
        ecoResProductMaster.SearchName = merchant.Styling;
        ecoResProductMaster.Brand      = merchant.Brand;
        ecoResProductMaster.Styling    = merchant.Styling;
        ecoResProductMaster.VariantConfigurationTechnology = EcoResVariantConfigurationTechnologyType::PredefinedVariants;

        if (ecoResProductMaster.validateWrite())
        {
            ecoResProductMaster.insert();
            ecoResProductIdentifier.clear();
            ecoResProductIdentifier.initValue();
            ecoResProductIdentifier.ProductNumber = ecoResProductMaster.DisplayProductNumber;
            ecoResProductIdentifier.Product = ecoResProductMaster.RecId;
            ecoResProductIdentifier.insert();

            //Product dimension group
            ecoResProductDimensionGroupProduct.clear();
            ecoResProductDimensionGroupProduct.initValue();
            ecoResProductDimensionGroupProduct.initFromProduct(ecoResProductMaster);
            ecoResProductDimensionGroupProduct.ProductDimensionGroup = EcoResProductDimensionGroup::findByDimensionGroupName(merchant.EcoResProductDimensionGroupName).RecId;
            if (ecoResProductDimensionGroupProduct.validateWrite())
            {
                ecoResProductDimensionGroupProduct.insert();
            }

            //Storage dimension group
            ecoResStorageDimensionGroupProduct.clear();
            ecoResStorageDimensionGroupProduct.initValue();
            ecoResStorageDimensionGroupProduct.Product = ecoResProductMaster.RecId;
            ecoResStorageDimensionGroupProduct.StorageDimensionGroup = EcoResStorageDimensionGroup::findByDimensionGroupName(merchant.StorageDimensionGrpName).RecId;
            if (ecoResStorageDimensionGroupProduct.validateWrite())
            {
                ecoResStorageDimensionGroupProduct.insert();
            }

            //Tracking dimension group
            ecoResTrackingDimensionGroupProduct.clear();
            ecoResTrackingDimensionGroupProduct.initValue();
            ecoResTrackingDimensionGroupProduct.Product = ecoResProductMaster.RecId;
            ecoResTrackingDimensionGroupProduct.TrackingDimensionGroup = EcoResTrackingDimensionGroup::findByDimensionGroupName(merchant.EcoResTrackingDimensionGrpName).RecId;
            if (ecoResTrackingDimensionGroupProduct.validateWrite())
            {
                ecoResTrackingDimensionGroupProduct.insert();
            }

            //Product modeling policy
            ecoResProductMasterModelingPolicy.clear();
            ecoResProductMasterModelingPolicy.initValue();

            ecoResProductMasterModelingPolicy.ProductMaster = ecoResProductMaster.RecId;
            if (ecoResProductMasterModelingPolicy.validateWrite())
            {
                ecoResProductMasterModelingPolicy.insert();
            }

            //Product translation
            EcoResProductTranslation::createOrUpdateTranslation(ecoResProductMaster.RecId, ecoResProductMaster.Product, ecoResProductMaster.Brand);

                 //Color
            ecoResColor = EcoResColor::findByName(merchant.Color);
            if (!ecoResColor)
            {
                ecoResColor.clear();
                ecoResColor.initValue();
                ecoResColor.Name = merchant.Color;
                ecoResColor.insert();
            }

            //Color assigned to product master
            ecoResProductMasterColor.clear();
            ecoResProductMasterColor.initValue();
            ecoResProductMasterColor.Color = ecoResColor.RecId;
            ecoResProductMasterColor.ColorProductDimensionAttribute = EcoResProductDimensionAttribute::inventDimFieldId2DimensionAttributeRecId(fieldNum(InventDim, InventColorId));
            ecoResProductMasterColor.ColorProductMaster = ecoResProductMaster.RecId;
            ecoResProductMasterColor.insert();

              //Style
            ecoResStyle = EcoResStyle::findByName(merchant.StyleName);
            if (!ecoResStyle)
            {
                ecoResStyle.clear();
                ecoResStyle.initValue();
                ecoResStyle.Name = merchant.StyleName;
                ecoResStyle.insert();
            }

            //Style assigned to product master
            ecoResProductMasterStyle.clear();
            ecoResProductMasterStyle.initValue();
            ecoResProductMasterStyle.Style = ecoResStyle.RecId;
            ecoResProductMasterStyle.StyleProductDimensionAttribute = EcoResProductDimensionAttribute::inventDimFieldId2DimensionAttributeRecId(fieldNum(InventDim, InventStyleId));
            ecoResProductMasterStyle.StyleProductMaster = ecoResProductMaster.RecId;
            ecoResProductMasterStyle.insert();


              //Size
            ecoResSize = EcoResSize::findByName(merchant.Size);
            if (!ecoResSize)
            {
                ecoResSize.clear();
                ecoResSize.initValue();
                ecoResSize.Name = merchant.Size;
                ecoResSize.insert();
            }

            //Size assigned to product master
            ecoResProductMasterSize.clear();
            ecoResProductMasterSize.initValue();
            ecoResProductMasterSize.Size = ecoResSize.RecId;
            ecoResProductMasterSize.SizeProductDimensionAttribute = EcoResProductDimensionAttribute::inventDimFieldId2DimensionAttributeRecId(fieldNum(InventDim, InventSizeId));
            ecoResProductMasterSize.SizeProductMaster = ecoResProductMaster.RecId;
            ecoResProductMasterSize.insert();

            //Product variant
            ecoResDistinctProductVariant.clear();
            ecoResDistinctProductVariant.initValue();
            ecoResDistinctProductVariant.DisplayProductNumber = EcoResProductNumberBuilderVariant::buildFromProductNumberAndDimensions(
            ecoResProductMaster.productNumber(),
            EcoResProductVariantDimValue::getDimensionValuesContainer(ecoResColor.Name,ecoResSize.Name,ecoResStyle.Name));
            ecoResDistinctProductVariant.SearchName = merchant.Styling; //ecoResProductMaster.SearchName + ecoResColor.Name;
            ecoResDistinctProductVariant.ProductType = ecoResProductMaster.ProductType;
            ecoResDistinctProductVariant.ProductMaster = ecoResProductMaster.RecId;
            ecoResDistinctProductVariant.insert();

            // Product Variant Color
            ecoResProductVariantColor.clear();
            ecoResProductVariantColor.initValue();
            ecoResProductVariantColor.initFromDistinctProductVariant(ecoResDistinctProductVariant);
            ecoResProductVariantColor.ProductDimensionAttribute = EcoResProductDimensionAttribute::inventDimFieldId2DimensionAttributeRecId(fieldNum(InventDim, InventColorId));
            ecoResProductVariantColor.Color = ecoResColor.RecId;
            ecoResProductVariantColor.insert();

             // Product Variant Style
            ecoResProductVariantStyle.clear();
            ecoResProductVariantStyle.initValue();
            ecoResProductVariantStyle.initFromDistinctProductVariant(ecoResDistinctProductVariant);
            ecoResProductVariantStyle.ProductDimensionAttribute = EcoResProductDimensionAttribute::inventDimFieldId2DimensionAttributeRecId(fieldNum(InventDim, InventStyleId));
            ecoResProductVariantStyle.Style = ecoResStyle.RecId;
            ecoResProductVariantStyle.insert();

            // Product Variant Size
            ecoResProductVariantSize.clear();
            ecoResProductVariantSize.initValue();
            ecoResProductVariantSize.initFromDistinctProductVariant(ecoResDistinctProductVariant);
            ecoResProductVariantSize.ProductDimensionAttribute = EcoResProductDimensionAttribute::inventDimFieldId2DimensionAttributeRecId(fieldNum(InventDim, InventSizeId));
            ecoResProductVariantSize.Size = ecoResSize.RecId;
            ecoResProductVariantSize.insert();

            //Product variant translation
            EcoResProductTranslation::createOrUpdateTranslation(ecoResDistinctProductVariant.RecId,merchant.Product,merchant.Brand);

            //Released product
            inventTable.clear();
            inventTable.initValue();
            inventTable.initFromEcoResProduct(ecoResProductMaster);
            inventTable.ItemId = ecoResProductMaster.DisplayProductNumber;
            inventTable.NameAlias = merchant.Styling;
            inventTable.ABSProduct = merchant.Product;
            inventTable.Brand = merchant.Brand;  //customized field
            inventTable.Fiber = merchant.Fiber;
            inventTable.Finish = merchant.Finish;
            inventTable.ABSStyle = merchant.Style;
            inventTable.Usage = merchant.Usage;
            inventTable.Styling = merchant.Styling;

            if (inventTable.validateWrite())
            {
                inventTable.insert();
                //Inventory model group
                inventModelGroupItem.clear();
                inventModelGroupItem.initValue();
                inventModelGroupItem.ItemDataAreaId = inventTable.dataAreaId;
                inventModelGroupItem.ItemId = inventTable.ItemId;
                inventModelGroupItem.ModelGroupId = merchant.InventModelGroupId;
                inventModelGroupItem.ModelGroupDataAreaId = curext();
                inventModelGroupItem.insert();
               
                //Item group
                inventItemGroupItem.clear();
                inventItemGroupItem.initValue();
                inventItemGroupItem.ItemDataAreaId = inventTable.dataAreaId;
                inventItemGroupItem.ItemId = inventTable.ItemId;
                inventItemGroupItem.ItemGroupId = merchant.ItemGroupId;
                inventItemGroupItem.ItemGroupDataAreaId = curext();
                inventItemGroupItem.insert();

                //Extended product details - Inventory
                inventTableModule.clear();
                inventTableModule.initValue();
                inventTableModule.ItemId = inventTable.ItemId;
                inventTableModule.ModuleType = ModuleInventPurchSales::Invent;
                inventTableModule.UnitId = merchant.InventUnitId;
                inventTableModule.insert();

                //Extended product details - Purchase
                inventTableModule.clear();
                inventTableModule.initValue();
                inventTableModule.ItemId = inventTable.ItemId;
                inventTableModule.ModuleType = ModuleInventPurchSales::Purch;
                inventTableModule.UnitId = merchant.PurchUnit;
                inventTableModule.insert();

                //Extended product details - Sales
                inventTableModule.clear();
                inventTableModule.initValue();
                inventTableModule.ItemId = inventTable.ItemId;
                inventTableModule.ModuleType = ModuleInventPurchSales::Sales;
                inventTableModule.UnitId = merchant.SalesUnit;
                inventTableModule.insert();

                //Warehouse items
                InventItemLocation::createDefault(inventTable.ItemId);

                //Supply type setup
                inventItemSetupSupplyType.clear();
                inventItemSetupSupplyType.initValue();
                inventItemSetupSupplyType.ItemId = inventTable.ItemId;
                inventItemSetupSupplyType.ItemDataAreaId = inventTable.DataAreaId;
                inventItemSetupSupplyType.insert();

                //Product storage dimension group
                ecoResStorageDimensionGroupProduct = EcoResStorageDimensionGroupProduct::findByProduct(ecoResProductMaster.RecId);
                if (ecoResStorageDimensionGroupProduct.RecId)
                {
                    ecoResStorageDimensionGroupItem.clear();
                    ecoResStorageDimensionGroupItem.initValue();
                    ecoResStorageDimensionGroupItem.ItemDataAreaId = inventTable.DataAreaId;
                    ecoResStorageDimensionGroupItem.ItemId = inventTable.ItemId;
                    ecoResStorageDimensionGroupItem.StorageDimensionGroup   = ecoResStorageDimensionGroupProduct.StorageDimensionGroup;
                    ecoResStorageDimensionGroupItem.insert();
                }

                //Product tracking dimension group
                ecoResTrackingDimensionGroupProduct = EcoResTrackingDimensionGroupProduct::findByProduct(ecoResProductMaster.RecId);
                if (ecoResTrackingDimensionGroupProduct.RecId)
                {
                    ecoResTrackingDimensionGroupItem.clear();
                    ecoResTrackingDimensionGroupItem.initValue();
                    ecoResTrackingDimensionGroupItem.ItemDataAreaId = inventTable.DataAreaId;
                    ecoResTrackingDimensionGroupItem.ItemId = inventTable.ItemId;
                    ecoResTrackingDimensionGroupItem.TrackingDimensionGroup = ecoResTrackingDimensionGroupProduct.TrackingDimensionGroup;
                    ecoResTrackingDimensionGroupItem.insert();
                }
            }

            inventDim.clear();
            inventDim.InventColorId = ecoResColor.Name;
            inventDim.InventSizeId  = ecoResSize.Name;
            inventDim.InventStyleId = ecoResStyle.Name;
            inventDim = InventDim::findOrCreate(inventDim);

            //Released product variant
            inventDimCombination.clear();
            inventDimCombination.initValue();
            inventDimCombination.DistinctProductVariant = ecoResDistinctProductVariant.RecId;
            inventDimCombination.ItemId = inventTable.ItemId;
            inventDimCombination.InventDimId = inventDim.InventDimId;
            inventDimCombination.insert();

            merchant = MerchandisingTable_ds.getNext();
            }
        }
    }
    catch
    {
        error("Error!");
        return;
    }
      info("Done!");
}

Monday, June 5, 2017

How to send alert to mail through X++ code

Req : Once Project Status Changed mail goes to particular Project Sales or Delivery Manager.
Add below methods in ProjStatusUpd Class :

find Sales or Deli. Mgr  email Address 
private email Emailaddress(RecId    _recid)
{

    LogisticsElectronicAddress  logisticsElectronicAddress;
    HcmWorker                   hcmWorker;
    DirPerson                   dirPerson;
    DirPartyTable               dirPartyTable;
    List list   = new List(Types::String);

     select hcmWorker
                where hcmWorker.RecId == _recid
            join dirPerson
                where dirPerson.RecId == hcmWorker.Person
            join dirPartyTable
                where dirPartyTable.RecId == dirPerson.RecId
            join logisticsElectronicAddress
                where dirPartyTable.PrimaryContactEmail == logisticsElectronicAddress.RecId;

    return  logisticsElectronicAddress.Locator;
}
Send mail:
public static void Mailsend(ProjTable  _projTable, ProjStatus _projStatus, boolean    _updateSubProj = false)
{
    str                                   sender;
    str                                   recipient;
    str                                   cc;
    str                                   subject;
    str                                   body,userid;
    int                                   i;
    List                                  toList;
    List                                  ccList;
    ListEnumerator                        le;

    Set                                   permissionSet;
    System.Exception                      e;

    str                                   mailServer;
    int                                   mailServerPort;
    System.Net.Mail.SmtpClient            mailClient;
    System.Net.Mail.MailMessage           mailMessage;
    System.Net.Mail.MailAddress           mailFrom;
    System.Net.Mail.MailAddress           mailTo;
    System.Net.Mail.MailAddressCollection          mailToCollection;
    System.Net.Mail.MailAddressCollection          mailCCCollection;
    System.Net.Mail.AttachmentCollection           mailAttachementCollection;
    System.Net.Mail.Attachment                            mailAttachment;
    ProjStatusUpd                                                   projStatusUpd;

    EventInbox                            EventInbox,inbox;
    SysUserInfo                           SysUserInfo;


    Name                                  name;
    Email                                 email,emailforroles;
    Enumerator                            enumarator;

    LogisticsElectronicAddress  logisticsElectronicAddress;
    HcmWorker                          hcmWorker;
    DirPerson                            dirPerson;
    DirPartyTable                     dirPartyTable;
    List list   = new List(Types::String);

    PSAProjSchedRole        pSAProjSchedRole;
    EventRule               eventRule;
    ProjId                  projId;
     str                    pwd;
    SysEmailParameters parameters = SysEmailParameters::find();


    ;
    projStatusUpd = ProjStatusUpd::construct(_projTable, _projStatus,_updateSubProj);
    projId = _projTable.ProjId;
    //projStatusUpd.Emailaddress(_projTable);
    sender = SysUserInfo::find(curUserId(), false).Email;
    try
    {
            if(_projTable.WorkerResponsibleSales)
            {
                list.addEnd(projStatusUpd.Emailaddress(_projTable.WorkerResponsibleSales));
            }
            if(_projTable.WorkerResponsible)
            {
                list.addEnd(projStatusUpd.Emailaddress(_projTable.WorkerResponsible));
            }
            if(_projTable.WorkerResponsibleFinancial)
            {
            list.addEnd(projStatusUpd.Emailaddress(_projTable.WorkerResponsibleFinancial));
            }
            ccList = strSplit(cc, ';');

        // for roles workers++
        while select * from pSAProjSchedRole where pSAProjSchedRole.ProjId == projId && _projStatus == ProjStatus::Scheduled
        {
            if(pSAProjSchedRole.Worker)
            {
                emailforroles = projStatusUpd.Emailaddress(pSAProjSchedRole.Worker);
                if(emailforroles)
                {
                    list.addEnd(emailforroles);
                }
            }
        }
        // for roles workers--
        enumarator = list.getEnumerator();
        while(enumarator.moveNext())
        {
        permissionSet = new Set(Types::Class);
        permissionSet.add(new InteropPermission(InteropKind::ClrInterop));
        CodeAccessPermission::assertMultiple(permissionSet);
        mailServer = SysEmaiLParameters::find(false).SMTPRelayServerName;
        mailServerPort = SysEmaiLParameters::find(false).SMTPPortNumber;
        mailClient = new System.Net.Mail.SmtpClient(mailServer, mailServerPort); //smtp-mail.outlook.com
      
        mailFrom = new System.Net.Mail.MailAddress(sender);
        mailTo  = new System.Net.Mail.MailAddress(enumarator.current());
        mailMessage = new System.Net.Mail.MailMessage(mailFrom, mailTo);

            mailToCollection = mailMessage.get_To();
            select * from  eventRule where eventRule.FormName like "Projtable";
            if(eventRule.AlertFieldLabel == "Project stage" )
            {
        subject = strFmt(_projTable.ProjId + " : " + _projTable.Name + " " + eventRule.Subject +" " +                             enum2str(_projStatus));
            mailToCollection.Add(enumarator.current());
            mailMessage.set_Priority(System.Net.Mail.MailPriority::Normal);
            mailMessage.set_Subject(subject);
            mailMessage.set_Body(eventRule.Message);
            mailClient.set_EnableSsl(true);
            pwd = SysEmaiLParameters::password();
            mailClient.set_Credentials(New System.Net.NetworkCredential(parameters.SMTPUserName, pwd));
            mailClient.Send(mailMessage);
            mailMessage.Dispose();
            CodeAccessPermission::revertAssert();

     ttsBegin;
     select SysUserInfo order by SysUserInfo.Id where SysUserInfo.Id!="";
     {
        select maxof(inboxId) from inbox;
        EventInbox.InboxId                           = EventInbox::nextEventId();
        EventInbox.CompanyId                         = curext();
        EventInbox.TypeId                            = classnum(EventType);
        EventInbox.AlertTableId                      = tablenum(ProjTable);//2271;
        EventInbox.AlertFieldId                      = fieldnum(ProjTable,Status);
        EventInbox.TypeTrigger                       = EventTypeTrigger::FieldChanged;
        EventInbox.AlertCreatedDateTime              = DateTimeUtil::utcNow();
        EventInbox.ParentTableId                     = 624;//2271;
        EventInbox.IsRead                            = NOYES::No;
        EventInbox.Subject                           = subject;
        EventInbox.AlertedFor                        = "Project Status :" + enum2str(_projStatus);
        i = strScan(enumarator.current(),"@",1,20);
        EventInbox.UserId                            = subStr(enumarator.current(),1,i-1);
        EventInbox.ShowPopup                         = NOYES::Yes;
        EventInbox.Visible                           = NOYES::Yes;
        EventInbox.SendEmail                         = NoYes::Yes;
        EventInbox.Message                           = eventRule.Message;
        EventInbox.EmailRecipient                    = EventInbox.UserId;
        EventInbox.insert();
      }
    ttsCommit;
       info(strFmt("Email sent .%1", EventInbox.UserId ));
      }
            }
        }
    catch (Exception::CLRError)
    {
        e = ClrInterop::getLastException();
        while (e)
        {
            info(e.get_Message());
            e = e.get_InnerException();
        }
        CodeAccessPermission::revertAssert();
    }
}
add below line of code in Main() Method.

 ProjStatusUpd::Mailsend(projTable, projStatus,updateSubProj);  


Friday, May 26, 2017

Lookup through X++ Code

Lookup through code based on selected control

public void lookup()
{
    Query query = new Query();
    QueryBuildDataSource qbds;
 

    // Instantiate sysTableLookup object using table which will provide the visible fields
    SysTableLookup sysTableLookup = sysTableLookup::newParameters(tableNum(BrandTable), this);
    ;

    // Create the query.
    qbds= query.addDataSource(tableNum(BrandTable));
   //Add range
  //Product Control set auto declaration YES
    qbds.addRange(fieldNum(BrandTable,Product)).value(Product.valueStr());

    // Set the query to be used by the lookup form
    sysTableLookup.parmQuery(query);

    // Specify the fields to show in the form.
    sysTableLookup.addLookupfield(fieldNum(BrandTable, Product));
    sysTableLookup.addLookupfield(fieldNum(BrandTable, Brand),true);
    sysTableLookup.addLookupfield(fieldNum(BrandTable, Description));

    // Perform the lookup
    sysTableLookup.performFormLookup();
}

Import data from Excel to AX through X++

static void ImportExcelData(Args _args)
{
    SysExcelApplication             application;
    SysExcelWorkbooks               workbooks;
    SysExcelWorkbook                workbook;
    SysExcelWorksheets              worksheets;
    SysExcelWorksheet               worksheet;
    SysExcelCells                   cells;
    COMVariantType                  type;
    System.DateTime                 ShlefDate;
    FilenameOpen                    filename;

    dialogField                     dialogFilename;
    Dialog                          dialog;
    #AviFiles
    // Progress Bar
    SysOperationProgress progress = new SysOperationProgress(1, NoYes::Yes); 

    StyleTable                      styleTable;  // Table name
    str                             style;
    int                             row = 0;
    #Excel

    str COMVariant2Str(COMVariant _cv,
                       int _decimals = 0,
                       int _characters = 0,
                       int _separator1 = 0,
                       int _separator2 = 0)
    {
        switch(_cv.variantType())
        {
            case (COMVariantType::VT_BSTR):
                return _cv.bStr();

            case (COMVariantType::VT_R4):
                return num2str(_cv.float(),
                                _characters,
                                _decimals,
                                _separator1,
                                _separator2);

            case (COMVariantType::VT_R8):
                return num2str(_cv.double(),
                                _characters,
                                _decimals,
                                _separator1,
                                _separator2);

            case (COMVariantType::VT_DECIMAL):
                return num2str(_cv.decimal(),
                                _characters,
                                _decimals,
                                _separator1,
                                _separator2);

            case (COMVariantType::VT_DATE):
                return date2str(_cv.date(),
                                123,
                                2,
                                1,
                                2,
                                1,
                                4);

            case (COMVariantType::VT_EMPTY):
                return "";

            default:
                throw error(strfmt("@SYS26908",_cv.variantType()));
        }
        return "";
    }
    ;

    dialog = new Dialog("ExcelUpload");
    dialogFilename      =   dialog.addFieldValue(extendedTypeStr(FilenameOpen),filename);
    dialog.filenameLookupFilter(["@SYS28576",#XLS,"@SYS28576",#XLSX]);
    dialog.filenameLookupTitle("Upload from Excel");
    dialog.caption("Excel Upload");
    dialogFilename.value(filename);

    if(!dialog.run())
        return;

    filename            =   dialogFilename.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();

    // Progress Caption & Animation
    progress.setCaption("Copying..");
    progress.setAnimation(#AviUpdate);

    do
    {
        try
        {
            ttsbegin;
            row++;
            // Getting EquipmentId value form Excel Row wise and assigning as str
            style = COMVariant2Str(cells.item(row,1).value());         

        // While Revecing datas from Excel Sheet If invalid value presents it wil not allowe to insert and the
            //   last  record also deleted
            if (!equipId)
            {
                ttsbegin;

                _TestXls.delete();

                ttscommit;

                box::warning(strfmt("Check the value in Excel Sheet row %1", row));

                return;

            }

            else
            {
                if (row > 1)
                {
                    // Progress bar Text and Total
                    progress.setText(strfmt("Importing to Ax Table : %1", row));
                    progress.setTotal(row, 1);

                    _TestXls.clear();
                    _TestXls.Style    =  equipId;
                    _TestXls.insert();

                }
            }

            ttscommit;
        }

        catch
        {
            Error(strfmt("Upload Failed in row %1", row));
        }

        type = cells.item(row + 1, 1).value().variantType();

    } while (type!= COMVariantType::VT_EMPTY);

    info(strfmt(" Details Uploaded Successfully"));

    application.quit(); 

}

update_recordset with joins

 update_recordset with joins update_recordSet storeTransfer         setting      TransactionId = transfertable.TransferId     join transfert...