Question

How to make an external API call from a processing screen

  • 10 October 2023
  • 12 replies
  • 287 views

Userlevel 4
Badge

Hi,

I have a customization that used to work in R2021 but is new throwing a “server has restarted” message since moving to R2022.  This is on a local instance (2022.217.202.5231) and I have narrowed my code right down to the smallest steps to replicate the issue.  This identifies that this appears to be the result of making an asynchronous API call from within a processing form.

So, my question is how should one make asynchronous calls from within a processing form and what is wrong with the code below (which was used to work on R2021)?

I have also found this link in my travels:

https://stackoverflow.com/questions/50910047/is-it-possible-to-use-async-methods-inside-acumaticas-pxlongoperation

 

Here is the simplified code that produces the problem:

 

I have a processing form:

This is looping over a MASTRemoteExt DAC which has 44 records

And the TestAPI method in the MASTRemoteMaint Graph:

All this is doing is, for each remote record, making an asynchronous API call using HTTPClient and setting the LastUpdatedTime on the MASTRemoteExt record.  I’m not currently doing anything with the result.  Furthermore, I have identified that it’s lines 73,74 & 76 which are causing the error to be thrown.  If these are commented out then no error.

 

This is what happens when the code above runs:

  1. Processing form before hitting Update All

     

    1. Code processes 19 of the 44 records and then throws “The server has been restarted.  Please reload the page”

      As mentioned above if lines 73,74 & 76 are commented out then there is no error, so I thin kit’s something about making the asynchronous call that’s causing the problem

Thanks in advance for any help.  I must have spent a good 5 hours trying to resolve this yesterday without any success..

 

Thanks,

John.

 


12 replies

Userlevel 4
Badge

Hi,

 

Further to the above, the JIT debugger is also being launched when the processing form hangs and lands in QueuedNetworkSender.cs whatever that is.  Not sure that this is relevant to the issue with the code? 

 

 

Thanks,

John.

Userlevel 7
Badge +11

Hi @JWS539 

Am using the below code and have not faced any such kind of issues. Please review once.
 

 public static HttpResponseMessage RestAPIRequest(token, string apiUrl, string method, string data)
        {
            HttpResponseMessage response = new HttpResponseMessage();
            try
            {
                HttpClient cl = APIHeader(token, apiUrl);
                var response1 = cl.GetAsync(apiUrl);
                response1.Wait();
                response = response1.Result;

            }
            catch (Exception)
            {
                response = null;
                throw;
            }
            return response;
        }


  private static HttpClient APIHeader(string token, string apiUrl)
        {
            try
            {
                HttpClient cl = new HttpClient();
                cl.BaseAddress = new Uri(apiUrl);
                int _TimeoutSec = 300;
                cl.Timeout = new TimeSpan(0, 0, _TimeoutSec);
                cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                cl.DefaultRequestHeaders.Add(KNMCConstants.Authorization, “Bearer  “+ token);
                return cl;
            }
            catch (Exception )
            {
                throw;
            }
           
        }

Userlevel 4
Badge

Hi Jini N,

 

Thanks for your code snippet.  Will give this a go today and let you know how it goes :)

 

 

 

Userlevel 4
Badge

Hi Jini N,

I reviewed and tried your code, and got the same result (the processing form ran for approx 19 of the 44 records and then the “Server has restarted” message pops and the form hangs.  See below for the modified code with the changes you suggested:

 

Only change I made was hard coding the token in APIHeader.  Can you see anything obviously wrong here?

I don’t doubt your code works, and mine did in R2021, just not R2023.

My suspicion is that there is nothing wrong with either sets of code but some issue in the build.  Not sure where to go from here.  Any suggestions?

We have had quite a bit of trouble with customisations that work in R2021 but not R2022.  Even now we are having to apply workarounds.  One such example is that unless we add the below to Web.Config we can’t get the simplest customisation to even publish on a local environment:

<add key="CheckCustomizationCompatibility" value="False" />

I wonder whether the code would run on a live site without any problems.  Might be worth a go but doesn’t make debugging/trouble shooting easy.

Any other thoughts on places we could go next to get a resolution greatly appreciated!

Thanks,

John.

 

 

 

 

 

 

Userlevel 7
Badge +11

Hi @JWS539 

You can check the request profiler screen to verify, and also review the system monitor screen to get an idea of the issue.

If unable to identify, please reach out Acumatica support.

 

Userlevel 4
Badge

Hi Jini N,

 

Thanks for the extra info.  I didn’t even know these tools existed, they look quite useful.  Had a look though and they didn’t shed much light on the problem.  The first and only exception logged was “The server has restarted”

Will contact support as suggested.

 

Thanks again for all your help,

JOhn.

 

Userlevel 4
Badge

Hi,

Still looking for some help on this one.  So far we haven’t been able to solve the problem and we have a client who is very close to walking away from Acumatica due to it.  Since 12 October there have been a couple of developments which I’m hoping may help someone on this forum help us out.

 

  1. The case finally made it to Acumatica support in late January.  Our client is based in New Zealand and run Acumatica branded as MYOB Advanced. (MYOB are the Australasian license holders for MYOB).  So, the MYOB team had to have a look at the issue first and only recently has it been passed on to Acumatica support.  We were supplied the code below as a recommended solution:

However, the code above doesn’t compile because SMSyncContext doesn’t exist in the PX.SM namespace.  We get the usual “Are you missing an assembly reference” message.  Haven’t found any clues on SMSyncContext via an internet search.

 

  1. We have just tried to upgrade to build 2023.112.200.6029. We found that the behaviour of the customisation was different in this build with a new error “Instances cannot be resolved and nested lifetimes cannot be created from the LifeTime scope as it has already been disposed”.  Maybe someone knows what this means and how to resolve?  I have tried an internet search and can find nothing relating to Acumatica.

A matrix of our experience of this problem in different versions is shown below:

 

And here is a screen shot of the “Instances cannot be resolved...” message which appears on the processing screen.

One other piece of info, the API call we are attempting to make occasionally returns a 500 Response.  When you fire valid API requests in quick succession the first few will work, then status code 500, then wait a bit and away you go again.  I don’t think this is relevant to the issue as the standard error handling in the processing form should be able to deal with this (I would have thought), but perhaps it is relevant?

 

Any and all potential leads on what we should try next gratefully received.  Maybe someone has some ideas based on the new error message?  

Thanks,

John.

 

 

Userlevel 7
Badge

Hi @JWS539 were you able to find a solution? Thank you!

Userlevel 4
Badge

Hi Chris,

 

No not yet.  Issue is currently sitting with Acumatica support who now have a copy of the customisation code.  Am hopeful of a resolution soon.

Did Acumatica support ever get you a method to handle this?

Userlevel 4
Badge

Hi Jim,

 

Thanks for taking the time to review this topic.

This is still not resolved, so unfortunately the answer to your question is no, and as a consequence we still have an unhappy client.

This issue is with Acumatica support.

Just for some context, we are based in New Zealand and are therefore supported by MYOB (who run Acumatica across Australasia but under an MYOB brand.  The software is the same, only the branding is different).  The MYOB support team are consulting the Acumatica support team around this but there is an extra layer  of comms which seems to make progress extremely slow.  

We are still pushing for a resolution on this one but are unsure of what the outcome will be.  Worst case is our client will decide to ditch Acumatica/MYOB altogether which is no good for anyone.

 

Thanks,

John.

 

 

I took all the async calls and converted them to single thread (at least non async), now seems to run OK for my use:

 

var baseAddress = new Uri(setup.URL.Trim());
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
    System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("x-api-key", setup.APIClientKey.TrimEnd());
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("x-api-secret", setup.APIClientSecret.TrimEnd());
    string JsonCustomer = JsonConvert.SerializeObject(customerDTO);
    using (var content = new StringContent(JsonCustomer, System.Text.Encoding.UTF7, "application/json"))
    {

        //    using (var response = await httpClient.PostAsync("customers", content))
        using (var response = httpClient.PostAsync("customers", content).GetAwaiter().GetResult())

        {
            string responseData = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        }
    }
}

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