Friday, July 22, 2022

Export CSV file to Microsoft Azure Storage in Dynamics 365 FO

using Microsoft.WindowsAzure.Storage;

using Microsoft.WindowsAzure.Storage.Auth;

using Microsoft.WindowsAzure.Storage.Blob;

Class ExportCSV

{

    public static void main(Args _args)

    {

        CommaStreamIo                       commaStreamIo;

        commaStreamIo = CommaStreamIo::constructForWrite();

        commaStreamIo.writeExp(['Name','Phone number']);

        commaStreamIo.writeExp(['Atul Yadav','9871286647']);


        System.IO.Stream stream = commaStreamIo.getStream();

        this.exportFileToAzureBlob(stream);

    }


    public void exportFileToAzureBlob(System.IO.Stream  _stream)

    {

        #define.dotcsv('.csv')

        #define.Underscore('_')

        MCOEDI888BlobParameters parameters = MCOEDI888BlobParameters::find();

        Filename    fileName;

        _stream.Position = 0;

        fileName = strfmt(parameters.FileName + #Underscore

                                        + date2str(DateTimeUtil::getToday(DateTimeUtil::getUserPreferredTimeZone()),213,2,0,2,0,4)

                                        + #Underscore

                                        + strRem(time2str(DateTimeUtil::getTimeNow(DateTimeUtil::getUserPreferredTimeZone()),2,TimeFormat::Hour24),'.')

                                        + #dotcsv);

        StorageCredentials storageCredentials = new StorageCredentials(parameters.AzureStorageAccount, parameters.AzureStorageKey);     //Account name and Azure storage key

        CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        CloudBlobContainer cont = blobClient.GetContainerReference(parameters.AzureBlobContainer);  //Name of the blob container where you want the file to be exported

        CloudBlockBlob cloudBlockBlob = cont.GetBlockBlobReference(fileName);

        cloudBlockBlob.UploadFromStream(_stream, null, null, null);

    }


}