/// <summary>
        ///
        /// </summary>
        /// <param name="spreadsheetId"></param>
        /// <param name="sheetTitle"></param>
        /// <param name="headers"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task <BatchUpdateValuesResponse> BatchUpdateAsync(string spreadsheetId, string sheetTitle, List <IList <object> > headers, List <IList <object> > data)
        {
            // How the input data should be interpreted.
            const string valueInputOption = "USER_ENTERED";

            var headerRange = CalculateCellRange(headers, "A", 1);
            var dataRange   = CalculateCellRange(data, "A", 2);
            // The new values to apply to the spreadsheet.
            var reqData = new List <ValueRange>
            {
                new ValueRange
                {
                    Range  = $"{sheetTitle}!{headerRange}",
                    Values = headers
                },
                new ValueRange
                {
                    Range  = $"{sheetTitle}!{dataRange}",
                    Values = data
                }
            };

            var requestBody = new BatchUpdateValuesRequest
            {
                ValueInputOption        = valueInputOption,
                IncludeValuesInResponse = true,
                Data = reqData
            };

            SpreadsheetsResource.ValuesResource.BatchUpdateRequest batchUpdateRequest = _sheetsService.Spreadsheets.Values.BatchUpdate(requestBody, spreadsheetId);

            BatchUpdateValuesResponse batchUpdateResponse = await batchUpdateRequest.ExecuteAsync();

            return(batchUpdateResponse);
        }
        public async Task <bool> UpdateMessageStatus(IEnumerable <INeedSend> messages)
        {
            List <ValueRange> data = new List <ValueRange>();

            foreach (var row in messages)
            {
                ValueRange valueRange = new ValueRange();
                valueRange.Range = row.CellForUpdate;
                var oblist = new List <object>()
                {
                    "да"
                };
                valueRange.Values = new List <IList <object> > {
                    oblist
                };

                data.Add(valueRange);
            }
            BatchUpdateValuesRequest requestBody = new BatchUpdateValuesRequest();

            requestBody.ValueInputOption = "RAW";
            requestBody.Data             = data;

            var service = await _sheetServiceProvider.GetService();

            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request = service.Spreadsheets.Values.BatchUpdate(requestBody, messages.First().Table);

            request.Execute();

            return(true);
        }
Exemple #3
0
        public object Edit(SheetRow _Row)
        {
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = WebApiApplication.credential,
                ApplicationName       = WebApiApplication.ApplicationName
            });
            ValueRange v = new ValueRange();

            v.Range = "Data!A" + _Row.RowIndex;
            IList <IList <object> > ret = new List <IList <object> >();
            IList <object>          row = new List <object>();
            IList <ValueRange>      lst = new List <ValueRange>();

            foreach (string s in _Row.Row)
            {
                row.Add(s);
            }
            ret.Add(row);
            v.Values = ret;
            lst.Add(v);
            Google.Apis.Sheets.v4.Data.BatchUpdateValuesRequest _body = new Google.Apis.Sheets.v4.Data.BatchUpdateValuesRequest();
            _body.Data             = lst;
            _body.ValueInputOption = "RAW";
            v.MajorDimension       = "ROWS";
            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request2 =
                service.Spreadsheets.Values.BatchUpdate(_body, spreadsheetId);
            request2.Fields = "totalUpdatedColumns,totalUpdatedRows";
            BatchUpdateValuesResponse response2 = request2.Execute();

            return(response2.TotalUpdatedRows);
        }
Exemple #4
0
        private void UpdateGoogleSpreadsheetCell(string spreadSheetID, string cell, string value)
        {
            List <List <string> > valueList = new List <List <string> >
            {
                new List <string> {
                    value
                }
            };

            string[] Scopes          = { SheetsService.Scope.Spreadsheets };
            string   ApplicationName = "Update Poker Data";

            UserCredential credential;
            string         credentialsPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Dropbox\\Projects\\Poker Wizard\\Poker Wizard\\credentials.json";

            using (var stream =
                       new FileStream(credentialsPath, FileMode.Open, FileAccess.ReadWrite))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.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 Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            List <ValueRange> dataList = new List <ValueRange>();

            var obList = new List <object>();
            var data   = new ValueRange
            {
                Values = valueList.Select(list => list.ToArray()).ToArray(),
                Range  = cell
            };

            dataList.Add(data);

            BatchUpdateValuesRequest requestBody = new BatchUpdateValuesRequest
            {
                ValueInputOption = "RAW",
                Data             = dataList
            };

            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request = service.Spreadsheets.Values.BatchUpdate(requestBody, spreadSheetID);

            BatchUpdateValuesResponse response = request.Execute();
        }
Exemple #5
0
        // Update data stored in the specified range.
        internal static void UpdateRangeDataSync(this SheetsService sheetsService, string spreadsheetId, string rangeString, IList <IList <object> > rangeData)
        {
            // Wait for google apis request quota availability.
            SessionRequestsLimiter.Instance.Wait();

            // Construct appropriate update range data google apis request.
            SpreadsheetsResource.ValuesResource.BatchUpdateRequest updateRangeDataRequest = GoogleServicesExtensionsRequestsFactory.GetUpdateRangeDataRequest(sheetsService, spreadsheetId, rangeString, rangeData);

            // Execute update range data request in safe synchronous manner.
            RequestsExecutor.SafeExecuteSync <BatchUpdateValuesResponse>(updateRangeDataRequest);
        }
 private static void Execute(SpreadsheetsResource.ValuesResource.BatchUpdateRequest request)
 {
     try
     {
         BatchUpdateValuesResponse response = request.Execute();
         if (response != null)
         {
         }
     }
     catch (Exception ex)
     {
         string msg = ex.Message;
         System.Diagnostics.Debugger.Break();
     }
 }
        public async Task BatchUpdate(string spreadsheetId, IEnumerable <UpdateRange> updateDatas)
        {
            BatchUpdateValuesRequest body = new BatchUpdateValuesRequest();

            body.Data = updateDatas.Select(d => new ValueRange
            {
                Range          = d.Range.GetStr(),
                Values         = d.Data,
                MajorDimension = "ROWS"
            }).ToList();
            body.ValueInputOption = "USER_ENTERED";
            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request =
                _service.Spreadsheets.Values.BatchUpdate(body, spreadsheetId);

            await autoAuthorize(request);
        }
Exemple #8
0
        public object Create(SheetRow _Row)
        {
            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = WebApiApplication.credential,
                ApplicationName       = WebApiApplication.ApplicationName
            });

            // Define request parameters.
            SpreadsheetsResource.ValuesResource.GetRequest request =
                service.Spreadsheets.Values.Get(spreadsheetId, "Data!A:B");
            ValueRange response            = request.Execute();
            IList <IList <Object> > values = response.Values;
            ValueRange v = new ValueRange();

            v.Range = "Data!A" + (values.Count + 1) + ":Z" + (values.Count + 1);
            IList <IList <object> > ret = new List <IList <object> >();
            IList <object>          row = new List <object>();
            IList <ValueRange>      lst = new List <ValueRange>();

            foreach (string s in _Row.Row)
            {
                row.Add(s);
            }
            ret.Add(row);
            v.Values = ret;
            lst.Add(v);
            Google.Apis.Sheets.v4.Data.BatchUpdateValuesRequest _body = new Google.Apis.Sheets.v4.Data.BatchUpdateValuesRequest();
            _body.Data             = lst;
            _body.ValueInputOption = "RAW";
            v.MajorDimension       = "ROWS";
            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request2 =
                service.Spreadsheets.Values.BatchUpdate(_body, spreadsheetId);
            request2.Fields = "totalUpdatedRows";
            BatchUpdateValuesResponse response2 = request2.Execute();

            return(response2.TotalUpdatedRows);
        }
 public static void InserViewCountToPopularityColumn(List <SpotifyInfo> songs, string columnName)
 {
     try
     {
         var service = UserCredential();
         IList <SpotifyInfo> dataList = songs;
         List <Google.Apis.Sheets.v4.Data.ValueRange> data = new List <Google.Apis.Sheets.v4.Data.ValueRange>();
         ValueRange valueDataRange = new ValueRange()
         {
             MajorDimension = "ROWS"
         };
         valueDataRange.Values = new List <IList <object> >()
         {
         };
         valueDataRange.Values.Add(new List <object> {
             DateTime.Now.ToString("POPULARITY")
         });
         int max = dataList.Count + 1;
         valueDataRange.Range = range + "!" + columnName + "1:" + columnName + max.ToString();
         for (int i = 0; i < dataList.Count; i++)
         {
             IList <object> list = new List <object> {
                 dataList[i].Popularity
             };
             valueDataRange.Values.Add(list);
         }
         data.Add(valueDataRange);
         Google.Apis.Sheets.v4.Data.BatchUpdateValuesRequest requestBody = new Google.Apis.Sheets.v4.Data.BatchUpdateValuesRequest();
         requestBody.ValueInputOption = "USER_ENTERED";
         requestBody.Data             = data;
         // API to update data to sheet
         SpreadsheetsResource.ValuesResource.BatchUpdateRequest request  = service.Spreadsheets.Values.BatchUpdate(requestBody, spreadsheetId);
         Google.Apis.Sheets.v4.Data.BatchUpdateValuesResponse   response = request.Execute();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Exemple #10
0
        private void writeToGoogleSheet(DataTable dt)
        {
            List <IList <Object> > googleDataRows = new List <IList <Object> >();
            var googleDataRow = new List <object>();

            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < 6; i++)
                {
                    googleDataRow.Add(row[i]);
                }

                googleDataRows.Add(googleDataRow);
                googleDataRow = new List <object>();
            }

            // The new values to apply to the spreadsheet.
            List <Data.ValueRange> data = new List <Data.ValueRange>();  // TODO: Update placeholder value.

            Data.BatchUpdateValuesRequest requestBody = new Data.BatchUpdateValuesRequest();
            requestBody.ValueInputOption = "RAW";

            ValueRange vr = new ValueRange();

            vr.Values = googleDataRows;
            vr.Range  = monthStrings[monthIndex];

            data.Add(vr);

            requestBody.Data = data;

            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request = Program.SpreadsheetService.Spreadsheets.Values.BatchUpdate(requestBody, spreadsheetId);

            // To execute asynchronously in an async method, replace `request.Execute()` as shown:
            Data.BatchUpdateValuesResponse response = request.Execute();

            Console.Read();
        }
        public static void AddList(List <ServiceRequestModel> requestModelList, string spreadSheetId)
        {
            // Specifying Column Range for reading...
            var range = $"{sheet}!A:F";
            List <ValueRange> valueRangesList = new List <ValueRange>();

            // Data for another Student...
            for (int i = 2; i < requestModelList.Count + 2; i++)
            {
            }
            int index = 2;

            foreach (var requestModel in requestModelList)
            {
                var valueRange = new ValueRange();
                var oblist     = new List <object>()
                {
                    requestModel.TicketId, requestModel.FullName, requestModel.ServiceNm, requestModel.Status,
                    requestModel.StaffNm, requestModel.DepartmentNm
                };
                valueRange.Range  = $"{sheet}!A{index}:F";
                valueRange.Values = new List <IList <object> > {
                    oblist
                };
                valueRangesList.Add(valueRange);
                index++;
            }
            BatchUpdateValuesRequest requestBody = new BatchUpdateValuesRequest()
            {
                ValueInputOption = "USER_ENTERED",
                Data             = valueRangesList
            };

            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request = service.Spreadsheets.Values.BatchUpdate(requestBody, spreadSheetId);
            BatchUpdateValuesResponse response = request.Execute();
        }
 public static void InsertLinkYoutube(List <Songs> songs, int numberOfOldSongs)
 {
     try
     {
         var           service  = UserCredential();
         IList <Songs> dataList = songs;
         List <Google.Apis.Sheets.v4.Data.ValueRange> data = new List <Google.Apis.Sheets.v4.Data.ValueRange>();
         ValueRange valueDataRange = new ValueRange()
         {
             MajorDimension = "ROWS"
         };
         valueDataRange.Values = new List <IList <object> >()
         {
         };
         int max = numberOfOldSongs + songs.Count + 1;
         valueDataRange.Range = range + "!K" + (numberOfOldSongs + 2).ToString() + ":" + "K" + max.ToString();
         for (int i = 0; i < dataList.Count; i++)
         {
             IList <object> list = new List <object> {
                 dataList[i].YoutubeUrl
             };
             valueDataRange.Values.Add(list);
         }
         data.Add(valueDataRange);
         Google.Apis.Sheets.v4.Data.BatchUpdateValuesRequest requestBody = new Google.Apis.Sheets.v4.Data.BatchUpdateValuesRequest();
         requestBody.ValueInputOption = "USER_ENTERED";
         requestBody.Data             = data;
         // API to update data to sheet
         SpreadsheetsResource.ValuesResource.BatchUpdateRequest request  = service.Spreadsheets.Values.BatchUpdate(requestBody, spreadsheetId);
         Google.Apis.Sheets.v4.Data.BatchUpdateValuesResponse   response = request.Execute();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
 private static void ExecuteRequest(string spreadsheetId, BatchUpdateValuesRequest requestBody)
 {
     SpreadsheetsResource.ValuesResource.BatchUpdateRequest request = service.Spreadsheets.Values.BatchUpdate(requestBody, spreadsheetId);
     Execute(request);
 }
        // Add an event from raw data. Pretty much only used as a poor man's destructuring
        private async Task AddEvent(DateTime date, string prop, string opp, string context, string motion, string judges, string remarks, char start_column = 'B')
        {
            // Get the row that the cursor is in
            int row = GetNextRange();

            if (row == -1)
            {
                throw new Exception("Cursor not found in sheets file!");
            }

            // Range of actual values to add
            ValueRange range  = new ValueRange();
            var        values = new List <IList <object> >
            {
                new List <object> {
                    date.ToString("dd/MM/yyyy"), date.DayOfWeek.ToString(), prop, opp, context, motion, judges, remarks
                }
            };

            range.MajorDimension = "ROWS";
            range.Range          = $"'{SheetName}'!{start_column}{row}:{(char)(start_column + 9)}{row}";
            range.Values         = values;

            // Range to move the cursor down
            ValueRange cursorMover = new ValueRange();
            var        cVals       = new List <IList <object> >
            {
                new List <object> {
                    Program.config.RegisterClubbyCursor
                }
            };

            cursorMover.MajorDimension = "ROWS";
            cursorMover.Range          = $"'{SheetName}'!{CursorColumn}{row + 1}:{CursorColumn}{row + 1}";
            cursorMover.Values         = cVals;

            // Range to delete the cursor from previous location
            ValueRange cursor_deletor = new ValueRange();
            var        cDVals         = new List <IList <object> >
            {
                new List <object> {
                    ""
                }
            };

            cursor_deletor.MajorDimension = "ROWS";
            cursor_deletor.Range          = $"'{SheetName}'!{CursorColumn}{row}:{CursorColumn}{row}";
            cursor_deletor.Values         = cDVals;

            BatchUpdateValuesRequest req = new BatchUpdateValuesRequest
            {
                Data = new List <ValueRange>()
                {
                    range, cursorMover, cursor_deletor
                },
                ValueInputOption = "USER_ENTERED"
            };

            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request = service.Spreadsheets.Values.BatchUpdate(req, spreadSheetId);

            await request.ExecuteAsync();
        }
Exemple #15
0
        //TODO start moving this crap to methods or other objects.
        public void MainRun()
        {
            //TODO MEthod to connect and pull data from SQL
            //TODO Method to clear the sheet
            //TODO Method to write the header and data

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            UserCredential credential;

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

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("Credential file saved to:\r\n" + credPath + "\r\n");
            }

            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Setup the SQL connection
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            SqlConnection sqlConnection = new SqlConnection(connection);

            SqlCommand cmd = new SqlCommand
            {
                Connection     = sqlConnection,
                CommandTimeout = 60,
                CommandType    = CommandType.Text,
                CommandText    = select
            };

            try
            {
                SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("Open the SQL connection");
                sqlConnection.Open();
            }
            catch (Exception e)
            {
                SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("Whoops we cannot connect to SQL - exception " + e.HResult.ToString());
                //Environment.Exit(1);
            }

            SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("Please wait while reading data from SQL server");
            SqlDataReader reader;

            reader = cmd.ExecuteReader();


            //API method to clear the sheet of all previous values
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("Clear the Sheet");
            ClearValuesRequest clearValuesRequest = new ClearValuesRequest();

            SpreadsheetsResource.ValuesResource.ClearRequest cr = service.Spreadsheets.Values.Clear(clearValuesRequest, sID, dataRange);
            // TODO add a try catch statement
            ClearValuesResponse clearResponse = cr.Execute();

            /*
             * //API method to batch update and Delete all the rows
             * ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
             * SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("Delete all rows in Sheet");
             * DimensionRange dr = new DimensionRange
             * {
             *  Dimension = "ROWS",
             *  StartIndex = 1000,
             *  SheetId = 1809337217 //this is a problem
             * };
             *
             * DeleteDimensionRequest ddr = new DeleteDimensionRequest() { Range = dr };
             *
             * Request r = new Request { DeleteDimension = ddr };
             *
             * //THIS IS FOR deleteDimension { "requests": [{ "deleteDimension": { "range": { "sheetId": 1809337217, "startIndex": 1}} }  ]};
             * List<Request> batchRequests = new List<Request>() { r };
             *
             * BatchUpdateSpreadsheetRequest requestBody = new BatchUpdateSpreadsheetRequest() { Requests = batchRequests };
             * SpreadsheetsResource.BatchUpdateRequest bRequest = service.Spreadsheets.BatchUpdate(requestBody, sID);
             * BatchUpdateSpreadsheetResponse busr = bRequest.Execute();
             */

            /* I have added this to the batch method
             * //API method to update the header in the Sheet
             * ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
             * SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("Write the header to the Sheet");
             * IList<object> headerList;
             * headerList = header.Split(',');
             *
             * ValueRange valueRange = new ValueRange { MajorDimension = "ROWS" };
             * valueRange.Values = new List<IList<object>> { headerList };
             *
             * SpreadsheetsResource.ValuesResource.UpdateRequest update = service.Spreadsheets.Values.Update(valueRange, sID, dataRange);
             * update.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
             * UpdateValuesResponse result;
             * result = update.Execute();
             */

            //API method to batch value update the data in the Sheet
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("Write the data to the Sheet");

            IList <object> headerList;

            headerList = header.Split(',');
            ValueRange headerVR = new ValueRange
            {
                MajorDimension = "ROWS",
                Range          = "A1",
                Values         = new List <IList <object> > {
                    headerList
                }
            };

            ValueRange dataVR = new ValueRange()
            {
                MajorDimension = "ROWS",
                Range          = "A2:ZZ",
                Values         = new List <IList <object> >()
            };

            //Need a list of ValueRanges for the BatchUpdateValuesRequest API
            List <ValueRange> data = new List <ValueRange>
            {
                headerVR,
                dataVR
            };

            //Build the data 2D List object with SQL data
            if (reader.HasRows)
            {
                Object[] colValues = new Object[reader.FieldCount];
                List <IList <object> > valueList = new List <IList <object> >();
                var rows = 0;
                while (reader.Read())
                {
                    List <object> rowData = new List <object>();
                    for (int i = 0; i < reader.GetValues(colValues); i++)
                    {
                        rowData.Add(colValues[i]);
                    }
                    valueList.Add(rowData);
                    rows++;
                }
                //after 2D list is built point it to the Values method in the ValueRange object
                dataVR.Values = valueList;
            }
            else
            {
                SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("No rows found");
            }

            BatchUpdateValuesRequest buvr = new BatchUpdateValuesRequest()
            {
                ValueInputOption = "RAW",
                Data             = data
            };

            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request = service.Spreadsheets.Values.BatchUpdate(buvr, sID);
            BatchUpdateValuesResponse response = request.Execute();


            /*
             * //API to append data to sheet. This does not use the batchUpdate
             * ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
             * // Data is accessible through the DataReader object here.
             * ValueRange valueDataRange = new ValueRange() { MajorDimension = "ROWS" };
             *
             * var dataList = new List<object>();
             * valueDataRange.Values = new List<IList<object>> { dataList };
             *
             * SpreadsheetsResource.ValuesResource.AppendRequest appendRequest = service.Spreadsheets.Values.Append(valueDataRange, sID, dataRange);
             * appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.RAW;
             * appendRequest.InsertDataOption = SpreadsheetsResource.ValuesResource.AppendRequest.InsertDataOptionEnum.INSERTROWS;
             *
             * if (reader.HasRows)
             * {
             *  Object[] colValues = new Object[reader.FieldCount];
             *
             *  int throttleCount = 0;
             *  int cnt = 0;
             *  while (reader.Read())
             *  {
             *      //This logic is flawed. If we get hit by the quota then the data row gets lost the next time this runs.
             *      dataList.Clear();
             *      for (int i = 0; i < reader.GetValues(colValues); i++)
             *      {
             *          dataList.Add(colValues[i]);
             *      }
             *
             *      try
             *      {
             *          //This is the GOOGLE query Throttle they only allow 100 writes per 100 sec per user
             *          System.Threading.Thread.Sleep(20);
             *          AppendValuesResponse appendValueResponse = appendRequest.Execute();
             *          SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("Writing to Sheet: row{" + cnt.ToString() + "}");
             *      }
             *      catch (Exception e)
             *      {
             *          SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("Whoa buddy slowdown! Exception " + e.HResult.ToString());
             *          System.Threading.Thread.Sleep(3000);
             *          throttleCount++;
             *      }
             *      cnt++;
             *  }
             * }
             * else
             * {
             *  SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("No rows found");
             * }
             */

            SQL2Sheets.MainWindow.AppWindow.SetDebugScreen("Close reader and SQL");
            reader.Close();
            sqlConnection.Close();
        }
Exemple #16
0
        private async Task <IResult <string> > UpdateGoogleSheet(
            List <ValueRange> ranges, IList <string> rangesToClear, Uri sheetsUri, int attemptedRetries)
        {
            if (this.Service == null)
            {
                return(new FailureResult <string>(
                           "This instance of the bot doesn't support Google Sheets, because the Google account information for the bot isn't configured."));
            }

            IResult <string> sheetsIdResult = TryGetSheetsId(sheetsUri);

            if (!sheetsIdResult.Success)
            {
                return(sheetsIdResult);
            }

            string sheetsId = sheetsIdResult.Value;

            try
            {
                BatchUpdateValuesRequest updateValuesData = new BatchUpdateValuesRequest()
                {
                    Data             = ranges,
                    ValueInputOption = "RAW"
                };
                SpreadsheetsResource.ValuesResource.BatchUpdateRequest batchUpdateRequest = new SpreadsheetsResource.ValuesResource.BatchUpdateRequest(
                    this.Service, updateValuesData, sheetsId);

                if (rangesToClear.Count > 0)
                {
                    BatchClearValuesRequest clearValuesData = new BatchClearValuesRequest()
                    {
                        Ranges = rangesToClear
                    };
                    SpreadsheetsResource.ValuesResource.BatchClearRequest clearRequest = new SpreadsheetsResource.ValuesResource.BatchClearRequest(
                        this.Service, clearValuesData, sheetsId);
                    await clearRequest.ExecuteAsync();
                }

                BatchUpdateValuesResponse batchUpdateResponse = await batchUpdateRequest.ExecuteAsync();

                if (batchUpdateResponse.Responses.Any(response => response.UpdatedCells == 0))
                {
                    return(new FailureResult <string>("Could only partially update the spreadsheet. Try again."));
                }

                return(new SuccessResult <string>("Export successful"));
            }
            catch (Google.GoogleApiException exception)
            {
                // See https://developers.google.com/drive/api/v3/handle-errors
                int errorCode = exception.Error?.Code ?? 0;
                if (errorCode == 403 &&
                    exception.Error.Errors != null &&
                    exception.Error.Errors.Any(error => error.Reason == "appNotAuthorizedToFile" || error.Reason == "forbidden" || error.Reason == "insufficientFilePermissions"))
                {
                    Logger.Error(exception, $"Error writing to the UCSD scoresheet: bot doesn't have permission");
                    return(new FailureResult <string>(
                               $"The bot doesn't have write permissions to the Google Sheet. Please give `{this.Options.CurrentValue.GoogleAppEmail}` access to the Sheet by sharing it with them as an Editor."));
                }
                else if (attemptedRetries < MaxRetries && (errorCode == 403 || errorCode == 429))
                {
                    // Retry
                    attemptedRetries++;
                    Logger.Error(
                        exception,
                        $"Retry attempt {attemptedRetries} after getting a {errorCode} error for the UCSD scoresheet at the URL {sheetsUri.AbsoluteUri}");

                    // Use exponential back-off: wait for 2 seconds, then 5, then 9, etc.
                    await Task.Delay(1000 *(1 + (int)Math.Pow(2, attemptedRetries)));

                    return(await this.UpdateGoogleSheet(ranges, rangesToClear, sheetsUri, attemptedRetries));
                }

                // Log
                Logger.Error(exception, $"Error writing to the UCSD scoresheet for URL {sheetsUri.AbsoluteUri}");
                return(new FailureResult <string>($"Error writing to the Google Sheet: \"{exception.Message}\""));
            }
        }
Exemple #17
0
        public static void SaveToGoogleDrive(string fullName, string name, int seriaCount)
        {
            UserCredential credential;

            using (var stream =
                       new FileStream(Directory.GetFiles(@"C:\MoviesParser")[0], FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-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);
            }
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });



            String spreadsheetId = "1SRMlO18VipcSsekYMlsP2UMSKaNX7GOEXHjIulEeEsw";
            int    rowNum        = 6080 + seriaCount;
            String range         = "B" + rowNum + ":D" + rowNum;
            //String rangeGet = "A1:E1";

            IList <object> valueToWrite = new List <object>()
            {
                fullName,
                name,
                "Жигайло"
            };


            ValueRange requestBody = new ValueRange()
            {
                MajorDimension = "ROWS",
                Range          = range,
                Values         = new List <IList <object> >()
                {
                    valueToWrite
                }
            };

            //SpreadsheetsResource.ValuesResource.GetRequest requestGet = service.Spreadsheets.Values.Get(spreadsheetId, rangeGet);
            //ValueRange response = requestGet.Execute();
            //IList<IList<Object>> values = response.Values;

            BatchUpdateValuesRequest batchUpdate = new BatchUpdateValuesRequest();

            batchUpdate.Data = new List <ValueRange>()
            {
                requestBody
            };
            batchUpdate.ValueInputOption = "RAW";

            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request =
                service.Spreadsheets.Values.BatchUpdate(batchUpdate, spreadsheetId);

            request.Execute();
        }
Exemple #18
0
        private void sendDataToGoogleSpreadsheets(object sender, EventArgs e)
        {
            UserCredential credential;

            waitwindow f = new waitwindow();

            f.Show();

            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None).Result;
            }

            service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            String spreadsheetId = SheetId;
            String range         = "A:A";

            SpreadsheetsResource.ValuesResource.GetRequest getRequest =
                service.Spreadsheets.Values.Get(spreadsheetId, range);

            ValueRange getResponse            = getRequest.Execute();
            IList <IList <Object> > getValues = getResponse.Values;
            List <List <object> >   data      = new List <List <object> >();
            int               currentCount    = getValues.Count() + 2;
            String            newRange        = "A" + currentCount + ":A";
            List <ValueRange> info            = new List <ValueRange>();
            int               count           = 3;
            char              cell            = 'A';

            foreach (var recipe in groceryList)
            {
                var reciperange = new ValueRange();
                reciperange.Range          = Char.ToString(cell) + count.ToString();
                reciperange.MajorDimension = "COLUMNS";
                List <object> ingreds = new List <object>();
                foreach (var x in recipe)
                {
                    string y = x.Substring(0, x.Length - 1);
                    ingreds.Add("----" + y + "----");
                    foreach (var item in ingredientList[x])
                    {
                        ingreds.Add(item);
                    }
                    ingreds.Add("");
                }
                reciperange.Values = new List <IList <object> > {
                    ingreds
                };
                info.Add(reciperange);
                cell++;
            }

            string valueInputOption = "USER_ENTERED";

            Google.Apis.Sheets.v4.Data.ClearValuesRequest    yeah  = new ClearValuesRequest();
            SpreadsheetsResource.ValuesResource.ClearRequest clear = service.Spreadsheets.Values.Clear(yeah, spreadsheetId, "A1:G50");
            clear.Execute();
            BatchUpdateValuesRequest requestBody = new BatchUpdateValuesRequest();

            requestBody.ValueInputOption = valueInputOption;
            requestBody.Data             = info;
            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request = service.Spreadsheets.Values.BatchUpdate(requestBody, spreadsheetId);
            BatchUpdateValuesResponse response = request.Execute();

            var           headerRange = new ValueRange();
            List <object> hd          = new List <object>();

            hd.Add("Monday");
            hd.Add("Tuesday");
            hd.Add("Wednesday");
            hd.Add("Thursday");
            hd.Add("Friday");
            hd.Add("Saturday");
            hd.Add("Sunday");
            headerRange.Range  = "A1:G1";
            headerRange.Values = new List <IList <object> > {
                hd
            };
            List <ValueRange> headerinfo = new List <ValueRange>();

            headerinfo.Add(headerRange);
            BatchUpdateValuesRequest requestBody2 = new BatchUpdateValuesRequest();

            requestBody2.ValueInputOption = valueInputOption;
            requestBody2.Data             = headerinfo;
            SpreadsheetsResource.ValuesResource.BatchUpdateRequest request2 = service.Spreadsheets.Values.BatchUpdate(requestBody2, spreadsheetId);
            BatchUpdateValuesResponse response2 = request2.Execute();

            f.Close();
            MessageBox.Show("Grocery Info Sent to Google Spreadsheet.");
        }