ExecuteScalar() public method

Allows the programmer to retrieve single items from the DB.
public ExecuteScalar ( string sql ) : string
sql string The query to run.
return string
        protected string GetStats()
        {
            long   entitySpaceUsed = long.Parse(db.ExecuteScalar("SELECT SUM(size) FROM entities"));
            long   blockSpaceUsed  = long.Parse(db.ExecuteScalar("SELECT SUM(size) FROM blocks"));
            long   chunks          = long.Parse(db.ExecuteScalar("SELECT count(id) from blocks"));
            long   diffSpace       = entitySpaceUsed - blockSpaceUsed;
            string stats           = "";

            stats += $"Space used for entites => {entitySpaceUsed.GetBytesReadable()}\n";
            stats += $"Space used for blocks => {blockSpaceUsed.GetBytesReadable()}\n";
            stats += $"Space saved => {diffSpace.GetBytesReadable()}\n";
            stats += $"Blocks used => {chunks}\n";
            stats += "\n";
            return(stats);
        }
        private void bt_save_Click(object sender, EventArgs e)
        {
            if (Int32.Parse(cb_equipe1.SelectedValue.ToString()) == Int32.Parse(cb_equipe2.SelectedValue.ToString()))
            {
                MessageBox.Show("Vous ne pouvez pas ajouter une exception d'une équipe sur elle-même.");
                return;
            }
            this.db = new SQLiteDatabase();
            String query = "SELECT COUNT(*) FROM exception WHERE equipe1_id = "
                           + cb_equipe1.SelectedValue.ToString() + " AND equipe2_id = "
                           + cb_equipe2.SelectedValue.ToString() + " OR equipe1_id = "
                           + cb_equipe2.SelectedValue.ToString() + " AND equipe2_id = "
                           + cb_equipe1.SelectedValue.ToString();
            int count = Int32.Parse(db.ExecuteScalar(query));

            if (count > 0)
            {
                MessageBox.Show("Cette exception est déjà présente dans la base de données.");
                return;
            }
            query = "INSERT INTO exception VALUES (" + cb_equipe1.SelectedValue.ToString()
                    + ", " + cb_equipe2.SelectedValue.ToString() + ");";
            this.db.ExecuteNonQuery(query);
            this.Close();
        }
Example #3
0
        public Tournoi()
        {
            String query = "select count(*) from equipe";

            nbEquipes = Int32.Parse(db.ExecuteScalar(query));
            query     = "select * from equipe";
            DataTable data = db.GetDataTable(query);

            foreach (DataRow row in data.Rows)
            {
                Equipe equ = new Equipe(Int32.Parse(row["id"].ToString()), row["nom"].ToString(), Int32.Parse(row["capitaine_id"].ToString()));
                this.Equipes[equ.id] = equ;
            }

            query = "select * from exception";
            DataTable dataExc = db.GetDataTable(query);

            foreach (DataRow row in dataExc.Rows)
            {
                this.Equipes[Int32.Parse(row["equipe1_id"].ToString())].exceptions.Add(Int32.Parse(row["equipe2_id"].ToString()));
                this.Equipes[Int32.Parse(row["equipe2_id"].ToString())].exceptions.Add(Int32.Parse(row["equipe1_id"].ToString()));
            }

            query = "select * from personne where equipe_id is null and arbitre = 1";
            DataTable arb = db.GetDataTable(query);

            foreach (DataRow row in arb.Rows)
            {
                Personne pers;
                if (row["equipe_id"] == System.DBNull.Value)
                {
                    pers = new Personne(Int32.Parse(row["id"].ToString()), row["prenom"].ToString(), row["nom"].ToString(), 0, true);
                }
                else
                {
                    pers = new Personne(Int32.Parse(row["id"].ToString()), row["prenom"].ToString(), row["nom"].ToString(), Int32.Parse(row["equipe_id"].ToString()), true);
                }

                this.Arbitres[pers.id] = pers;
            }

            query = "select * from personne where equipe_id is not null and equipe_id > 0";
            DataTable players = db.GetDataTable(query);

            foreach (DataRow row in players.Rows)
            {
                Personne pers;
                pers = new Personne(Int32.Parse(row["id"].ToString()), row["prenom"].ToString(), row["nom"].ToString(), Int32.Parse(row["equipe_id"].ToString()), false);

                this.Joueurs[pers.id] = pers;
            }
            foreach (KeyValuePair <int, Equipe> equipe in this.Equipes)
            {
                equipe.Value.setJoueurs(this.Joueurs);
            }
        }
        /// <summary>
        ///     Checks whether a specified account exists and whether the password supplied
        ///     is correct
        /// </summary>
        /// <param name="id">The ID of the student/teacher - Corresponds to the id field
        /// in the DB</param>
        /// <param name="pass">The password to check as a string</param>
        /// <param name="stuteach">A string containing "students" or "teachers"</param>
        /// <returns>true when account is correct, false otherwise</returns>
        public static bool checkAccount(int id, string pass, string stuteach)
        {
            SQLiteDatabase db = new SQLiteDatabase();
            string dbPass = db.ExecuteScalar(string.Format("SELECT hash FROM {0} WHERE id={1};", stuteach, id));
            string passHash = Password.hashAsString(pass);

            if (dbPass == passHash)
                return true;

            return false;
        }
Example #5
0
        private void bt_generate_Click(object sender, EventArgs e)
        {
            updateAll();
            db = new SQLiteDatabase();
            String query      = "select count(*) from equipe";
            int    nbEquipes  = Int32.Parse(db.ExecuteScalar(query));
            int    nbTerrains = Properties.Settings.Default.nbTerrains;

            query = "select count(*) from personne where equipe_id is null and arbitre = 1";
            int     nbArbitres = Int32.Parse(db.ExecuteScalar(query));
            Boolean erreur     = false;

            if (nbArbitres < 1)
            {
                MessageBox.Show("Il vous faut au moins un arbitre n'appartenant pas à une équipe !");
                erreur = true;
            }
            else if (nbTerrains < 1)
            {
                MessageBox.Show("Il vous faut au moins un terrain disponible !");
                erreur = true;
            }
            else if (nbEquipes < 3)
            {
                MessageBox.Show("Il vous faut au moins trois équipes !");
                erreur = true;
            }
            else if (!cb_lundi.Checked && !cb_mardi.Checked && !cb_mercredi.Checked && !cb_jeudi.Checked &&
                     !cb_vendredi.Checked && !cb_samedi.Checked && !cb_dimanche.Checked)
            {
                MessageBox.Show("Il vous faut au moins une journée disponible !");
                erreur = true;
            }
            if (!erreur)
            {
                Tournoi tour = new Tournoi();
                Dictionary <int, Dictionary <int, int> > poules = tour.getPossiblesPoules();
                ChoixPoules cp = new ChoixPoules(tour, poules);
                cp.ShowDialog();
            }
        }
        public GDriveFileStream(string fileName, string mimeType, DriveService svc, SQLiteDatabase db)
        {
            this.fileName = fileName;
            this.svc      = svc;
            this.mimeType = mimeType;
            this.db       = db;

            //string fileId =
            //    db.ExecuteScalar($"SELECT fileid FROM gdrive WHERE filename = '{fileName}' AND directory = 0");
            string fileId =
                db.ExecuteScalar("SELECT fileid FROM gdrive WHERE filename = @fileName AND directory = @directory",
                                 new Dictionary <string, object>()
            {
                { "@fileName", fileName },
                { "@directory", 0 }
            });

            if (fileId != "")
            {
                //var req2 = svc.Files.List();
                //string fnameURLEncode = System.Web.HttpUtility.UrlEncode(fileName);
                //req2.Q = $"id = '{fileId}'";
                //req2.Fields = "nextPageToken, files(id, name,parents,mimeType, trashed)";
                //var feed = req2.Execute();
                var request = svc.Files.Get(fileId);
                //request.Fields = "*";
                //string fid = request.FileId;
                //var t = request.RequestParameters;
                var z          = request.DownloadWithStatus(this);
                int totalTries = 10;
                int tries      = 0;
                if (Length == 0)
                {
                    while (Length == 0 && tries <= totalTries)
                    {
                        z = request.DownloadWithStatus(this);
                        tries++;
                    }

                    if (Length == 0)
                    {
                        throw new Exception(z.ToString());
                    }
                }

                this.Position = 0;
                //this.Position = 0;
                //var fileResp = request.Execute();
                //this.Position = 0;
            }
        }
Example #7
0
        private void login_btn_Click(object sender, EventArgs e)
        {
            username = "";
            string u = database.ExecuteScalar("select user_id from tbl_user where username='******' and password='******';");

            if (u != "")
            {
                username = username_textbox.Text;
                this.Close();
            }
            else
            {
                login_error_lbl.Visible = true;
            }
        }
Example #8
0
    public void AddFile(string file, byte[] data)
    {
        string check = _db.ExecuteScalar("SELECT name FROM filestorage WHERE name = @name",
                                         new Dictionary <string, object>()
        {
            { "@name", file }
        });

        if (check != string.Empty)
        {
            throw new Exception("File already exists in storage - no support for overwriting");
        }
        long start, end, size;

        size = data.Length;
        if (_file != string.Empty)
        {
            using (var fs = new FileStream(_file, FileMode.OpenOrCreate))
            {
                long endPoint = fs.Length;
                fs.Seek(endPoint, SeekOrigin.Begin);
                start = fs.Position;
                end   = start + size;
                fs.Write(data);
            }
        }
        else
        {
            long endPoint = _stream.Length;
            _stream.Seek(endPoint, SeekOrigin.Begin);
            start = _stream.Position;
            end   = start + size;
            _stream.Write(data);
        }
        _db.ExecuteNonQuery(
            "INSERT INTO filestorage (name, start, end, size) VALUES (@name, @start, @end, @size)",
            new Dictionary <string, object>()
        {
            { "@name", file },
            { "@start", start },
            { "@end", end },
            { "@size", size }
        });
    }
Example #9
0
        private void runMigrations(SQLiteDatabase db)
        {
            string[] files = System.IO.Directory.GetFiles(System.IO.Directory.GetCurrentDirectory() + "/migrations/sqlite/").Select(Path.GetFileName).ToArray();
            files = files.OrderByNatural(file => file).ToArray();
            //int lastMigration = Int32.Parse(db.ExecuteScalar("SELECT value FROM settings WHERE key = 'migration'"));
            int lastMigration = Int32.Parse(db.ExecuteScalar("SELECT value FROM settings WHERE key = @migration", new Dictionary <string, object>()
            {
                { "@migration", "migration" }
            }));

            Log.Instance.Add($"lastMigration = {lastMigration}");
            if (files.Length > 0)
            {
                int highestMigration = lastMigration;
                foreach (string file in files)
                {
                    int migrationNumber = Int32.Parse(file.Split('.')[0]);
                    Log.Instance.Add($"migrationNumber = {migrationNumber}");
                    if (migrationNumber > lastMigration)
                    {
                        db.ExecuteNonQuery(System.IO.File.ReadAllText(System.IO.Directory.GetCurrentDirectory() + $"/migrations/sqlite/{migrationNumber}.sql"));
                        highestMigration = migrationNumber;
                        Log.Instance.Add($"highestMigration = {highestMigration}");
                    }
                }

                //db.ExecuteNonQuery($"UPDATE settings set key = '{highestMigration}' WHERE value = 'migration'");
                Log.Instance.Add($"key = {highestMigration}");
                db.ExecuteNonQuery("UPDATE settings set value = @highestMigration WHERE key = @migration",
                                   new Dictionary <string, object>()
                {
                    { "@highestMigration", highestMigration },
                    { "@migration", "migration" }
                });
            }
        }
        /// <summary>
        ///     Adds a student to the system
        /// </summary>
        /// <param name="name">The student's full name</param>
        /// <param name="pass">The student's password</param>
        /// <param name="stuClass">The student's class</param>
        public static void addStudent(string name, string pass, string stuClass)
        {
            /* The following variables are
             * db        - Instance of the SQLiteDatabase class
             * hash      - The SHA-256 hash of the password to be added as a string
             * added     - Used to avoid a bug with adding students if one has been deleted
             * attempts  - See above
             * studentID - The ID of the student to be added
             */
            SQLiteDatabase db = new SQLiteDatabase();
            string hash       = Password.hashAsString(pass);
            bool added        = false;
            int attempts      = 0;
            int studentID     = Convert.ToInt16(db.ExecuteScalar("SELECT id FROM students ORDER BY id DESC")) + 1;

            // While the db call hasn't executed
            while (!added)
            {
                try
                {
                    db.ExecuteNonQuery(string.Format("INSERT INTO students VALUES ({0}, \"{1}\", \"{2}\", \"{3}\");",
                        studentID, name, stuClass, hash));
                    added = true;
                }
                // Checks the number of attempts and if they're less than 10 it adds one to the studentID
                catch
                {
                    if (attempts > 9)
                    {
                        throw new Exception("Too many attempts");
                    }
                    studentID++;
                    attempts++;
                }
            }
        }
Example #11
0
    public void Download()
    {
        DataTable fileInfo;
        string    directoryID = db.ExecuteScalar("SELECT id FROM directories WHERE fullpath = @path",
                                                 new Dictionary <string, object>()
        {
            { "@path", vsrc.ParentPath.Path }
        });

        fileInfo =
            db.GetDataTable("SELECT * from entities where isdir = @isdir and fname = @name and dir = @dir", new Dictionary <string, object>()
        {
            { "@name", vsrc.EntityName },
            { "@isdir", 0 },
            { "@dir", directoryID }
        });

        // While we write the blocks to multiple -
        // We only need data from one file system -
        // I want to test the file system to make sure it is working before attempting access
        int  fsToUse        = 0;
        bool continueSearch = false;

        for (int i = 0; i < fsdst.Count; i++)
        {
            try
            {
                using (Stream s = fsdst[fsToUse].CreateFile(FileSystemPath.Parse("/test")))
                {
                }

                continueSearch = false;
            }
            catch (Exception)
            {
                Console.WriteLine("[Error]: file system - " + fsdst[fsToUse].ToString() + " missing - trying a backup");
                continueSearch = true;
                fsToUse++;
            }

            if (!continueSearch)
            {
                break;
            }
        }

        DataTable blocks = db.GetDataTable(@"SELECT * FROM fileblocks 
        inner join blocks on blocks.id = fileblocks.block_id
        WHERE file_id = @fileid 
        and blocks.location = @location
        order by block_order asc"
                                           , new Dictionary <string, object>()
        {
            { "@fileid", fileInfo.Rows[0]["id"] },
            { "@location", fsdst[fsToUse].ToString() }
        });

        using (ProgressBar pb = new ProgressBar(disableProgress))
        {
            Int64 rowCount = 0;
            foreach (DataRow r in blocks.Rows)
            {
                pb.Report((((double)rowCount) / blocks.Rows.Count));
                rowCount += 1;



                /*string remotename = db.ExecuteScalar("SELECT name FROM blocks where id = @blockID and location = @name",
                 *  new Dictionary<string, object>()
                 *  {
                 *      {"@blockID", r["block_id"]},
                 *      {"@name", fsdst[fsToUse].ToString()}
                 *  });*/
                string remotename = r["name"].ToString();
                remotename = "/" + remotename;
                remotename = remotename.Replace("//", "/");


                using (var fstream = fsdst[fsToUse].OpenFile(FileSystemPath.Parse($"/{DATAFILE}"), FileAccess.Read))
                {
                    DeDupeStorage storage   = new DeDupeStorage(fstream, db);
                    byte[]        buffer    = storage.GetFile(remotename);
                    byte[]        plainText = AESWrapper.DecryptToByte(buffer, key);
                    using (FileStream f = System.IO.File.Open(this.Path, FileMode.Append, FileAccess.Write))
                    {
                        f.Write(plainText);
                    }
                }

                /*using (var fstream = fsdst[fsToUse].OpenFile(FileSystemPath.Parse($"/{DATAFILE}"), FileAccess.Read))
                 * {
                 *  DeDupeStorage storage = new DeDupeStorage(fstream, db);
                 *  byte[] buffer = storage.GetFile(remotename);
                 *  byte[] plainText = AESWrapper.DecryptToByte(buffer, key);
                 *  using (var zippedStream = new MemoryStream(plainText))
                 *  {
                 *      using (var archive = new ZipArchive(zippedStream, ZipArchiveMode.Read))
                 *      {
                 *          var ent = archive.GetEntry("data.bin");
                 *          using (var zipent = ent.Open())
                 *          {
                 *              byte[] bufferinner = zipent.ReadAllBytes();
                 *              using (FileStream f = System.IO.File.Open(this.Path, FileMode.Append, FileAccess.Write))
                 *              {
                 *                  f.Write(bufferinner);
                 *              }
                 *              //fstream.Write(bufferinner);
                 *          }
                 *      }
                 *  }
                 * }*/

                /*using (var fstream = fsdst[fsToUse].OpenFile(FileSystemPath.Parse($"/{DATAFILE}"), FileAccess.Read))
                 * {
                 *  using (var zipfile = new ZipArchive(fstream, ZipArchiveMode.Read))
                 *  {
                 *      var ent = zipfile.GetEntry(remotename);
                 *      using (var zipent = ent.Open())
                 *      {
                 *          byte[] buffer = zipent.ReadAllBytes();
                 *          byte[] plainText = AESWrapper.DecryptToByte(buffer, key);
                 *
                 *          if (plainText == null)
                 *          {
                 *              throw new Exception("[Error]: Could not decrypt file");
                 *          }
                 *
                 *          using (FileStream f = System.IO.File.Open(this.Path, FileMode.Append, FileAccess.Write))
                 *          {
                 *              f.Write(plainText);
                 *          }
                 *      }
                 *  }
                 * }*/



                /*using (Stream s = fsdst[fsToUse].OpenFile(FileSystemPath.Parse(remotename), FileAccess.Read))
                 * {
                 *
                 *  using (FileStream f = System.IO.File.Open(this.Path, FileMode.Append, FileAccess.Write))
                 *  {
                 *      byte[] buffer = s.ReadAllBytes();
                 *      byte[] plainText = AESWrapper.DecryptToByte(buffer, key);
                 *      if (plainText == null)
                 *      {
                 *          throw new Exception("[Error]: Could not decrypt file");
                 *      }
                 *
                 *      f.Write(plainText);
                 *  }
                 * }*/
            }
            string fileHash = fileInfo.Rows[0]["filehash"].ToString();
            if (fileHash != "")
            {
                string newHash = "";
                using (FileStream fs = System.IO.File.Open(this.Path, FileMode.Open, FileAccess.Read))
                {
                    newHash = fs.GetSHA512();
                }
                if (fileHash != newHash)
                {
                    Console.WriteLine("[Warning]: File hashs do not match - data corruption possible!");
                }
            }
        }
    }
Example #12
0
        private void NouvelleEquipe_Load(object sender, EventArgs e)
        {
            db = new SQLiteDatabase();
            try
            {
                db = new SQLiteDatabase();

                String query = "";
                if (this.id_equipe != 0)
                {
                    query = "select nom from equipe where id = " + this.id_equipe;
                    String teamName = db.ExecuteScalar(query);
                    tb_nom.Text = teamName;
                    query       = "select capitaine_id from equipe where id = " + this.id_equipe;
                    capitaineId = Int32.Parse(db.ExecuteScalar(query));
                }

                query = "select * FROM personne WHERE equipe_id is null or equipe_id = 0";
                if (this.id_equipe != 0)
                {
                    query += " or equipe_id = " + this.id_equipe;
                }
                personnes = db.GetDataTable(query);
                DataColumn inTeam = new DataColumn("Selection", typeof(Boolean));
                personnes.Columns.Add(inTeam);
                DataColumn isCap = new DataColumn("Capitaine", typeof(Boolean));
                personnes.Columns.Add(isCap);

                foreach (DataRow r in personnes.Rows)
                {
                    if (r["equipe_id"] != System.DBNull.Value)
                    {
                        r["Selection"] = 1;
                        playerCount++;
                    }
                    else
                    {
                        r["Selection"] = 0;
                    }
                    if (Int32.Parse(r["id"].ToString()) == capitaineId)
                    {
                        r["Capitaine"] = 1;
                    }
                    else
                    {
                        r["Capitaine"] = 0;
                    }
                }
                dataGridView1.DataSource         = personnes;
                dataGridView1.Columns[0].Width   = 30;
                dataGridView1.Columns[3].Visible = false;
                dataGridView1.Columns[4].Visible = false;
                for (int i = 0; i < 5; i++)
                {
                    dataGridView1.Columns[i].ReadOnly = true;
                }
            }
            catch (Exception fail)
            {
                String error = "The following error has occurred:\n\n";
                error += fail.Message.ToString() + "\n\n";
                MessageBox.Show(error);
                this.Close();
            }
        }
Example #13
0
        private void bt_save_Click(object sender, EventArgs e)
        {
            if (tb_nom.TextLength < 6)
            {
                MessageBox.Show("Le nom de l'équipe doit comporter au moins 6 caractères !");
                return;
            }
            capitaineId = 0;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if ((Boolean)row.Cells["Capitaine"].Value == true)
                {
                    capitaineId = Int32.Parse(row.Cells["id"].Value.ToString());
                }
            }
            if (playerCount < 6)
            {
                MessageBox.Show("Une équipe doit comporter au minimum 6 joueurs.");
            }
            else if (capitaineId == 0)
            {
                MessageBox.Show("L'équipe doit avoir un capitaine !");
            }
            else
            {
                db = new SQLiteDatabase();
                int idEquipe;
                Dictionary <String, String> data = new Dictionary <String, String>();
                data.Add("nom", this.tb_nom.Text);
                data.Add("capitaine_id", capitaineId.ToString());
                if (this.id_equipe == 0)
                {
                    db.Insert("equipe", data);
                    String query = "select max(id) FROM equipe";
                    idEquipe = Int32.Parse(db.ExecuteScalar(query));
                }
                else
                {
                    db.Update("equipe", data, "id = " + this.id_equipe);
                    idEquipe = this.id_equipe;
                }
                Dictionary <String, String> dataUpdate = new Dictionary <String, String>();
                dataUpdate.Add("equipe_id", "NULL");
                db.Update("personne", dataUpdate, " equipe_id = " + idEquipe);
                string  whereString = " id IN (";
                Boolean first       = true;
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if ((Boolean)row.Cells["Selection"].Value)
                    {
                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            whereString += ", ";
                        }
                        whereString += row.Cells["id"].Value.ToString();
                    }
                }
                whereString            += ")";
                dataUpdate["equipe_id"] = idEquipe.ToString();
                db.Update("personne", dataUpdate, whereString);

                this.Close();
            }
        }
Example #14
0
        public void Run()
        {
            string[]     arguments = Environment.GetCommandLineArgs();
            string       key;
            SettingsData data;

            if (File.Exists("settings.xml"))
            {
                data = SettingsFile.Read("settings.xml");
            }
            else
            {
                Console.WriteLine("Can't find settings.xml file - attempting to generate one");
                data = GenerateSettings();
                SettingsFile.Write(data, "settings.xml");
            }

            if (arguments.Length > 1 && arguments[1] == "fuse")
            {
                try
                {
                    Fuse.LazyUnmount(arguments[2]);
                    key = AESWrapper.GenerateKeyString(ConsoleEx.Password("Key: "), data.salt, data.iterations,
                                                       data.keySize);
                    using (var mount = Fuse.Mount(arguments[2], new DeDupeFuseFileSystem(key, data)))
                    {
                        Task t = mount.WaitForUnmountAsync();
                        t.Wait();
                    }
                }
                catch (FuseException fe)
                {
                    Console.WriteLine($"Fuse throw an exception: {fe}");

                    Console.WriteLine("Try unmounting the file system by executing:");
                    Console.WriteLine($"fuser -kM {arguments[2]}");
                    Console.WriteLine($"sudo umount -f {arguments[2]}");
                }
            }
            else
            {
                string         input            = "";
                FileSystemPath currentDirectory = FileSystemPath.Parse("/");


                string[] Scopes = { DriveService.Scope.Drive, DriveService.Scope.DriveFile };


                if (arguments.Length > 1)
                {
                    key = AESWrapper.GenerateKeyString(arguments[1], data.salt, data.iterations,
                                                       data.keySize);
                }
                else
                {
                    key = AESWrapper.GenerateKeyString(ConsoleEx.Password("Key: "), data.salt, data.iterations,
                                                       data.keySize);
                }

                using (EncryptedTempFile dbfile = new EncryptedTempFile("data.sqlite.enc", key))
                {
                    SQLiteDatabase db  = new SQLiteDatabase(dbfile.Path);
                    var            res = db.GetDataTable("PRAGMA table_info(settings)");
                    if (res.Rows.Count == 0)
                    {
                        this.setUpDatabase(db);
                    }

                    this.runMigrations(db);
                    dbfile.Flush();
                    //GDriveFileSystem gdrive = new GDriveFileSystem(Scopes, "DistrubtedDeDupe", dbfile.Path);
                    Log.Instance.Write("log.txt");


                    DeDupeFileSystem fs = new DeDupeFileSystem(dbfile.Path, key);
                    foreach (KeyValuePair <string, string> kv in data.locations)
                    {
                        fs.AddFileSystem(new DeDupeLocalFileSystem(kv.Value, kv.Key));
                    }

                    //fs.AddFileSystem(gdrive);
                    string fileName;
                    byte[] fileData;
                    do
                    {
                        if (currentDirectory.Path == "/")
                        {
                            Console.Write($"#:{currentDirectory.Path}> ");
                        }
                        else
                        {
                            Console.Write($"#:{currentDirectory.Path.TrimEnd('/')}> ");
                        }

                        if (arguments.Length > 1)
                        {
                            input = arguments[2];
                        }
                        else
                        {
                            input = Console.ReadLine();
                        }

                        switch (input.Split(" ")[0])
                        {
                        case "stats":
                            long entitySpaceUsed = long.Parse(db.ExecuteScalar("SELECT SUM(size) FROM entities"));
                            long blockSpaceUsed  = long.Parse(db.ExecuteScalar("SELECT SUM(size) FROM blocks"));
                            long chunks          = long.Parse(db.ExecuteScalar("SELECT count(id) from blocks"));
                            long diffSpace       = entitySpaceUsed - blockSpaceUsed;
                            Console.WriteLine($"Space used for entites => {entitySpaceUsed.GetBytesReadable()}");
                            Console.WriteLine($"Space used for blocks => {blockSpaceUsed.GetBytesReadable()}");
                            Console.WriteLine($"Space saved => {diffSpace.GetBytesReadable()}");
                            Console.WriteLine($"Blocks used => {chunks}");
                            break;

                        case "addstorage":
                            string location = input.Split(" ")[1].Trim();
                            string name     = input.Split(" ")[2].Trim();
                            data.locations[name] = Path.GetFullPath(location);
                            fs.AddFileSystem(new DeDupeLocalFileSystem(Path.GetFullPath(location), name));
                            SettingsFile.Write(data, "settings.xml");
                            break;

                        case "decryptdb":
                            fileName = input.Split(" ")[1].Trim();
                            //byte[] plain = AESWrapper.DecryptToByte(System.IO.File.ReadAllBytes(dbfile.Path), key);
                            System.IO.File.WriteAllBytes(fileName, System.IO.File.ReadAllBytes(dbfile.Path));
                            break;

                        case "help":
                            ShowHelp();
                            break;

                        case "changekey":
                            key = AESWrapper.GenerateKeyString(ConsoleEx.Password("Key: "), data.salt,
                                                               data.iterations,
                                                               data.keySize);
                            fs.UpdateKey(key);
                            break;

                        case "generate":
                            data = GenerateSettings();
                            if (data != null)
                            {
                                SettingsFile.Write(data, "settings.xml");
                                key = AESWrapper.GenerateKeyString(ConsoleEx.Password("Key: "), data.salt,
                                                                   data.iterations,
                                                                   data.keySize);
                                fs.UpdateKey(key);
                            }

                            break;

                        case "showsettings":
                            Console.WriteLine($"Iterations = {data.iterations}");
                            Console.WriteLine($"Salt = {data.salt}");
                            Console.WriteLine($"Key size = {data.keySize}");
                            foreach (var kv in data.locations)
                            {
                                Console.WriteLine($"{kv.Key} = {kv.Value}");
                            }

                            break;

                        case "ls":
                            Console.WriteLine(
                                VirtualDirectoryListing.List(fs.GetExtendedEntities(currentDirectory)));
                            break;

                        case "ll":
                            Console.WriteLine(
                                VirtualDirectoryListing.ListWithHash(fs.GetExtendedEntities(currentDirectory)));
                            break;

                        case "put":
                            if (data.locations.Count == 0)
                            {
                                Console.WriteLine("[Error]: No file locations setup");
                                break;
                            }

                            fileName = input.Split(" ")[1].Trim();
                            byte[] fileDataPut = System.IO.File.ReadAllBytes(fileName);
                            //string encFile = AESWrapper.EncryptToString(fileData, key);
                            Stopwatch watch1 = new Stopwatch();
                            watch1.Start();
                            using (Stream f = fs.CreateFile(FileSystemPath.Parse(currentDirectory.Path + fileName)))
                            {
                                f.Write(fileDataPut, 0, fileDataPut.Length);
                            }

                            fs.FlushTempFile();
                            dbfile.Flush();
                            watch1.Stop();
                            Console.WriteLine($"Elapsed time: {watch1.Elapsed.ToString("g")}");
                            break;

                        case "localcat":
                            if (data.locations.Count == 0)
                            {
                                Console.WriteLine("[Error]: No file locations setup");
                                break;
                            }

                            fileName = input.Split(" ")[1].Trim();
                            fileData = System.IO.File.ReadAllBytes(fileName);
                            Console.WriteLine(AESWrapper.DecryptToString(fileData, key));
                            break;

                        case "remotecat":
                            if (data.locations.Count == 0)
                            {
                                Console.WriteLine("[Error]: No file locations setup");
                                break;
                            }

                            fileName = input.Split(" ")[1].Trim();
                            try
                            {
                                using (Stream f = fs.OpenFile(
                                           FileSystemPath.Parse(currentDirectory.Path + fileName),
                                           FileAccess.Read))
                                {
                                    Console.WriteLine(f.ReadAllText());
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("[Error]: " + e.ToString());
                            }

                            break;

                        case "get":
                            if (data.locations.Count == 0)
                            {
                                Console.WriteLine("[Error]: No file locations setup");
                                break;
                            }

                            fileName = input.Split(" ")[1].Trim();
                            string    dstFileName = input.Split(" ")[2].Trim();
                            Stopwatch watch2      = new Stopwatch();
                            watch2.Start();
                            using (Stream f = fs.OpenFile(FileSystemPath.Parse(currentDirectory.Path + fileName),
                                                          FileAccess.Read))
                            {
                                byte[] test = f.ReadAllBytes();
                                System.IO.File.WriteAllBytes(dstFileName, test);
                            }

                            watch2.Stop();
                            Console.WriteLine($"Elapsed time: {watch2.Elapsed.ToString("g")}");
                            break;

                        case "mkdir":
                            string newDir = input.Split(" ")[1].Trim();
                            fs.CreateDirectory(currentDirectory.AppendDirectory(newDir));
                            dbfile.Flush();
                            break;

                        case "cd":
                            string dirtmpStr;
                            //dirtmp = currentDirectory.AppendDirectory(input.Split(" ")[1]);
                            dirtmpStr = ParseDotDot(currentDirectory.Path, input.Split(" ")[1]);
                            FileSystemPath dirtmp;
                            if (dirtmpStr == "/")
                            {
                                dirtmp = FileSystemPath.Parse(dirtmpStr);
                            }
                            else
                            {
                                dirtmp = FileSystemPath.Parse(dirtmpStr + "/");
                            }

                            if (fs.Exists(dirtmp))
                            {
                                //currentDirectory = currentDirectory.AppendDirectory(input.Split(" ")[1]);
                                currentDirectory = dirtmp;
                            }
                            else
                            {
                                Console.WriteLine("No such directory exists");
                            }

                            break;
                        }

                        if (arguments.Length > 1)
                        {
                            break;
                        }
                    } while (input != "exit" && input != "quit");

                    dbfile.Flush();
                }
            }
        }
        public override void Write(byte[] buffer, int offset, int count)
        {
            base.Write(buffer, offset, count);
            // Someday I will separate it out and make a PR to SharpFileSystem
            //string directoryID =
            //    db.ExecuteScalar("SELECT fileid FROM gdrive WHERE filename = 'distrodedup' AND directory = 1");
            string directoryID =
                db.ExecuteScalar("SELECT fileid FROM gdrive WHERE filename = @fileName AND directory = @directory",
                                 new Dictionary <string, object>()
            {
                { "@fileName", "distrodedup" },
                { "@directory", 1 }
            });

            if (directoryID == "")
            {
                File fileData = new File();
                fileData.Name     = "DistroDeDup";
                fileData.MimeType = "application/vnd.google-apps.folder";
                var req = svc.Files.Create(fileData);
                req.Fields = "id";
                var folder = req.Execute();
                //db.ExecuteNonQuery(
                //    $"INSERT INTO gdrive (filename, fileid, directory) VALUES ('distrodedup', '{folder.Id}', 1)");
                db.ExecuteNonQuery(
                    "INSERT INTO gdrive (filename, fileid, directory) VALUES (@fileName, @fileID, @directory)",
                    new Dictionary <string, object>()
                {
                    { "@fileName", "distrodedup" },
                    { "@fileID", folder.Id },
                    { "@directory", 1 }
                });

                directoryID = folder.Id;
            }

            //string fileId =
            //    db.ExecuteScalar($"SELECT fileid FROM gdrive WHERE filename = '{fileName}' AND directory = 0");
            string fileId =
                db.ExecuteScalar("SELECT fileid FROM gdrive WHERE filename = @fileName AND directory = @directory",
                                 new Dictionary <string, object>()
            {
                { "@fileName", fileName },
                { "@directory", 0 }
            });

            if (fileId != "")
            {
                FilesResource.ListRequest reqExists = svc.Files.List();
                reqExists.Q      = String.Format("name = '{0}' and trashed=false and parents in '{1}'", fileName, directoryID);
                reqExists.Fields = "nextPageToken, files(id, name,parents,mimeType, trashed)";
                var  result    = reqExists.Execute();
                bool foundFile = false;
                foreach (var file in result.Files)
                {
                    if (file.Id == fileId)
                    {
                        // I guess we need to create another file object?

                        /*File uploadFile = new File();
                         * uploadFile.Name = fileName;
                         * uploadFile.MimeType = mimeType;
                         * var res = svc.Files.Update(uploadFile, fileId, this, mimeType);
                         * var req = res.Upload();*/
                        GDriveFile f = new GDriveFile(this, fileName, mimeType, directoryID, db, GDriveFile.Operation.NONE);
                        f.Update(svc, fileId);
                        foundFile = true;
                        break;
                    }
                }

                if (!foundFile)
                {
                    GDriveFile f = new GDriveFile(this, fileName, mimeType, directoryID, db, GDriveFile.Operation.UPDATE);
                    f.Upload(svc);

                    /*File body = new File();
                     * body.Name = fileName;
                     * body.MimeType = mimeType;
                     * body.Parents = new List<string>();
                     * body.Parents.Add(directoryID);
                     * FilesResource.CreateMediaUpload req = svc.Files.Create(body, this, mimeType);
                     * req.Fields = "id, parents";
                     * var res = req.Upload();
                     * string newFileId = req.ResponseBody.Id;
                     *
                     * //db.ExecuteNonQuery(
                     * //    $"UPDATE gdrive set fileid = '{newFileId}' WHERE filename = '{fileName}' and directory = 0");
                     *
                     * db.ExecuteNonQuery(
                     *  "UPDATE gdrive set fileid = @newFileId WHERE filename = @fileName and directory = 0",
                     *  new Dictionary<string, object>()
                     *  {
                     *      {"@newFileId", newFileId},
                     *      {"@fileName", fileName}
                     *  });*/
                }
            }
            else
            {
                GDriveFile f = new GDriveFile(this, fileName, mimeType, directoryID, db, GDriveFile.Operation.CREATE);
                f.Upload(svc);

                /*File body = new File();
                 * body.Name = fileName;
                 * body.MimeType = mimeType;
                 * body.Parents = new List<string>();
                 * body.Parents.Add(directoryID);
                 * FilesResource.CreateMediaUpload req = svc.Files.Create(body, this, mimeType);
                 * req.Fields = "id, parents";
                 * req.ProgressChanged += ReqOnProgressChanged;
                 * //req.UploadAsync()
                 * var res = req.Upload();
                 *
                 * string newFileId = req.ResponseBody.Id;
                 *
                 * //db.ExecuteNonQuery(
                 * //    $"INSERT INTO gdrive (filename, fileid, directory) VALUES ('{fileName}', '{newFileId}', 0)");
                 * db.ExecuteNonQuery(
                 *  "INSERT INTO gdrive (filename, fileid, directory) VALUES (@fileName, @newFileId, 0)",
                 *  new Dictionary<string, object>()
                 *  {
                 *      {"@fileName", fileName},
                 *      {"@newFileID", newFileId}
                 *  });*/
            }
        }
Example #16
0
        private void SaveButton_Click(object sender, EventArgs e)
        {
            try {
                string dayOfWeek = (DayOfWeekComboBox.SelectedIndex + 1).ToString();
                string clockIn   = ClockInTimePicker.Value.ToString("HH:mm");
                string clockOut  = ClockOutTimePicker.Value.ToString("HH:mm");

                Dictionary <String, String> data = new Dictionary <String, String> {
                    { "dayOfWeek", dayOfWeek },
                    { "clockIn", clockIn },
                    { "clockOut", clockOut }
                };

                if (SaveButton.Text == "Save" && AvgHoursGridView.SelectedRows.Count > 0)
                {
                    string entryId = AvgHoursGridView.SelectedRows[0].Cells[0].Value.ToString();

                    if (sql.Update("avgHours", data, String.Format("avgHours.id = {0}", entryId)))
                    {
                        AvgHoursGridView.SelectedRows[0].Cells[1].Value = dayOfWeek;
                        AvgHoursGridView.SelectedRows[0].Cells[2].Value = clockIn;
                        AvgHoursGridView.SelectedRows[0].Cells[3].Value = clockOut;

                        SetAddButton();
                    }
                }
                else if (SaveButton.Text == "Add" && AvgHoursGridView.SelectedRows.Count == 0)
                {
                    // TODO see if count == 0 check is actually necessary
                    data.Add("employeeID", TextBoxCardID.Text.Trim());

                    if (sql.Insert("avgHours", data))
                    {
                        DataTable dt = AvgHoursGridView.DataSource as DataTable;

                        if (dt == null)
                        {
                            dt = new DataTable();
                            dt.Columns.Add("id", typeof(int));
                            dt.Columns.Add("Day", typeof(string));
                            dt.Columns.Add("clockIn", typeof(string));
                            dt.Columns.Add("clockOut", typeof(string));

                            AvgHoursGridView.DataSource         = dt;
                            AvgHoursGridView.Columns[0].Visible = false; // hide ID column
                        }

                        DataRow dr = dt.NewRow();
                        dr[0] = sql.ExecuteScalar("select seq from sqlite_sequence where name='avgHours';");
                        dr[1] = dayOfWeek;
                        dr[2] = clockIn;
                        dr[3] = clockOut;

                        // TODO find out why this event gets deregistered and re-registered (and possibly do whatever it does directly to make it less confusing)
                        AvgHoursGridView.RowStateChanged -= new DataGridViewRowStateChangedEventHandler(AvgHoursGridView_RowStateChanged);

                        dt.Rows.Add(dr);
                        dt.AcceptChanges();
                        AvgHoursGridView.ClearSelection();

                        AvgHoursGridView.RowStateChanged += new DataGridViewRowStateChangedEventHandler(AvgHoursGridView_RowStateChanged);
                    }
                }
            } catch (Exception err) {
                MessageBox.Show(this, "There was an error while trying to save the entry.\n\n" + err.Message, "Save Avg Hours Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #17
0
        public int newUniqueID(MediaStreamingRequest request, bool getIDOnly)
        {
            int newId = IdsAndInputFilesContains(request.InputFile + request.UniekClientID);

            if (request.KeepSameIDForSameInputFile && newId != 0) // != 0 means found as existing id that can be resumed
            {
                var ms = GetStreamerByID(newId);
                if (ms != null && !getIDOnly)
                {
                    //mediaStreamers.Remove(newId);
                    Functions.WriteLineToLogFile("Streamer newId=" + newId + " about to stop (in background), mediaStreamers.ContainsKey(newId) : " +
                                                 mediaStreamers.ContainsKey(newId));
                    StopStreamer(newId, 2);
                    Functions.WriteLineToLogFile("Streamer newId=" + newId + " stopped (in background), mediaStreamers.ContainsKey(newId) : " +
                                                 mediaStreamers.ContainsKey(newId));
                }

                if (!getIDOnly)
                {
                    DeleteStreamingFiles(newId);             //begin anew, s.t. if new quality, this will be used.
                }
                //bump up the id in the database
                db.Delete("IDANDINPUTFILE", String.Format("STREAMID = {0}", "" + newId));
                var item = new Dictionary <string, string>();
                item.Add("STREAMID", "" + newId);
                string i = request.InputFile.Replace("'", "''");
                string u = request.UniekClientID.Replace("'", "''");
                item.Add("INPUTFILE", i + u);
                db.Insert("IDANDINPUTFILE", item);

                return(newId);
            }



            //clean up if database is large
            const int maxFileToRememberResume = 1000;
            int       count = 0;

            Int32.TryParse(db.ExecuteScalar("select COUNT(*) from IDANDINPUTFILE where STREAMID IS NOT NULL;"),
                           out count);
            if (count > maxFileToRememberResume)
            {
                try
                {
                    DataTable tabel;
                    String    query = "select STREAMID, INPUTFILE from IDANDINPUTFILE;";
                    tabel = db.GetDataTable(query);
                    // The results can be directly applied to a DataGridView control
                    //                            recipeDataGrid.DataSource = tabel;
                    // Or looped through for some other reason
                    var i = 0;
                    foreach (DataRow r in tabel.Rows)
                    {
                        if (i < count / 2)
                        {
                            db.ExecuteNonQuery("delete from IDANDINPUTFILE where STREAMID=" + r["STREAMID"] + ";");
                        }
                        else
                        {
                        }
                        i++;
                    }
                }
                catch (Exception fail)
                {
                    String error = "The following error has occurred in cleaning up database : " + db.ToString() + "\n";
                    error += fail.Message;
                    if (Settings.Default.DebugStreaming)
                    {
                        Functions.WriteLineToLogFile("StreamingManager: " + error);
                    }
                }
            }



            do
            {
                var r = new Random();
                //newId = (getIDOnly ? r.Next(100000, 999999) : r.Next(10000, 99999));
                newId = r.Next(10000, 99999);
            } while (mediaStreamers.ContainsKey(newId) || !IdsAndInputFilesContains(newId).Equals(""));

            if (IdsAndInputFilesContains(request.InputFile + request.UniekClientID) == 0 && !request.InputFile.Contains("RMCLiveTV")) //live tv gets a new iD all the time anyway, due to randowm nr in inputfile string
            {
                var item = new Dictionary <string, string>();
                item.Add("STREAMID", "" + newId);
                string i = request.InputFile.Replace("'", "''");
                string u = request.UniekClientID.Replace("'", "''");
                item.Add("INPUTFILE", i + u);
                db.Insert("IDANDINPUTFILE", item);
                //  db.CommitTransaction();
            }
            return(newId);
        }