DBD Killergame

Installer

Download

MD5: 3e2e8dfdb673711a9f7a9c4123c7c97c

Use Case

With this program you can change the value of a Google Sheet cell depending on the value in a given text document
e.g. scores for each killer

How to use

Required files: killer-name.txt, score-1.txt, score-2.txt
Either place them in the same directory as the executable or call to executable with the directory that contains the files as a parameter
Filenames, Google Sheet Id, etc. could be changed in the config file

Source Code

Show

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using static System.Net.Mime.MediaTypeNames;
using static Google.Apis.Sheets.v4.SheetsService;
using System.Xml.Linq;
using System.Collections;
using Newtonsoft.Json.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Net.Http;
using System.Configuration;

namespace DBDContest
{
    internal class Program
    {   
        // Initial declarations
        static readonly string[] Scopes = {Scope.Spreadsheets};
        static readonly string ApplicationName = "Score";
        static readonly string SpreadsheetId = ConfigurationManager.AppSettings["sheet-id"];
        static readonly string sheet = ConfigurationManager.AppSettings["sheet"];
        static SheetsService service;
        static readonly string score1file = ConfigurationManager.AppSettings["score1-file"];
        static readonly string score2file = ConfigurationManager.AppSettings["score2-file"];
        static readonly string killerfile = ConfigurationManager.AppSettings["killer-file"];
        static readonly string[] validNames = ConfigurationManager.AppSettings["valid-killers"].Split(',');

        static void Main(string[] args)
        {   
            // if query for future parameter support
            string basePath = Directory.GetCurrentDirectory();
            if (args.Length == 0)
            {
                Console.WriteLine("No parameter set -> using local path");
            }
            else
            {
                basePath = args[0];
                if (!(Directory.Exists(basePath)))
                {
                    Console.WriteLine("gibs nich");
                }
            }

            // Authentication to google api
            GoogleCredential credential;
            string authJson = ConfigurationManager.AppSettings["auth-json"];
            using (var stream = new FileStream(authJson, FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                    .CreateScoped(Scopes);
            }

            // Initialization sheet
            service = new SheetsService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Create array with [0] = Killer / [1] = Score1 / [2] = Score2
            string[] fileContent = CreateContent(killerfile, score1file, score2file, basePath);

            // Read the data of one column and return the index of matching row with given name
            // string A: Killer, B: Score 1, C: Score 2 | int = top buffer | int = killer count | Killername taken from fileContent array
            // Buffer: How many rows to skip (header for example)
            string column = ConfigurationManager.AppSettings["column"];
            string buffer = ConfigurationManager.AppSettings["buffer"];
            string count = ConfigurationManager.AppSettings["count"];
            int killerrow = ReadCol(column, Int16.Parse(buffer), Int16.Parse(count), fileContent[0]);

            // Update the data of the row matching the killers name
            UpdateEntry(killerrow, fileContent[0], fileContent[1], fileContent[2]);
        }

        static string[] CreateContent(string killerfile, string score1file, string score2file, string basePath)
        {
            string killer = ReadFile(killerfile, basePath);

            string prefix = ConfigurationManager.AppSettings["prefix"];
            if (killer.Contains(prefix))
            {
                killer = killer.Replace(prefix, "");
            }
            if (CheckName(killer) == true)
            {
                Console.WriteLine("name passt");
            }
            else
            {
                Console.WriteLine("name passt nicht");
            }

            string score1 = ReadFile(score1file, basePath);
            if (CheckScore(score1) == true)
            {
                Console.WriteLine("score1 passt");
            }
            else
            {
                Console.WriteLine("score1 passt nicht");
            }

            string score2 = ReadFile(score2file, basePath);
            if (CheckScore(score2) == true)
            {
                Console.WriteLine("score2 passt");
            }
            else
            {
                Console.WriteLine("score2 passt nicht");
            }
            
            string[] content = { killer, score1, score2 };

            return content;
        }

        static bool CheckName(string name)
        {
            foreach (string str in validNames)
            {
                if (str == name)
                {
                    return true;
                }                
            }
            return false;
        }

        static bool CheckScore(string score)
        {
            string minScore = ConfigurationManager.AppSettings["min-score"];
            string maxScore = ConfigurationManager.AppSettings["max-score"];
            if (Enumerable.Range(Int16.Parse(minScore), Int16.Parse(maxScore)).Contains(Int16.Parse(score)))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        static string ReadFile(string file, string basePath)
        {
            var path = Path.Combine(basePath, file);
            string text = File.ReadAllText(path);
            return text;
        }

        static int ReadCol(string col, int buffer, int count, string killername)
        {
            int start = buffer + 1;
            int end = count + buffer;
            List rows = new List();
            var range = $"{sheet}!{col}{start}:{col}{end}";
            var request = service.Spreadsheets.Values.Get(SpreadsheetId, range);

            var response = request.Execute();
            var values = response.Values;
            if (values != null && values.Count > 0)
            {
                foreach (var row in values)
                {
                    rows.Add(row[0]);
                }
            }
            else
            {
                Console.WriteLine("No data found.");
            }

            int idx = rows.IndexOf(killername) + 1 + buffer;
            return idx;
        }

        static void UpdateEntry(int row, string killername, string score1, string score2)
        {
            var range = $"{sheet}!A{row}:C{row}";
            var valueRange = new ValueRange();

            var oblist = new List() { killername, score1, score2 };
            valueRange.Values = new List> { oblist };

            var updateRequest = service.Spreadsheets.Values.Update(valueRange, SpreadsheetId, range);
            updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
            var appendReponse = updateRequest.Execute();
        }

        static void CreateEntry(string[] values)
        { 
            var range = $"{sheet}!A:Z";
            var valueRange = new ValueRange();

            var oblist = new List( values );
            valueRange.Values = new List> { oblist };

            var appendRequest = service.Spreadsheets.Values.Append(valueRange, SpreadsheetId, range);
            appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
            var appendReponse = appendRequest.Execute();
        }
    }
}