Пример #1
0
            private static void CreateProvinces()
            {
                foreach (ProvincePixel pixel in Cities)
                {
                    if (Engine.Game.FindProvince(pixel.ID) == null)
                    {
                        Province province = new Province();
                        province.ID    = pixel.ID;
                        province.Name  = "Province " + (province.ID);
                        province.Owner = Engine.Game.FindCountry(0);
                        Engine.Game.Provinces.Add(province, province.ID);
                    }
                }

                GoogleSheet sheet = new GoogleSheet();

                sheet.SetSheetUrl("1ZjzbXTa93K7G3zTYgRdyk7jA7aS0i4Mo_myblGjOE18");
                sheet.SetSheetTab("Provinces");
                List <GoogleCell[]> cells = sheet.ReadCells("A2:B");

                foreach (GoogleCell[] cell in cells)
                {
                    if (cell.Length < 2 || cell[0] == null || cell[1] == null)
                    {
                        continue;
                    }
                    int      id    = Convert.ToInt32(cell[0].Content.ToString());
                    string   name  = cell[1].Content.ToString();
                    Province local = Engine.Game.FindProvince(id);
                    if (local != null)
                    {
                        local.Name = name;
                    }
                }
            }
Пример #2
0
        /// <summary>
        /// Creates GoogleTable wiht lists of servers, that described in .json configuration file.
        /// </summary>
        /// <param name="configuration">name of configuration .json file, that lay in project directory</param>
        public GoogleTable(string configuration)
        {
            googleSheetList = new List <GoogleSheet>();
            string jsonString;

            try
            {
                using (StreamReader stream = new StreamReader(configuration))
                {
                    jsonString = stream.ReadToEnd();
                }
                this.serverList    = JsonConvert.DeserializeObject <ServerList>(jsonString);
                this.spreadsheetId = JsonConvert.DeserializeObject <SpreadsheetId>(jsonString);
            }
            catch (Exception e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }

            foreach (Server server in serverList.servers)
            {
                GoogleSheet googleSheet = new GoogleSheet(server.Name, this.spreadsheetId.get(), server);
                this.googleSheetList.Add(googleSheet);
            }
        }
Пример #3
0
        public async Task <bool> Retrieve()
        {
            try
            {
                _logger.LogDebug($"Retrieving email address google-sheet \"{_googleSheetUri.AbsolutePath}\"...", ClassName);

                GoogleSheet sheet = await _requestMaker.Get <GoogleSheet>(_googleSheetUri);

                if (sheet == null)
                {
                    _logger.LogError("Null email address google-sheet returned.", ClassName);
                    return(false);
                }

                ValidateColumnHeaders(sheet);
                ExtractData(sheet);
            }
            catch (RestRequestException ex)
            {
                _logger.LogError(
                    $"Failed to retrieve email address google-sheet \"{_googleSheetUri.AbsolutePath}\", an exception occurred.",
                    ClassName,
                    ex);

                return(false);
            }

            return(true);
        }
        /// <summary>
        /// For a given google account check for a spreasheet file existence and return the content from that spreadsheet
        /// </summary>
        /// <param name="authorizationTokenId"></param>
        /// <param name="spreadsheetName"></param>
        /// <returns></returns>
        public async Task <StandardTableDataCM> GetSpreadsheetIfExist(Guid authorizationTokenId, string spreadsheetName)
        {
            var defaultGoogleAuthToken = GetGoogleAuthToken(authorizationTokenId);

            var googleSheetApi = new GoogleSheet(new GoogleIntegration(ObjectFactory.GetInstance <IRestfulServiceClient>()), new GoogleDrive());
            var googleSheets   = await googleSheetApi.GetSpreadsheets(defaultGoogleAuthToken);

            Assert.IsNotNull(googleSheets.FirstOrDefault(x => x.Value == spreadsheetName), "Selected spreadsheet was not found into existing google files.");
            var spreadSheeturl = googleSheets.FirstOrDefault(x => x.Value == spreadsheetName).Key;

            var worksheets = await googleSheetApi.GetWorksheets(spreadSheeturl, defaultGoogleAuthToken);

            Assert.IsNotNull(worksheets.FirstOrDefault(x => x.Value == "Sheet1"), "Worksheet was not found into google excel file.");
            var worksheetUri = worksheets.FirstOrDefault(x => x.Value == "Sheet1").Key;
            var dataRows     = (await googleSheetApi.GetData(spreadSheeturl, worksheetUri, defaultGoogleAuthToken)).ToList();

            var hasHeaderRow = false;

            //Adding header row if possible
            if (dataRows.Count > 0)
            {
                dataRows.Insert(0, new TableRowDTO {
                    Row = dataRows.First().Row.Select(x => new TableCellDTO {
                        Cell = new KeyValueDTO(x.Cell.Key, x.Cell.Key)
                    }).ToList()
                });
                hasHeaderRow = true;
            }

            return(new StandardTableDataCM {
                Table = dataRows, FirstRowHeaders = hasHeaderRow
            });
        }
        public static List <ALittleAlliteration> GetCluesForTheme(string theme, int season = 0)
        {
            List <ALittleAlliteration> matchingPuzzles = new List <ALittleAlliteration>();

            GoogleSheet sheet = new GoogleSheet()
            {
                GoogleSheetKey = ALittleAlliterationGoogleSheet
            };
            string query = $"SELECT * WHERE H LIKE '%{theme}%'";

            if (season == 1)
            {
                sheet.GoogleSheetKey = ALittleAlliterationSeasonOneGoogleSheet;
                query = $"SELECT * WHERE I LIKE '%{theme}%'";
            }


            foreach (var result in sheet.ExecuteQuery(query))
            {
                ALittleAlliteration aLittleAlliteration = new ALittleAlliteration(result, season);
                if (!string.IsNullOrWhiteSpace(aLittleAlliteration.Clue))
                {
                    matchingPuzzles.Add(aLittleAlliteration);
                }
            }

            return(matchingPuzzles);
        }
        private static string[] GetUrlsLinkedin(IOutput outputConsole)
        {
            GoogleSheet googleSheet = new GoogleSheet(outputConsole);

            outputConsole.WriteText("Endereços de amigos que serão connectados!");
            outputConsole.WriteText(Environment.NewLine);
            return(googleSheet.GetAddresses());
        }
Пример #7
0
        public Opt10001EventHandler(object sender, AxKHOpenAPI axKHOpenAPI1)
        {
            this.axKHOpenAPI1 = axKHOpenAPI1;
            this.axKHOpenAPI1.OnReceiveTrData += axKHOpenAPI1_OnReceiveTrData;

            db          = new MariaDB();
            googleSheet = new GoogleSheet();
        }
Пример #8
0
        public async Task <bool> Retrieve()
        {
            try
            {
                _logger.LogDebug($"Retrieving meets google-sheet \"{_googleSheetUri.AbsolutePath}\"...", ClassName);

                GoogleSheet sheet = await _requestMaker.Get <GoogleSheet>(_googleSheetUri);

                if (sheet == null)
                {
                    _logger.LogError("Null meets google-sheet returned.", ClassName);
                    return(false);
                }

                FindFirstCellCoordinates(
                    sheet,
                    out int headerRowIndex,
                    out int headerColumnIndex);

                FindColumnCount(
                    sheet,
                    headerRowIndex,
                    headerColumnIndex,
                    out int headerColumnCount);

                FindLastRow(
                    sheet,
                    out int lastRow);

                ReadHeaders(
                    sheet,
                    headerRowIndex,
                    headerColumnIndex,
                    headerColumnCount,
                    ref _fields);

                ReadData(
                    sheet,
                    headerRowIndex,
                    headerColumnIndex,
                    headerColumnCount,
                    lastRow,
                    ref _valuesByRow);
            }
            catch (RestRequestException ex)
            {
                _logger.LogError(
                    $"Failed to retrieve meets google-sheet \"{_googleSheetUri.AbsolutePath}\", an exception occurred.",
                    ClassName,
                    ex);

                return(false);
            }

            return(true);
        }
Пример #9
0
        public GoogleSheetPriceMonitor()
        {
            sheet = new GoogleSheet("Crypnostic Example",
                                    "1jEEQF_gAHFSQPOS9mE3HkOwA7HOdpxFf6np9MLJtpyY");

            refreshTimer = new Timer()
            {
                AutoReset = false,
                Interval  = TimeSpan.FromSeconds(10).TotalMilliseconds
            };
            refreshTimer.Elapsed += RefreshTimer_Elapsed;
        }
        public List <ALittleAlliteration> FindPuzzle(string firstThreeLetters)
        {
            GoogleSheet sheet = new GoogleSheet()
            {
                GoogleSheetKey = ALittleAlliterationGoogleSheet
            };

            string firstThreeLetters1 = firstThreeLetters.ToLower();

            List <ALittleAlliteration> results = new List <ALittleAlliteration>();

            foreach (var dictionary in sheet.ExecuteQuery($"SELECT * WHERE E = '{firstThreeLetters1}'"))
            {
                var aLittleAlliteration = new ALittleAlliteration(dictionary);
                if (string.IsNullOrWhiteSpace(aLittleAlliteration.TwitterUrl) &&
                    string.IsNullOrWhiteSpace(aLittleAlliteration.DatePosted) &&
                    !string.IsNullOrWhiteSpace(aLittleAlliteration.Clue))
                {
                    results.Add(aLittleAlliteration);
                }
            }
            return(results);
        }
        /// <summary>
        /// Create new spreadsheet file for a given google account, and write data inside the speadsheet
        /// </summary>
        /// <param name="authorizationTokenId"></param>
        /// <param name="spreadsheetName"></param>
        /// <param name="worksheetName"></param>
        /// <param name="tableData"></param>
        /// <returns></returns>
        public async Task <string> CreateNewSpreadsheet(Guid authorizationTokenId, string spreadsheetName, string worksheetName, StandardTableDataCM tableData)
        {
            var googleSheetApi         = new GoogleSheet(new GoogleIntegration(ObjectFactory.GetInstance <IRestfulServiceClient>()), new GoogleDrive());
            var defaultGoogleAuthToken = GetGoogleAuthToken(authorizationTokenId);
            var spreadsheetId          = await googleSheetApi.CreateSpreadsheet(spreadsheetName, defaultGoogleAuthToken);

            var googleSheets = await googleSheetApi.GetSpreadsheets(defaultGoogleAuthToken);

            var spreadsheetUri = googleSheets.FirstOrDefault(x => x.Value == spreadsheetName).Key;
            //create worksheet for this new created spreadsheet
            var existingWorksheets = await googleSheetApi.GetWorksheets(spreadsheetUri, defaultGoogleAuthToken);

            var existingWorksheetUri = existingWorksheets.Where(x => string.Equals(x.Value.Trim(), worksheetName, StringComparison.InvariantCultureIgnoreCase))
                                       .Select(x => x.Key).FirstOrDefault();

            if (string.IsNullOrEmpty(existingWorksheetUri))
            {
                existingWorksheetUri = await googleSheetApi.CreateWorksheet(spreadsheetUri, defaultGoogleAuthToken, worksheetName);
            }

            await googleSheetApi.WriteData(spreadsheetUri, existingWorksheetUri, tableData, defaultGoogleAuthToken);

            return(spreadsheetId);
        }
Пример #12
0
        public void Update()
        {
            processor.ProcessRows();

            GoogleSheet.WriteValues(processor.UpdateValues, SpreadsheetId, SheetRange);
        }
Пример #13
0
        public List <VowelMovement> FindPuzzle(string startConsonant, string endConsonant)
        {
            // ReSharper disable StringLiteralTypo
            GoogleSheet sheet = new GoogleSheet()
            {
                GoogleSheetKey = "1iYI-nE-5hYN7J3ckXmJjmzbxLmqs5UAGpGJh5yNUKgM"
            };
            // ReSharper restore StringLiteralTypo

            string startConsonant1;

            if (string.IsNullOrWhiteSpace(startConsonant))
            {
                startConsonant1 = null;
            }
            else
            {
                startConsonant1 = startConsonant.ToLower();
                switch (startConsonant1)
                {
                case "c":
                case "k":
                    startConsonant1 = "c, k";
                    break;

                case "g":
                    startConsonant1 = "g (hard)";
                    break;

                case "n":
                case "kn":
                    startConsonant1 = "n, kn";
                    break;

                case "q":
                    startConsonant1 = "qu";
                    break;

                case "j":
                    startConsonant1 = "j/soft g";
                    break;
                }
            }


            if (!string.IsNullOrWhiteSpace(endConsonant))
            {
                endConsonant = endConsonant.ToLower();
                switch (endConsonant)
                {
                case "c":
                case "k":
                    endConsonant = "c, k";
                    break;

                case "h":
                case "w":
                case "y":
                    endConsonant = "(h) (w) (y)";
                    break;
                }
            }



            List <Dictionary <int, string> > queryResults = sheet.ExecuteQuery(string.Format($@"SELECT * WHERE I = '{startConsonant1}' AND J = '{endConsonant}'"));

            List <VowelMovement> vowelMovements = new List <VowelMovement>();

            foreach (var dictionary in queryResults)
            {
                var vowelMovement = new VowelMovement(dictionary);
                if (string.IsNullOrWhiteSpace(vowelMovement.TwitterUrl) &&
                    string.IsNullOrWhiteSpace(vowelMovement.DatePosted))
                {
                    vowelMovements.Add(vowelMovement);
                }
            }
            return(vowelMovements);
        }
        public async Task GoogleIntoGoogleEndToEnd()
        {
            var googleAuthTokenId      = await new Fr8.Testing.Integration.Tools.Terminals.IntegrationTestTools_terminalGoogle(this).ExtractGoogleDefaultToken();
            var defaultGoogleAuthToken = GetGoogleAuthToken(googleAuthTokenId);

            //create a new plan
            var googleSheetApi             = new GoogleSheet(new GoogleIntegration(ObjectFactory.GetInstance <IRestfulServiceClient>()), new GoogleDrive());
            var sourceSpreadsheetUri       = string.Empty;
            var destinationSpreadsheetUri  = string.Empty;
            var sourceSpreadsheetName      = Guid.NewGuid().ToString();
            var destinationSpreadsheetName = Guid.NewGuid().ToString();

            try
            {
                //Save test data into test spreadsheet
                sourceSpreadsheetUri = await googleSheetApi.CreateSpreadsheet(sourceSpreadsheetName, defaultGoogleAuthToken);

                var sourceWorksheetUri = (await googleSheetApi.GetWorksheets(sourceSpreadsheetUri, defaultGoogleAuthToken)).Select(x => x.Key).First();
                await googleSheetApi.WriteData(sourceSpreadsheetUri, sourceWorksheetUri, GetTestSpreadsheetContent(), defaultGoogleAuthToken);

                var thePlan = await _plansHelper.CreateNewPlan();

                //Configure Get_Google_Sheet_Data activity to read data from this test spreadsheet
                await _googleActivityConfigurator.AddAndConfigureGetFromGoogleSheet(thePlan, 1, sourceSpreadsheetName, true);

                //Configure Build_Message activity to build message based on the data from this spreadsheet
                await _fr8ActivityConfigurator.AddAndConfigureBuildMessage(thePlan, 2, "message", "Email - [email], subject - [subject], body - [body]");

                //Configure Save_To_Google activity to save this message into new test spreadsheet
                destinationSpreadsheetUri = await googleSheetApi.CreateSpreadsheet(destinationSpreadsheetName, defaultGoogleAuthToken);

                await _googleActivityConfigurator.AddAndConfigureSaveToGoogleSheet(thePlan, 3, "Standard Payload Data", Build_Message_v1.RuntimeCrateLabel, destinationSpreadsheetName);

                //run the plan
                await _plansHelper.RunPlan(thePlan.Id);

                var googleSheets = await googleSheetApi.GetSpreadsheets(defaultGoogleAuthToken);

                Assert.IsNotNull(googleSheets.FirstOrDefault(x => x.Value == destinationSpreadsheetName), "New created spreadsheet was not found into existing google files.");
                var spreadSheeturl = googleSheets.FirstOrDefault(x => x.Value == destinationSpreadsheetName).Key;

                //Checking that new test spreadsheet contains the same message that was generated
                var worksheets = await googleSheetApi.GetWorksheets(spreadSheeturl, defaultGoogleAuthToken);

                Assert.IsNotNull(worksheets.FirstOrDefault(x => x.Value == "Sheet1"), "Worksheet was not found into newly created google excel file.");
                var worksheetUri = worksheets.FirstOrDefault(x => x.Value == "Sheet1").Key;
                var dataRows     = (await googleSheetApi.GetData(spreadSheeturl, worksheetUri, defaultGoogleAuthToken)).ToArray();

                Assert.AreEqual(1, dataRows.Length, "Only one data row is expected to be in crated spreadsheet");
                var storedData = dataRows[0].Row[0].Cell;
                Assert.AreEqual("message", storedData.Key, "Saved message header doesn't match the expected data");
                Assert.AreEqual("Email - [email protected], subject - Fake Subject, body - Fake Body", storedData.Value, "Saved message body doesn't match the expected data");
            }
            finally
            {
                if (!string.IsNullOrEmpty(sourceSpreadsheetUri))
                {
                    await googleSheetApi.DeleteSpreadSheet(sourceSpreadsheetUri, defaultGoogleAuthToken);
                }
                if (!string.IsNullOrEmpty(destinationSpreadsheetUri))
                {
                    await googleSheetApi.DeleteSpreadSheet(destinationSpreadsheetUri, defaultGoogleAuthToken);
                }
            }
        }
Пример #15
0
        public async Task <string> AddThumbnails()
        {
            Response.Headers.Add("Cache-Control", "no-cache");
            string result         = string.Empty;
            string newFolderId    = null;
            string imagesFolderId = null;
            string accountName    = this._httpContextAccessor.HttpContext.Request.Headers[DriveImportConstants.VTEX_ACCOUNT_HEADER_NAME];

            FolderIds folderIds = await _driveImportRepository.LoadFolderIds(accountName);

            if (folderIds != null)
            {
                newFolderId    = folderIds.NewFolderId;
                imagesFolderId = folderIds.ImagesFolderId;
                ListFilesResponse imageFiles = new ListFilesResponse();
                imageFiles.Files = new List <GoogleFile>();
                string nextPageToken = string.Empty;
                do
                {
                    ListFilesResponse listFilesResponse = await _googleDriveService.ListImagesInFolder(newFolderId, nextPageToken);

                    imageFiles.Files.AddRange(listFilesResponse.Files);
                    nextPageToken = listFilesResponse.NextPageToken;
                } while (!string.IsNullOrEmpty(nextPageToken));

                ListFilesResponse spreadsheets = await _googleDriveService.ListSheetsInFolder(imagesFolderId);

                if (imageFiles != null && spreadsheets != null)
                {
                    var sheetIds = spreadsheets.Files.Select(s => s.Id);
                    if (sheetIds != null)
                    {
                        foreach (var sheetId in sheetIds)
                        {
                            Dictionary <string, int> headerIndexDictionary = new Dictionary <string, int>();
                            string sheetContent = await _googleDriveService.GetSheet(sheetId, string.Empty);

                            GoogleSheet googleSheet    = JsonConvert.DeserializeObject <GoogleSheet>(sheetContent);
                            string      valueRange     = googleSheet.ValueRanges[0].Range;
                            string      sheetName      = valueRange.Split("!")[0];
                            string[]    sheetHeader    = googleSheet.ValueRanges[0].Values[0];
                            int         headerIndex    = 0;
                            int         rowCount       = googleSheet.ValueRanges[0].Values.Count();
                            int         writeBlockSize = rowCount;
                            foreach (string header in sheetHeader)
                            {
                                headerIndexDictionary.Add(header.ToLower(), headerIndex);
                                headerIndex++;
                            }

                            string[][] arrValuesToWrite = new string[writeBlockSize][];

                            for (int index = 1; index < rowCount; index++)
                            {
                                string imageFileName = string.Empty;

                                string[] dataValues = googleSheet.ValueRanges[0].Values[index];
                                if (headerIndexDictionary.ContainsKey("image") && headerIndexDictionary["image"] < dataValues.Count())
                                {
                                    imageFileName = dataValues[headerIndexDictionary["image"]];
                                }

                                GoogleFile file = imageFiles.Files.FirstOrDefault(f => f.Name.Equals(imageFileName));
                                if (file != null)
                                {
                                    string[] row = new string[headerIndexDictionary.Count];
                                    row[headerIndexDictionary["thumbnail"]] = $"=IMAGE(\"{ file.ThumbnailLink}\")";
                                    arrValuesToWrite[index - 1]             = row;
                                }
                            }

                            string lastColumn = ((char)(headerIndexDictionary.Count + 65)).ToString();

                            ValueRange valueRangeToWrite = new ValueRange
                            {
                                Range  = $"{sheetName}!A2:{lastColumn}{rowCount + 1}",
                                Values = arrValuesToWrite
                            };

                            await _googleDriveService.WriteSpreadsheetValues(sheetId, valueRangeToWrite);
                        }
                    }
                }
            }

            return(result);
        }
 /// <summary>
 /// Delete from existence spreadsheet file
 /// </summary>
 /// <param name="authorizationTokenId"></param>
 /// <param name="spreadsheetId"></param>
 /// <returns></returns>
 public async Task DeleteSpreadSheet(Guid authorizationTokenId, string spreadsheetId)
 {
     var googleSheetApi         = new GoogleSheet(new GoogleIntegration(ObjectFactory.GetInstance <IRestfulServiceClient>()), new GoogleDrive());
     var defaultGoogleAuthToken = GetGoogleAuthToken(authorizationTokenId);
     await googleSheetApi.DeleteSpreadSheet(spreadsheetId, defaultGoogleAuthToken);
 }
Пример #17
0
            private static void CreateCities()
            {
                int j = 1;

                foreach (ProvincePixel pixel in Cities)
                {
                    foreach (ProvincePixel.CityPixel city in pixel.Cities)
                    {
                        if (Engine.Game.FindTile(city.ID) == null)
                        {
                            if (j == 8)
                            {
                                j = 1;
                            }
                            Tile local = new Landscape();
                            local.ID              = city.ID;
                            local.Name            = "S " + (local.ID);
                            local.Owner           = Engine.Game.FindProvince(pixel.ID);
                            local.Culture         = Engine.Game.FindCulture(Cultures.Deutsch);
                            local.BackGroundImage = Images.FromPath(Images.map_tiles + "tile_landschaft_" + j);
                            int n = Random.Next(1, 4 + 1) + Random.Next(1, 6 + 1);
                            for (int i = 0; i < n; i++)
                            {
                                local.CreatePeasant();
                            }
                            Engine.Game.Tiles.Add(local, local.ID);
                            j++;
                        }
                    }
                }

                GoogleSheet sheet = new GoogleSheet();

                sheet.SetSheetUrl("1ZjzbXTa93K7G3zTYgRdyk7jA7aS0i4Mo_myblGjOE18");
                sheet.SetSheetTab("Cities");
                List <GoogleCell[]> cells = sheet.ReadCells("A2:C");

                int k = 1;

                foreach (GoogleCell[] cell in cells)
                {
                    if (cell.Length < 2 || cell[0] == null || cell[1] == null)
                    {
                        continue;
                    }

                    int    id      = Convert.ToInt32(cell[0].Content.ToString());
                    string name    = cell[1].Content.ToString();
                    bool   is_city = false;
                    if (cell.Length == 3)
                    {
                        is_city = Convert.ToBoolean(cell[2].Content.ToString());
                    }

                    Tile local = Engine.Game.FindTile(id);
                    if (local != null)
                    {
                        local.Name = name;
                        //- Debug pls fix later
                        if (is_city)
                        {
                            if (k == 5)
                            {
                                k = 1;
                            }
                            City city = new City();
                            Engine.CopyProperties(local, city);
                            city.Founder         = city.CountryOwner;
                            city.BackGroundImage = Images.FromPath(Images.map_tiles + "tile_city_" + k);
                            int n = 2 + Random.Next(1, 10 + 1) + Random.Next(1, 10 + 1);
                            for (int i = 0; i < n; i++)
                            {
                                city.CreateCitizen();
                            }
                            Engine.Game.Tiles.Remove(city.ID);
                            Engine.Game.Tiles.Add(city, city.ID);
                            k++;
                        }
                    }
                }
            }
        //= new Dictionary<string, int>();
        public static void Init()
        {
            GoogleSheet googleSheet = new GoogleSheet();

            googleSheet.Url = "https://docs.google.com/spreadsheets/d/1lYBNEs-YhKCHwYCFeHQNZXM1wW1NnJH6LUsr8aix0-U";
            //googleSheet.TabName = "2019";
            googleSheet.TabName = "2020";
            googleSheet.Range   = "A2:J";
            googleSheet.Init();
            IList <IList <Object> > values     = googleSheet.ResponseValues();
            HashSet <string>        namceounts = new HashSet <string>();

            namceountKeyActualTimeValue = new Dictionary <string, int>();
            if (values != null && values.Count > 0)
            {
                foreach (var row in values)
                {
                    int countCell = 0;
                    foreach (var cell in row)
                    {
                        countCell++;
                        if (countCell == 4)
                        {
                            namceounts.Add(cell.ToString());
                        }
                    }
                }
            }
            foreach (string namceount in namceounts)
            {
                namceountKeyActualTimeValue.Add(namceount, 0);
            }
            if (values != null && values.Count > 0)
            {
                foreach (var row in values)
                {
                    int    countCell = 0;
                    string namceount = "";
                    foreach (var cell in row)
                    {
                        countCell++;

                        if (countCell == 1)
                        {
                            namceount = "";
                        }
                        if (countCell == 4)
                        {
                            namceount = cell.ToString();
                        }
                        if (countCell == 7)
                        {
                            if (!namceountKeyActualTimeValue.ContainsKey(namceount))
                            {
                                continue;
                            }
                            int val = namceountKeyActualTimeValue[namceount];
                            try
                            {
                                val = val + int.Parse(cell.ToString());
                            }
                            catch (Exception e)
                            {
                                string g = e.Message;
                            }

                            namceountKeyActualTimeValue[namceount] = val;
                        }
                    }
                }
            }
        }
Пример #19
0
    static IEnumerator TestComponents(List <KtaneModule> modules)
    {
        IEnumerable <BombComponent> untestedComponents = GetUntestedComponents(modules);
        Dictionary <string, string> nameMap            = GetNameMap(modules);

        GameObject fakeModule = new GameObject();

        gameObjects.Add(fakeModule);
        TwitchModule module = fakeModule.AddComponent <TwitchModule>();

        module.enabled = false;

        HashSet <string>          unsupportedModules = new HashSet <string>();
        Dictionary <string, bool> supportStatus      = new Dictionary <string, bool>();

        ComponentSolverFactory.SilentMode = true;

        // Try to create a ComponentSolver for each module so we can see what modules are supported.
        foreach (BombComponent bombComponent in untestedComponents)
        {
            ComponentSolver solver = null;
            try
            {
                module.BombComponent = bombComponent.GetComponent <BombComponent>();

                solver = ComponentSolverFactory.CreateSolver(module);

                module.StopAllCoroutines();                 // Stop any coroutines to prevent any exceptions or from affecting the next module.
            }
            catch (Exception e)
            {
                DebugHelper.LogException(e, $"Couldn't create a component solver for \"{bombComponent.GetModuleDisplayName()}\" during startup for the following reason:");
            }

            ModuleData.DataHasChanged |= solver != null;

            DebugHelper.Log(solver != null
                                ? $"Found a solver of type \"{solver.GetType().FullName}\" for component \"{bombComponent.GetModuleDisplayName()}\". This module is {(solver.UnsupportedModule ? "not supported" : "supported")} by Twitch Plays."
                                : $"No solver found for component \"{bombComponent.GetModuleDisplayName()}\". This module is not supported by Twitch Plays.");

            string moduleID = bombComponent.GetComponent <KMBombModule>()?.ModuleType ?? bombComponent.GetComponent <KMNeedyModule>()?.ModuleType;
            if (solver?.UnsupportedModule != false && moduleID != null)
            {
                unsupportedModules.Add(moduleID);
            }

            supportStatus[bombComponent.GetModuleDisplayName()] = !(solver?.UnsupportedModule != false && moduleID != null);

            yield return(null);
        }

        ComponentSolverFactory.SilentMode = false;
        ModuleData.WriteDataToFile();
        Object.Destroy(fakeModule);

        // Always disable the modules from the spreadsheet
        var disabledSheet = new GoogleSheet("1G6hZW0RibjW7n72AkXZgDTHZ-LKj0usRkbAwxSPhcqA", "1849453757", "modulename");

        yield return(disabledSheet);

        if (disabledSheet.Success && TwitchPlaySettings.data.AllowSheetDisabledModules)
        {
            foreach (var row in disabledSheet.GetRows())
            {
                if (!nameMap.TryGetValue(row["modulename"], out string moduleID))
                {
                    DebugHelper.Log($"Couldn't map \"{row["modulename"]}\" to a module ID when disabling modules from the spreadsheet.");
                    continue;
                }

                unsupportedModules.Add(moduleID);
            }
        }

        // Always disable modules that are marked as "Unplayable"
        foreach (var moduleInfo in modules)
        {
            if (moduleInfo.Compatibility != "Unplayable")
            {
                continue;
            }

            unsupportedModules.Add(moduleInfo.ModuleID);
        }

        // Using the list of unsupported module IDs stored in unsupportedModules, make a Mod Selector profile.
        string profilesPath = Path.Combine(Application.persistentDataPath, "ModProfiles");

        if (Directory.Exists(profilesPath))
        {
            Dictionary <string, object> profileData = new Dictionary <string, object>()
            {
                { "DisabledList", unsupportedModules },
                { "Operation", 1 }
            };

            File.WriteAllText(Path.Combine(profilesPath, "TP_Supported.json"), SettingsConverter.Serialize(profileData));
        }

        alertProgressBar.localScale = Vector3.one;

        // Send a message to chat if any modules aren't marked as having support
        if (supportStatus.Values.Count(status => status) > 0)
        {
            var supportedList = supportStatus.Where(pair => pair.Value).Select(pair => pair.Key).Join(", ");
            IRCConnection.SendMessage($"These modules have TP support: {supportedList}");
            alertText.text = $"These modules have TP support: {supportedList}";
            yield return(new WaitForSeconds(4));
        }
        else
        {
            alertText.text = "Support checks passed succesfully!";
            yield return(new WaitForSeconds(2));
        }

        // Log out the full results of the testing
        DebugHelper.Log($"Support testing results:\n{supportStatus.OrderByDescending(pair => pair.Value).Select(pair => $"{pair.Key} - {(pair.Value ? "" : "Not ")}Supported").Join("\n")}");
    }
        public async Task <ActionResult> Data2019()
        {
            Services.GoogleSheet googleSheet = new GoogleSheet();
            googleSheet.Url     = "https://docs.google.com/spreadsheets/d/1lYBNEs-YhKCHwYCFeHQNZXM1wW1NnJH6LUsr8aix0-U";
            googleSheet.TabName = "2019";
            googleSheet.Range   = "A2:J";

            //googleSheet.Url = "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
            //googleSheet.TabName = "Class Data";
            //googleSheet.Range = "A2:E";
            googleSheet.Init();

            ViewBag.Data2019 = googleSheet.ResponseValues();
            IList <IList <Object> >  values     = googleSheet.ResponseValues();
            HashSet <string>         namceounts = new HashSet <string>();
            Dictionary <string, int> namceountKeyActualTimeValue = new Dictionary <string, int>();

            if (values != null && values.Count > 0)
            {
                foreach (var row in values)
                {
                    int countCell = 0;
                    foreach (var cell in row)
                    {
                        countCell++;
                        if (countCell == 4)
                        {
                            namceounts.Add(cell.ToString());
                        }
                    }
                }
            }
            foreach (string namceount in namceounts)
            {
                namceountKeyActualTimeValue.Add(namceount, 0);
            }
            if (values != null && values.Count > 0)
            {
                foreach (var row in values)
                {
                    int    countCell = 0;
                    string namceount = "";
                    foreach (var cell in row)
                    {
                        countCell++;

                        if (countCell == 1)
                        {
                            namceount = "";
                        }
                        if (countCell == 4)
                        {
                            namceount = cell.ToString();
                        }
                        if (countCell == 7)
                        {
                            if (!namceountKeyActualTimeValue.ContainsKey(namceount))
                            {
                                continue;
                            }
                            int val = namceountKeyActualTimeValue[namceount];
                            try
                            {
                                val = val + int.Parse(cell.ToString());
                            }
                            catch (Exception e)
                            {
                                string g = e.Message;
                            }

                            namceountKeyActualTimeValue[namceount] = val;
                        }
                    }
                }
            }
            ViewBag.Total = namceountKeyActualTimeValue;

            return(View());
        }