Dispose() protected method

Disposes of the command and clears all member variables
protected Dispose ( bool disposing ) : void
disposing bool Whether or not the class is being explicitly or implicitly disposed
return void
Example #1
0
        public static bool Init()
        {
            try
            {
                m_cards = new Dictionary <int, CardData>();

                string currentPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                currentPath = Path.GetDirectoryName(currentPath) ?? "";
                string absolutePath = Path.Combine(currentPath, "Content/cards.cdb");

                if (!File.Exists(absolutePath))
                {
                    return(false);
                }

                using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + absolutePath))
                {
                    connection.Open();

                    const string select =
                        "SELECT datas.id, alias, type, level, race, attribute, atk, def, name, desc " +
                        "FROM datas INNER JOIN texts ON datas.id = texts.id";

                    SQLiteCommand command = new SQLiteCommand(select, connection);
                    using (SQLiteDataReader reader = command.ExecuteReader())
                        InitCards(reader);
                    command.Dispose();
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #2
0
        private void apply_Click(object sender, EventArgs e)
        {
            SqliteCommand command = new SqliteCommand(connection);
            String date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            command.CommandText = "INSERT OR REPLACE INTO comments (guid, comment, date) VALUES (@guid, @comment, @date)";
            command.Parameters.Add(new SqliteParameter("@guid", guid));
            command.Parameters.Add(new SqliteParameter("@comment", input.Text));
            command.Parameters.Add(new SqliteParameter("@date", date));
            command.ExecuteNonQuery();

            command.Dispose();

            if (mode == "players")
            {
                Thread thread = new Thread(new ThreadStart(gui.thread_Player));
                thread.IsBackground = true;
                thread.Start();
            }
            else if (mode == "bans")
            {
                Thread thread = new Thread(new ThreadStart(gui.thread_Bans));
                thread.IsBackground = true;
                thread.Start();
            }
            else if (mode == "player database")
            {
                Thread thread = new Thread(new ThreadStart(gui.thread_Database));
                thread.IsBackground = true;
                thread.Start();
            }

            this.Close();
        }
Example #3
0
        public static bool Init()
        {
            try
            {
                m_cards = new Dictionary<int, CardData>();

                string currentPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                currentPath = Path.GetDirectoryName(currentPath) ?? "";
                string absolutePath = Path.Combine(currentPath, "Content/cards.cdb");

                if (!File.Exists(absolutePath))
                    return false;

                using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + absolutePath))
                {
                    connection.Open();

                    const string select =
                        "SELECT datas.id, alias, type, level, race, attribute, atk, def, name, desc " +
                        "FROM datas INNER JOIN texts ON datas.id = texts.id";

                    SQLiteCommand command = new SQLiteCommand(select, connection);
                    using (SQLiteDataReader reader = command.ExecuteReader())
                        InitCards(reader);
                    command.Dispose();
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
Example #4
0
    public static List<Dictionary<string, string>> QueryImpl(string handler, string statement, string[] param)
    {
        List<Dictionary<string,string>> result = new List<Dictionary<string,string>>();
         var db = dbs[handler];
         var dbcmd = new SqliteCommand(ConvertStatment(statement), db);

         // Hard and ugly hack to use '?'
         for (var i = 1; i <= param.Length; i++) {
            dbcmd.Parameters.AddWithValue("@a" + i, param[i-1]);
         }
         IDataReader reader = dbcmd.ExecuteReader();
         while(reader.Read())
         {
            Dictionary<string,string> row = new Dictionary<string,string>();
            for (var i = 0; i < reader.FieldCount; i++) {
               string val = reader.GetValue(i).ToString();
               row.Add(reader.GetName(i),val);
            }
            result.Add(row);
         }
         reader.Dispose();
         dbcmd.Dispose();

          	return result;
    }
Example #5
0
    public void Open(string filePath)
    {
      if (_command != null)
        _command.Dispose();

      if (_conn != null)
        _conn.Close();

      try
      {
        ConnectionStringBuilder connstr = new ConnectionStringBuilder();
        _conn = new Connection();

        connstr.DataSource = (filePath.EndsWith("/") || filePath.EndsWith("\\")) ? filePath + "sys.db" : filePath + "/sys.db";
        _conn.ConnectionString = connstr.ToString();
        _conn.Open();

        _command = new Command(_conn);
        _command.CommandText = "SELECT Content FROM [Text] WHERE [Name]=:name AND [Language]=:language";
        _command.Parameters.Add(new Parameter(":name", DbType.Binary));
        _command.Parameters.Add(new Parameter(":language", DbType.Binary));
      }
      catch
      {
        if (_command != null)
          _command.Dispose();
        if (_conn != null)
          _conn.Dispose();

        _command = null;
        _conn = null;

        throw new DatabaseException("Cannot Open System Database");
      }
    }
Example #6
0
        private bool _ConvertV2toV3(SQLiteConnection connection)
        {
            var command = new SQLiteCommand(connection)
            {
                CommandText = "ALTER TABLE Songs ADD DateAdded BIGINT"
            };

            command.ExecuteNonQuery();
            command.CommandText = "UPDATE Songs SET [DateAdded] = @DateAdded";
            command.Parameters.Add("@DateAdded", DbType.Int64, 0).Value = DateTime.Now.Ticks;
            command.ExecuteNonQuery();
            command.CommandText = "UPDATE Version SET [Value] = @version";
            command.Parameters.Add("@version", DbType.Int32, 0).Value = 3;
            command.ExecuteNonQuery();

            //Read NumPlayed from Scores and save to Songs
            command.CommandText = "SELECT SongID, Date FROM Scores ORDER BY Date ASC";

            SQLiteDataReader reader;

            try
            {
                reader = command.ExecuteReader();
            }
            catch (Exception)
            {
                return(false);
            }

            long       lastDateAdded = -1;
            int        lastID        = -1;
            DateTime   dt            = new DateTime(1, 1, 1, 0, 0, 5);
            long       sec           = dt.Ticks;
            List <int> ids           = new List <int>();

            while (reader.Read())
            {
                int  id        = reader.GetInt32(0);
                long dateAdded = reader.GetInt64(1);
                if (id != lastID || dateAdded > lastDateAdded + sec)
                {
                    ids.Add(id);
                    lastID        = id;
                    lastDateAdded = dateAdded;
                }
            }
            reader.Dispose();

            foreach (int id in ids)
            {
                _IncreaseSongCounter(id, command);
            }
            command.Dispose();

            return(true);
        }
Example #7
0
    public static void ExecImpl(string handler, string statement, string[] param)
    {
        var db = dbs[handler];
         var dbcmd = new SqliteCommand(ConvertStatment(statement), db);

         // Hard and ugly hack to use '?'
         for (var i = 1; i <= param.Length; i++) {
            dbcmd.Parameters.AddWithValue("@a" + i, param[i-1]);
         }
         dbcmd.ExecuteNonQuery();
         dbcmd.Dispose();
    }
Example #8
0
        public void CreateStandardTables()
        {
            SQLiteCommand command = new SQLiteCommand(connection);


            command.CommandText  = "CREATE TABLE IF NOT EXISTS `world_container` (";
            command.CommandText += "  `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,";
            command.CommandText += "  `name` text NOT NULL,";
            command.CommandText += " `posx` REAL  NOT NULL,";
            command.CommandText += " `posy` REAL  NOT NULL,";
            command.CommandText += " `posz` REAL  NOT NULL,";
            command.CommandText += " `world` text NOT NULL,";
            command.CommandText += " `opened` INTEGER NOT NULL";
            command.CommandText += ")";
            command.ExecuteNonQuery();

            command.CommandText  = "CREATE TABLE IF NOT EXISTS `world_items` (";
            command.CommandText += "  `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,";
            command.CommandText += "  `iteminstance` text NOT NULL,";
            command.CommandText += "  `amount` INTEGER NOT NULL,";
            command.CommandText += "  `posx` REAL NOT NULL,";
            command.CommandText += "  `posy` REAL NOT NULL,";
            command.CommandText += "  `posz` REAL NOT NULL,";
            command.CommandText += "  `world` text NOT NULL";
            command.CommandText += ")";
            command.ExecuteNonQuery();


            command.CommandText  = "CREATE TABLE IF NOT EXISTS `world_mobinteract` (";
            command.CommandText += " `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,";
            command.CommandText += " `vobType` INTEGER NOT NULL,";
            command.CommandText += " `name` text NOT NULL,";
            command.CommandText += " `posx` REAL NOT NULL,";
            command.CommandText += " `posy` REAL NOT NULL,";
            command.CommandText += " `posz` REAL NOT NULL,";
            command.CommandText += " `world` text NOT NULL,";
            command.CommandText += " `triggered` INTEGER NOT NULL";
            command.CommandText += ")";
            command.ExecuteNonQuery();


            command.CommandText  = "CREATE TABLE IF NOT EXISTS `world_container_items` (";
            command.CommandText += " `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,";
            command.CommandText += " `containerid` INTEGER NOT NULL,";
            command.CommandText += " `item` text NOT NULL,";
            command.CommandText += " `amount` INTEGER NOT NULL";
            command.CommandText += ")";
            command.ExecuteNonQuery();

            command.Dispose();
        }
Example #9
0
 public void Dispose()
 {
     try
     {
         if (_SqlTransaction != null)
         {
             _SqlTransaction.Commit();
             _SqlTransaction.Dispose();
         }
         if (_SqlCommand != null)
         {
             _SqlCommand.Dispose();
         }
         if (_SqlConnection != null)
         {
             _SqlConnection.Dispose();
         }
     }
     catch { }
 }
Example #10
0
        public static void Execute(string command, Object obj, Dictionary<string, DbType> lookup)
        {
            SqliteConnection conn = new SqliteConnection (data_source);
            SqliteCommand cmd;

            conn.Open ();
            cmd = new SqliteCommand (command, conn);

            try {
                if (obj != null)
                    Database.AddParameters (cmd, obj, lookup);
                cmd.ExecuteNonQuery ();
            } catch (KeyNotFoundException) {
                Log.Warning ("Missing a parameter somewhere; not executing SQL statement");
            } catch (Exception e) {
                Log.Exception ("Exception occurred while executing query", e);
            } finally {
                cmd.Dispose ();
                conn.Dispose ();
            }
        }
Example #11
0
        public void Comment(GUImain gui, SqliteConnection connection, String name, String guid, String mode)
        {
            this.gui = gui;
            this.connection = connection;
            this.Text = "Comment " + name;
            this.guid = guid;
            this.mode = mode;

            SqliteCommand command = new SqliteCommand(connection);
            command.CommandText = "SELECT comment FROM comments WHERE guid = @guid";
            command.Parameters.Add(new SqliteParameter("@guid", guid));

            SqliteDataReader reader = command.ExecuteReader();

            if (reader.Read())
                input.Text = gui.GetSafeString(reader, 0);

            reader.Close();
            reader.Dispose();
            command.Dispose();
        }
        private void DoExpire()
        {
            SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now', 'localtime')");
            ExecuteNonQuery(cmd, m_Connection);

            cmd.Dispose();

            m_LastExpire = System.Environment.TickCount;
        }
        public bool SetToken(UUID principalID, string token, int lifetime)
        {
            if (System.Environment.TickCount - m_LastExpire > 30000)
                DoExpire();

            SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() + 
                "', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))");

            if (ExecuteNonQuery(cmd, m_Connection) > 0)
            {
                cmd.Dispose();
                return true;
            }

            cmd.Dispose();
            return false;
        }
        public bool CheckToken(UUID principalID, string token, int lifetime)
        {
            if (System.Environment.TickCount - m_LastExpire > 30000)
                DoExpire();

            SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() + 
                " minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')");

            if (ExecuteNonQuery(cmd, m_Connection) > 0)
            {
                cmd.Dispose();
                return true;
            }

            cmd.Dispose();

            return false;
        }
Example #15
0
        private static void CreateCreditsRessourcesDB()
        {
            SQLiteConnection connection = new SQLiteConnection();
            connection.ConnectionString = "Data Source=" + _CreditsRessourcesFilePath;
            SQLiteCommand command;

            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                return;
            }

            command = new SQLiteCommand(connection);

            command.CommandText = "CREATE TABLE IF NOT EXISTS Version ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Value INTEGER NOT NULL);";
            command.ExecuteNonQuery();

            command.CommandText = "INSERT INTO Version (id, Value) VALUES(NULL, " + CSettings.iDatabaseCreditsRessourcesVersion.ToString() + ")";
            command.ExecuteNonQuery();

            command.CommandText = "CREATE TABLE IF NOT EXISTS Images ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
                "Path TEXT NOT NULL, width INTEGER NOT NULL, height INTEGER NOT NULL);";
            command.ExecuteNonQuery();

            command.CommandText = "CREATE TABLE IF NOT EXISTS ImageData ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
                "ImageID INTEGER NOT NULL, Data BLOB NOT NULL);";
            command.ExecuteNonQuery();

            command.Dispose();
            connection.Close();
            connection.Dispose();
        }
        public void SqliteInsert10000Entries()
        {
            using (var conn = new SqliteConnection("URI=" + _db)) {
                SqliteCommand c;
                conn.Open ();
                for (int i = 1; i < 10001; i++) {

                    c = new SqliteCommand ( String.Format("INSERT INTO DataIndex (SearchKey, Name, Email) VALUES ({0}, '{1}', '{2}')", i, "Name " + i, "Email" + i) , conn );
                        c.ExecuteNonQuery ();
                        c.Dispose();

                    #if DEBUG
                    Console.WriteLine("INSERT: {0}", i);
                    #endif
                }
                conn.Close();
            }
            Assert.IsTrue(true);
        }
Example #17
0
        /// <summary>
        /// Converts a USDX 1.1 database into the Vocaluxe format
        /// </summary>
        /// <param name="FilePath">Database file path</param>
        /// <returns>True if succeeded</returns>
        private static bool ConvertFrom110(string FilePath)
        {
            SQLiteConnection connection = new SQLiteConnection();
            connection.ConnectionString = "Data Source=" + FilePath;
            SQLiteCommand command;

            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                return false;
            }

            command = new SQLiteCommand(connection);

            //The USDX database has no column for LineNr, Medley and Duet so just fill 0 in there
            command.CommandText = "INSERT INTO Scores (SongID, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongID, Player, Score, '0', Date, '0', '0', Difficulty from US_Scores";
            command.ExecuteNonQuery();

            command.CommandText = "INSERT INTO Songs SELECT ID, Artist, Title, TimesPlayed from US_Songs";
            command.ExecuteNonQuery();

            List<SData> scores = new List<SData>();
            List<SData> songs = new List<SData>();

            SQLiteDataReader reader = null;
            command.CommandText = "SELECT id, PlayerName, Date FROM Scores";
            try
            {
                reader = command.ExecuteReader();
            }
            catch (Exception)
            {
                throw;
            }

            if (reader != null && reader.HasRows)
            {
                while (reader.Read())
                {
                    SData data = new SData();
                    data.id = reader.GetInt32(0);
                    data.str1 = reader.GetString(1);
                    data.ticks = UnixTimeToTicks((int)reader.GetInt64(2));

                    scores.Add(data);
                }
                reader.Close();
            }

            command.CommandText = "SELECT id, Artist, Title FROM Songs";
            try
            {
                reader = command.ExecuteReader();
            }
            catch (Exception)
            {
                throw;
            }

            if (reader != null && reader.HasRows)
            {
                while (reader.Read())
                {
                    SData data = new SData();
                    data.id = reader.GetInt32(0);
                    data.str1 = reader.GetString(1);
                    data.str2 = reader.GetString(2);
                    songs.Add(data);
                }
                reader.Close();
            }

            reader.Dispose();

            SQLiteTransaction _Transaction = connection.BeginTransaction();
            // update Title and Artist strings
            foreach (SData data in songs)
            {
                command.CommandText = "UPDATE Songs SET [Artist] = @artist, [Title] = @title WHERE [ID] = @id";
                command.Parameters.Add("@title", System.Data.DbType.String, 0).Value = data.str2;
                command.Parameters.Add("@artist", System.Data.DbType.String, 0).Value = data.str1;
                command.Parameters.Add("@id", System.Data.DbType.Int32, 0).Value = data.id;
                command.ExecuteNonQuery();
            }

            // update player names
            foreach (SData data in scores)
            {
                command.CommandText = "UPDATE Scores SET [PlayerName] = @player, [Date] = @date WHERE [id] = @id";
                command.Parameters.Add("@player", System.Data.DbType.String, 0).Value = data.str1;
                command.Parameters.Add("@date", System.Data.DbType.Int64, 0).Value = data.ticks;
                command.Parameters.Add("@id", System.Data.DbType.Int32, 0).Value = data.id;
                command.ExecuteNonQuery();
            }
            _Transaction.Commit();

            //Delete old tables after conversion
            command.CommandText = "DROP TABLE US_Scores;";
            command.ExecuteNonQuery();

            command.CommandText = "DROP TABLE US_Songs;";
            command.ExecuteNonQuery();

            command.CommandText = "DROP TABLE us_statistics_info;";
            command.ExecuteNonQuery();

            //This versioning is not used in Vocaluxe so reset it to 0
            command.CommandText = "PRAGMA user_version = 0";
            command.ExecuteNonQuery();

            command.Dispose();
            connection.Close();
            connection.Dispose();

            return true;
        }
Example #18
0
        private static bool GetDataBaseSongInfos(int SongID, out string Artist, out string Title, out int NumPlayed, string FilePath)
        {
            Artist = String.Empty;
            Title = String.Empty;
            NumPlayed = 0;

            SQLiteConnection connection = new SQLiteConnection();
            connection.ConnectionString = "Data Source=" + FilePath;
            SQLiteCommand command;

            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                return false;
            }

            command = new SQLiteCommand(connection);
            command.CommandText = "SELECT Artist, Title, NumPlayed FROM Songs WHERE [id] = @id";
            command.Parameters.Add("@id", System.Data.DbType.String, 0).Value = SongID;

            SQLiteDataReader reader = null;
            try
            {
                reader = command.ExecuteReader();
            }
            catch (Exception)
            {
                return false;
            }

            if (reader != null && reader.HasRows)
            {
                reader.Read();
                Artist = reader.GetString(0);
                Title = reader.GetString(1);
                NumPlayed = reader.GetInt32(2);
                reader.Close();
                reader.Dispose();

                command.Dispose();
                connection.Close();
                connection.Dispose();
                return true;
            }
            else
            {
                if (reader != null)
                    reader.Close();
            }

            command.Dispose();
            connection.Close();
            connection.Dispose();

            return false;
        }
        /// <summary>
        /// see IRegionDatastore
        /// </summary>
        /// <param name="primID"></param>
        /// <param name="items"></param>
        public void StorePrimInventory(UUID primID, ICollection<TaskInventoryItem> items)
        {
//            m_log.DebugFormat(":[SQLITE REGION DB]: Entered StorePrimInventory with prim ID {0}", primID);

            RemoveItems(primID);

            using (SqliteCommand cmd = new SqliteCommand())
            {
                if (items.Count == 0)
                    return;

                cmd.CommandText = "insert into primitems (" +
                        "invType, assetType, name, " +
                        "description, creationDate, nextPermissions, " +
                        "currentPermissions, basePermissions, " +
                        "everyonePermissions, groupPermissions, " +
                        "flags, itemID, primID, assetID, " +
                        "parentFolderID, creatorID, ownerID, " +
                        "groupID, lastOwnerID) values (:invType, " +
                        ":assetType, :name, :description, " +
                        ":creationDate, :nextPermissions, " +
                        ":currentPermissions, :basePermissions, " +
                        ":everyonePermissions, :groupPermissions, " +
                        ":flags, :itemID, :primID, :assetID, " +
                        ":parentFolderID, :creatorID, :ownerID, " +
                        ":groupID, :lastOwnerID)";
                cmd.Connection = m_conn;

                foreach (TaskInventoryItem item in items)
                {
                    cmd.Parameters.Clear();

                    FillItemCommand(cmd, item);

                    cmd.ExecuteNonQuery();
                }

                cmd.Dispose();
            }
        }
Example #20
0
        private static int GetDataBaseSongID(string Artist, string Title, string FilePath, int DefNumPlayed)
        {
            SQLiteConnection connection = new SQLiteConnection();
            connection.ConnectionString = "Data Source=" + FilePath;
            SQLiteCommand command;

            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                return -1;
            }

            command = new SQLiteCommand(connection);
            int id = GetDataBaseSongID(Artist, Title, DefNumPlayed, command);
            command.Dispose();
            connection.Close();
            connection.Dispose();

            return id;
        }
        public override long InsertWithOnConflict (String table, String nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy)
        {
            if (!String.IsNullOrWhiteSpace(nullColumnHack)) {
                var e = new InvalidOperationException("{0} does not support the 'nullColumnHack'.".Fmt(Tag));
                Log.E(Tag, "Unsupported use of nullColumnHack", e);
                throw e;
            }

            var command = GetInsertCommand(table, initialValues, conflictResolutionStrategy);

            var lastInsertedId = -1L;
            try {
                command.ExecuteNonQuery();

                // Get the new row's id.
                // TODO.ZJG: This query should ultimately be replaced with a call to sqlite3_last_insert_rowid.
                var lastInsertedIndexCommand = new SqliteCommand("select last_insert_rowid()", Connection, currentTransaction);
                lastInsertedId = (Int64)lastInsertedIndexCommand.ExecuteScalar();
                lastInsertedIndexCommand.Dispose();
                if (lastInsertedId == -1L) {
                    Log.E(Tag, "Error inserting " + initialValues + " using " + command.CommandText);
                } else {
                    Log.V(Tag, "Inserting row " + lastInsertedId + " from " + initialValues + " using " + command.CommandText);
                }
            } catch (Exception ex) {
                Log.E(Tag, "Error inserting into table " + table, ex);
            } finally {
                command.Dispose();
            }
            return lastInsertedId;
        }
		///////////////////////////////////////////////////////////////////

		// Return all attributes in the attributes database, used for merging

		private ICollection ReadAllAttributes () 
		{
			ArrayList attributes = new ArrayList ();
			
			SqliteCommand command;
			SqliteDataReader reader;
				
			lock (connection) {
				command = new SqliteCommand ();
				command.Connection = connection;
				command.CommandText =
					"SELECT unique_id, directory, filename, last_mtime, last_attrtime, filter_name, filter_version " +
					"FROM file_attributes";
				
				reader = SqliteUtils.ExecuteReaderOrWait (command);
				
				while (SqliteUtils.ReadOrWait (reader)) {
					attributes.Add (GetFromReader (reader));
				}
				reader.Close ();
				command.Dispose ();
			}
			
			return attributes;
		}
Example #23
0
        public static int AddScore(string PlayerName, int Score, int LineNr, long Date, int Medley, int Duet, int ShortSong, int Diff,
            string Artist, string Title, int NumPlayed, string FilePath)
        {
            SPlayer player = new SPlayer();
            player.Name = PlayerName;
            player.Points = Score;
            player.LineNr = LineNr;
            player.DateTicks = Date;
            player.Medley = (Medley == 1);
            player.Duet = (Duet == 1);
            player.ShortSong = (ShortSong == 1);
            player.Difficulty = (EGameDifficulty)Diff;

            SQLiteConnection connection = new SQLiteConnection();
            SQLiteCommand command;

            connection.ConnectionString = "Data Source=" + FilePath;
            

            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                return -1;
            }

            command = new SQLiteCommand(connection);

            int DataBaseSongID = GetDataBaseSongID(Artist, Title, NumPlayed, command);
            int result = AddScore(player, command, DataBaseSongID);

            command.Dispose();
            connection.Close();
            connection.Dispose();

            return result;
        }
Example #24
0
        private static bool ConvertV1toV2(SQLiteConnection connection)
        {
            SQLiteCommand command;

            command = new SQLiteCommand(connection);

            command.CommandText = "ALTER TABLE Scores ADD ShortSong INTEGER";
            command.ExecuteNonQuery();
            command.CommandText = "UPDATE Scores SET [ShortSong] = @ShortSong";
            command.Parameters.Add("@ShortSong", System.Data.DbType.Int32, 0).Value = 0;
            command.ExecuteNonQuery();
            command.CommandText = "UPDATE Version SET [Value] = @version";
            command.Parameters.Add("@version", System.Data.DbType.Int32, 0).Value = 2;
            command.ExecuteNonQuery();
            command.Dispose();

            return true;
        }
Example #25
0
        /// <summary>
        /// Converts a USDX 1.01 or CMD 1.01 database to Vocaluxe format
        /// </summary>
        /// <param name="FilePath">Database file path</param>
        /// <returns>True if succeeded</returns>
        private static bool ConvertFrom101(string FilePath)
        {
            SQLiteConnection connection = new SQLiteConnection();
            connection.ConnectionString = "Data Source=" + FilePath;
            SQLiteCommand command;
            SQLiteDataReader reader = null;

            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                return false;
            }

            command = new SQLiteCommand(connection);

            command.CommandText = "PRAGMA table_info(US_Scores);";
            reader = command.ExecuteReader();


            bool dateExists = false;

            //Check for column Date
            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    if (reader.GetName(i) == "name")
                    {
                        if (reader.GetString(i) == "Date")
                            dateExists = true;
                        break;
                    }
                }
            }


            reader.Close();

            //This is a USDX 1.01 DB
            if (!dateExists)
                command.CommandText = "INSERT INTO Scores (SongID, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongID, Player, Score, '0', '0', '0', '0', Difficulty from US_Scores";
            else // This is a CMD 1.01 DB
                command.CommandText = "INSERT INTO Scores (SongID, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongID, Player, Score, '0', Date, '0', '0', Difficulty from US_Scores";
            command.ExecuteNonQuery();

            command.CommandText = "INSERT INTO Songs SELECT ID, Artist, Title, TimesPlayed from US_Songs";
            command.ExecuteNonQuery();

            // convert from CP1252 to UTF8
            List<SData> scores = new List<SData>();
            List<SData> songs = new List<SData>();

            Sqlite3.sqlite3 OldDB;
            int res = Sqlite3.sqlite3_open(FilePath, out OldDB);

            if (res != Sqlite3.SQLITE_OK)
            {
                CLog.LogError("Error opening Database: " + FilePath + " (" + Sqlite3.sqlite3_errmsg(OldDB) + ")");
            }
            else
            {
                Sqlite3.Vdbe Stmt = new Sqlite3.Vdbe();
                res = Sqlite3.sqlite3_prepare_v2(OldDB, "SELECT id, Artist, Title FROM Songs", -1, ref Stmt, 0);

                if (res != Sqlite3.SQLITE_OK)
                {
                    CLog.LogError("Error query Database: " + FilePath + " (" + Sqlite3.sqlite3_errmsg(OldDB) + ")");
                }
                else
                {
                    //Sqlite3.sqlite3_step(Stmt);

                    Encoding UTF8 = Encoding.UTF8;
                    Encoding CP1252 = Encoding.GetEncoding(1252);

                    while (Sqlite3.sqlite3_step(Stmt) == Sqlite3.SQLITE_ROW)
                    {
                        SData data = new SData();

                        data.id = Sqlite3.sqlite3_column_int(Stmt, 0);

                        byte[] bytes = Sqlite3.sqlite3_column_rawbytes(Stmt, 1);
                        if (bytes != null)
                            data.str1 = UTF8.GetString(Encoding.Convert(CP1252, UTF8, bytes));
                        else
                            data.str1 = "Someone";

                        bytes = Sqlite3.sqlite3_column_rawbytes(Stmt, 2);
                        if (bytes != null)
                            data.str2 = UTF8.GetString(Encoding.Convert(CP1252, UTF8, bytes));
                        else
                            data.str2 = "Someone";

                        songs.Add(data);
                    }
                    Sqlite3.sqlite3_finalize(Stmt);
                }

                Stmt = new Sqlite3.Vdbe();

                if (!dateExists)
                    res = Sqlite3.sqlite3_prepare_v2(OldDB, "SELECT id, PlayerName FROM Scores", -1, ref Stmt, 0);
                else
                    res = Sqlite3.sqlite3_prepare_v2(OldDB, "SELECT id, PlayerName, Date FROM Scores", -1, ref Stmt, 0);

                if (res != Sqlite3.SQLITE_OK)
                {
                    CLog.LogError("Error query Database: " + FilePath + " (" + Sqlite3.sqlite3_errmsg(OldDB) + ")");
                }
                else
                {
                    //Sqlite3.sqlite3_step(Stmt);

                    Encoding UTF8 = Encoding.UTF8;
                    Encoding CP1252 = Encoding.GetEncoding(1252);

                    while (Sqlite3.sqlite3_step(Stmt) == Sqlite3.SQLITE_ROW)
                    {
                        SData data = new SData();

                        data.id = Sqlite3.sqlite3_column_int(Stmt, 0);

                        byte[] bytes = Sqlite3.sqlite3_column_rawbytes(Stmt, 1);
                        if (bytes != null)
                            data.str1 = UTF8.GetString(Encoding.Convert(CP1252, UTF8, bytes));
                        else
                            data.str1 = "Someone";

                        if (dateExists)
                            data.ticks = UnixTimeToTicks(Sqlite3.sqlite3_column_int(Stmt, 2));

                        scores.Add(data);
                    }
                    Sqlite3.sqlite3_finalize(Stmt);
                }
            }
            Sqlite3.sqlite3_close(OldDB);

            SQLiteTransaction _Transaction = connection.BeginTransaction();      
             
            // update Title and Artist strings
            foreach (SData data in songs)
            {
                command.CommandText = "UPDATE Songs SET [Artist] = @artist, [Title] = @title WHERE [ID] = @id";
                command.Parameters.Add("@title", System.Data.DbType.String, 0).Value = data.str2;
                command.Parameters.Add("@artist", System.Data.DbType.String, 0).Value = data.str1;
                command.Parameters.Add("@id", System.Data.DbType.Int32, 0).Value = data.id;
                command.ExecuteNonQuery();
            }           

            // update player names
            foreach (SData data in scores)
            {
                if (!dateExists)
                    command.CommandText = "UPDATE Scores SET [PlayerName] = @player WHERE [id] = @id";
                else
                {
                    command.CommandText = "UPDATE Scores SET [PlayerName] = @player, [Date] = @date WHERE [id] = @id";
                    command.Parameters.Add("@date", System.Data.DbType.Int64, 0).Value = data.ticks;
                }
                command.Parameters.Add("@player", System.Data.DbType.String, 0).Value = data.str1;
                command.Parameters.Add("@id", System.Data.DbType.Int32, 0).Value = data.id;
                command.ExecuteNonQuery();
            }
            _Transaction.Commit();

            //Delete old tables after conversion
            command.CommandText = "DROP TABLE US_Scores;";
            command.ExecuteNonQuery();

            command.CommandText = "DROP TABLE US_Songs;";
            command.ExecuteNonQuery();

            reader.Dispose();
            command.Dispose();
            connection.Close();
            connection.Dispose();

            return true;
        }
Example #26
0
 public void NonQuery(string data, params object[] parameters)
 {
     Linux.SqliteCommand cmd = new Linux.SqliteCommand(data, m_dbConnection);
     int i = 0;
     foreach (var param in parameters)
     {
         cmd.Parameters.Add(new Linux.SqliteParameter(i++.ToString(), param));
     }
     cmd.ExecuteNonQuery();
     cmd.Dispose();
 }
Example #27
0
        private static void CreateHighscoreDBV1(string FilePath)
        {
            SQLiteConnection connection = new SQLiteConnection();
            connection.ConnectionString = "Data Source=" + FilePath;
            SQLiteCommand command;

            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                return;
            }

            command = new SQLiteCommand(connection);

            command.CommandText = "CREATE TABLE IF NOT EXISTS Version ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Value INTEGER NOT NULL);";
            command.ExecuteNonQuery();

            command.CommandText = "INSERT INTO Version (id, Value) VALUES(NULL, 1 )";
            command.ExecuteNonQuery();

            command.CommandText = "CREATE TABLE IF NOT EXISTS Songs ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
                "Artist TEXT NOT NULL, Title TEXT NOT NULL, NumPlayed INTEGER);";
            command.ExecuteNonQuery();

            command.CommandText = "CREATE TABLE IF NOT EXISTS Scores ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
                "SongID INTEGER NOT NULL, PlayerName TEXT NOT NULL, Score INTEGER NOT NULL, LineNr INTEGER NOT NULL, Date BIGINT NOT NULL, " +
                "Medley INTEGER NOT NULL, Duet INTEGER NOT NULL, Difficulty INTEGER NOT NULL);";
            command.ExecuteNonQuery();

            command.Dispose();
            connection.Close();
            connection.Dispose();
        }
Example #28
0
 public List<Dictionary<string, object>> QueryAll(string data, List<string> fields, params object[] parameters)
 {
     Linux.SqliteCommand cmd = new Linux.SqliteCommand(data, m_dbConnection);
     int i = 0;
     foreach (var param in parameters)
     {
         cmd.Parameters.Add(new Linux.SqliteParameter(i++.ToString(), param));
     }
     Linux.SqliteDataReader reader = cmd.ExecuteReader();
     List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
     while (reader.Read())
     {
         Dictionary<string, object> dict = new Dictionary<string, object>();
         foreach (string field in fields)
             dict[field] = reader[field];
         list.Add(dict);
     }
     reader.Close();
     cmd.Dispose();
     return list;
 }
Example #29
0
        /// <summary>
        /// Creates a new Vocaluxe Database if no file exists. Converts an existing old Ultrastar Deluxe highscore database into vocaluxe format.
        /// </summary>
        /// <param name="FilePath">Database file path</param>
        /// <returns></returns>
        private static bool CreateOrConvert(string FilePath)
        {
            SQLiteConnection connection = new SQLiteConnection();
            connection.ConnectionString = "Data Source=" + FilePath;
            SQLiteCommand command;

            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                return false;
            }

            SQLiteDataReader reader = null;
            command = new SQLiteCommand(connection);

            command.CommandText = "PRAGMA user_version";
            reader = command.ExecuteReader();
            reader.Read();

            int version = reader.GetInt32(0);

            reader.Close();
            reader.Dispose();

            //Check if old scores table exists
            command.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='US_Scores';";
            reader = command.ExecuteReader();
            reader.Read();
            bool scoresTableExists = reader.HasRows;

            reader.Close();
            reader.Dispose();

            command.CommandText = "SELECT Value FROM Version";
            reader = null;

            try
            {
                reader = command.ExecuteReader();
            }
            catch (Exception)
            {
                ;
            }

            if (reader == null)
            {
                // create new database/tables
                if (version == 1) //Check for USDX 1.1 DB
                {
                    CreateHighscoreDBV1(FilePath);
                    ConvertFrom110(FilePath);
                    UpdateDatabase(1, connection);
                }
                else if (version == 0 && scoresTableExists) //Check for USDX 1.01 or CMD Mod DB
                {
                    CreateHighscoreDBV1(FilePath);
                    ConvertFrom101(FilePath);
                    UpdateDatabase(1, connection);
                }
                else
                    CreateHighscoreDB(FilePath);
            }
            else if (reader.FieldCount == 0)
            {
                // create new database/tables
                if (version == 1) //Check for USDX 1.1 DB
                {
                    CreateHighscoreDBV1(FilePath);
                    ConvertFrom110(FilePath);
                    UpdateDatabase(1, connection);
                }
                else if (version == 0 && scoresTableExists) //Check for USDX 1.01 or CMD Mod DB
                {
                    CreateHighscoreDBV1(FilePath);
                    ConvertFrom101(FilePath);
                    UpdateDatabase(1, connection);
                }
                else
                    CreateHighscoreDB(FilePath);
            }
            else
            {
                reader.Read();
                int CurrentVersion = reader.GetInt32(0);
                if (CurrentVersion < CSettings.iDatabaseHighscoreVersion)
                {
                    // update database
                    UpdateDatabase(CurrentVersion, connection);
                }
            }

            if (reader != null)
            {
                reader.Close();
                reader.Dispose();
            }

            command.Dispose();

            connection.Close();
            connection.Dispose();

            return true;
        }
		public FileAttributesStore_Sqlite (string directory, string index_fingerprint)
		{
			bool create_new_db = false;
			path_flags = new BitArray (65536);

			if (! File.Exists (GetDbPath (directory))) {
				create_new_db = true;
			} else {
				
				// Funky logic here to deal with sqlite versions.
				//
				// When sqlite 3 tries to open an sqlite 2 database,
				// it will throw an SqliteException with SqliteError
				// NOTADB when trying to execute a command.
				//
				// When sqlite 2 tries to open an sqlite 3 database,
				// it will throw an ApplicationException when it
				// tries to open the database.

				try {
					connection = Open (directory);
				} catch (ApplicationException) {
					Logger.Log.Warn ("Likely sqlite database version mismatch trying to open {0}.  Purging.", GetDbPath (directory));
					create_new_db = true;
				}

				if (! create_new_db) {
					SqliteCommand command;
					SqliteDataReader reader = null;
					int stored_version = 0;
					string stored_fingerprint = null;


					command = new SqliteCommand ();
					command.Connection = connection;
					command.CommandText =
						"SELECT version, fingerprint FROM db_info";
					try {
						reader = SqliteUtils.ExecuteReaderOrWait (command);
					} catch (Exception ex) {
						Logger.Log.Warn ("Likely sqlite database version mismatch trying to read from {0}.  Purging.", GetDbPath (directory));
						create_new_db = true;
					}
					if (reader != null && ! create_new_db) {
						if (SqliteUtils.ReadOrWait (reader)) {
							stored_version = reader.GetInt32 (0);
							stored_fingerprint = reader.GetString (1);
						}
						reader.Close ();
					}
					command.Dispose ();

					if (VERSION != stored_version
					    || (index_fingerprint != null && index_fingerprint != stored_fingerprint))
						create_new_db = true;
				}
			}

			if (create_new_db) {
				if (connection != null)
					connection.Dispose ();
				File.Delete (GetDbPath (directory));
				connection = Open (directory);

				SqliteUtils.DoNonQuery (connection,
							"CREATE TABLE db_info (             " +
							"  version       INTEGER NOT NULL,  " +
							"  fingerprint   TEXT NOT NULL    " +
							")");

				SqliteUtils.DoNonQuery (connection,
							"INSERT INTO db_info (version, fingerprint) VALUES (@version, @index_fingerprint)",
							new string [] {"@version", "@index_fingerprint"},
							new object [] {VERSION, index_fingerprint});

				SqliteUtils.DoNonQuery (connection,
							"CREATE TABLE file_attributes (         " +
							"  unique_id      TEXT NOT NULL,        " +
							"  directory      TEXT NOT NULL,        " +
							"  filename       TEXT NOT NULL,        " +
							"  last_mtime     TEXT NOT NULL,        " +
							"  last_attrtime  TEXT NOT NULL,        " +
							"  filter_name    TEXT NOT NULL,        " +
							"  filter_version TEXT NOT NULL,        " +
							"  UNIQUE (directory, filename)         " +
							")");
			} else {
				SqliteCommand command;
				SqliteDataReader reader;
				int count = 0;

				DateTime dt1 = DateTime.Now;

				// Select all of the files and use them to populate our bit-vector.
				command = new SqliteCommand ();
				command.Connection = connection;
				command.CommandText = "SELECT directory, filename FROM file_attributes";

				reader = SqliteUtils.ExecuteReaderOrWait (command);

				while (SqliteUtils.ReadOrWait (reader)) {

					string dir = reader.GetString (0);
					string file = reader.GetString (1);
					string path = Path.Combine (dir, file);
					SetPathFlag (path);
					++count;
				}

				reader.Close ();
				command.Dispose ();

				DateTime dt2 = DateTime.Now;

				Logger.Log.Debug ("Loaded {0} records from {1} in {2:0.000}s", 
						 count, GetDbPath (directory), (dt2 - dt1).TotalSeconds);
			}
			ReadCommand = new SqliteCommand (this.connection);
			ReadCommand.CommandText = "SELECT unique_id, directory, filename, last_mtime, last_attrtime, filter_name, filter_version " +
				"FROM file_attributes WHERE directory=@dir AND filename=@fname";
			InsertCommand = new SqliteCommand (this.connection);
			InsertCommand.CommandText = "INSERT OR REPLACE INTO file_attributes " +
							" (unique_id, directory, filename, last_mtime, last_attrtime, filter_name, filter_version) " +
							" VALUES (@unique_id, @directory, @filename, @last_mtime, @last_attrtime, @filter_name, @filter_version)";
			DeleteCommand = new SqliteCommand (this.connection);
			DeleteCommand.CommandText = "DELETE FROM file_attributes WHERE directory=@directory AND filename=@filename";
		}
Example #31
0
        private static bool InitCreditsRessourcesDB()
        {
            SQLiteConnection connection = new SQLiteConnection();
            connection.ConnectionString = "Data Source=" + _CreditsRessourcesFilePath;
            SQLiteCommand command;

            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                return false;
            }

            command = new SQLiteCommand(connection);
            command.CommandText = "SELECT Value FROM Version";

            SQLiteDataReader reader = null;

            try
            {
                reader = command.ExecuteReader();
            }
            catch (Exception)
            {
                ;
            }

            if (reader == null)
            {
                // Log error
                CLog.LogError("Can't find Credits-DB!");
            }
            else if (reader.FieldCount == 0)
            {
                // Log error
                CLog.LogError("Can't find Credits-DB! Field-Count = 0");
            }
            else
            {
                reader.Read();

                if (reader.GetInt32(0) < CSettings.iDatabaseHighscoreVersion)
                {
                    // update database
                }
            }

            if (reader != null)
            {
                reader.Close();
                reader.Dispose();
            }

            command.Dispose();

            connection.Close();
            connection.Dispose();

            return true;
        }
        /// <summary>
        /// Adds an object into region storage
        /// </summary>
        /// <param name="obj">the object</param>
        /// <param name="regionUUID">the region UUID</param>
        public void StoreObject(SceneObjectGroup obj, UUID regionUUID)
        {
            uint flags = obj.RootPart.GetEffectiveObjectFlags();

            // Eligibility check
            //
            if ((flags & (uint)PrimFlags.Temporary) != 0)
                return;
            if ((flags & (uint)PrimFlags.TemporaryOnRez) != 0)
                return;

            using (SqliteCommand cmd = new SqliteCommand())
            {
                cmd.Connection = m_conn;
                foreach (SceneObjectPart prim in obj.ChildrenList)
                {
                    try
                    {
                        cmd.Parameters.Clear();

                        //Remove the old prim
                        cmd.CommandText = "delete from prims where UUID = '" + prim.UUID + "' OR SceneGroupID = '" + prim.UUID + "'";
                        cmd.ExecuteNonQuery();

                        cmd.CommandText = "replace into prims (" +
                                "UUID, CreationDate, " +
                                "Name, Text, Description, " +
                                "SitName, TouchName, ObjectFlags, " +
                                "OwnerMask, NextOwnerMask, GroupMask, " +
                                "EveryoneMask, BaseMask, PositionX, " +
                                "PositionY, PositionZ, GroupPositionX, " +
                                "GroupPositionY, GroupPositionZ, VelocityX, " +
                                "VelocityY, VelocityZ, AngularVelocityX, " +
                                "AngularVelocityY, AngularVelocityZ, " +
                                "AccelerationX, AccelerationY, " +
                                "AccelerationZ, RotationX, " +
                                "RotationY, RotationZ, " +
                                "RotationW, SitTargetOffsetX, " +
                                "SitTargetOffsetY, SitTargetOffsetZ, " +
                                "SitTargetOrientW, SitTargetOrientX, " +
                                "SitTargetOrientY, SitTargetOrientZ, " +
                                "RegionUUID, CreatorID, " +
                                "OwnerID, GroupID, " +
                                "LastOwnerID, SceneGroupID, " +
                                "PayPrice, PayButton1, " +
                                "PayButton2, PayButton3, " +
                                "PayButton4, LoopedSound, " +
                                "LoopedSoundGain, TextureAnimation, " +
                                "OmegaX, OmegaY, OmegaZ, " +
                                "CameraEyeOffsetX, CameraEyeOffsetY, " +
                                "CameraEyeOffsetZ, CameraAtOffsetX, " +
                                "CameraAtOffsetY, CameraAtOffsetZ, " +
                                "ForceMouselook, ScriptAccessPin, " +
                                "AllowedDrop, DieAtEdge, " +
                                "SalePrice, SaleType, " +
                                "ColorR, ColorG, ColorB, ColorA, " +
                                "ParticleSystem, ClickAction, Material, " +
                                "CollisionSound, CollisionSoundVolume, " +
                                "PassTouches, " +
                                "LinkNumber, VolumeDetect, Generic) values (" + ":UUID, " +
                                ":CreationDate, :Name, :Text, " +
                                ":Description, :SitName, :TouchName, " +
                                ":ObjectFlags, :OwnerMask, :NextOwnerMask, " +
                                ":GroupMask, :EveryoneMask, :BaseMask, " +
                                ":PositionX, :PositionY, :PositionZ, " +
                                ":GroupPositionX, :GroupPositionY, " +
                                ":GroupPositionZ, :VelocityX, " +
                                ":VelocityY, :VelocityZ, :AngularVelocityX, " +
                                ":AngularVelocityY, :AngularVelocityZ, " +
                                ":AccelerationX, :AccelerationY, " +
                                ":AccelerationZ, :RotationX, " +
                                ":RotationY, :RotationZ, " +
                                ":RotationW, :SitTargetOffsetX, " +
                                ":SitTargetOffsetY, :SitTargetOffsetZ, " +
                                ":SitTargetOrientW, :SitTargetOrientX, " +
                                ":SitTargetOrientY, :SitTargetOrientZ, " +
                                ":RegionUUID, :CreatorID, :OwnerID, " +
                                ":GroupID, :LastOwnerID, :SceneGroupID, " +
                                ":PayPrice, :PayButton1, :PayButton2, " +
                                ":PayButton3, :PayButton4, :LoopedSound, " +
                                ":LoopedSoundGain, :TextureAnimation, " +
                                ":OmegaX, :OmegaY, :OmegaZ, " +
                                ":CameraEyeOffsetX, :CameraEyeOffsetY, " +
                                ":CameraEyeOffsetZ, :CameraAtOffsetX, " +
                                ":CameraAtOffsetY, :CameraAtOffsetZ, " +
                                ":ForceMouselook, :ScriptAccessPin, " +
                                ":AllowedDrop, :DieAtEdge, :SalePrice, " +
                                ":SaleType, :ColorR, :ColorG, " +
                                ":ColorB, :ColorA, :ParticleSystem, " +
                                ":ClickAction, :Material, :CollisionSound, " +
                                ":CollisionSoundVolume, :PassTouches, :LinkNumber, :VolumeDetect, :Generic)";

                        FillPrimCommand(cmd, prim, obj.UUID, regionUUID);

                        cmd.ExecuteNonQuery();

                        cmd.Parameters.Clear();

                        cmd.CommandText = "replace into primshapes (" +
                                "UUID, Shape, ScaleX, ScaleY, " +
                                "ScaleZ, PCode, PathBegin, PathEnd, " +
                                "PathScaleX, PathScaleY, PathShearX, " +
                                "PathShearY, PathSkew, PathCurve, " +
                                "PathRadiusOffset, PathRevolutions, " +
                                "PathTaperX, PathTaperY, PathTwist, " +
                                "PathTwistBegin, ProfileBegin, ProfileEnd, " +
                                "ProfileCurve, ProfileHollow, Texture, " +
                                "ExtraParams, State) values (:UUID, " +
                                ":Shape, :ScaleX, :ScaleY, :ScaleZ, " +
                                ":PCode, :PathBegin, :PathEnd, " +
                                ":PathScaleX, :PathScaleY, " +
                                ":PathShearX, :PathShearY, " +
                                ":PathSkew, :PathCurve, :PathRadiusOffset, " +
                                ":PathRevolutions, :PathTaperX, " +
                                ":PathTaperY, :PathTwist, " +
                                ":PathTwistBegin, :ProfileBegin, " +
                                ":ProfileEnd, :ProfileCurve, " +
                                ":ProfileHollow, :Texture, :ExtraParams, " +
                                ":State)";

                        FillShapeCommand(cmd, prim);

                        cmd.ExecuteNonQuery();
                    }
                    catch( Exception ex)
                    {
                        string mes = ex.Message.Replace("\n", "");
                        mes = mes.Replace("\r", "");
                        m_log.Warn("[NxGSQLite]: Error saving prim " + mes);
                    }
                }
                cmd.Dispose();
            }
        }
Example #33
0
        public static void LoadScore(ref List<SScores> Score, SPlayer player)
        {
            SQLiteConnection connection = new SQLiteConnection();
            connection.ConnectionString = "Data Source=" + _HighscoreFilePath;
            SQLiteCommand command;

            Score = new List<SScores>();

            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                return;
            }

            command = new SQLiteCommand(connection);

            int Medley = 0;
            if (player.Medley)
                Medley = 1;

            int Duet = 0;
            if (player.Duet)
                Duet = 1;

            int ShortSong = 0;
            if (player.ShortSong)
                ShortSong = 1;

            int DataBaseSongID = GetDataBaseSongID(player, command);
            if (DataBaseSongID >= 0)
            {
                command.CommandText = "SELECT PlayerName, Score, Date, Difficulty, LineNr, id FROM Scores " +
                    "WHERE [SongID] = @SongID AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " +
                    "ORDER BY [Score] DESC";
                command.Parameters.Add("@SongID", System.Data.DbType.Int32, 0).Value = DataBaseSongID;
                command.Parameters.Add("@Medley", System.Data.DbType.Int32, 0).Value = Medley;
                command.Parameters.Add("@Duet", System.Data.DbType.Int32, 0).Value = Duet;
                command.Parameters.Add("@ShortSong", System.Data.DbType.Int32, 0).Value = ShortSong;

                SQLiteDataReader reader = null;
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (Exception)
                {
                    throw;
                }

                if (reader != null && reader.HasRows)
                {
                    while (reader.Read())
                    {
                        SScores score = new SScores();
                        score.Name = reader.GetString(0);
                        score.Score = reader.GetInt32(1);
                        score.Date = new DateTime(reader.GetInt64(2)).ToString("dd/MM/yyyy");
                        score.Difficulty = (EGameDifficulty)reader.GetInt32(3);
                        score.LineNr = reader.GetInt32(4);
                        score.ID = reader.GetInt32(5);

                        Score.Add(score);
                    }

                    reader.Close();
                    reader.Dispose();
                }

            }


            command.Dispose();
            connection.Close();
            connection.Dispose();
        }
Example #34
0
        /// <summary>
        /// Closes the datareader, potentially closing the connection as well if CommandBehavior.CloseConnection was specified.
        /// </summary>
        public override void Close()
        {
            try
            {
                if (_command != null)
                {
                    try
                    {
                        try
                        {
                            // Make sure we've not been canceled
                            if (_version != 0)
                            {
                                try
                                {
                                    while (NextResult())
                                    {
                                    }
                                }
                                catch
                                {
                                }
                            }
                            _command.ClearDataReader();
                        }
                        finally
                        {
                            // If the datareader's behavior includes closing the connection, then do so here.
                            if ((_commandBehavior & CommandBehavior.CloseConnection) != 0 && _command.Connection != null)
                            {
                                // We need to call Dispose on the command before we call Dispose on the Connection,
                                // otherwise we'll get a SQLITE_LOCKED exception.
                                var conn = _command.Connection;
                                _command.Dispose();
                                conn.Close();
                                _disposeCommand = false;
                            }
                        }
                    }
                    finally
                    {
                        if (_disposeCommand)
                        {
                            _command.Dispose();
                        }
                    }
                }

                _command         = null;
                _activeStatement = null;
                _fieldTypeArray  = null;
            }
            finally
            {
                if (_keyInfo != null)
                {
                    _keyInfo.Dispose();
                    _keyInfo = null;
                }
            }
        }
Example #35
0
        //If you want to add an image to db, call this method!
        private static bool AddImageToCreditsDB(String ImagePath)
        {
            bool result = false;
            STexture tex;

            if (File.Exists(ImagePath))
            {

                SQLiteConnection connection = new SQLiteConnection();
                connection.ConnectionString = "Data Source=" + _CreditsRessourcesFilePath;
                SQLiteCommand command;
                try
                {
                    connection.Open();
                }
                catch (Exception)
                {
                    return false;
                }
                command = new SQLiteCommand(connection);

                SQLiteDataReader reader = null;

                if (reader != null)
                    reader.Close();

                Bitmap origin;
                try
                {
                    origin = new Bitmap(ImagePath);
                }
                catch (Exception)
                {
                    CLog.LogError("Error loading Texture: " + ImagePath);
                    tex = new STexture(-1);

                    if (reader != null)
                    {
                        reader.Close();
                        reader.Dispose();
                    }
                    command.Dispose();
                    connection.Close();
                    connection.Dispose();

                    return false;
                }

                int w = origin.Width;
                int h = origin.Height;

                Bitmap bmp = new Bitmap(w, h);
                Graphics g = Graphics.FromImage(bmp);
                g.DrawImage(origin, new Rectangle(0, 0, w, h));
                g.Dispose();
                tex = CDraw.AddTexture(bmp);
                byte[] data = new byte[w * h * 4];

                BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                Marshal.Copy(bmp_data.Scan0, data, 0, w * h * 4);
                bmp.UnlockBits(bmp_data);
                bmp.Dispose();

                command.CommandText = "INSERT INTO Images (Path, width, height) " +
                    "VALUES (@path, " + w.ToString() + ", " + h.ToString() + ")";
                command.Parameters.Add("@path", System.Data.DbType.String, 0).Value = Path.GetFileName(ImagePath);
                command.ExecuteNonQuery();

                command.CommandText = "SELECT id FROM Images WHERE [Path] = @path";
                command.Parameters.Add("@path", System.Data.DbType.String, 0).Value = Path.GetFileName(ImagePath);
                reader = null;
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (Exception)
                {
                    throw;
                }

                if (reader != null)
                {
                    reader.Read();
                    int id = reader.GetInt32(0);
                    reader.Close();
                    command.CommandText = "INSERT INTO ImageData (ImageID, Data) " +
                    "VALUES ('" + id.ToString() + "', @data)";
                    command.Parameters.Add("@data", System.Data.DbType.Binary, 20).Value = data;
                    command.ExecuteReader();
                    result = true;
                }
            }

            return result;
        }