Sunday, November 23, 2014

Encrypt and Decrypt String in Ax 2012 (Using Base64 string)

//Encrypt and Decrypt in C#
Reference Link: http://www.obviex.com/samples/encryption.aspx

https://stackoverflow.com/questions/10168240/encrypting-decrypting-a-string-in-c-sharp

// Encrypt and Decrypt String in Ax 2012

// Job

static void EncryptDecrypt(Args _args)
{
    San_AdBaseCryptography   crypto = new San_AdBaseCryptography();
    str  inputText = "pos.user123";
    str     enStr,deStr;
    ;
    enStr =crypto.encrypt(inputText);
    deStr = crypto.decrypt(enStr);

    info(inputText);
    info(enStr);
    info(deStr);
}

//Class

// New Class --> San_AdBaseCryptography
public class San_AdBaseCryptography
{
    #define.fixedPassPhrase('Pas5pr@se')
    #define.fixedSaltValue('s@1tValue')
    #define.fixedPasswordIterations(2)
    #define.fixedInitVector('@1B2c3D4e5F6g7H8')
    #define.fixedKeySize(32)

    System.String                                       passPhrase;
    System.String                                       saltValue;
    System.Int32                                        passwordIterations;
    System.String                                       initVector;
    System.Int32                                        keySize;
    System.Text.Encoding                                asciiEncoding;
    System.Text.Encoding                                utf8Encoding;
    System.Byte[]                                       initVectorBytes;
    System.Byte[]                                       saltValueBytes;
    System.Byte[]                                       plainTextBytes;
    System.Byte[]                                       keyBytes;
    System.Byte[]                                       cipherTextBytes;
    System.Security.Cryptography.Rfc2898DeriveBytes     password;
    System.Security.Cryptography.RijndaelManaged        symmetricKey;
    System.Security.Cryptography.ICryptoTransform       encryptor;
    System.Security.Cryptography.ICryptoTransform       decryptor;
    System.IO.MemoryStream                              memoryStream;
    System.Security.Cryptography.CryptoStream           cryptoStream;
    System.String                                       plainText, cipherText;
    System.Exception                                    e;
}
//New Method
public str decrypt(str _cipherText)
{
    System.String plainValue;

    this.init();

    plainValue = this.decrypt_san(
        _cipherText,
        passPhrase,
        saltValue,
        passwordIterations,
        initVector,
        keySize);

    return plainValue;
}
//New Method
protected System.String decrypt_san(
    str             _cipherText,
    System.String   _passPhrase,
    System.String   _saltValue,
    System.Int32    _passwordIterations,
    System.String   _initVector,
    System.Int32    _keySize)
{
    System.Int32 plainTextBytesLength, cipherTextBytesLength, decryptedByteCount;

    try
    {
        new InteropPermission(InteropKind::ClrInterop).assert();

        asciiEncoding           = System.Text.Encoding::get_ASCII();
        utf8Encoding            = System.Text.Encoding::get_UTF8();
        initVectorBytes         = asciiEncoding.GetBytes(_initVector);
        saltValueBytes          = asciiEncoding.GetBytes(_saltValue);
        cipherTextBytes         = System.Convert::FromBase64String(_cipherText);

        password = new System.Security.Cryptography.Rfc2898DeriveBytes(
            _passPhrase,
            saltValueBytes,
            _passwordIterations);

        keyBytes                = password.GetBytes(_keySize);
        symmetricKey = new System.Security.Cryptography.RijndaelManaged();//RijndaelManaged
        symmetricKey.set_Mode(System.Security.Cryptography.CipherMode::CBC);
        decryptor               = symmetricKey.CreateDecryptor(
            keyBytes,
            initVectorBytes);

        memoryStream = new System.IO.MemoryStream(cipherTextBytes);
        cryptoStream = new System.Security.Cryptography.CryptoStream(
            memoryStream,
            decryptor,
            System.Security.Cryptography.CryptoStreamMode::Read);

        cipherTextBytesLength   = cipherTextBytes.get_Length();
        plainTextBytes          = System.Convert::FromBase64String(_cipherText);
        plainTextBytesLength    = plainTextBytes.get_Length();
        decryptedByteCount      = cryptoStream.Read(plainTextBytes, 0, plainTextBytesLength);
        plainText = utf8Encoding.GetString(plainTextBytes, 0, decryptedByteCount);
        memoryStream.Close();
        cryptoStream.Close();

    }
    catch (Exception::CLRError)
    {
        e = CLRInterop::getLastException();

        while( e )
        {
            info( e.get_Message() );
            e = e.get_InnerException();
        }
    }

    return plainText;
}
//New Method
public str encrypt(str _plainText)
{
    System.String cipherValue;

    this.init();

    cipherValue = this.encrypt_San(
        _plainText,
        passPhrase,
        saltValue,
        passwordIterations,
        initVector,
        keySize);

    return cipherValue;
}
//New Method
protected System.String encrypt_San(
    str             _plainText,
    System.String   _passPhrase,
    System.String   _saltValue,
    System.Int32    _passwordIterations,
    System.String   _initVector,
    System.Int32    _keySize)
{
    try
    {
        new InteropPermission(InteropKind::ClrInterop).assert();

        asciiEncoding       = System.Text.Encoding::get_ASCII();
        utf8Encoding        = System.Text.Encoding::get_UTF8();
        initVectorBytes     = asciiEncoding.GetBytes(_initVector);
        saltValueBytes      = asciiEncoding.GetBytes(_saltValue);
        plainTextBytes      = utf8Encoding.GetBytes(_plainText);
        password            = new System.Security.Cryptography.Rfc2898DeriveBytes(
            _passPhrase,
            saltValueBytes,
            _passwordIterations);

        keyBytes            = password.GetBytes(_keySize);
        symmetricKey        = new System.Security.Cryptography.RijndaelManaged();
        symmetricKey.set_Mode(System.Security.Cryptography.CipherMode::CBC);
        encryptor           = symmetricKey.CreateEncryptor(
            keyBytes,
            initVectorBytes);

        memoryStream        = new System.IO.MemoryStream();
        cryptoStream        = new System.Security.Cryptography.CryptoStream(memoryStream,
            encryptor,
            System.Security.Cryptography.CryptoStreamMode::Write);

        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.get_Length());
        cryptoStream.FlushFinalBlock();

        cipherTextBytes     = memoryStream.ToArray();
        cipherText          = System.Convert::ToBase64String(cipherTextBytes);

        memoryStream.Close();
        cryptoStream.Close();

    }
    catch (Exception::CLRError)
    {
        e = CLRInterop::getLastException();

        while( e )
        {
            info( e.get_Message() );
            e = e.get_InnerException();
        }
    }

    return cipherText;
}
//New Method
protected void init()
{
    passPhrase          = #fixedPassPhrase;         // can be any string
    saltValue           = #fixedSaltValue;          // can be any string
    passwordIterations  = #fixedPasswordIterations; // can be any number
    initVector          = #fixedInitVector;         // must be 16 bytes
    keySize             = #fixedKeySize;            // 32 = 256b, 24=192b or 16=128b
}
// Encrypt and Decrypt Done....


//Encrypt and Decrypt in SQL

https://sangeethwiki.blogspot.in/2017/10/encrypt-and-decrypt-in-sql.html

Count of day without Friday,saturday in ax 2012

// Count of day without Friday,saturday

static void San_DateFriSat(Args _args)
{
    date d,f,g;
    int i,months,day,countday;
    d = mkDate(01,12,2014);
    f = mkDate(31,12,2014);
    g = nextMth(f);  
    months = intvNo(g,d,intvScale::Day);
    //info(strfmt("%1",months));
    for (i=0;i<= months;i++)
    {
        day = dayOfwk(d);
        //info(strfmt("Weekday number - %1",day));
        if (day == 1 || day == 2 || day == 3 || day == 4 || day ==7)
        {
             countday++;  
        }
        d = d +1;
    }
    info(strFmt("%1",countday));
   
}

Random password both Number and String in ax 2012

// Random password

static void RandomNumberString(Args _args)
{
    //RandomGenerate RandomRange = new RandomGenerate();
    //Random Random = new Random();
    //;
    //info(int2Str(RandomRange.randomInt(20,100)));
    //info(int2Str(Random.nextInt()));

    int i;
    RandomGenerate random = new RandomGenerate();
    str password;
    int passwordLength = 8
    ;
    for (i=1; i<= max(2, passwordLength); i++)
    {
        if (i mod 2)
            password += num2char(random.randomInt(char2num('a', 1), char2num('z', 1)));
        else
            password += num2char(random.randomInt(char2num('0', 1), char2num('9', 1)));
    }
    info(password);
}

Sunday, November 16, 2014

Date interval Month

// Date Between the interval Month

static void dateintervalmonth(Args _args)
{
    date d,f;
    int i,months;
    int interval = 8;
    d = mkDate(01,02,2014);
    f = mkDate(01,11,2013);
 
    months = intvNo(d,f,intvScale::YearMonth);
    info(strFmt("%1",months));
 
    for(i = 0;i<= months; i++)
    {
        info(strFmt("%1 - %2",mthname(mthofYr(d)),year(d)));
        d = prevmth(d);
    }
}

Friday, November 14, 2014

Report Parameter to run X++

// Report Parameter to run X++

static void ReportParameterRUn(Args _args)
{
    MenuFunction    BurkanReport; //CopyOfCommercialEvaluation
    Args    args;
    str parmId;
   
    BurkanReport = new MenuFunction(menuitemOutputStr(CopyOfCommercialEvaluation),MenuItemType::Output);
    args = new Args();
    parmId = "00000088_183";
    args.parm(parmId);
    BurkanReport.run(args);
}

Enum Element Label X++

//Enum Element Label X++

static void enumElementLabel(Args _args)
{
    SysDictEnum dictEnum = new SysDictEnum(enumNum(MonthsOfYear));
    Counter values = dictEnum.values();
    int idx;
   
    for(idx = 1; idx< values ;idx++)
    {
        info(strfmt("%1",dictEnum.index2Label(idx)));
    }
}

Upload data from Excel in D365FO X++

 Action Menu Item: SAN_UploadExcelData Object type: Class Object: <Controller class name> Label: <> Class: Controller class clas...