예제 #1
0
        private string ProcessResult(ScriptsResource.RunRequest runReq)
        {
            var errorMessages = new StringBuilder("");

            try
            {
                var op = runReq.Execute();

                if (op.Error != null)
                {
                    IDictionary <string, object> error = op.Error.Details[0];
                    errorMessages.AppendLine($"Script error message: {error["errorMessage"]}");
                    if (error["scriptStackTraceElements"] != null)
                    {
                        // There may not be a stacktrace if the script didn't
                        // start executing.
                        errorMessages.AppendLine("Script error stacktrace:");
                        Newtonsoft.Json.Linq.JArray st =
                            (Newtonsoft.Json.Linq.JArray)error["scriptStackTraceElements"];
                        foreach (var trace in st)
                        {
                            errorMessages.AppendLine($"\t{trace["function"]}: {trace["lineNumber"]}");
                        }
                    }
                }
                else
                {
                    return(op.Response["result"].ToString());
                }
            }
            catch (Google.GoogleApiException e)
            {
                errorMessages.AppendLine($"Error calling API:\n{e}");
            }

            throw new Exception(errorMessages.ToString());
        }
예제 #2
0
        public Newtonsoft.Json.Linq.JObject getFormResponses(string formURL)
        {
            UserCredential credential;

            using (var stream =
                       new FileStream(Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory) + "\\client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/script-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Apps Script Execution API service.
            string scriptId = "M0YSrBk4T63lHaeGk0azzG-rKGMnPQbcl";
            var    service  = new ScriptService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Create an execution request object.
            ExecutionRequest request = new ExecutionRequest();

            request.Function = "getFormAnswers";

            string[] requestParam = new string[] { formURL };

            request.Parameters = requestParam;

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

            try
            {
                // Make the API request.
                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];
                    Console.WriteLine(
                        "Script error message: {0}", error["errorMessage"]);
                    if (error["scriptStackTraceElements"] != null)
                    {
                        // There may not be a stacktrace if the script didn't
                        // start executing.
                        Console.WriteLine("Script error stacktrace:");
                        Newtonsoft.Json.Linq.JArray st =
                            (Newtonsoft.Json.Linq.JArray)error["scriptStackTraceElements"];
                        foreach (var trace in st)
                        {
                            Console.WriteLine(
                                "\t{0}: {1}",
                                trace["function"],
                                trace["lineNumber"]);
                        }
                    }
                }
                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).

                    String resp = (String)op.Response["result"];

                    Newtonsoft.Json.Linq.JObject response = Newtonsoft.Json.Linq.JObject.Parse(resp);

                    if (response.Count == 0)
                    {
                        Console.WriteLine("No responses returned!");
                    }
                    else
                    {
                        Console.WriteLine("Responses:");
                        Console.WriteLine(response);

                        /*foreach (var folder in folderSet)
                         * {
                         *  Console.WriteLine(
                         *      "\t{0} ({1})", folder.Value, folder.Key);
                         * }*/
                    }

                    return(response);
                }
            }
            catch (Google.GoogleApiException entry)
            {
                // The API encountered a problem before the script
                // started executing.
                Console.WriteLine("Error calling API:\n{0}", entry);
            }

            return(null);
        }
예제 #3
0
        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/script-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Apps Script Execution API service.
            string scriptId = "MIZ8ME5AgqFMS6rD8ZLQTQxU3ND9pJt_J";
            var    service  = new ScriptService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Create an execution request object.
            ExecutionRequest request = new ExecutionRequest();

            request.Function = "getFormAnswers";

            // Form url TODO: valor proveniente do powerpoint

            string[] formUrl = new string[] { String.Format("https://" + "docs.google.com/forms/d/11Vnlhtcw_kvjAB5QZFrYXiRUiu5Imlix-H8XOOEp9Vs/edit") };

            request.Parameters = formUrl;

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

            try
            {
                // Make the API request.
                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];
                    Console.WriteLine(
                        "Script error message: {0}", error["errorMessage"]);
                    if (error["scriptStackTraceElements"] != null)
                    {
                        // There may not be a stacktrace if the script didn't
                        // start executing.
                        Console.WriteLine("Script error stacktrace:");
                        Newtonsoft.Json.Linq.JArray st =
                            (Newtonsoft.Json.Linq.JArray)error["scriptStackTraceElements"];
                        foreach (var trace in st)
                        {
                            Console.WriteLine(
                                "\t{0}: {1}",
                                trace["function"],
                                trace["lineNumber"]);
                        }
                    }
                }
                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 responseSet =
                        (Newtonsoft.Json.Linq.JObject)op.Response["result"];
                    if (responseSet.Count == 0)
                    {
                        Console.WriteLine("No responses returned!");
                    }
                    else
                    {
                        Console.WriteLine("Responses:");
                        Console.WriteLine(responseSet);

                        /*foreach (var folder in folderSet)
                         * {
                         *  Console.WriteLine(
                         *      "\t{0} ({1})", folder.Value, folder.Key);
                         * }*/
                    }
                }
            }
            catch (Google.GoogleApiException e)
            {
                // The API encountered a problem before the script
                // started executing.
                Console.WriteLine("Error calling API:\n{0}", e);
            }
            Console.Read();
        }
예제 #4
0
        static void Main(string[] args)
        {
            /* Load pre-authorized user credentials from the environment.
             * TODO(developer) - See https://developers.google.com/identity for
             * guides on implementing OAuth2 for your application. */
            GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                                          .CreateScoped(ScriptService.Scope.ScriptDeployments);

            // Create Google Apps Script API service.
            string scriptId = "ENTER_YOUR_SCRIPT_ID_HERE";
            var    service  = new ScriptService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "AppsScript API Execute",
            });

            // Create an execution request object.
            ExecutionRequest request = new ExecutionRequest
            {
                Function = "getFoldersUnderRoot"
            };

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

            try
            {
                // Make the API request.
                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];
                    Console.WriteLine(
                        "Script error message: {0}", error["errorMessage"]);
                    {
                        // There may not be a stacktrace if the script didn't
                        // start executing.
                        Console.WriteLine("Script error stacktrace:");
                        Newtonsoft.Json.Linq.JArray st =
                            (Newtonsoft.Json.Linq.JArray)error["scriptStackTraceElements"];
                        foreach (var trace in st)
                        {
                            Console.WriteLine(
                                "\t{0}: {1}",
                                trace["function"],
                                trace["lineNumber"]);
                        }
                    }
                }
                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"];
                    if (folderSet.Count == 0)
                    {
                        Console.WriteLine("No folders returned!");
                    }
                    else
                    {
                        Console.WriteLine("Folders under your root folder:");
                        foreach (var folder in folderSet)
                        {
                            Console.WriteLine(
                                "\t{0} ({1})", folder.Value, folder.Key);
                        }
                    }
                }
            }
            catch (Google.GoogleApiException e)
            {
                // The API encountered a problem before the script
                // started executing.
                Console.WriteLine("Error calling API:\n{0}", e);
            }
        }