Search code examples
asp.netgoogle-apps-scriptgoogle-apps-script-api

How to send List of objects to google execution api and handle it in google apps script


In general I want to export data from asp.net mvc application to Google Sheets for example list of people. I've already set up connection and authenticated app with my Google account (trough OAuth2) but now I'm trying to send my list of objects to api and then handle it in script (by putting all data in new file) and couldn't get my head around this.

Here is some sample code in my app that sends the request.

public async Task<ActionResult> SendTestData()
    {
        var result = new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
            AuthorizeAsync(CancellationToken.None).Result;

        if (result.Credential != null)
        {
            string scriptId = "MY_SCRIPT_ID";

            var service = new ScriptService(new BaseClientService.Initializer
            {
                HttpClientInitializer = result.Credential,
                ApplicationName = "Test"
            });


            IList<object> parameters = new List<object>();

            var people= new List<Person>(); // next i'm selecting data from db.Person to this variable

            parameters.Add(people);

            ExecutionRequest req = new ExecutionRequest();
            req.Function = "testFunction";
            req.Parameters = parameters;

            ScriptsResource.RunRequest runReq = service.Scripts.Run(req, scriptId);

            try
            {
                Operation op = runReq.Execute();

                if (op.Error != null)
                {
                    // The API executed, but the script returned an error.

                    // Extract the first (and only) set of error details
                    // as a IDictionary. The values of this dictionary are
                    // the script's 'errorMessage' and 'errorType', and an
                    // array of stack trace elements. Casting the array as
                    // a JSON JArray allows the trace elements to be accessed
                    // directly.
                    IDictionary<string, object> error = op.Error.Details[0];
                    if (error["scriptStackTraceElements"] != null)
                    {
                        // There may not be a stacktrace if the script didn't
                        // start executing.
                        Newtonsoft.Json.Linq.JArray st =
                            (Newtonsoft.Json.Linq.JArray)error["scriptStackTraceElements"];
                    }
                }
                else
                {
                    // The result provided by the API needs to be cast into
                    // the correct type, based upon what types the Apps
                    // Script function returns. Here, the function returns
                    // an Apps Script Object with String keys and values.
                    // It is most convenient to cast the return value as a JSON
                    // JObject (folderSet).
                    Newtonsoft.Json.Linq.JObject folderSet =
                            (Newtonsoft.Json.Linq.JObject)op.Response["result"];
                }
            }
            catch (Google.GoogleApiException e)
            {
                // The API encountered a problem before the script
                // started executing.
                AddAlert(Severity.error, e.Message);
            }


            return RedirectToAction("Index", "Controller");

        }
        else
        {
            return new RedirectResult(result.RedirectUri);
        }
    }

The next is how to handle this data in scripts - are they serialized to JSON there?


Solution

  • The execution API calls are essentially REST calls so the payload should be serialized as per that. Stringified JSON is typically fine. Your GAS function should then parse that payload to consume the encoded lists

    var data = JSON.parse(payload);