Tuesday, June 17, 2014

Automatic Mail From SMTP server and attachments

// Automatic Mail From SMTP server and attachments

clicked()



    SrsReportRunController          controller = new SrsReportRunController();
    PurchPurchaseOrderContract      purchPurchaseOrderContract;
    Args                            args = new Args();
    SrsReportRunImpl                srsReportRun;
    VendPurchOrderJour              vendPurchJour;
    SrsPrintMgmtExecutionInfo       printMgmtExecutionInfo;

    ReportName reportName = "PurchPurchaseOrder.Report";
    str                      email;
    Set                      permissionSet;
    int i;
    System.Exception    e;
    str 100             fileName,invoiceSubject;

    SysEmailMessageTable    message;


    Dialog              dialog;
    DialogField         dfFileName;
    str                 mailServer;
    int                 mailServerPort;
    str testmail = "admin@cbizol.com";

    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;

    ;

    dialog = new Dialog("Pick location");
    dfFileName = dialog.addField(extendedTypeStr(FilePath));

    dialog.run();

    permissionSet = new Set(Types::Class);
    permissionSet.add(new InteropPermission(InteropKind::ClrInterop));
    permissionSet.add(new FileIOPermission(filename, 'rw'));
    CodeAccessPermission::assertMultiple(permissionSet);

    mailServer = SysEmaiLParameters::find(false).SMTPRelayServerName;
    mailServerPort = SysEmaiLParameters::find(false).SMTPPortNumber;
    mailClient = new System.Net.Mail.SmtpClient(mailServer, mailServerPort);

    message = SysEmailMessageTable::find("Alerts", "en-us");

    mailFrom = new System.Net.Mail.MailAddress(testmail);
    mailTo  = new System.Net.Mail.MailAddress(testmail);//strLTrim(strRTrim(custTable.email())));
    mailMessage = new System.Net.Mail.MailMessage(mailFrom, mailTo);
    mailToCollection = mailMessage.get_To();

    mailMessage.set_Priority(System.Net.Mail.MailPriority::High);
    mailMessage.set_Subject(invoiceSubject);

    mailAttachementCollection = mailMessage.get_Attachments();

    select firstOnly vendPurchJour;
    args.record(vendPurchJour);
    fileName = strfmt("%1\\PurchPurchaseOrder %2.pdf",dfFileName.value(), vendPurchJour.PurchOrderDocNum);


    controller.parmReportName(reportName);

    purchPurchaseOrderContract = controller.parmReportContract().parmRdpContract();
    purchPurchaseOrderContract.parmRecordId(vendPurchJour.RecId);
    purchPurchaseOrderContract.parmDocumentTitle("test");//(custInvoiceJour.RecId); // Record id must be passed otherwise the report will be empty

    controller.parmArgs(args);

    srsReportRun = controller.parmReportRun() as SrsReportRunImpl;

    controller.parmReportRun(srsReportRun);
    controller.parmReportContract().parmPrintSettings().printMediumType(SRSPrintMediumType::File);
    controller.parmReportContract().parmPrintSettings().overwriteFile(true);
    controller.parmReportContract().parmPrintSettings().fileFormat(SRSReportFileFormat::PDF);
    controller.parmReportContract().parmPrintSettings().fileName(fileName);
    controller.runReport();


        mailAttachment = new System.Net.Mail.Attachment(fileName);
        mailAttachementCollection.Add(mailAttachment);

        // get the next selected record
        vendPurchJour = VendPurchOrderJour_ds.getNext();

    mailClient.SendAsyncCancel();
  //  mailClient.Send(mailMessage);
    mailMessage.Dispose();


     CodeAccessPermission::revertAssert();

Thursday, June 5, 2014

Setting Up Email parameters in AX 2012


Auto mail sending with multiple attachment from selected record in Project Invoice journals through x++

This summary is not available. Please click here to view the post.

Rar Conversion Through X++

// Rar Conversion Through X++
static void rarconversion(Args _args)
{
    WinAPI::shellExecute("C:\\Program Files\\WinRAR\\WinRAR.exe",
        "a -afzip -df c:\\test.zip C:\\xls");
}
//C:\\PurchPurchaseOrderReport.pdf;
//c:\\code.txt
//


    CodeAccessPermission    perm;
    System.Exception        ex;

    str filePath    = @'C:\Temp\TestZipFolder';
    str zipPath     = @'C:\Temp\test.zip';
    str extractPath = @'C:\Temp\UnZip';

    try
    {
        perm = new InteropPermission(InteropKind::CLRInterop);
        perm.assert();

        //Archive folder content to file
        System.IO.Compression.ZipFile::CreateFromDirectory(filePath, zipPath);

        //extract Zip to folder
        System.IO.Compression.ZipFile::ExtractToDirectory(zipPath, extractPath);

        CodeAccessPermission::revertAssert();
    }

    catch (Exception::CLRError)
    {
        ex = ClrInterop::getLastException();
        if (ex != null)
        {
            ex = ex.get_InnerException();
            throw error(ex.ToString());
       }
    }

Table Creation through X++ code in AX 2012

// Table Creation through X++ code in AX 2012

Static void newTablewithField(args_args)

{

TreeNode                           treenode;

AOTTableFieldList              fieldlist;

#AOT

;

treenode = TreeNode   ::findNode(#TablePath);

treeNode.AoTadd("TableName");

sqlDataDictionary::Synchronize();

treeNode.AoTFindChild(TableName);

filedlist = treenode::AOTfieldchild(TableName).AOTfindchild('Fileds');

fieldList.addString('FieldName');

fieldList.addInteger('FieldName');

fieldList.addReal('FieldName');

info( "Table Created");

}

read and write data from text (.txt) file

// read and write data from text (.txt) file with AsciiIo

Method:

AsciiIo readFile;
str line;
container fileRecord;
;

readFile = new AsciiIo("C:\\test.txt" , 'R');
readFile.inFieldDelimiter("1234567890abcdefghijklmnop");

fileRecord = readFile.read();
while (fileRecord)
{
line = con2str(fileRecord);
info(line);
fileRecord = readFile.read();
}


// Read Data

#File
    TextIo                  io;
    //NotepadTest     notepadTest;
    container               c;
    str               item, name;
    ;
 
 
    io = new TextIo("C:\\Test.txt", #io_read);
 
    if (!io)
    {
        throw error("Error reading file");
    }
 
    io.inFieldDelimiter(','); //This can be any delimiter, I'm just using Semicolon as an example
    io.inRecordDelimiter(#delimiterCRLF); //CRLF = Carriage Return Line Feed
 
    ttsbegin;
    delete_from NotepadTest;
    while (io.status() == IO_Status::Ok)
    {
        c = io.read();
        if (io.status() != IO_Status::Ok)
        {
            break;
        }
        item = conpeek(c, 1);
        NotepadTest.ItemId = item;
        name=  conpeek(c, 2);
        NotepadTest.ItemName  = name;
     
        NotepadTest.insert();
        info(item + '-->' + name);
    }
    ttscommit;
 
    super();
    NotepadTest_DS.research();
    NotepadTest_DS.reread();
    NotepadTest_DS.refresh();


// Write Data

    //NotepadTest     notepadTest;
    BinData     binData;
    TextBuffer  textBuffer;
    Dialog      dialog;
    DialogGroup dialogGroup;
    DialogField dialogfieldItmeid;
    str 100 itemDialog;
    ;
    dialog = new Dialog("ItemId");
    dialogGroup = dialog.addGroup("Item Group");
    dialogfieldItmeid = dialog.addField(extendedTypeStr(Name),"Itemid > = :");
 
    textBuffer = new TextBuffer();
    textBuffer.setText('');
        if(dialog.run())
        {
            itemDialog = dialogfieldItmeid.value();
           // info(strfmt("%1", itemDialog));
         
            while select notepadTest where notepadTest.ItemId >= itemDialog
            {
                textBuffer.appendText(strfmt('%1\r\t',notepadTest.ItemId));
                textBuffer.appendText(strfmt('%1\r\n',notepadTest.ItemName));
            }
        }
    textBuffer.getText();
    NotepadTest_DS.research();
    NotepadTest_DS.reread();
    NotepadTest_DS.refresh();
    binData = new BinData();
    binData.setStrData(textBuffer.getText());
    binData.saveFile(@"c:\Test1.txt");

    super();

Delete a DirParty record in Ax2012

// delete a DirParty record in Ax2012

static void DirParty_Delete(Args _args)
{
DirPartyTable dirPartyTable;
DirPerson dirPerson;
Common partyRecord;
DirParty dirPartyClass;
DirPersonRecId personRecId;
;
select firstOnly * from dirPerson where dirPerson.name == "ABCDEFG";
personRecId = DirPerson.RecId;
//This is after the worker has been deleted on the HcmWorkerListPage form on HRM

dirPartyTable = DirPartyTable::findRec(DirPerson::find(personRecId).RecId);if (dirPartyTable)
{
partyRecord = dirPartyTable;
dirPartyClass = new DirParty(partyRecord);
if (DirParty::canDeleteParty(dirPartyClass.getPartyRecId(),true))
{
DirParty::autoDeleteParty(dirPartyTable.RecId);
}
}
}

Dialog field mandatory in Axapta reports

// Dialog field mandatory in Axapta reports

public Object dialog(Object _dialog)
{
    int                                  i;
    DialogRunbase              dialog = _dialog;
    DialogField                   checkField;
    FormDateControl          control;
    ;
    dialog.addGroup("@SYS119346");
    fieldConversionDate = dialog.addFieldValue(typeid(InventStdCostConvEndDate),  conversionDate);
    control = fieldConversionDate.fieldControl();
    control.mandatory(true);
    control.allowEdit(false);
    return dialog;
}

Read a Text File

// Read a Text File

static void ReadDateFromTxtFile(Args _args)
{
    #File
    TextIo                  io;
    container               c;
    str               itm, name;
    ;
    io = new TextIo("U:\\Test.txt", #io_read);
    if (!io)
    {
        throw error("Error reading file");
    }
    io.inFieldDelimiter(','); //This can be any delimiter, I'm just using Semicolon as an example
    io.inRecordDelimiter(#delimiterCRLF); //CRLF = Carriage Return Line Feed
    ttsbegin;
    while (io.status() == IO_Status::Ok)
    {
        c = io.read();
        if (io.status() != IO_Status::Ok)
        {
            break;
        }
        itm = conpeek(c, 1);
        name=  conpeek(c, 2);
        info(itm + '-->' + name);
    }
    ttscommit;
}

Based on the input given Number sequence will generate

//Based on the input given Number sequence will generate

static void TimeSheetNumFromQty(Args _args)
{
    TSTimesheetNbr      num;
    CustTable           custTable;
    NumTmp              tmp;
    int                 i = 1;
    NumberSeq           numberSeq;
    Dialog              dialog;
    DialogGroup         dialogGroup;
    DialogField         dialogFieldQty;
    ;
    dialog          = new   Dialog("Quantity Input");
    dialogGroup     = dialog.addGroup(" qty");
    dialogFieldQty  = dialog.addField(ExtendedTypestr(Name),"Qty :");
    numberSeq       = NumberSeq::newGetNum(ProjParameters::numRefTimesheetNbr());

    if(dialog.run())
    {
        while(i <= any2int(dialogFieldQty.value()))
        {
            num             = numberSeq.num();
            tmp.AccountNum  = "1001";
            tmp.SerialNum   = num;
            tmp.CustName    = "CBS";
            //info(num);
            //info(strFmt("%1",dialogFieldQty.value()));
            info(strFmt("%1    - %2   - %3   - %4",i,tmp.AccountNum,tmp.SerialNum,tmp.CustName));
            i++;
        }
     }
}

Convert Call stack to readable format in D365FO X++

//Input --container _xppCallStack = xSession::xppCallStack();  Public static str POL_formatXppCallStack(container _xppCallStack, int _skipFr...