Skip to main content
Solved

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


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?)

Best answer by darylbowman

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.

View original
Did this topic help you find an answer to your question?

3 replies

RohitRattan88
Acumatica Moderator
Forum|alt.badge.img+4
  • Acumatica Moderator
  • 253 replies
  • March 6, 2024

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);

   }

}

 

 


darylbowman
Captain II
Forum|alt.badge.img+13

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


Cookie policy

We use cookies to enhance and personalize your experience. If you accept you agree to our full cookie policy. Learn more about our cookies.

 
Cookie settings