Solved

A PDF is being received from an API but I cannot attach it to a record using code

  • 6 March 2024
  • 3 replies
  • 55 views

Related to the topic, I have the following code, but this time I try to obtain the pdf from an api, and save it in Shipment, I show you the code and the error that appears:

[PXButton(CommitChanges = true)]
[PXUIField(DisplayName = "Track")]

protected void apiTracking()
{
    DownloadAndUploadFile();
}


public void DownloadAndUploadFile()
{
    try
    {
        using (HttpClient client = new HttpClient())
        {
            string url = "http://qaglp.paquetexpress.mx:8083/wsReportPaquetexpress/GenCartaPorte?trackingNoGen=19167736449";
            HttpResponseMessage queryResult = client.GetAsync(url).Result;

            if (queryResult.IsSuccessStatusCode)
            {
                byte[] fileContent = queryResult.Content.ReadAsByteArrayAsync().Result;

                UploadFile(fileContent, "downloadedFile55.pdf");
            }
            else
            {
                PXTrace.WriteWarning("HTTP request was not successful.");
            }
        }
    }
    catch (Exception ex)
    {
        PXTrace.WriteWarning("An exception occurred: " + ex.Message);
    }
}


private void UploadFile(byte[] file, string fileName)
{
    try
    {
        // Create an instance of PX.SM.UploadFileMaintenance
        PX.SM.UploadFileMaintenance uploadFileMaintenanceGraph = PXGraph.CreateInstance<PX.SM.UploadFileMaintenance>();

        // Create a FileInfo object for the file
        PX.SM.FileInfo fileInfo = new PX.SM.FileInfo(fileName, null, file);

        // Save the file
        if (uploadFileMaintenanceGraph.SaveFile(fileInfo, PX.SM.FileExistsAction.CreateVersion))
        {
            PXTrace.WriteInformation("File uploaded successfully.");

            // Associate the file with each shipment
            foreach (SOShipment shipment in Base.Document.Select().RowCast<SOShipment>().ToList())
            {
                // Upload the file and associate it with the shipment
                uploadFileMaintenanceGraph.SaveFile(fileInfo, PX.SM.FileExistsAction.CreateVersion);
                uploadFileMaintenanceGraph.AttachFile(typeof(SOShipment).FullName, shipment.ShipmentNbr, fileInfo);
            }
        }
        else
        {
            PXTrace.WriteWarning("Error uploading the file.");
        }
    }
    catch (Exception ex)
    {
        PXTrace.WriteWarning("An exception occurred: " + ex.Message);
    }
}
and I get this error:

[2024-03-05 18:21:11.673] \App_RuntimeCode\SOShipmentEntry.cs(164): error CS1061: 'UploadFileMaintenance' does not contain a definition for 'AttachFile' and no accessible extension method 'AttachFile' accepting a first argument of type 'UploadFileMaintenance' could be found (are you missing a using directive or an assembly reference?)
icon

Best answer by darylbowman 6 March 2024, 19:46

View original

3 replies

Userlevel 7
Badge +4

Please see related discussion:

How do we attach report PDF/Excel file when i click on custom action on Sales order screen using Acumatica code - Stack Overflow

Attach files to file section from process screen does not work in Acumatica - Stack Overflow

 

I believe you need to use PXNoteAttribute.AttachFile

The file could already be uploaded but now I have the following problem that the pdf comes without any information, does anyone know how to solve it?

 

I would appreciate your support. I leave you the code I use:

 

   [PXButton(CommitChanges = true)]

   [PXUIField(DisplayName = "Rastreo")]

   

   protected void apiRastreo()

   {

     ApiRastreoLogic(Base);

   }

 

 

 

protected void ApiRastreoLogic(SOShipmentEntry graph)

{

   try

   {

     using (HttpClient cliente = new HttpClient())

     {

       string url = "http://qaglp.paquetexpress.mx:8083/wsReportPaquetexpress/GenCartaPorte?trackingNoGen=19167736449";

       HttpResponseMessage resultadoConsulta = cliente.GetAsync(url).Result;

 

       if (resultadoConsulta.IsSuccessStatusCode)

       {

         using (Stream stream = resultadoConsulta.Content.ReadAsStreamAsync().Result)

         {

           UploadFileMaintenance upl = PXGraph.CreateInstance<UploadFileMaintenance>();

           

           // Creamos un objeto FileInfo para el archivo

           PX.SM.FileInfo fileinfo = new PX.SM.FileInfo("archivoDescargado88.pdf", null, ReadFully(stream));

 

           foreach (SOShipment shipment in Base.Document.Select().RowCast<SOShipment>().ToList())

           {

             graph.Clear();

             graph.Document.Current = graph.Document.Search<SOShipment.shipmentNbr>(shipment.ShipmentNbr);

 

             if (upl.SaveFile(fileinfo, FileExistsAction.CreateVersion))

             {

               PXNoteAttribute.SetFileNotes(graph.Document.Cache, graph.Document.Current, fileinfo.UID.Value);

               graph.Save.Press();

             }

           }

         }

       }

       else

       {

         // Manejar el caso en que la solicitud HTTP no fue exitosa

         PXTrace.WriteWarning("La solicitud HTTP no fue exitosa.");

       }

     }

   }

   catch (Exception ex)

   {

     // Manejar excepciones

     PXTrace.WriteWarning("Se produjo una excepción: " + ex.Message);

   }

}

 

 

Badge +11

I’m not sure this is your issue, but you may want to save the UploadFileMaintenance graph like this:

if (upl.SaveFile(fileinfo, FileExistsAction.CreateVersion))
{
PXNoteAttribute.SetFileNotes(graph.Document.Cache, graph.Document.Current, fileinfo.UID.Value);

// Save UploadFileMaintenance graph
upl.Persist();

graph.Save.Press();
}

 

It stands to reason that if the file being saved is empty, you are probably creating an empty file. I would make sure that the incoming stream is actually being filled with data.

Reply


About Acumatica ERP system
Acumatica Cloud ERP provides the best business management solution for transforming your company to thrive in the new digital economy. Built on a future-proof platform with open architecture for rapid integrations, scalability, and ease of use, Acumatica delivers unparalleled value to small and midmarket organizations. Connected Business. Delivered.
© 2008 — 2024  Acumatica, Inc. All rights reserved