Showing posts with label blob. Show all posts
Showing posts with label blob. Show all posts

Sunday, November 16, 2025

Blob file upload and download


    The following code is designed to download invoice and credit note reports, digitally sign them using an external API, and then handle the upload and download of the signed PDF files through Azure Blob Storage.

using Microsoft.Azure; 
using Microsoft.WindowsAzure.Storage; 
using Microsoft.WindowsAzure.Storage.Blob; 
using Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer; 
using Microsoft.WindowsAzure.Storage.File; 
using System.IO; 
public class  DigitalSignGenericClass 
      public boolean runDigitalSign(str reportbyteString, Filename fileName,str signSettingName) 
    {        
        SRSPrintDestinationSettings     settings; 
        Array                           arrayFiles; 
        System.Byte[]                   reportBytes = new System.Byte[0](); 
        str                             reportStreamString,signedReportString; 
        SRSProxy                        srsProxy; 
        SRSReportRunService             srsReportRunService = new SrsReportRunService(); 
        Microsoft.Dynamics.AX.Framework.Reporting.Shared.ReportingService.ParameterValue[]  parameterValueArray; 
        Map                             reportParametersMap; 
        SRSReportExecutionInfo          executionInfo = new SRSReportExecutionInfo(); 
        container                       binData; 
        Binary                          binaryData; 
        str                             fileUrl; 
        System.Net.WebHeaderCollection  httpHeader; 
        System.Net.WebClient            webClient; 
        System.Text.UTF8Encoding        encoder; 
        #define.allowedCharInWorkId('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/_-:') 
        str                             jsonResponse; 
        str                             jsonStr; 
        Map                             map; 
        LedgerJournalTable              LJTable; 
        SystemParameters                systemParameters; 
        boolean                         uploaded = false; 
        
  
  
     //   reportbyteString = System.Convert::ToBase64String(reportBytes); 
        try //Try - Catch section added by BKS to avoid the Bad request issue in FnO @05.03.2021 
        { 
            select systemParameters 
            where systemParameters. IntegrationDataArea == curExt(); 
  
            jsonStr = strFmt('{\"PdfData\":\"%1\",\"SignSettingName\":\"%2\",\"TokenPin\":\"%3\"}', 
                            reportbyteString,signSettingName,null); 
  
            webClient = new System.Net.WebClient(); 
            httpHeader = new System.Net.WebHeaderCollection(); 
            httpHeader = webClient.Headers; 
            httpHeader.Add("Authorization", "Bearer "+ this.getDigitalSignAPIAuthToken(systemParameters)); 
            httpHeader.Add("Content-Type", "application/json"); 
            encoder = new System.Text.UTF8Encoding(); 
            System.Byte[] encodedBytes = encoder.GetBytes(jsonStr); 
            System.Byte[] response = webClient.UploadData(systemParameters. DigitalSignAPIURL, encodedBytes); 
            jsonResponse = webClient.Encoding.GetString(response); 
  
            map = RetailCommonWebAPI::getMapFromJsonString(jsonResponse); 
  
            signedReportString = map.lookup("SignedFile"); 
  
            reportBytes = System.Convert::FromBase64String(signedReportString); 
  
            System.IO.Stream stream = new System.IO.MemoryStream(reportBytes); 
  
            /*FileUploadTemporaryStorageStrategy  fileUploadStrategy = new       FileUploadTemporaryStorageStrategy(); 
        FileUploadTemporaryStorageResult result =     fileUploadStrategy.uploadFile(stream, fileName, "", ".pdf") as    FileUploadTemporaryStorageResult; 
  
        if (result && result.getUploadStatus()) 
        { 
            fileUrl = result.getDownloadUrl(); 
            new Browser().navigate(fileUrl,true); 
        }*/ 
  
  
            uploaded = this.uploadDownloadfileBlobContainer(stream, fileName+".pdf", signSettingName); 
         
            return uploaded; 
        } 
        catch (Exception::Error) 
        { 
            error( ErrorHandlerClass::getErrorStr()); 
            return false; 
        } 
    } 
  
    public str getDigitalSignAPIAuthToken(SystemParameters sysParameters) 
    { 
        System.Net.WebHeaderCollection httpHeader; 
        System.Net.WebClient webClient; 
        System.Text.UTF8Encoding encoder; 
        #define.allowedCharInWorkId('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/_-:') 
        str         jsonResponse,authToken; 
        str         jsonStr; 
        Map         map; 
  
        jsonStr = strFmt('{\"UserName\":\"%1\",\"Password\":\"%2\"}',"Admin","Admin"); 
                             
  
        webClient = new System.Net.WebClient(); 
        httpHeader = new System.Net.WebHeaderCollection(); 
        httpHeader = webClient.Headers; 
        httpHeader.Add("Content-Type", "application/json"); 
        encoder = new System.Text.UTF8Encoding(); 
        System.Byte[] encodedBytes = encoder.GetBytes(jsonStr); 
        System.Byte[] response = webClient.UploadData(sysParameters. DigitalSignAuthTokenURL, encodedBytes); 
        jsonResponse = webClient.Encoding.GetString(response); 
  
        map = RetailCommonWebAPI::getMapFromJsonString(jsonResponse); 
  
        authToken = map.lookup("TxnOutcome"); 
  
        return authToken; 
    } 
  
    public boolean uploadDownloadfileBlobContainer(System.IO.Stream stream, str fileName, str fileType) 
    { 
         
        str                      connectionString; 
        CloudBlobClient          cloudBlobClient; 
        CloudBlobContainer       cloudBlobContainer; 
        CloudStorageAccount      cloudStorageAccount; 
        CloudBlobDirectory       cloudBlobDirectory;// The directory of the blob container 
        CloudBlockBlob           cloudBlobReference; 
        BlobProperties           blobProperties; 
        container                con; 
        int                      i = 0; 
        boolean                  uploaded = false; 
        SystemParameters         systemParameters; 
  
  
        select systemParameters 
            where systemParameters. IntegrationDataArea == curExt(); 
  
        connectionString     = systemParameters. DigitalSignConnectionString; 
         
        cloudStorageAccount  = CloudStorageAccount::Parse(connectionString); 
        cloudBlobClient      = cloudStorageAccount.CreateCloudBlobClient(); 
  
        if(fileType == "FTInvoice" || fileType == "FTInvoiceAS") 
        { 
            cloudBlobContainer   = cloudBlobClient.GetContainerReference(systemParameters. DigitalSignAzureContainerName); // container name 
  
            cloudBlobDirectory = cloudBlobContainer.GetDirectoryReference("D365FTI");//File path where the files are stored 
        } 
        else if(fileType == "DebitNote" || fileType == "CreditNote" || fileType == "TaxInvoice") 
        { 
            cloudBlobContainer   = cloudBlobClient.GetContainerReference(systemParameters. DigitalSignAzureContainerName); // container name 
  
            cloudBlobDirectory = cloudBlobContainer.GetDirectoryReference("D365CNDN");//File path where the files are stored 
        } 
       /* System.Collections.IEnumerable lstEnumarable = cloudBlobDirectory.ListBlobs(false, 0, null, null); 
        System.Collections.IEnumerator lstEnumarator = lstEnumarable.GetEnumerator(); 
        List filenames = new List(Types::String); 
        while(lstEnumarator.MoveNext()) 
        { 
            IListBlobItem item = lstEnumarator.Current; 
            if(item is CloudBlockBlob) 
            { 
                CloudBlockBlob blob = item; 
                blob.FetchAttributes(null, null, null); 
                con = str2con(blob.name, "/"); 
                filenames.addStart(conPeek(con,conlen(con))); 
  
               i = strScan(blob.name,fileName,0,strLen(blob.name)); 
            } 
  
            if(i > 0) 
            { 
                break; 
            } 
        }*/ 
  
  
        cloudBlobReference = cloudBlobDirectory.GetBlockBlobReference(fileName); 
        cloudBlobReference.UploadFromStream(stream,null,null,null); 
         
        blobProperties = cloudBlobReference.Properties; 
        if(blobProperties.Length == stream.Length) 
        { 
            uploaded = true; 
        } 
  
        return uploaded; 
  
    } 
  
    public void downloadfileFromBlobContainer(str fileName, str fileType, str60 _CustVendCode) 
    { 
        str                      connectionString; 
        CloudBlobClient          cloudBlobClient; 
        CloudStorageAccount      cloudStorageAccount; 
        CloudBlobDirectory       cloudBlobDirectory; 
        CloudBlobContainer       cloudBlobContainer; 
        SystemParameters         systemParameters; 
  
  
        select systemParameters 
            where systemParameters. IntegrationDataArea == curExt(); 
  
        connectionString     = systemParameters. DigitalSignConnectionString; 
         
        cloudStorageAccount  = CloudStorageAccount::Parse(connectionString); 
        cloudBlobClient      = cloudStorageAccount.CreateCloudBlobClient(); 
  
        
        if(fileType == "FTInvoice" || fileType == "FTInvoiceAS") 
        { 
            cloudBlobContainer   = cloudBlobClient.GetContainerReference(systemParameters. DigitalSignAzureContainerName); // container name 
  
            cloudBlobDirectory = cloudBlobContainer.GetDirectoryReference("D365FTI");//File path where the files are stored 
        } 
        else if(fileType == "DebitNote" || fileType == "CreditNote" || fileType == "TaxInvoice") 
        { 
            cloudBlobContainer   = cloudBlobClient.GetContainerReference(systemParameters. DigitalSignAzureContainerName); // container name 
  
            cloudBlobDirectory = cloudBlobContainer.GetDirectoryReference("D365CNDN");//File path where the files are stored 
        } 
  
        CloudBlockBlob blob        = cloudBlobDirectory.GetBlockBlobReference(fileName); 
  
       // new Browser().navigate(blob.Uri.OriginalString); 
        System.IO.Stream  stream = new System.IO.MemoryStream(); 
        blob.DownloadToStream(stream, null, null, null); 
        //blob.DownloadToFile(@"I:\"+fileName, FileMode::Create, null, null, null); 
        //blob.DownloadToFile(@"C:\DigiSign\"+fileName, FileMode::Create, null, null, null); 
  
        FileUploadTemporaryStorageStrategy  fileUploadStrategy = new       FileUploadTemporaryStorageStrategy(); 
        FileUploadTemporaryStorageResult result =     fileUploadStrategy.uploadFile(stream, _CustVendCode + "_" + fileName, "", ".pdf") as    FileUploadTemporaryStorageResult; 
  
        if (result && result.getUploadStatus()) 
        {             
            new Browser().navigate(result.getDownloadUrl(),true); 
        }                
         
    } 
  

Tuesday, November 11, 2025

Blob

 using Microsoft.WindowsAzure.Storage; 

Using Microsoft.WindowsAzure.Storage.Blob; 

using System.IO; 

final class FinancialReport 

{ 

    /// <summary> 

    /// Class entry point. The system will call this method when a designated menu  

    /// is selected or when execution starts and this class is set as the startup class. 

    /// </summary> 

    /// <param name = "_args">The specified arguments.</param> 

    public static void main(Args _args) 

    { 

        financialReportVersion financialReportVersion; 

        FinancialReports       financialReports; 

        PeriodEnd              periodEndDate; 

        str                    reportName; 

        str                    fileContent; 

        const str              fileName = 'FinancialReport.xlsx'; 

        reportName = "12 Month Rolling Single Column Income Statement - Default"; 

        periodEndDate = mkDate(31,12,2023); 

        CloudBlobClient cloudBlobClient; 

        CloudBlobContainer cloudBlobContainer; 

        CloudStorageAccount cloudStorageAccount; 

        CloudBlockBlob          CloudBlockBlob; 

        System.Byte[]           reportBytes = new System.Byte[0](); 

        cloudStorageAccount = CloudStorageAccount::Parse("DefaultEndpointsProtocol=https;AccountName=financialreport1;AccountKey=SqnPJgr09oY2ayWNgA31aBihbexyaP7ZNkUYqqZ2f1IXHh1iKT9axXmNtIQ8yeVQReCVEmpUmoF9+AStV81m8A==;EndpointSuffix=core.windows.net"); 

        // Example : 

        // ("DefaultEndpointsProtocol = https; 

        // AccountName = 'AccountName';AccountKey = 'AccountKey';EndpointSuffix=core.windows.net"); 

        cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient(); 

        cloudBlobContainer = cloudBlobClient.GetContainerReference("inputreport"); 

        CloudBlockBlob      = cloudBlobContainer.GetBlockBlobReference(fileName); 

        //FiscalCalendarYear::findYearByCalendarDate(       // Ledger::fiscalCalendar(CompanyInfo::find().RecId), systemDateGet()).EndDate; 

        select firstonly financialReportVersion        order by recid desc    join financialReports 

    where financialReports.DesignId==financialReportVersion.DesignId 

    && financialReports.reportName == reportName; 

        FinancialReportingIReportExport reportExporter = new FinancialReportingReportExport(); 

        System.Text.Encoding encodingGB18030 = System.Text.Encoding::GetEncoding("utf-8"); 

        if (!financialReports.DesignId) 

        { 

            throw error(strfmt("Design not found for Report %1", reportName)); 

        } 

        System.IO.Stream stream = reportExporter.GenerateAndExportReport(        financialReports.DesignId,        curExt(),        periodEndDate,            FinancialReportingReportExportFormat::Excel,        encodingGB18030); 

        if (stream == null) 

        { 

            throw error(strfmt("Stream is empty for Report %1 period %2",            reportNameperiodEndDate)); 

        } 

       // System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); 

       // reportBytes = enc.GetBytes("YOUR XML STRING/TEXT or Data in file"); 

       // System.IO.MemoryStream stream = new System.IO.MemoryStream(reportBytes); 

        CloudBlockBlob.UploadFromStream(stream, null, null, null); 

         

       // System.IO.StreamReader sReader = new System.IO.StreamReader(stream) 

  

; 

        //fileContent = sReader.ReadToEnd(); 

        //File::SendStringAsFileToUser(fileContentfileName); 

    } 

  

}