Exemplo n.º 1
0
        public WatchList()
        {
            _watchItemList = new List <WatchItem>();
            //_seriesList = new List<SeriesItem>();
            _sqlClient = new SQLiteClient(Config.GetFile(Config.Dir.Database, "MyTorrents.db3"));
            DatabaseUtility.SetPragmas(_sqlClient);

            if (!DatabaseUtility.TableExists(_sqlClient, "WatchList"))
            {
                SQLiteResultSet result = _sqlClient.Execute("CREATE TABLE WatchList (Search CHAR(256), Added BIGINT, Label CHAR(256) );");
            }
            if (!DatabaseUtility.TableExists(_sqlClient, "SeriesWatchList"))
            {
                SQLiteResultSet result = _sqlClient.Execute("CREATE TABLE SeriesWatchList (SeriesName CHAR(256), OriginalSeriesName CHAR(256), SeriesID CHAR(256), Added BIGINT, Quality CHAR(256), Tracker CHAR(256), Type CHAR(256), Source CHAR(256), Folder CHAR(256), IncludeSpecials CHAR (256));");
            }
            RSSChannelManager channelManager = RSSChannelManager.Instance();

            channelManager.RSSChannelUpdated += new RSSChannelUpdated(channelManager_RSSChannelUpdated);
            System.Timers.Timer SearchTimer = new System.Timers.Timer(30 * 60 * 1000);
            SearchTimer.Elapsed += new ElapsedEventHandler(SearchTimer_Elapsed);
            SearchTimer.Start();
            if (IsMPTVSeriesAvailable())
            {
                MPTVSeriesWorker.DoWork             += new DoWorkEventHandler(MPTVSeriesWorker_DoWork);
                MPTVSeriesWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(MPTVSeriesWorker_Completed);
                MPTVSeriesWorker.RunWorkerAsync();
            }
        }
Exemplo n.º 2
0
        private void UpgradeDBV13_V14()
        {
            try
            {
                // First rename the tracks table
                string strSQL = "alter table tracks rename to tracksV13";
                MusicDbClient.Execute(strSQL);

                // Now call the Create Database function to create the new table
                if (!CreateDatabase())
                {
                    Log.Error("MusicDatabase: Error creating new database. aborting upgrade}");
                    return;
                }

                // Now copy the content of the old V13 tracks table to the new V14 tracks table
                strSQL =
                    "insert into tracks select idTrack, strPath, strArtist, strAlbumArtist, strAlbum, strGenre, strComposer, strConductor, " +
                    "strTitle, iTRack, iNumTracks, iDuration, iYear, iTimesPlayed, iRating, iFavorite, iResumeAt, iDisc, iNumDisc, " +
                    "strLyrics, strComment, '', '', '', '', '','','','',''," +
                    "strFileType, strFullCodec, strBitRateMode, iBPM, iBitRate, iChannels, iSampleRate, dateLastPlayed, dateAdded from tracksV13";

                MusicDbClient.Execute(strSQL);

                strSQL = "drop table tracksV13";
                MusicDbClient.Execute(strSQL);

                Log.Info("MusicDatabase: Finished upgrading database.");
            }
            catch (Exception ex)
            {
                Log.Error("MusicDatabase: exception while renaming table:{0} stack:{1}", ex.Message, ex.StackTrace);
            }
        }
Exemplo n.º 3
0
 public static void SetPragmas(SQLiteClient m_db)
 {
     m_db.Execute("PRAGMA encoding = \"UTF-8\"");
     m_db.Execute("PRAGMA cache_size=-5000"); // abs(-5000*1024) Bytes of memory
     m_db.Execute("PRAGMA page_size=4096");   // Windows fastest value 4096
     m_db.Execute("PRAGMA synchronous='OFF'");
     m_db.Execute("PRAGMA auto_vacuum=0");
 }
        private int AddPath(string FilteredPath)
        {
            if (string.IsNullOrEmpty(FilteredPath))
            {
                return(-1);
            }

            if (null == m_db)
            {
                return(-1);
            }
            try
            {
                SQLiteResultSet results;
                string          strSQL = String.Format("select * from tblPath where strPath like '{0}'", FilteredPath);
                results = m_db.Execute(strSQL);
                if (results.Rows.Count == 0)
                {
                    // doesnt exists, add it
                    strSQL = String.Format("insert into tblPath (idPath, strPath) values ( NULL, '{0}' )", FilteredPath);
                    m_db.Execute(strSQL);
                    return(m_db.LastInsertID());
                }
                else
                {
                    return(Int32.Parse(Get(results, 0, "idPath")));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
            return(-1);
        }
Exemplo n.º 5
0
        private void AddToAlreadyDownloaded(string hash)
        {
            SQLiteClient sqlClient = new SQLiteClient(Config.GetFile(Config.Dir.Database, "MyTorrents.db3"));

            DatabaseUtility.SetPragmas(sqlClient);

            if (!DatabaseUtility.TableExists(sqlClient, "Downloaded"))
            {
                SQLiteResultSet result = sqlClient.Execute("CREATE TABLE Downloaded (Hash CHAR(4096) );");
            }
            sqlClient.Execute(String.Format("INSERT INTO Downloaded VALUES (\"{0}\");", hash));
            sqlClient.Close();
        }
Exemplo n.º 6
0
 public database(string filename)
 {
     _sql = new SQLiteClient(filename);
     try {               //"IF NOT EXIST" DOES NOT EXIST in the SQLite version for C#.
         _sql.Execute("CREATE TABLE roms (id INTEGER AUTOINCREMENT PRIMARY KEY, file TEXT, sum TEXT)");
     } catch (SQLiteException e) { /* Oh well. */ }
 }
Exemplo n.º 7
0
        public static bool IntegrityCheck(SQLiteClient m_db)
        {
            SQLiteResultSet results;

            if (m_db == null)
            {
                return(false);
            }

            results = m_db.Execute("PRAGMA integrity_check;");
            if (results != null)
            {
                if (results.Rows.Count == 1)
                {
                    SQLiteResultSet.Row arr = results.Rows[0];
                    if (arr.fields.Count == 1)
                    {
                        if (arr.fields[0] == "ok")
                        {
                            Log.Debug("IntegrityCheck: the {0} is OK", m_db.DatabaseName);
                            return(true);
                        }
                    }
                }
            }
            Log.Error("IntegrityCheck: the {0} is corrupt.", m_db.DatabaseName);
            return(false);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Check if a view exists
        /// </summary>
        /// <param name="table">name of view</param>
        /// <returns>true: view exists
        /// false: view does not exist</returns>
        public static bool ViewExists(SQLiteClient m_db, string view)
        {
            SQLiteResultSet results;

            if (m_db == null)
            {
                return(false);
            }
            if (view == null)
            {
                return(false);
            }
            if (view.Length == 0)
            {
                return(false);
            }
            results = m_db.Execute("SELECT name FROM sqlite_master WHERE name like '" + view + "' and type like 'view'");
            // UNION ALL SELECT name FROM sqlite_temp_master WHERE type='view' ORDER BY name");
            if (results != null)
            {
                if (results.Rows.Count == 1)
                {
                    SQLiteResultSet.Row arr = results.Rows[0];
                    if (arr.fields.Count == 1)
                    {
                        if (arr.fields[0] == view)
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Exemplo n.º 9
0
 public SQLiteResultSet ExecuteWithoutLock(string query, params object[] args)
 {
     if (!isInit)
     {
         Logger.LogError("Database has not initialised correctly");
         return(new SQLiteResultSet());
     }
     try
     {
         string          exeQuery = string.Format(System.Globalization.CultureInfo.InvariantCulture, query, args);
         SQLiteResultSet result   = sqlClient.Execute(exeQuery);
         return(result);
     }
     catch (Exception ex)
     {
         if (supressExceptions)
         {
             Logger.LogError(ex);
             return(new SQLiteResultSet());
         }
         else
         {
             throw (ex);
         }
     }
 }
Exemplo n.º 10
0
        public FolderSettingsSqlLite()
        {
            try
            {
                // Open database
                Log.Info("Open FolderDatabase");
                m_db = new SQLiteClient(Config.GetFile(Config.Dir.Database, "FolderDatabase3.db3"));

                _dbHealth = DatabaseUtility.IntegrityCheck(m_db);

                DatabaseUtility.SetPragmas(m_db);
                DatabaseUtility.AddTable(m_db, "tblPath", "CREATE TABLE tblPath ( idPath integer primary key, strPath text)");
                DatabaseUtility.AddTable(m_db, "tblSetting",
                                         "CREATE TABLE tblSetting ( idSetting integer primary key, idPath integer , tagName text, tagValue text)");
                // Indexes for tblPath
                DatabaseUtility.AddIndex(m_db, "idx_tblPath_strPath", "CREATE INDEX idx_tblPath_strPath ON tblPath (strPath ASC)");
                DatabaseUtility.AddIndex(m_db, "idx_tblPath_idPath_strPath", "CREATE INDEX idx_tblPath_idPath_strPath ON tblPath (idPath ASC, strPath ASC)");

                // Indexes for tblSetting
                DatabaseUtility.AddIndex(m_db, "idx_tblSetting_idPath", "CREATE INDEX idx_tblSetting_idPath ON tblSetting (idPath ASC)");
                DatabaseUtility.AddIndex(m_db, "idx_tblSetting_tagName", "CREATE INDEX idx_tblSetting_tagName ON tblSetting (tagName ASC)");
                DatabaseUtility.AddIndex(m_db, "idx_tblSetting_idPath_tagName", "CREATE INDEX idx_tblSetting_idPath_tagName ON tblSetting (idPath ASC, tagName ASC)");

                // Cleanup DB
                Log.Debug("Cleanup FolderDatabase");
                string strSQL = String.Format("delete from tblPath where idPath not in (select idPath from tblSetting)");
                m_db.Execute(strSQL);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
Exemplo n.º 11
0
        private bool verifyIntegrity(SQLiteClient client)
        {
            string query = "PRAGMA integrity_check;";

            logger.Info("Executing SQL integrity check");

            try {
                SQLiteResultSet results = client.Execute(query);
                if (results != null)
                {
                    if (results.Rows.Count == 1)
                    {
                        SQLiteResultSet.Row arr = results.Rows[0];
                        if (arr.fields.Count == 1)
                        {
                            if (arr.fields[0] == "ok")
                            {
                                logger.Info("Database integrity check succeeded");
                                return(true);
                            }
                        }
                    }
                }
            }
            catch (Exception e) {
                logger.Info("Integrity check failed, database is corrupt. Reason = '{0}', Filename = '{1}'", e.Message, client.DatabaseName);
                return(false);
            }
            logger.Info("Integrity check failed, database is corrupt. Filename = '{0}'", client.DatabaseName);
            return(false);
        }
Exemplo n.º 12
0
 private static void ExecutePragmas()
 {
     // Each page uses about 1.5K of memory
     m_db.Execute("PRAGMA cache_size=5000;");
     m_db.Execute("PRAGMA synchronous='OFF';");
     m_db.Execute("PRAGMA count_changes=1;");
     m_db.Execute("PRAGMA full_column_names=0;");
     m_db.Execute("PRAGMA short_column_names=0;");
     m_db.Execute("PRAGMA temp_store = MEMORY;");
 }
Exemplo n.º 13
0
 public static void SetPragmas(SQLiteClient m_db)
 {
     m_db.Execute("PRAGMA encoding = \"UTF-8\"");
     m_db.Execute("PRAGMA cache_size=4096");
     m_db.Execute("PRAGMA page_size=8192");
     m_db.Execute("PRAGMA synchronous='OFF'");
     m_db.Execute("PRAGMA count_changes=1");
     m_db.Execute("PRAGMA full_column_names=0");
     m_db.Execute("PRAGMA short_column_names=0");
     m_db.Execute("PRAGMA auto_vacuum=0");
 }
        public void InitDatabase()
        {
            bool dbExists;

            try
            {
                // Open database
                dbExists = System.IO.File.Exists(Config.GetFile(Config.Dir.Database, "YouTubeFm_Data_V01.db3"));
                m_db     = new SQLiteClient(Config.GetFile(Config.Dir.Database, "YouTubeFm_Data_V01.db3"));

                DatabaseUtility.SetPragmas(m_db);

                if (!dbExists)
                {
                    m_db.Execute(
                        "CREATE TABLE VIDEOS(ID integer primary key autoincrement,VIDEO_ID text, ARTIST_ID text, TITLE text, IMG_URL text, LENGTH integer,STATE integer, rating integer, hd integer)\n");
                    m_db.Execute(
                        "CREATE TABLE PLAY_HISTORY(ID integer primary key autoincrement,VIDEO_ID text, datePlayed timestamp, loved integer)\n");

                    CreateArtistTable(m_db);

                    DatabaseUtility.AddIndex(m_db, "idx_video_id", "CREATE INDEX idx_video_id ON VIDEOS(VIDEO_ID)");
                    DatabaseUtility.AddIndex(m_db, "idx_ARTIST_ID", "CREATE INDEX idx_ARTIST_ID ON VIDEOS(ARTIST_ID)");
                    DatabaseUtility.AddIndex(m_db, "idx_his_video_id", "CREATE INDEX idx_his_video_id ON PLAY_HISTORY(VIDEO_ID)");
                    DatabaseUtility.AddIndex(m_db, "idx_his_date", "CREATE INDEX idx_his_date ON PLAY_HISTORY(datePlayed DESC)");
                }
                else
                {
                    if (!DatabaseUtility.TableColumnExists(m_db, "VIDEOS", "hd"))
                    {
                        m_db.Execute("ALTER TABLE VIDEOS ADD hd integer");
                    }
                    if (!DatabaseUtility.TableExists(m_db, "ARTISTS"))
                    {
                        CreateArtistTable(m_db);
                    }
                }
            }
            catch (SQLiteException ex)
            {
                Log.Error("database exception err:{0} stack:{1}", ex.Message, ex.StackTrace);
            }
        }
Exemplo n.º 15
0
        private ArrayList _find(string retcol, string findcol, string val)
        {
            SQLiteResultSet find;

            try {
                find = _sql.Execute(String.Format("SELECT {0} FROM roms WHERE {1}={2}", retcol, findcol, _quote(val)));
            } catch (SQLiteException e) { return(null); }
            if (find.Rows.Count == 0)
            {
                return(null);
            }
            ArrayList ret = new ArrayList();

            for (int i = 0; i < find.Rows.Count; i++)
            {
                ret.Add(((ArrayList)find.Rows[i])[0]);
            }
            return(ret);
        }
 private FavoritesDatabase()
 {
     try
     {
         m_db = new SQLiteClient(Config.GetFile(Config.Dir.Database, "OnlineVideoDatabase.db3"));
         DatabaseUtility.SetPragmas(m_db);
         DatabaseUtility.AddTable(m_db, "FAVORITE_VIDEOS", "CREATE TABLE FAVORITE_VIDEOS(VDO_ID integer primary key autoincrement,VDO_NM text,VDO_URL text,VDO_DESC text,VDO_TAGS text,VDO_LENGTH text,VDO_OTHER_NFO text,VDO_IMG_URL text,VDO_SITE_ID text)\n");
         DatabaseUtility.AddTable(m_db, "FAVORITE_Categories", "CREATE TABLE FAVORITE_Categories(CAT_ID integer primary key autoincrement,CAT_Name text,CAT_Desc text,CAT_ThumbUrl text,CAT_Hierarchy text,CAT_SITE_ID text, CAT_IS_SEARCH boolean, SEARCH_CAT_HASSUBS boolean)\n");
         DatabaseUtility.AddTable(m_db, "PREFERRED_LAYOUT", "CREATE TABLE PREFERRED_LAYOUT(Site_Name text, Category_Hierarchy text, Layout integer, PRIMARY KEY (Site_Name, Category_Hierarchy) ON CONFLICT REPLACE)\n");
         if (!DatabaseUtility.TableColumnExists(m_db, "FAVORITE_Categories", "CAT_IS_SEARCH"))
         {
             m_db.Execute("ALTER TABLE FAVORITE_Categories ADD COLUMN CAT_IS_SEARCH boolean DEFAULT false");
             m_db.Execute("ALTER TABLE FAVORITE_Categories ADD COLUMN SEARCH_CAT_HASSUBS boolean DEFAULT false");
         }
     }
     catch (SQLiteException ex)
     {
         Log.Instance.Error("database exception err:{0} stack:{1}", ex.Message, ex.StackTrace);
     }
 }
Exemplo n.º 17
0
        public static bool SaveModel(IViewModel model, string tableName)
        {
            var data = model.GetType().GetProperties().Where
                           (x => !Attribute.IsDefined(x, typeof(PropInsertIgnore))).ToDictionary
                           (x => x.Name, x => x.GetValue(model));

            var columns = data.Keys.Select(x => x).ToList();
            var query   = string.Format("INSERT INTO {0} ({1}) VALUES({2});",
                                        tableName,
                                        string.Join(",", columns).TrimEnd(','),
                                        string.Join(",", columns.Select(x => "@" + x)).TrimEnd(','));

            var parameters = new List <SQLiteParameter>(data.Select(x => new SQLiteParameter(x.Key, x.Value))).ToArray();
            var command    = client.Command(query, parameters);

            lock (dbLock)
            {
                return(client.Execute(command) > 0);
            }
        }
Exemplo n.º 18
0
        static SQLiteResultSet dbExecute(string query)
        {
            if (!isDBInit)
            {
                Logger.LogDebug("Attempting to access database before initialisation complete");
                return(new SQLiteResultSet());
            }
            SQLiteResultSet result;

            lock (dbLock)
            {
                if (sqlDB == null)
                {
                    return(new SQLiteResultSet());
                }

                result = sqlDB.Execute(query);
            }
            return(result);
        }
Exemplo n.º 19
0
        public void Save()
        {
            if (DatabaseUtility.TableExists(_sqlClient, "WatchList"))
            {
                _sqlClient.Execute("DELETE FROM WatchList;");
                _sqlClient.Execute("DELETE FROM SeriesWatchList;");
                foreach (WatchItem watch in _watchItemList)
                {
                    if (watch is SeriesItem)
                    {
                        try
                        {
                            var series = watch as SeriesItem;
                            _sqlClient.Execute(String.Format("INSERT INTO SeriesWatchList (SeriesName, OriginalSeriesName, SeriesID, Added, Quality, Tracker, Type, Source, Folder, IncludeSpecials) VALUES (\"{0}\",\"{1}\",{2},\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\");", series.show.Name, series.show.OriginalName, series.show.ID, series.Added.Ticks, series.quality, series.tracker, series.type, series.source, series.folder, (series.includespecials).ToString()));
                        }
                        catch (Exception e) { }
                    }
                    else
                    {
                        try
                        {
                            _sqlClient.Execute(String.Format("INSERT INTO WatchList (Search, Added, Label) VALUES (\"{0}\", {1}, \"{2}\");", watch.SearchTerm, watch.Added.Ticks, watch.Label));
                        }
                        catch (Exception e) { }
                    }
                }
            }

            _sqlClient.Close();
        }
Exemplo n.º 20
0
        public static void AddIndex(SQLiteClient dbHandle, string indexName, string strSQL)
        {
            SQLiteResultSet results;

            results =
                dbHandle.Execute("SELECT name FROM sqlite_master WHERE name='" + indexName + "' and type='index' " +
                                 "UNION " +
                                 "SELECT name FROM sqlite_temp_master WHERE name ='" + indexName + "' and type='index'");
            if (results != null && results.Rows.Count == 1)
            {
                return;
            }
            try
            {
                dbHandle.Execute(strSQL);
            }
            catch (SQLiteException ex)
            {
                Log.Error("DatabaseUtility exception err:{0} stack:{1} sql:{2}", ex.Message, ex.StackTrace, strSQL);
            }
            return;
        }
Exemplo n.º 21
0
        public void InitDatabase()
        {
            bool dbExists;

            try
            {
                // Open database
                dbExists = System.IO.File.Exists(Config.GetFile(Config.Dir.Database, "YouTubeFm_V01.db3"));
                m_db     = new SQLiteClient(Config.GetFile(Config.Dir.Database, "YouTubeFm_V01.db3"));

                DatabaseUtility.SetPragmas(m_db);

                if (!dbExists)
                {
                    m_db.Execute("CREATE TABLE ARTISTS(ID integer primary key autoincrement,ARTIST_ID text,ARTIST_NAME text,ARTIST_IMG text, ARTIST_BIO text, ARTIST_USER text, ARTIST_TAG text)\n");
                    m_db.Execute("CREATE TABLE TAGS(ID integer primary key autoincrement,ARTIST_ID text, ARTIST_TAG text)\n");
                }
            }
            catch (SQLiteException ex)
            {
                //Log.Instance.Error("database exception err:{0} stack:{1}", ex.Message, ex.StackTrace);
            }
        }
Exemplo n.º 22
0
        public void GetSQLSettings()
        {
            SQLSettings.Clear();
            SQLiteClient _sqlClient = new SQLiteClient(Config.GetFile(Config.Dir.Database, "MyTorrents.db3"));

            if (!DatabaseUtility.TableExists(_sqlClient, "Settings"))
            {
                DatabaseUtility.AddTable(_sqlClient, "Settings", "CREATE TABLE Settings (ParameterName CHAR(256), ParameterValue CHAR(256));");
                _sqlClient.Execute(String.Format("INSERT INTO Settings (ParameterName, ParameterValue) VALUES (\"TorrentView\" , \"Active\");"));
                _sqlClient.Execute(String.Format("INSERT INTO Settings (ParameterName, ParameterValue) VALUES (\"SortOrder\" , \"Default\");"));
                _sqlClient.Execute(String.Format("INSERT INTO Settings (ParameterName, ParameterValue) VALUES (\"LabelFilter\" , \"None\");"));
            }

            SQLiteResultSet resultSet = _sqlClient.Execute("SELECT * FROM Settings;");

            foreach (SQLiteResultSet.Row row in resultSet.Rows)
            {
                SQLSettings.Add(row.fields[(int)resultSet.ColumnIndices["ParameterName"]], row.fields[(int)resultSet.ColumnIndices["ParameterValue"]]);
            }
            if (SQLSettings.Count == 0)
            {
                //Fail
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Check if a table column exists
        /// </summary>
        /// <param name="table">table name</param>
        /// <param name="column">column name</param>
        /// <returns>true if table + column exists
        /// false if table does not exists or if table doesnt contain the specified column</returns>
        public static bool TableColumnExists(SQLiteClient m_db, string table, string column)
        {
            SQLiteResultSet results;

            if (m_db == null)
            {
                return(false);
            }
            if (table == null)
            {
                return(false);
            }
            if (table.Length == 0)
            {
                return(false);
            }
            // This only works for tables that are not empty
            //results = m_db.Execute("SELECT * FROM '" + table + "'");
            //if (results != null)
            //{
            //  for (int i = 0; i < results.ColumnNames.Count; ++i)
            //  {
            //    if ((string)results.ColumnNames[i] == column)
            //    {
            //      return true;
            //    }
            //  }
            //}
            //return false;

            // We will use --> PRAGMA table_info( your_table_name )
            // PRAGMA returns one row for each column in the named table.
            // Columns in the result set include the columnID, column name, data type,
            // whether or not the column can be NULL, and the default value for the column.
            // More info: http://www.sqlite.org/pragma.html
            results = m_db.Execute("PRAGMA table_info('" + table + "')");
            if (results != null)
            {
                for (int i = 0; i < results.Rows.Count; ++i)
                {
                    if ((string)results.Rows[i].fields[1] == column) // fields[1] is column name
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 24
0
        public static void CommitTransaction()
        {
            string str = "BEGIN TRANSACTION; \n" + sqls + "\nCOMMIT;";

            try
            {
                transaction = false;
                sqlclient.Execute(str);
            }
            finally
            {
                sqls = "";
            }
        }
Exemplo n.º 25
0
        public bool IsAlreadyDownloaded(string hash)
        {
            SQLiteClient sqlClient = new SQLiteClient(Config.GetFile(Config.Dir.Database, "MyTorrents.db3"));

            DatabaseUtility.SetPragmas(sqlClient);

            if (!DatabaseUtility.TableExists(sqlClient, "Downloaded"))
            {
                return(false);
            }

            SQLiteResultSet results = sqlClient.Execute(String.Format("SELECT * FROM Downloaded WHERE Hash=\"{0}\";", hash));

            sqlClient.Close();

            return(results.Rows.Count >= 1);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Method to find the file's unique id in the MyVideo's database
        /// </summary>
        /// <param name="fileName">Filename to look for in the MyVideo's database</param>
        /// <returns>unique id as string</returns>
        private string getMovieID(string fileName)
        {
            string idMovie = String.Empty;

            fileName = fileName.Replace("'", "''");
            try
            {
                SQLiteClient    mp_db   = new SQLiteClient(Config.GetFile(Config.Dir.Database, @"VideoDatabaseV5.db3"));
                SQLiteResultSet results = mp_db.Execute("SELECT idMovie FROM files WHERE strFilename LIKE '\\" + fileName + "'");
                idMovie = results.GetField(0, 0);
                mp_db.Close();
            }
            catch
            {
            }
            return(idMovie);
        }
Exemplo n.º 27
0
 /// <summary>
 /// Helper function to create a new view in the database
 /// </summary>
 /// <param name="strView">name of view</param>
 /// <param name="strSQL">SQL command to create the new view</param>
 /// <returns>true if view is created</returns>
 public static bool AddView(SQLiteClient dbHandle, string strView, string strSQL)
 {
     if (ViewExists(dbHandle, strView))
     {
         return(false);
     }
     try
     {
         //Log.Info("create view:{0} {1}", strSQL,dbHandle);
         dbHandle.Execute(strSQL);
         //Log.Info("view created");
     }
     catch (SQLiteException ex)
     {
         Log.Error("DatabaseUtility exception err:{0} stack:{1} sql:{2}", ex.Message, ex.StackTrace, strSQL);
     }
     return(true);
 }
        public int AddPicture(string strPicture, int iRotation)
        {
            if (String.IsNullOrEmpty(strPicture))
            {
                return(-1);
            }

            if (m_db == null)
            {
                return(-1);
            }
            try
            {
                int    lPicId       = -1;
                string strPic       = strPicture;
                string strDateTaken = String.Empty;
                DatabaseUtility.RemoveInvalidChars(ref strPic);
                string          strSQL  = String.Format("select * from picture where strFile like '{0}'", strPic);
                SQLiteResultSet results = m_db.Execute(strSQL);
                if (results != null && results.Rows.Count > 0)
                {
                    lPicId = Int32.Parse(DatabaseUtility.Get(results, 0, "idPicture"));
                    return(lPicId);
                }

                // we need the date nevertheless for database view / sorting
                if (!GetExifDetails(strPicture, ref iRotation, ref strDateTaken))
                {
                    try
                    {
                        DateTime dat = File.GetLastWriteTime(strPicture);
                        if (!TimeZone.CurrentTimeZone.IsDaylightSavingTime(dat))
                        {
                            dat = dat.AddHours(1); // Try to respect the timezone of the file date
                        }
                        strDateTaken = dat.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    catch (Exception ex)
                    {
                        Log.Error("PictureDatabaseSqlLite: Conversion exception getting file date - err:{0} stack:{1}", ex.Message,
                                  ex.StackTrace);
                    }
                }

                // Save potential performance penalty
                if (_usePicasa)
                {
                    if (GetPicasaRotation(strPic, ref iRotation))
                    {
                        Log.Debug("PictureDatabaseSqlLite: Changed rotation of image {0} based on picasa file to {1}", strPic,
                                  iRotation);
                    }
                }

                // Transactions are a special case for SQLite - they speed things up quite a bit
                strSQL  = "begin";
                results = m_db.Execute(strSQL);
                strSQL  =
                    String.Format(
                        "insert into picture (idPicture, strFile, iRotation, strDateTaken) values(null, '{0}',{1},'{2}')", strPic,
                        iRotation, strDateTaken);

                results = m_db.Execute(strSQL);
                if (results.Rows.Count > 0)
                {
                    Log.Debug("PictureDatabaseSqlLite: Added to database - {0}", strPic);
                }
                strSQL  = "commit";
                results = m_db.Execute(strSQL);

                lPicId = m_db.LastInsertID();

                if (g_Player.Playing)
                {
                    Thread.Sleep(50);
                }
                else
                {
                    Thread.Sleep(1);
                }

                return(lPicId);
            }
            catch (Exception ex)
            {
                Log.Error("PictureDatabaseSqlLite: exception err:{0} stack:{1}", ex.Message, ex.StackTrace);
                Open();
            }
            return(-1);
        }
Exemplo n.º 29
0
 public static void CompactDatabase(SQLiteClient m_db)
 {
     m_db.Execute("PRAGMA count_changes=0");
     m_db.Execute("vacuum");
     m_db.Execute("PRAGMA count_changes=1");
 }
Exemplo n.º 30
0
 public static void CompactDatabase(SQLiteClient m_db)
 {
     m_db.Execute("vacuum");
 }