Friday, December 1, 2023

Write IOStream to azure blob using X++

/// <summary>
///     Service class for export customer details to blob storage
///    /// </summary>
using BlobStorage = Microsoft.WindowsAzure.Storage;
using Microsoft.Dynamics.AX.Framework.FileManagement;
using System.IO;
class ExportCustomerDetailsToAzureBlobService extends SysOperationServiceBase
{
    QueryRun    queryRun;
    CustTable   custTable;
 
    /// <summary>
    ///     Export customer details to blob storage
    /// </summary>
    /// <param name = "_contract">contract class</param>
    public void run(ExportCustomerDetailsToAzureBlobContract _contract)
    {
        // create a new queryrun object
        queryRun = new queryRun(_contract.getQuery());
 
        CommaStreamIo       io = CommaStreamIo::constructForWrite();
        const str           connectionString = "DefaultEndpointsProtocol=https;AccountName=arorasamplestorageacc;AccountKey=qRAbReWrFS5a4pVg7fVBdACk0/q4AzpwM6YBT7LYT4oAapZjCr1Wc5bNB1Lia9oYZXO7R/M17okx+AStaDNKFg==;EndpointSuffix=core.windows.net";
        const str           containerName = "arorasamplecontainer";
 
        TransDate   curDate = DateTimeUtil::getToday(DateTimeUtil::getUserPreferredTimeZone());
 
        str         curYear = int2Str(year(curDate));
        str         curMth  = int2Str(mthOfYr(curDate));
 
        if (strLen(curMth) == 1)
        {
            curMth = '0'+curMth;
        }
 
        str         curDay = int2Str(dayOfMth(curDate));
 
        if (strLen(curDay) == 1)
        {
            curDay = '0'+curDay;
        }
 
        str         mergedDate = curYear+curMth+curDay;
 
        TimeOfDay  curTime = DateTimeUtil::getTimeNow(DateTimeUtil::getUserPreferredTimeZone());
 
        str         mergedTime = time2StrHMS(curTime);
        mergedTime = strRem(mergedTime, ':');
        mergedTime = strRem(mergedTime, ' ');
 
        if (strLen(mergedTime) == 5)
        {
            mergedTime = '0'+mergedTime;
        }
 
        str         mergedDateTime = mergedDate+mergedTime;
 
        str         fileName = strFmt('%1_%2.csv',curExt(), mergedDateTime);
        BlobStorage.CloudStorageAccount storageAccount = BlobStorage.CloudStorageAccount::Parse(connectionString);
        BlobStorage.Blob.CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        BlobStorage.Blob.CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);
        blobContainer.CreateIfNotExistsAsync();
        io.writeExp(['Data area', 'Org number' , 'Tax receipt number']);
        // loop all results from the query
        while(queryRun.next())
        {
            custTable = queryRun.get(tablenum(CustTable));
 
            DirOrganization organization = DirOrganization::find(custTable.Party);
 
            io.writeExp([custTable.DataAreaId, organization.OrgNumber, subStr(custTable.VATNum, 2, -3)]);
        }
        BlobStorage.Blob.CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileName);
        if(blockBlob && !blockBlob.Exists(null,null))
        {
            System.IO.Stream stream = iO.getStream();
            stream.Position = 0;
            System.IO.StreamReader reader = new System.IO.StreamReader(stream);
            str csvFileContent = reader.ReadToEnd();
            if(csvFileContent)
            {
                blockBlob.UploadText(csvFileContent,null,null,null,null);
                blockBlob.FetchAttributes(null,null,null);
                BlobStorage.Blob.BlobProperties blobProperties = blockBlob.Properties;
                if(blobProperties.Length != 0)
                {
                    info('File upload successful');
                }
            }
        }
        else
        {
            info('File already exits');
        }
    }
 
}

No comments:

Post a Comment

Table browser URL in D365FO

Critical Thinking icon icon by Icons8