Example #1
2
 private void button9_Click( object sender, EventArgs e )
 {
     SQLiteConnection connection = new SQLiteConnection( GetConnectionString() );
     connection.SetPassword( new byte[] { 0xDE, 0xAD, 0xBE, 0xEF, 0xBA, 0xDC, 0xC0, 0xDE } );
     connection.Open();
     connection.ChangePassword( "" );
 }
Example #2
0
        static void Main(string[] args)
        {
            string databaseFile = "border_tile_pattern.sqlite";
            string currentPassword = "";
            string newPassword = "******";

            string currentDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            currentDir = currentDir.Replace("file:\\", "");

            string connString = "Data Source=" + currentDir + "/"+databaseFile+";Pooling=True";

            if (currentPassword != "") connString += ";Password="******"Changing password ... ");
            if (newPassword == "")
                conn.ChangePassword(new byte[0]);
            else
                conn.ChangePassword(newPassword);

            Console.WriteLine("Done !");
            Console.ReadLine();
        }
Example #3
0
        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <returns></returns>
        public bool InitializeDataBase()
        {
            var    result     = true;
            var    dbFileName = ConfigHelper.GetAppSettingValue("DbFileName");
            string filePath   = AppDomain.CurrentDomain.BaseDirectory + dbFileName;

            GlobalInfo.DbPath = filePath;
            ConfigHelper.SetConnection("DataModelContainerEntities", filePath);

            var isDBNewCreated = false;

            if (!File.Exists(filePath))
            {
                string path = filePath.Substring(0, filePath.LastIndexOf("\\"));
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (!File.Exists(filePath))
                {
                    isDBNewCreated = true;
                    System.Data.SQLite.SQLiteConnection.CreateFile(filePath);
                }

                try
                {
                    //读取配置信息,看数据库是否已经加密;如果没加密,则给数据库设置密码
                    var fileName    = AppDomain.CurrentDomain.BaseDirectory + @"\Init.ini";
                    var myIni       = new MyIniFile(fileName);
                    var isEncrypted = myIni.IniReadValue("InitializeInfo", "DbIsEncrypted");
                    //对已存在数据库,但没经过加密的(isEncrypted == "");及新建的数据库进行加密
                    if (string.IsNullOrEmpty(isEncrypted) || isDBNewCreated)
                    {
                        System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection("Data Source=" + filePath);
                        con.Open();
                        con.ChangePassword(PRO_ReceiptsInvMgr.Resources.Common.DbPwd);
                        myIni.IniWriteValue("InitializeInfo", "DbIsEncrypted", "True");//标示已经加密
                    }
                }
                catch (Exception ex)
                {
                    Logging.Log4NetHelper.Error(this, Message.DBEncryptFail + ex.Message + ex.InnerException + System.Environment.NewLine + ex.StackTrace);
                }

                try
                {
                    ExecSqlList(new List <string> {
                        ConfigHelper.GetAppSettingValue("InitializeScriptName")
                    });
                }
                catch (Exception ex)
                {
                    result = false;
                    Logging.Log4NetHelper.Error(this, Message.CreateDataBase + ex.Message + ex.InnerException + System.Environment.NewLine + ex.StackTrace);
                }
            }

            return(result);
        }
Example #4
0
        public sqlconnect(string data, string password)
        {
            if (!File.Exists(data))
            {
                SQLiteConnection.CreateFile(data);
                try
                {
                    m_dbConnection = new SQLiteConnection("Data Source=" + data + ";Version=3;");
                    m_dbConnection.Open();
                    m_dbConnection.ChangePassword(password);
                }
                catch(SQLiteException ex)
                {
                    Debug.WriteLine(ex.Message);

                }
            }
            else
            {
                try
                {
                    m_dbConnection = new SQLiteConnection("Data Source=" + data + "; Password="******"SELECT name FROM sqlite_master WHERE type='table' AND name='table_name'";
            string[] sqls = new string[]{
            "CREATE TABLE IF NOT EXISTS UrlListTmp(id INTEGER PRIMARY KEY,Url TEXT UNIQUE,Valid INT DEFAULT 0)",
            "CREATE TABLE IF NOT EXISTS ProxyListTmp(id INTEGER PRIMARY KEY,Ipport TEXT UNIQUE,Valid INT DEFAULT 0,Https INT DEFAULT 0,Google INT DEFAULT 0,Speed INT DEFAULT 0,Typeprox INT DEFAULT 0)",
            "CREATE TABLE IF NOT EXISTS UrlList(id INTEGER PRIMARY KEY,Url TEXT UNIQUE,Valid INT DEFAULT 0)",
            "CREATE TABLE IF NOT EXISTS ProxyList(id INTEGER PRIMARY KEY,Ipport TEXT UNIQUE,Valid INT DEFAULT 0,Https INT DEFAULT 0,Google INT DEFAULT 0,Speed INT DEFAULT 0,Typeprox INT DEFAULT 0)",
            "CREATE TABLE IF NOT EXISTS ProxyListFilter(id INTEGER PRIMARY KEY,Ipport TEXT UNIQUE,Valid INT DEFAULT 0,Https INT DEFAULT 0,Google INT DEFAULT 0,Speed INT DEFAULT 0,Typeprox INT DEFAULT 0)"

            //"CREATE INDEX UrlList_idx_1 on UrlList (url)",
            //"CREATE INDEX ProxyList_idx_1 on ProxyList (ipport)"

            };

            foreach (string sql in sqls)
            {

                try
                {
                    SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
                    command.ExecuteNonQuery();
                }
                catch (SQLiteException ex)
                {
                    Debug.WriteLine(ex.Message);

                }

            }
        }
 public void EncryptDb(byte[] password)
 {
     var connectionString = string.Format("Data Source={0}", this.DatabasePath);
     var connection = new SQLiteConnection(connectionString);
     connection.Open();
     connection.ChangePassword(password);
     connection.Close();
 }
Example #6
0
 public static void EncryptDatabase(string dbPath, string password)
 {
     SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbPath);
     connection.Open();
     #if !DEBUG
     connection.ChangePassword(password);
     #endif
     connection.Close();
 }
Example #7
0
 private static void SetPwd(string oldpwd,string newpwd)
 {
     using (SQLiteConnection conn = new SQLiteConnection(@"data source=F:\github\DFZ\source\DFZ.BenSeLing\App_Data\benseling.db"))
     {
         conn.SetPassword(oldpwd);
         conn.Open();
         conn.ChangePassword(newpwd);
         conn.Close();
     }
 }
Example #8
0
 public static void CreateDB(string dbPath, string pwd = "")
 {
     SQLiteConnection.CreateFile(dbPath);
     using (SQLiteConnection cnn = new SQLiteConnection("Data Source=" + dbPath))
     {
         cnn.Open();
         if (!string.IsNullOrEmpty(pwd))
         {
             cnn.ChangePassword(pwd);
         }
     }
 }
 public bool ChangePassword(string newpsd)
 {
     try
     {
         using (SQLiteConnection connection = new SQLiteConnection(connectionString))
         {
             connection.Open();
             connection.ChangePassword(newpsd);
             connection.Close();
             return true;
         }
     }
     catch
     {
         return false;
     }
 }
Example #10
0
 public static bool ChangePassword(string newPassword, string oldPassword = "")
 {
     if (oldPassword == conStr.Password)
     {
         using (SQLiteConnection conn = new SQLiteConnection(conStr.ConnectionString))
         {
             conn.Open();
             conn.ChangePassword(newPassword);
             conn.Close();
         }
         return true;
     }
     else
     {
         return false;
     }
 }
Example #11
0
        static void Main(string[] args)
        {
            string dbFile = "c:/test3d.db";
            SQLiteConnection.CreateFile(dbFile);

            using (var m_dbConnection =
                new SQLiteConnection(String.Format("Data Source={0};Version=3;", dbFile)))
            {

                m_dbConnection.Open();
                m_dbConnection.ChangePassword("Mypass");

                Action<string> funcSqlStr = delegate(string x)
                {
                    string sqlStr = x;
                    var commandDel = new SQLiteCommand(sqlStr, m_dbConnection);
                    commandDel.ExecuteNonQuery();
                    commandDel.Dispose();
                };

                string sql = "create table highscores (name varchar(20), score int)";
                funcSqlStr(sql);

                sql = "insert into highscores (name, score) values ('Me', 3000)";
                funcSqlStr(sql);

                sql = "insert into highscores (name, score) values ('Myself', 6000)";
                funcSqlStr(sql);

                sql = "insert into highscores (name, score) values ('And I', 9001)";
                funcSqlStr(sql);

                sql = "select * from highscores order by score desc";
                var command = new SQLiteCommand(sql, m_dbConnection);

                var reader = command.ExecuteReader();
                while (reader.Read())
                    Console.WriteLine("Name: " + reader["name"] + "\tScore: " + reader["score"]);
                reader.Dispose();

            }

            Console.ReadKey();
        }
Example #12
0
        public bool SetPasswrod(String dbfile, String currentpass, String newpassword)
        {
            bool retval = false;

            //String connStr = String.Format("Data Source={0};Version=3;New=False;Compress=True;Password={1};", dbfile, password);
            String connStr = String.Format("Data Source={0};Version=3;New=False;Compress=True;",
                dbfile);

            if (!String.IsNullOrEmpty(currentpass))
                connStr = String.Format("Data Source={0};Version=3;New=False;Compress=True;Password={1};",
                    dbfile, currentpass);

            try
            {
                using (var cnn = new SQLiteConnection(connStr))
                {
                    cnn.Open();
                    cnn.ChangePassword(newpassword);
                    //cnn.ChangePassword("");

                    String sql = "SELECT count(*) FROM sqlite_master WHERE type='table'";
                    using (SQLiteCommand myCommand = new SQLiteCommand(sql, cnn))
                    {
                        var a = myCommand.ExecuteScalar();
                        Console.WriteLine("Total : " + a.ToString() + " tables found!");
                    }

                    retval = true;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                // throw e;
            }

            return retval;
        }
Example #13
0
        // 创建SQLiteDB文件
        public void CreateSqliteDBFile()
        {
            // 若数据库文件不存在则创建数据库文件
            if (!(System.IO.File.Exists(DataSource)))
            {
                try
                {
                    System.Data.SQLite.SQLiteConnection.CreateFile(DataSource);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            if (connState == ConnectionState.Closed)
            {
                conn.Open();                                            // 打开数据库
                conn.ChangePassword(Password);                          // 设置数据库密码
                conn.Close();                                           // 密码设置后关闭数据库连接
            }
        }
Example #14
0
        private static void InitSystemDB(string systemDB)
        {
            Trace.TraceInformation ("Creating storage folder...");
            if (!Directory.Exists (BaseSystem.GetSystemDBBaseLocation ())) {
                Directory.CreateDirectory (BaseSystem.GetSystemDBBaseLocation ());
            }

            Trace.TraceInformation ("Creating system db...");
            SQLiteConnection cnn = new SQLiteConnection (SYSTEMDB_CONN_STR_FOR_WRITING);

            Debug.Print ("New connection created. Opening connection for system db...");
            cnn.Open ();

            Debug.Print ("Changing password.");
            cnn.ChangePassword (BaseSystem.GetSystemDBPassword ());

            string sql = SystemSchema.GetSystemSchema ();
            Debug.Print ("Adding system db table schema: " + sql);

            SQLiteCommand myCommand = new SQLiteCommand (sql, cnn);
            myCommand.ExecuteNonQuery ();
            Trace.TraceInformation ("Done creating system db!");

            cnn.Dispose ();
            Debug.Print ("Closed connection for creating system db.");
        }
Example #15
0
 internal void ChangePassword(string passwd)
 {
     using (SQLiteConnection conn = new SQLiteConnection(_db_connstring_builder.ToString()))
     {
         conn.Open();
         conn.ChangePassword(passwd);                
         _db_connstring_builder.Password = passwd;
     }
 }
Example #16
0
 private void btn_lockdb_Click(object sender, EventArgs e)
 {
     if (MyConfigs.IsDbPassActive)
     {
         string constr = new SQLiteConnectionStringBuilder()
         {
             DataSource = @"Contacts.db",
             ForeignKeys = true,
             Version = 3
         }
             .ConnectionString;
         Clipboard.SetText(constr);
         MessageBox.Show(constr);
         SQLiteConnection con = new SQLiteConnection(constr);
         con.Open();
         con.ChangePassword(MyConfigs.DbPassword);
         con.Close();
     }
 }
Example #17
0
 public static bool SendEncryptedQuery(string db, string cmd)
 {
     bool success = false;
     using (SQLiteConnection sql_con = new SQLiteConnection(db))
     {
         try
         {
             sql_con.Open();
             sql_con.ChangePassword("Jawad");
         }
         catch (Exception es)
         {
             SystemLogs_DB.Add(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "Failed to open database connection,Error: " + es);
         }
         if (sql_con.State == ConnectionState.Open)
         {
             Connected = true;
         }
         else
         {
             Connected = false;
         }
         if (Connected)
         {
             try
             {
                 SQLiteCommand sql_cmd = sql_con.CreateCommand();
                 sql_cmd.CommandText = cmd;
                 sql_cmd.ExecuteNonQuery();
                 success = true;
             }
             catch (Exception es)
             {
                 SystemLogs_DB.Add(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "Failed to send query,Error: " + es);
             }
         }
     }
     return success;
 }
        //private static SQLiteDataReader sqReader;
        //private static SQLiteParameter fileParameter; //Parameterized Query
        // Creates the three tables: scanned, unScanned, and unScannable
        public static void SQLDatabaseInitilize()
        {
            String dbName = Environment.UserName+"@"+Environment.MachineName+"_"+System.DateTime.Now.ToString("MM_dd_yy_H_mm_ss");
            //MessageBox.Show(dbName);
            try
            {
               //if (File.Exists(".db"))
                    //File.Delete("db.db");
                sqlCon = new SQLiteConnection("Data Source="+dbName+".sdb;Version=3;New=True;Compress=True;"); //create a new database
                sqlCon.Open(); //open the connection
                String []password = dbName.Split('@');
                String[] dbPassword = password[1].Split('_');
                sqlCon.ChangePassword(password[0] + dbPassword[0]);

                sqlCmd = sqlCon.CreateCommand();
                // Create scanned table
                sqlCmd.CommandText = "CREATE TABLE if not exists Scanned (fileIndex integer PRIMARY KEY AUTOINCREMENT, filename text, " +
                                     "filePath text, count integer, priority text, pattern_D9_Count integer, pattern_D324_Count integer);";
                sqlCmd.ExecuteNonQuery();
                // Create unScannable table
                sqlCmd.CommandText = "CREATE TABLE if not exists UnScannable (filename text, filePath text, owner text, reason text);";
                sqlCmd.ExecuteNonQuery();
                // Create CreditCard table
                sqlCmd.CommandText = "CREATE TABLE if not exists CreditCard (filename text, filePath text, count integer, priority text, " +
                                     "visa integer, mastercard integer, americanExpress integer, discover integer, dinerClub integer, JCB integer);";
                sqlCmd.ExecuteNonQuery();
                //Create CrashStatus table
                sqlCmd.CommandText = "CREATE TABLE if not exists CrashStatus (status text);";
                sqlCmd.ExecuteNonQuery();
            }
            catch (Exception) { /*MessageBox.Show(e.ToString());*/ }
        }
Example #19
0
        private static void InitLogDB(string logDB)
        {
            Trace.TraceInformation ("Creating log db...");
            SQLiteConnection cnn = new SQLiteConnection (LOGDB_CONN_STR_FOR_WRITING);

            Debug.Print ("New connection created. Opening connection for log db...");
            cnn.Open ();

            Debug.Print ("Changing password.");
            cnn.ChangePassword (BaseSystem.GetLogDBPassword ());

            string sql = LogSchema.GetLogSchema ();
            Debug.Print ("Adding log db table schema: " + sql);

            SQLiteCommand myCommand = new SQLiteCommand (sql, cnn);
            myCommand.ExecuteNonQuery ();
            Trace.TraceInformation ("Done creating log db!");

            cnn.Close ();
            Debug.Print ("Closed connection for creating log db.");
        }
Example #20
0
        /**
         * Warning: Implicitly overwrites existing file!
         */
        private void createNewDb(String name, bool overwrite)
        {
            try
            {
                if (!name.EndsWith(".reminder19"))
                    name += ".reminder19";

                if (File.Exists(name) && overwrite)
                {
                    File.Delete(name);
                }
                else if (File.Exists(name) && !overwrite)
                {
                    throw new Exception("Database already exists.");
                }

                SQLiteConnection.CreateFile(name);
                conn = new SQLiteConnection("Data Source=" + name);
                conn.Open();
                conn.ChangePassword("reminder19!!!");

                //Create the tables
                SQLiteCommand cmd = conn.CreateCommand();
                cmd.CommandText = createAlertsTable;
                cmd.ExecuteNonQuery();
                cmd.Dispose();

                initSettingsTable();
            }
            catch (Exception)
            {
                MsgBox.Show(true, "Failed to create database!  Please make sure the Reminder 19 directory can be written to!",
                    "Fatal Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
        }
 private void SetPwdClick(object sender, RoutedEventArgs e)
 {
     using (var sqliteConn = new SQLiteConnection(string.Format(@"Data Source={0}\Abiz.db3;UTF8Encoding=True;Version=3;Pooling=True", txt.Text)))
     {
         sqliteConn.Open();
         sqliteConn.ChangePassword(_pwd);
         sqliteConn.Close();
     }
 }
Example #22
0
        private void InitDatabase()
        {
            // Create the connection string needed.
            dbConnection = new SQLiteConnection("Data Source =" + dbName + ";" + "Version = 3;");

            // Associate the connection string with an SQLiteCommand.
            dbCommand = new SQLiteCommand(dbConnection);

            // Check if the database-file exists.
            if (!File.Exists(dbName))
            {
                // Create the database-file.
                SQLiteConnection.CreateFile(dbName);

                // Open the newly created database.
                dbConnection.Open();

                // Create a table called "mailaddresses" with nine columns.
                dbCommand.CommandText =   "CREATE TABLE mailaddresses (address TEXT, password TEXT, receiveserver TEXT, receiveport INT, receivessl TEXT,"
                                      + "sendserver TEXT, sendport INT, sendssl TEXT, autologin TEXT);";

                // Execute the newly created command.
                dbCommand.ExecuteNonQuery();

                // Create a table called "mails" with two columns called "address" and "rawmessage".
                dbCommand.CommandText = "CREATE TABLE mails (address TEXT, rawmessage TEXT);";

                // Execute the newly created command.
                dbCommand.ExecuteNonQuery();

                // Give the database a simple password.
                dbConnection.ChangePassword(dbPassword);

                // Close the database again.
                dbConnection.Close();
            }

            // Add the password to the connection string.
            dbCommand.Connection.ConnectionString += "Password ="******";";

            // Close the database again.
            dbConnection.Close();
        }