Tuesday, May 14, 2019

Save file to AZURE blob storage account in D365 FO

using BlobStorage = Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.Dynamics.AX.Framework.FileManagement;
using Microsoft.Azure;
using fileShareStorage = Microsoft.WindowsAzure.Storage.File;
/// <summary>
/// Class Saving File to Azure Storage contianer Blob or file share folder
/// </summary>
class SONFileToAzureStorage
{
    NoYes               IsSuccess;
    public Str          accountName;
    public Str          accountKey;

    /// <summary>
    /// Get /set Operation completion status
    /// </summary>
    /// <param name = "_IsSuccess">setting Operational current status</param>
    /// <returns>operational Status</returns>
    public NoYes parmOperationSuccess(NoYes _IsSuccess = IsSuccess)
    {
        IsSuccess = _IsSuccess;
        return IsSuccess;
    }

    /// <summary>
    /// Get /set Operation completion status
    /// </summary>
    public void initialize()
    {
        accountName = "";// TODO - Need to map
        accountKey = "";// TODO - Need to Map
    }

    /// <summary>
    /// Method will execute code to save file to Azure storage folders based current system setup
    /// </summary>
    /// <param name = "_fileName">Getting file name to process in to Azure storage</param>
    /// <param name = "_fileContent">Get total fiel count to process</param>
    /// <param name = "_containerName">Get specific azure container to process
    /// <param name = "_fileFormat">Get specific file format to process
    /// </param>
    public void saveFileInAzureBlobStorage(str _fileName,str _fileContent,Str  _containerName, Str  _fileFormat)
    {
        System.Exception            ex;
     
        try
        {           
            TextStreamIo            file = TextStreamIo::constructForWrite();
            container               mainContainer; 
            mainContainer = conNull();
            mainContainer = conIns(mainContainer,1,_fileContent);
     
            file.writeExp(mainContainer);

            str filetemppath = File::SendFileToTempStore(file.getStream(),_fileName);
            System.IO.Stream fileStream = File::UseFileFromURL(filetemppath);

            var storageCredentials = new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(accountName, accountKey);
            BlobStorage.CloudStorageAccount storageAccount = new Microsoft.WindowsAzure.Storage.CloudStorageAccount(storageCredentials, true);
            if (storageAccount)
            {
                fileShareStorage.CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
                fileShareStorage.CloudFileShare share = fileClient.GetShareReference(_containerName);

                //Create container in blob if not exists
                // var blobcli = storageAccount.CreateCloudBlobClient();
                //Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer cont = blobcli.GetContainerReference("from-d365")

                if (!share.Exists(null, null))
                {
                    throw error(strFmt("@SSY:AzureFileShareIsMissing",_containerName));
                }

                fileShareStorage.CloudFileDirectory cloudDir = share.GetRootDirectoryReference();
                fileShareStorage.CloudFile fileToSave = cloudDir.GetFileReference(_fileName);

                try
                {
                    fileToSave.UploadFromStreamAsync(fileStream,null,null,null);
                    info(strFmt("@SSY:FilePlacedInAzure",_fileName));
                    this.parmOperationSuccess(NoYes::Yes);
                }
                catch(Exception::Error)
                {
                    ex = CLRInterop::getLastException();
                    error(ex.ToString());
                    //info("@SSY:ErrorWhileUploadingFileInAzureBlobStoarge");
                }
                Catch(Exception::Warning)
                {
                    ex = CLRInterop::getLastException();
                    warning(ex.ToString());
                }
                Catch(Exception::CLRError)
                {
                    ex = CLRInterop::getLastException();
                    checkFailed(ex.ToString());
                }
         
            }
            else
            {
                info("@SSY:ErrorInAzureStorageAccount");
            }
        }
        catch(Exception::Error)
        {
            ex = CLRInterop::getLastException();
            error(ex.ToString());
            //info("@SSY:ErrorWhileUploadingFileInAzureBlobStoarge");
        }
        Catch(Exception::Warning)
        {
            ex = CLRInterop::getLastException();
            warning(ex.ToString());
        }
        Catch(Exception::CLRError)
        {
            ex = CLRInterop::getLastException();
            checkFailed(ex.ToString());
        }

    }

    public static SONFileToAzureStorage construct()
    {
        return new SONFileToAzureStorage();
    }

}


//Test
Static void Man(Args  _args)
{
//TODO. Map Account Name and Account key
SONFileToAzureStorage azureStorage;
azureStorage = new SONFileToAzureStorage();
azureStorage.Intialize();
azureStorage.saveFileInAzureBlobStorage("Test.txt","Blob file content","TestCon",".txt");
if(azureStorage.parmOperationSuccess())
{
//File placed in to specified folder
}
}

No comments:

Post a Comment

Copy Markup charges while posting purchase invoice using X++

 Copy Markup charges while posting purchase invoice using X++ Class: Important: Code logic is just for Reference.  New class => Duplicate...