0

I am working on Azure Function (Http Trigger), and came across with this task.

I am trying to display the output of method (ListVendors.Run(logger)) into inside variable (responseMessage) so that the values would be carried into Http post.

public static class Function1
    {
        [FunctionName("HttpTrigger_1111_1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            ///Calling from other method starts:
            ILogger logger = Bootstrap.Logger("Program"); 
            ListVendors.Run(logger);
            ///Calling from other method ends:
    
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);                  
        }
    }

Basically, I am trying to insert the output of:

ListVendors.Run(logger);

Inside "responseMessage".

return new OkObjectResult(responseMessage); 

How do I modify the code to do that?
Bottom is code for ListVendors:

 public static class ListVendors
{
    public static void Run(ILogger logger)
    {
        OnlineClient client = Bootstrap.Client(logger);

        ReadByQuery query = new ReadByQuery()
        {
            ObjectName = "VENDOR",
            PageSize = 2, // Keep the count to just 2 for the example
            Fields =
            {
                "RECORDNO",
                "VENDORID",
            }
        };

        logger.LogInformation("Executing query to Intacct API");

        Task<OnlineResponse> task = client.Execute(query);
        task.Wait();
        OnlineResponse response = task.Result;
        Result result = response.Results[0];

        try
        {
            dynamic json = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(result.Data));

            string jsonString = json.ToString();
        
            logger.LogDebug(
                "Query successful - page 1 [ Total count={0}, Data={1} ]",
                result.TotalCount,
                jsonString
            );

            Console.WriteLine("Page 1 success! Number of vendor objects found: " + result.TotalCount + ". Number remaining: " + result.NumRemaining);

        } catch (NullReferenceException e)
        {
            logger.LogDebug("No response in Data. {0}", e);
        }
        
        LogManager.Flush();
        int i = 1;
        while (result.NumRemaining > 0 && i <= 3 && !string.IsNullOrEmpty(result.ResultId))
        {
            i++;
            ReadMore more = new ReadMore()
            {
                ResultId = result.ResultId
            };
            
            Task<OnlineResponse> taskMore = client.Execute(more);
            taskMore.Wait();
            OnlineResponse responseMore = taskMore.Result;
            Result resultMore = responseMore.Results[0];

            try
            {
                dynamic resultMoreJson =
                    JsonConvert.DeserializeObject(JsonConvert.SerializeObject(resultMore.Data));
                string resultMoreJsonString = resultMoreJson.ToString();

                logger.LogDebug(
                    "Read More successful - page " + i + " [ Total remaining={0}, Data={1} ]",
                    resultMore.NumRemaining,
                    resultMoreJsonString
                );

                Console.WriteLine("Page " + i + " success! Records remaining: " + resultMore.NumRemaining);
            }
            catch (NullReferenceException e)
            {
                logger.LogDebug("No response in Data. {0}", e);
            }
            finally
            {
                LogManager.Flush();
            }
        }
        
        Console.WriteLine("Successfully read " + i + " pages");
    }
}

}

Java
  • 1,208
  • 3
  • 15
  • 29
  • What type is `ListVendors` and what is inside its `Run` method? – John Wu Nov 12 '21 at 00:09
  • Now you've just moved the problem. What is inside `ReadByQuery`? I don't see anything that tells us how `Run` outputs anything, or what that even means. Is it writing to the `ILogger`? Is it writing to standard output? If these are standard libraries of some kind please edit your tags. – John Wu Nov 12 '21 at 00:26
  • 1
    There's a lot wrong with that code. Don't catch `NullReferenceException`. Also, don't call `Task.Wait`, instead write `var responseMore = await client.Execute(more);` – Aluan Haddad Nov 12 '21 at 00:32
  • @JohnWu I just added the whole code of ListVendors class. I am using intacct SDK and NLog. – Java Nov 12 '21 at 00:33
  • @Aluan Haddad Basically, the majority of code of Function1 class is given (default) https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=csharp inside Azure Solution file. I am just trying to call other methods (ListVendors.Run & Bootstrap.Logger) to get the values. Sorry. regards to the code of ListVendors, it was given from third party vendor (https://github.com/Intacct/intacct-sdk-net-examples/blob/master/Intacct.Examples/ListVendors.cs). – Java Nov 12 '21 at 00:36
  • 1
    So you're trying to [capture console output](https://learn.microsoft.com/en-us/dotnet/api/system.console.setout?view=net-5.0)? – John Wu Nov 12 '21 at 00:41
  • @JohnWu That is a good question. No I need to change the code of ListVendors.cs to have a tabular output to move data into SQL. I am trying to test moving the value of ListVendors to http. – Java Nov 12 '21 at 00:43
  • So... modify the return type of `Run` so that it returns a `DataTable`, then modify the implementation to create one and populate it instead of writing to the console. Which part of that is causing you trouble? – John Wu Nov 12 '21 at 00:45
  • @JohnWu I think both.. – Java Nov 12 '21 at 00:52
  • Please see [How to create a DataTable and add rows](https://stackoverflow.com/a/1042638/2791540) – John Wu Nov 12 '21 at 01:03
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/239141/discussion-between-java-and-john-wu). – Java Nov 12 '21 at 01:07

0 Answers0