public bool Next()
        {
            this.CheckDisposed();
            this.CheckHandle();
            SQLiteErrorCode sQLiteErrorCode  = UnsafeNativeMethods.sqlite3changeset_next(this.iterator);
            SQLiteErrorCode sQLiteErrorCode1 = sQLiteErrorCode;

            if (sQLiteErrorCode1 == SQLiteErrorCode.Ok)
            {
                throw new SQLiteException(SQLiteErrorCode.Ok, "sqlite3changeset_next: unexpected result Ok");
            }
            switch (sQLiteErrorCode1)
            {
            case SQLiteErrorCode.Row:
            {
                return(true);
            }

            case SQLiteErrorCode.Done:
            {
                return(false);
            }
            }
            throw new SQLiteException(sQLiteErrorCode, "sqlite3changeset_next");
        }
Ejemplo n.º 2
0
 public static void Initialize()
 {
     if (SQLite3.StaticIsInitialized())
     {
         return;
     }
     if (!AppDomain.CurrentDomain.IsDefaultAppDomain() && UnsafeNativeMethods.GetSettingValue("Force_SQLiteLog", null) == null)
     {
         return;
     }
     lock (SQLiteLog.syncRoot)
     {
         if (SQLiteLog._domainUnload == null)
         {
             SQLiteLog._domainUnload = new EventHandler(SQLiteLog.DomainUnload);
             AppDomain.CurrentDomain.DomainUnload += SQLiteLog._domainUnload;
         }
         if (SQLiteLog._sql == null)
         {
             SQLiteLog._sql = new SQLite3(SQLiteDateFormats.ISO8601, DateTimeKind.Unspecified, null, IntPtr.Zero, null, false);
         }
         if (SQLiteLog._callback == null)
         {
             SQLiteLog._callback = new SQLiteLogCallback(SQLiteLog.LogCallback);
             SQLiteErrorCode sQLiteErrorCode = SQLiteLog._sql.SetLogCallback(SQLiteLog._callback);
             if (sQLiteErrorCode != SQLiteErrorCode.Ok)
             {
                 throw new SQLiteException(sQLiteErrorCode, "Failed to initialize logging.");
             }
         }
         SQLiteLog._enabled = true;
         SQLiteLog.AddDefaultHandler();
     }
 }
Ejemplo n.º 3
0
        ///////////////////////////////////////////////////////////////////////////

#if !PLATFORM_COMPACTFRAMEWORK
        /// <summary>
        /// Private constructor for use with serialization.
        /// </summary>
        /// <param name="info">
        /// Holds the serialized object data about the exception being thrown.
        /// </param>
        /// <param name="context">
        /// Contains contextual information about the source or destination.
        /// </param>
        private SQLiteException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            _errorCode = (SQLiteErrorCode)info.GetInt32("errorCode");

            Initialize();
        }
Ejemplo n.º 4
0
        private static void LogEventHandler(object sender, LogEventArgs e)
        {
            if (e == null)
            {
                return;
            }
            string message = e.Message;

            if (message != null)
            {
                message = message.Trim();
                if (message.Length == 0)
                {
                    message = "<empty>";
                }
            }
            else
            {
                message = "<null>";
            }
            object errorCode = e.ErrorCode;
            string str       = "error";

            if (errorCode as SQLiteErrorCode? != SQLiteErrorCode.Ok || errorCode is int)
            {
                SQLiteErrorCode sQLiteErrorCode = (SQLiteErrorCode)((int)(errorCode ?? -1));
                sQLiteErrorCode &= SQLiteErrorCode.NonExtendedMask;
                if (sQLiteErrorCode == SQLiteErrorCode.Ok)
                {
                    str = "message";
                }
                else if (sQLiteErrorCode == SQLiteErrorCode.Notice)
                {
                    str = "notice";
                }
                else if (sQLiteErrorCode == SQLiteErrorCode.Warning)
                {
                    str = "warning";
                }
                else if (sQLiteErrorCode == SQLiteErrorCode.Row || sQLiteErrorCode == SQLiteErrorCode.Done)
                {
                    str = "data";
                }
            }
            else if (errorCode == null)
            {
                str = "trace";
            }
            if (errorCode == null || object.ReferenceEquals(errorCode, string.Empty))
            {
                CultureInfo currentCulture = CultureInfo.CurrentCulture;
                object[]    objArray       = new object[] { str, message };
                Trace.WriteLine(HelperMethods.StringFormat(currentCulture, "SQLite {0}: {1}", objArray));
                return;
            }
            CultureInfo cultureInfo = CultureInfo.CurrentCulture;

            object[] objArray1 = new object[] { str, errorCode, message };
            Trace.WriteLine(HelperMethods.StringFormat(cultureInfo, "SQLite {0} ({1}): {2}", objArray1));
        }
Ejemplo n.º 5
0
        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Default logger.  Currently, uses the Trace class (i.e. sends events
        /// to the current trace listeners, if any).
        /// </summary>
        /// <param name="sender">Should be null.</param>
        /// <param name="e">The data associated with this event.</param>
        private static void LogEventHandler(
            object sender,
            LogEventArgs e
            )
        {
#if !NET_COMPACT_20
            if (e == null)
            {
                return;
            }

            string message = e.Message;

            if (message == null)
            {
                message = "<null>";
            }
            else
            {
                message = message.Trim();

                if (message.Length == 0)
                {
                    message = "<empty>";
                }
            }

            object errorCode = e.ErrorCode;
            string type      = "error";

            if ((errorCode is SQLiteErrorCode) || (errorCode is int))
            {
                SQLiteErrorCode rc = (SQLiteErrorCode)(int)errorCode;

                rc &= SQLiteErrorCode.NonExtendedMask;

                if (rc == SQLiteErrorCode.Ok)
                {
                    type = "message";
                }
                else if (rc == SQLiteErrorCode.Notice)
                {
                    type = "notice";
                }
                else if (rc == SQLiteErrorCode.Warning)
                {
                    type = "warning";
                }
                else if ((rc == SQLiteErrorCode.Row) ||
                         (rc == SQLiteErrorCode.Done))
                {
                    type = "data";
                }
            }

            Trace.WriteLine(String.Format(
                                CultureInfo.CurrentCulture, "SQLite {0} ({1}): {2}",
                                type, errorCode, message));
#endif
        }
Ejemplo n.º 6
0
        public void InsertNewUsers(string name, string password, string path)
        {
            MyLogger.Log($"inserting new user name : {name} password : {password} path : {path}");
            // INSERT INTO DATABASE
            query = "INSERT INTO users (name, password, pathToDir) VALUES (@name, @password, @path)";

            try
            {
                using (SQLiteCommand myCommand = new SQLiteCommand(query, MyConnection()))
                {
                    OpenConnection();
                    myCommand.Parameters.AddWithValue("@name", name);
                    myCommand.Parameters.AddWithValue("@password", password);
                    myCommand.Parameters.AddWithValue("@path", path);
                    returnValue = myCommand.ExecuteNonQuery();
                    CloseConnection();
                    Console.WriteLine("Rows Added : {0}", returnValue);
                }
                MyLogger.Log($"Inserting of {name} and {password} and {path} is completed");
            }
            catch (SQLiteException exc)
            {
                SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                MyLogger.Log(exc.ToString());
            }
        }
Ejemplo n.º 7
0
        ///////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Public constructor for generating a SQLite exception given the error
        /// code and message.
        /// </summary>
        /// <param name="errorCode">
        /// The SQLite return code to report.
        /// </param>
        /// <param name="message">
        /// Message text to go along with the return code message text.
        /// </param>
        public SQLiteException(SQLiteErrorCode errorCode, string message)
            : base(GetStockErrorMessage(errorCode, message))
        {
            _errorCode = errorCode;

            Initialize();
        }
Ejemplo n.º 8
0
        public async void updatePwd(string userName, string newPass)// update user password
        {
            await MyLogger.Log($"updating PWD by username : {userName} and PWD {newPass}");

            query = "UPDATE users SET password = @password WHERE name = @name";
            try
            {
                using (SQLiteCommand myCommand = new SQLiteCommand(query, MyConnection()))
                {
                    OpenConnection();
                    myCommand.Parameters.AddWithValue("@password", newPass);
                    myCommand.Parameters.AddWithValue("@name", userName);
                    try
                    {
                        returnValue = myCommand.ExecuteNonQuery();
                    }
                    catch (SQLiteException exc)
                    {
                        SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                    }

                    MyLogger.Log("pwd updated");
                    CloseConnection();
                }
            }
            catch (SQLiteException exc)
            {
                SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                MyLogger.Log(exc.ToString());
            }
        }
Ejemplo n.º 9
0
 private void ThrowOnError(SQLiteErrorCode errorCode)
 {
     if (errorCode != SQLiteErrorCode.Ok)
     {
         throw new SQLiteException(errorCode, DatabaseHandle);
     }
 }
Ejemplo n.º 10
0
        public async void CreateTable()
        {
            await MyLogger.Log("creating table if not exist");

            // CREATE NEW TABLE
            query = @"CREATE TABLE IF NOT EXISTS
                             [users] (
                             [id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                             [name] TEXT,
                             [password] TEXT,
                             [pathToDir] TEXT)";
            try
            {
                using (SQLiteCommand myCommand = new SQLiteCommand(query, MyConnection()))
                {
                    OpenConnection();
                    myCommand.CommandText = query;
                    myCommand.ExecuteNonQuery();
                    CloseConnection();
                }
                MyLogger.Log("Table Created ");
            }
            catch (SQLiteException exc)
            {
                SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                MyLogger.Log(exc.ToString());
            }
        }
Ejemplo n.º 11
0
        public SQLiteConnection MyConnection()
        {
            if (!File.Exists("./database.sqlite3"))
            {
                try
                {
                    MyLogger.Log("trying to create DB ");
                    SQLiteConnection.CreateFile("database.sqlite3"); //creating the DB
                    MyLogger.Log("trying to create table ");
                    CreateTable();                                   // creating the table ''
                }
                catch (SQLiteException exc)
                {
                    SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                    MyLogger.Log(exc.ToString());
                }

                MyLogger.Log("DB created ! ");
            }

            try
            {
                MyLogger.Log("trying connect to DB ");
                myConnection = new SQLiteConnection("Data Source=database.sqlite3");
            }
            catch (SQLiteException exc)
            {
                SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                MyLogger.Log(exc.ToString());
            }
            return(myConnection);
        }
        public void Lock()
        {
            this.CheckDisposed();
            if (this.statement != IntPtr.Zero)
            {
                return;
            }
            IntPtr zero = IntPtr.Zero;

            try
            {
                int num = 0;
                zero = SQLiteString.Utf8IntPtrFromString("SELECT 1;", ref num);
                IntPtr          intPtr          = IntPtr.Zero;
                int             num1            = 0;
                SQLiteErrorCode sQLiteErrorCode = UnsafeNativeMethods.sqlite3_prepare_interop(this.GetIntPtr(), zero, num, ref this.statement, ref intPtr, ref num1);
                if (sQLiteErrorCode != SQLiteErrorCode.Ok)
                {
                    throw new SQLiteException(sQLiteErrorCode, "sqlite3_prepare_interop");
                }
            }
            finally
            {
                if (zero != IntPtr.Zero)
                {
                    SQLiteMemory.Free(zero);
                    zero = IntPtr.Zero;
                }
            }
        }
Ejemplo n.º 13
0
Archivo: SqlDB.cs Proyecto: Solaire/GLC
        /// <summary>
        /// Prepare and execure SELECT statement
        /// </summary>
        /// <returns>SQL success/failure status code</returns>
        public SQLiteErrorCode Select()
        {
            m_selectResult = null;
            string mainStmt       = PrepareMainStatement(CSqlField.QryFlag.cSelRead);
            string whereCondition = PrepareWhereStatement(CSqlField.QryFlag.cSelWhere);

            string query = "SELECT " + mainStmt + " FROM " + m_tableName;

            if (whereCondition.Length > 0)
            {
                query += " WHERE " + whereCondition;
            }
            if (SelectExtraCondition.Length > 0)
            {
                query += " " + SelectExtraCondition;
            }
            SQLiteErrorCode err = CSqlDB.Instance.ExecuteRead(query, out m_selectResult);

            if (err == SQLiteErrorCode.Ok)
            {
                if (!Fetch()) // Perform a fetch on the first row, if available
                {
                    return(SQLiteErrorCode.NotFound);
                }
            }
            return(err);
        }
Ejemplo n.º 14
0
 public static void ThrowOnError(this SQLiteErrorCode errorCode)
 {
     if (errorCode != SQLiteErrorCode.Ok)
     {
         throw new SQLiteException(errorCode);
     }
 }
Ejemplo n.º 15
0
        public void CreateChangeSet(ref byte[] rawData)
        {
            this.CheckDisposed();
            this.CheckHandle();
            IntPtr zero = IntPtr.Zero;

            try
            {
                int             num             = 0;
                SQLiteErrorCode sQLiteErrorCode = UnsafeNativeMethods.sqlite3session_changeset(this.session, ref num, ref zero);
                if (sQLiteErrorCode != SQLiteErrorCode.Ok)
                {
                    throw new SQLiteException(sQLiteErrorCode, "sqlite3session_changeset");
                }
                rawData = SQLiteBytes.FromIntPtr(zero, num);
            }
            finally
            {
                if (zero != IntPtr.Zero)
                {
                    SQLiteMemory.Free(zero);
                    zero = IntPtr.Zero;
                }
            }
        }
Ejemplo n.º 16
0
 private static void DomainUnload(object sender, EventArgs e)
 {
     lock (SQLiteLog.syncRoot)
     {
         SQLiteLog.RemoveDefaultHandler();
         SQLiteLog._enabled = false;
         if (SQLiteLog._sql != null)
         {
             SQLiteErrorCode sQLiteErrorCode = SQLiteLog._sql.Shutdown();
             if (sQLiteErrorCode != SQLiteErrorCode.Ok)
             {
                 throw new SQLiteException(sQLiteErrorCode, "Failed to shutdown interface.");
             }
             sQLiteErrorCode = SQLiteLog._sql.SetLogCallback(null);
             if (sQLiteErrorCode != SQLiteErrorCode.Ok)
             {
                 throw new SQLiteException(sQLiteErrorCode, "Failed to shutdown logging.");
             }
         }
         if (SQLiteLog._callback != null)
         {
             SQLiteLog._callback = null;
         }
         if (SQLiteLog._domainUnload != null)
         {
             AppDomain.CurrentDomain.DomainUnload -= SQLiteLog._domainUnload;
             SQLiteLog._domainUnload = null;
         }
     }
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Encrypt an SQLite database
        /// </summary>
        /// <param name="dbName">Fully Qulified File Name of the SQLite database</param>
        /// <param name="password">Password</param>
        /// <returns></returns>
        internal static bool EncryptDB(string dbName, string password, out SQLiteErrorCode returnCode)
        {
            SQLiteConnection conn = null;
            SQLiteCommand    cmd  = null;

            returnCode = SQLiteErrorCode.Ok;

            if (!OpenDB(dbName, ref conn, ref cmd, out returnCode, true))
            {
                return(false);
            }

            try
            {
                conn.ChangePassword(password);
            }
            catch (Exception ex)
            {
                returnCode = conn.ExtendedResultCode();
                LastError  = ex.Message;
                return(false);
            }
            finally { CloseDB(conn); }
            return(true);
        }
Ejemplo n.º 18
0
        internal static bool BackupDatabase(string DBLocation, string BackupDBName, out SQLiteErrorCode returnCode)
        {
            SQLiteConnection conn     = null;
            SQLiteCommand    cmd      = null;
            SQLiteConnection connDest = new SQLiteConnection();
            SQLiteCommand    cmdDest  = null;

            returnCode = SQLiteErrorCode.Ok;

            if (!OpenDB(DBLocation, ref conn, ref cmd, out returnCode))
            {
                return(false);
            }
            if (!OpenDB(BackupDBName, ref connDest, ref cmdDest, out returnCode))
            {
                CloseDB(conn);
                return(false);
            }

            try
            {
                bCancelBackup = false;
                conn.BackupDatabase(connDest, "main", "main", 80, BackupCallback, 1000);
                return(true);
            }
            catch (Exception ex)
            {
                LastError  = ex.Message;
                returnCode = conn.ExtendedResultCode();
                return(false);
            }
            finally { CloseDB(conn); CloseDB(connDest); }
        }
        public void AddChangeSet(byte[] rawData)
        {
            this.CheckDisposed();
            this.CheckHandle();
            SQLiteSessionHelpers.CheckRawData(rawData);
            IntPtr zero = IntPtr.Zero;

            try
            {
                int num = 0;
                zero = SQLiteBytes.ToIntPtr(rawData, ref num);
                SQLiteErrorCode sQLiteErrorCode = UnsafeNativeMethods.sqlite3changegroup_add(this.changeGroup, num, zero);
                if (sQLiteErrorCode != SQLiteErrorCode.Ok)
                {
                    throw new SQLiteException(sQLiteErrorCode, "sqlite3changegroup_add");
                }
            }
            finally
            {
                if (zero != IntPtr.Zero)
                {
                    SQLiteMemory.Free(zero);
                    zero = IntPtr.Zero;
                }
            }
        }
Ejemplo n.º 20
0
        public void Apply(SessionConflictCallback conflictCallback, SessionTableFilterCallback tableFilterCallback, object clientData)
        {
            this.CheckDisposed();
            SQLiteSessionHelpers.CheckRawData(this.rawData);
            if (conflictCallback == null)
            {
                throw new ArgumentNullException("conflictCallback");
            }
            UnsafeNativeMethods.xSessionFilter   @delegate         = base.GetDelegate(tableFilterCallback, clientData);
            UnsafeNativeMethods.xSessionConflict _xSessionConflict = base.GetDelegate(conflictCallback, clientData);
            IntPtr zero = IntPtr.Zero;

            try
            {
                int num = 0;
                zero = SQLiteBytes.ToIntPtr(this.rawData, ref num);
                SQLiteErrorCode sQLiteErrorCode = UnsafeNativeMethods.sqlite3changeset_apply(base.GetIntPtr(), num, zero, @delegate, _xSessionConflict, IntPtr.Zero);
                if (sQLiteErrorCode != SQLiteErrorCode.Ok)
                {
                    throw new SQLiteException(sQLiteErrorCode, "sqlite3changeset_apply");
                }
            }
            finally
            {
                if (zero != IntPtr.Zero)
                {
                    SQLiteMemory.Free(zero);
                    zero = IntPtr.Zero;
                }
            }
        }
Ejemplo n.º 21
0
        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Log a message to all the registered log event handlers without going
        /// through the SQLite library.
        /// </summary>
        /// <param name="errorCode">The SQLite error code.</param>
        /// <param name="message">The message to be logged.</param>
        public static void LogMessage(
            SQLiteErrorCode errorCode,
            string message
            )
        {
            LogMessage((object)errorCode, message);
        }
Ejemplo n.º 22
0
        internal static void CloseConnectionV2(SQLiteConnectionHandle hdl, IntPtr db)
        {
            if ((hdl == null) || (db == IntPtr.Zero))
            {
                return;
            }

            try
            {
                // do nothing.
            }
            finally /* NOTE: Thread.Abort() protection. */
            {
#if PLATFORM_COMPACTFRAMEWORK
                lock (hdl.syncRoot)
#else
                lock (hdl)
#endif
                {
#if !SQLITE_STANDARD
                    SQLiteErrorCode n = UnsafeNativeMethods.sqlite3_close_interop(db);
#else
                    ResetConnection(hdl, db, false);

                    SQLiteErrorCode n = UnsafeNativeMethods.sqlite3_close_v2(db);
#endif
                    if (n != SQLiteErrorCode.Ok)
                    {
                        throw new SQLiteException(n, GetLastError(hdl, db));
                    }
                }
            }
        }
Ejemplo n.º 23
0
        internal static void FinalizeStatement(SQLiteConnectionHandle hdl, IntPtr stmt)
        {
            if ((hdl == null) || (stmt == IntPtr.Zero))
            {
                return;
            }

            try
            {
                // do nothing.
            }
            finally /* NOTE: Thread.Abort() protection. */
            {
#if PLATFORM_COMPACTFRAMEWORK
                lock (hdl.syncRoot)
#else
                lock (hdl)
#endif
                {
#if !SQLITE_STANDARD
                    SQLiteErrorCode n = UnsafeNativeMethods.sqlite3_finalize_interop(stmt);
#else
                    SQLiteErrorCode n = UnsafeNativeMethods.sqlite3_finalize(stmt);
#endif
                    if (n != SQLiteErrorCode.Ok)
                    {
                        throw new SQLiteException(n, null);
                    }
                }
            }
        }
        private static string GetStockErrorMessage(SQLiteErrorCode errorCode, string message)
        {
            CultureInfo currentCulture = CultureInfo.CurrentCulture;

            object[] errorString = new object[] { SQLiteException.GetErrorString(errorCode), Environment.NewLine, message };
            return(HelperMethods.StringFormat(currentCulture, "{0}{1}{2}", errorString).Trim());
        }
        private static string GetErrorString(SQLiteErrorCode errorCode)
        {
            BindingFlags bindingFlag = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
            Type         type        = typeof(SQLite3);

            object[] objArray = new object[] { errorCode };
            return(type.InvokeMember("GetErrorString", bindingFlag, null, null, objArray) as string);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Display an abbreviated error message in the statusbar and place the entire message in the tooltip for the message.
        /// </summary>
        /// <param name="errMessage">Message to display.</param>
        /// <param name="returnCode">Error code returned by SQLite.</param>
        private void GenerateErrorMessage(string errMessage, SQLiteErrorCode returnCode)
        {
            string eMsg = string.Format(errMessage, DataAccess.LastError, returnCode.ToString());

            toolStripExecutionStatus.Text        = eMsg.IndexOf(":") > 0 ? eMsg.Substring(0, eMsg.IndexOf(":")) : eMsg.Substring(0, 18);
            toolStripExecutionStatus.ToolTipText = eMsg;
            btnExecute.Enabled = true;
        }
Ejemplo n.º 27
0
 public void SetErrorCode(SQLiteErrorCode value)
 {
     if (this.pContext == IntPtr.Zero)
     {
         throw new InvalidOperationException();
     }
     UnsafeNativeMethods.sqlite3_result_error_code(this.pContext, value);
 }
Ejemplo n.º 28
0
 protected virtual bool ResultCodeToFindFunctionResult(SQLiteErrorCode resultCode)
 {
     if (resultCode != SQLiteErrorCode.Ok)
     {
         return(false);
     }
     return(true);
 }
Ejemplo n.º 29
0
        ///////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Creates a <see cref="SQLiteBlob" /> object.  This will not work
        /// for tables that were created WITHOUT ROWID.
        /// </summary>
        /// <param name="connection">
        /// The connection to use when opening the blob object.
        /// </param>
        /// <param name="databaseName">
        /// The name of the database containing the blob object.
        /// </param>
        /// <param name="tableName">
        /// The name of the table containing the blob object.
        /// </param>
        /// <param name="columnName">
        /// The name of the column containing the blob object.
        /// </param>
        /// <param name="rowId">
        /// The integer identifier for the row associated with the desired
        /// blob object.
        /// </param>
        /// <param name="readOnly">
        /// Non-zero to open the blob object for read-only access.
        /// </param>
        /// <returns>
        /// The newly created <see cref="SQLiteBlob" /> instance -OR- null
        /// if an error occurs.
        /// </returns>
        public static SQLiteBlob Create(
            SQLiteConnection connection,
            string databaseName,
            string tableName,
            string columnName,
            long rowId,
            bool readOnly
            )
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            SQLite3 sqlite3 = connection._sql as SQLite3;

            if (sqlite3 == null)
            {
                throw new InvalidOperationException("Connection has no wrapper");
            }

            SQLiteConnectionHandle handle = sqlite3._sql;

            if (handle == null)
            {
                throw new InvalidOperationException("Connection has an invalid handle.");
            }

            SQLiteBlobHandle blob = null;

            try
            {
                // do nothing.
            }
            finally /* NOTE: Thread.Abort() protection. */
            {
                IntPtr ptrBlob = IntPtr.Zero;

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3_blob_open(
                    handle, SQLiteConvert.ToUTF8(databaseName),
                    SQLiteConvert.ToUTF8(tableName), SQLiteConvert.ToUTF8(
                        columnName), rowId, readOnly ? 0 : 1, ref ptrBlob);

                if (rc != SQLiteErrorCode.Ok)
                {
                    throw new SQLiteException(rc, null);
                }

                blob = new SQLiteBlobHandle(handle, ptrBlob);
            }

            SQLiteConnection.OnChanged(connection, new ConnectionEventArgs(
                                           SQLiteConnectionEventType.NewCriticalHandle, null, null,
                                           null, null, blob, null, new object[] { typeof(SQLiteBlob),
                                                                                  databaseName, tableName, columnName, rowId, readOnly }));

            return(new SQLiteBlob(sqlite3, blob));
        }
Ejemplo n.º 30
0
 protected virtual bool SetMethodResultCode(string methodName, SQLiteErrorCode resultCode)
 {
     if (methodName == null || this.resultCodes == null)
     {
         return(false);
     }
     this.resultCodes[methodName] = resultCode;
     return(true);
 }
		private static string GetErrorString(SQLiteErrorCode errorCode, SqliteDatabaseHandle database)
		{
#if NET45
			string errorString = SQLiteConnection.FromUtf8(NativeMethods.sqlite3_errstr(errorCode));
#else
			string errorString = errorCode.ToString();
#endif
			return database != null ? "{0}: {1}".FormatInvariant(errorString, SQLiteConnection.FromUtf8(NativeMethods.sqlite3_errmsg(database)))
				: errorString;
		}
Ejemplo n.º 32
0
    /// <summary>
    /// Returns the error message for the specified SQLite return code using
    /// the sqlite3_errstr() function, falling back to the internal lookup
    /// table if necessary.
    /// </summary>
    /// <param name="rc">The SQLite return code.</param>
    /// <returns>The error message or null if it cannot be found.</returns>
    internal static string GetErrorString(SQLiteErrorCode rc)
    {
        try
        {
            IntPtr ptr = UnsafeNativeMethods.sqlite3_errstr(rc);

            if (ptr != IntPtr.Zero)
            {
#if !PLATFORM_COMPACTFRAMEWORK
                return Marshal.PtrToStringAnsi(ptr);
#else
                return UTF8ToString(ptr, -1);
#endif
            }
        }
        catch (EntryPointNotFoundException)
        {
            // do nothing.
        }

        return FallbackGetErrorString(rc);
    }
Ejemplo n.º 33
0
    ///////////////////////////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// Returns the error message for the specified SQLite return code using
    /// the internal static lookup table.
    /// </summary>
    /// <param name="rc">The SQLite return code.</param>
    /// <returns>The error message or null if it cannot be found.</returns>
    private static string FallbackGetErrorString(SQLiteErrorCode rc)
    {
        if (_errorMessages == null)
            return null;

        int index = (int)rc;

        if ((index < 0) || (index >= _errorMessages.Length))
            index = (int)SQLiteErrorCode.Error; /* Make into generic error. */

        return _errorMessages[index];
    }
Ejemplo n.º 34
0
 /// <summary>
 /// Add a log message via the SQLite sqlite3_log interface.
 /// </summary>
 /// <param name="iErrCode">Error code to be logged with the message.</param>
 /// <param name="zMessage">String to be logged.  Unlike the SQLite sqlite3_log()
 /// interface, this should be pre-formatted.  Consider using the
 /// String.Format() function.</param>
 /// <returns></returns>
 internal abstract void LogMessage(SQLiteErrorCode iErrCode, string zMessage);
Ejemplo n.º 35
0
 /// <summary>
 /// Private constructor for use with serialization.
 /// </summary>
 /// <param name="info">
 /// Holds the serialized object data about the exception being thrown.
 /// </param>
 /// <param name="context">
 /// Contains contextual information about the source or destination.
 /// </param>
 private SQLiteException(SerializationInfo info, StreamingContext context)
   : base(info, context)
 {
   _errorCode = (SQLiteErrorCode)info.GetInt32("errorCode");
 }
		public SQLiteException(SQLiteErrorCode errorCode)
			: this(errorCode, null)
		{
		}
 internal static extern IntPtr sqlite3_errstr(SQLiteErrorCode rc); /* 3.7.15+ */
Ejemplo n.º 38
0
        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Converts a <see cref="SQLiteErrorCode" /> value into a boolean
        /// return value for use with the
        /// <see cref="ISQLiteManagedModule.Eof" /> method.
        /// </summary>
        /// <param name="resultCode">
        /// The <see cref="SQLiteErrorCode" /> value to convert.
        /// </param>
        /// <returns>
        /// The <see cref="Boolean" /> value.
        /// </returns>
        protected virtual bool ResultCodeToEofResult(
            SQLiteErrorCode resultCode
            )
        {
            return (resultCode == SQLiteErrorCode.Ok) ? false : true;
        }
Ejemplo n.º 39
0
        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Log a message to all the registered log event handlers without going
        /// through the SQLite library.
        /// </summary>
        /// <param name="errorCode">The SQLite error code.</param>
        /// <param name="message">The message to be logged.</param>
        public static void LogMessage(
            SQLiteErrorCode errorCode,
            string message
            )
        {
            LogMessage((object)errorCode, message);
        }
Ejemplo n.º 40
0
 /// Add a log message via the SQLite sqlite3_log interface.
 internal override void LogMessage(SQLiteErrorCode iErrCode, string zMessage)
 {
   UnsafeNativeMethods.sqlite3_log(iErrCode, ToUTF8(zMessage));
 }
Ejemplo n.º 41
0
        /// <summary>
        /// Logs sqlite database exceptions
        /// </summary>
        /// <param name="code">SQLiteErrorCode</param>
        /// <param name="sql">String</param>
        public static void LogSQLiteExceptionReason(SQLiteErrorCode code, String sql = "")
        {
            String msg = LearnByError.Internazional.Resource.Inst.Get("r139");
            switch (code)
            {
                case SQLiteErrorCode.Abort:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r140");
                    break;
                case SQLiteErrorCode.CantOpen:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r141");
                    break;
                case SQLiteErrorCode.Corrupt:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r142");
                    break;
                case SQLiteErrorCode.Locked:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r143");
                    break;
                case SQLiteErrorCode.NoMem:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r144");
                    break;
                case SQLiteErrorCode.NotFound:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r145");
                    break;
                case SQLiteErrorCode.Perm:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r146");
                    break;
                case SQLiteErrorCode.ReadOnly:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r147");
                    break;
                case SQLiteErrorCode.Schema:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r148");
                    break;
                case SQLiteErrorCode.Error:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r149") + sql;
                    break;
                case SQLiteErrorCode.Empty:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r150");
                    break;
                case SQLiteErrorCode.TooBig:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r151");
                    break;
                case SQLiteErrorCode.Misuse:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r152");
                    break;
                case SQLiteErrorCode.NotADb:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r153");
                    break;
                default:
                    msg += LearnByError.Internazional.Resource.Inst.Get("r154");
                    break;
            }

            Error = msg;
            Common.Log.Write(msg);
        }
Ejemplo n.º 42
0
    /// <summary>
    /// Returns the error message for the specified SQLite return code.
    /// </summary>
    /// <param name="errorCode">The SQLite return code.</param>
    /// <returns>The error message or null if it cannot be found.</returns>
    private static string GetErrorString(
        SQLiteErrorCode errorCode
        )
    {
#if !PLATFORM_COMPACTFRAMEWORK
        //
        // HACK: This must be done via reflection in order to prevent
        //       the RuntimeHelpers.PrepareDelegate method from over-
        //       eagerly attempting to locate the new (and optional)
        //       sqlite3_errstr() function in the SQLite core library
        //       because it happens to be in the static call graph for
        //       the AppDomain.DomainUnload event handler registered
        //       by the SQLiteLog class.
        //
        BindingFlags flags = BindingFlags.Static |
            BindingFlags.NonPublic | BindingFlags.InvokeMethod;

        return typeof(SQLiteBase).InvokeMember("GetErrorString",
            flags, null, null, new object[] { errorCode }) as string;
#else
        return SQLiteBase.GetErrorString(errorCode);
#endif
    }
Ejemplo n.º 43
0
    /// <summary>
    /// Returns the composite error message based on the SQLite return code
    /// and the optional detailed error message.
    /// </summary>
    /// <param name="errorCode">The SQLite return code.</param>
    /// <param name="message">Optional detailed error message.</param>
    /// <returns>Error message text for the return code.</returns>
    private static string GetStockErrorMessage(
        SQLiteErrorCode errorCode,
        string message
        )
    {
        return String.Format("{0}{1}{2}",
            GetErrorString(errorCode),
#if !NET_COMPACT_20
            Environment.NewLine, message).Trim();
#else
            "\r\n", message).Trim();
#endif
    }
 internal static extern void sqlite3_log(SQLiteErrorCode iErrCode, byte[] zFormat);
Ejemplo n.º 45
0
        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Converts a <see cref="SQLiteErrorCode" /> value into a boolean
        /// return value for use with the
        /// <see cref="ISQLiteManagedModule.FindFunction" /> method.
        /// </summary>
        /// <param name="resultCode">
        /// The <see cref="SQLiteErrorCode" /> value to convert.
        /// </param>
        /// <returns>
        /// The <see cref="Boolean" /> value.
        /// </returns>
        protected virtual bool ResultCodeToFindFunctionResult(
            SQLiteErrorCode resultCode
            )
        {
            return (resultCode == SQLiteErrorCode.Ok) ? true : false;
        }
Ejemplo n.º 46
0
        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Sets the <see cref="SQLiteErrorCode" /> value that should be
        /// returned by the specified <see cref="ISQLiteManagedModule" />
        /// interface method if it lack an overridden implementation.
        /// </summary>
        /// <param name="methodName">
        /// The name of the method.  Currently, this method must be part of
        /// the <see cref="ISQLiteManagedModule" /> interface.
        /// </param>
        /// <param name="resultCode">
        /// The <see cref="SQLiteErrorCode" /> value that should be returned
        /// by the <see cref="ISQLiteManagedModule" /> interface method.
        /// </param>
        /// <returns>
        /// Non-zero upon success.
        /// </returns>
        protected virtual bool SetMethodResultCode(
            string methodName,
            SQLiteErrorCode resultCode
            )
        {
            if ((methodName == null) || (resultCodes == null))
                return false;

            resultCodes[methodName] = resultCode;
            return true;
        }
Ejemplo n.º 47
0
    /// <summary>
    /// Returns the composite error message based on the SQLite return code
    /// and the optional detailed error message.
    /// </summary>
    /// <param name="errorCode">The SQLite return code.</param>
    /// <param name="message">Optional detailed error message.</param>
    /// <returns>Error message text for the return code.</returns>
    private static string GetStockErrorMessage(
        SQLiteErrorCode errorCode,
        string message
        )
    {
        return UnsafeNativeMethods.StringFormat(
            CultureInfo.CurrentCulture,
            "{0}{1}{2}",
            GetErrorString(errorCode),
#if !NET_COMPACT_20
            Environment.NewLine, message).Trim();
#else
            "\r\n", message).Trim();
#endif
    }
    /// Add a log message via the SQLite sqlite3_log interface.
    public void LogMessage(SQLiteErrorCode iErrCode, string zMessage)
    {
      CheckDisposed();

      if (_sql == null)
          throw new InvalidOperationException("Database connection not valid for logging message.");

      _sql.LogMessage(iErrCode, zMessage);
    }
 internal static extern void sqlite3_result_error_code(IntPtr context, SQLiteErrorCode value);
Ejemplo n.º 50
0
    /// <summary>
    /// Returns the error message for the specified SQLite return code using
    /// the sqlite3_errstr() function, falling back to the internal lookup
    /// table if necessary.
    /// </summary>
    /// <param name="rc">The SQLite return code.</param>
    /// <returns>The error message or null if it cannot be found.</returns>
    internal static string GetErrorString(SQLiteErrorCode rc)
    {
        try
        {
            if (have_errstr == null)
            {
                int versionNumber = SQLiteVersionNumber;
                have_errstr = (versionNumber >= 3007015);
            }

            if ((bool)have_errstr)
            {
                IntPtr ptr = UnsafeNativeMethods.sqlite3_errstr(rc);

                if (ptr != IntPtr.Zero)
                {
#if !PLATFORM_COMPACTFRAMEWORK
                    return Marshal.PtrToStringAnsi(ptr);
#else
                    return UTF8ToString(ptr, -1);
#endif
                }
            }
        }
        catch (EntryPointNotFoundException)
        {
            // do nothing.
        }

        return FallbackGetErrorString(rc);
    }
Ejemplo n.º 51
0
 /// Add a log message via the SQLite sqlite3_log interface.
 internal static void StaticLogMessage(SQLiteErrorCode iErrCode, string zMessage)
 {
   UnsafeNativeMethods.sqlite3_log(iErrCode, ToUTF8(zMessage));
 }
Ejemplo n.º 52
0
		public static extern IntPtr sqlite3_errstr(SQLiteErrorCode rc);
Ejemplo n.º 53
0
        ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Sets the context result to the specified <see cref="SQLiteErrorCode" />
        /// value.
        /// </summary>
        /// <param name="value">
        /// The <see cref="SQLiteErrorCode" /> value to use.
        /// </param>
        public void SetErrorCode(SQLiteErrorCode value)
        {
            if (pContext == IntPtr.Zero)
                throw new InvalidOperationException();

            UnsafeNativeMethods.sqlite3_result_error_code(pContext, value);
        }
		internal SQLiteException(SQLiteErrorCode errorCode, SqliteDatabaseHandle database)
			: base(GetErrorString(errorCode, database), (int) errorCode)
		{
		}
Ejemplo n.º 55
0
 /// <summary>
 /// Public constructor for generating a SQLite error given the base error code
 /// </summary>
 /// <param name="errorCode">The SQLite error code to report</param>
 /// <param name="extendedInformation">Extra text to go along with the error message text</param>
 public SQLiteException(int errorCode, string extendedInformation)
   : base(GetStockErrorMessage(errorCode, extendedInformation))
 {
   _errorCode = (SQLiteErrorCode)errorCode;
 }
Ejemplo n.º 56
0
 /// Add a log message via the SQLite sqlite3_log interface.
 internal override void LogMessage(SQLiteErrorCode iErrCode, string zMessage)
 {
   StaticLogMessage(iErrCode, zMessage);
 }
Ejemplo n.º 57
0
 /// <summary>
 /// Public constructor for generating a SQLite exception given the error
 /// code and message.
 /// </summary>
 /// <param name="errorCode">
 /// The SQLite return code to report.
 /// </param>
 /// <param name="message">
 /// Message text to go along with the return code message text.
 /// </param>
 public SQLiteException(SQLiteErrorCode errorCode, string message)
   : base(GetStockErrorMessage(errorCode, message))
 {
   _errorCode = errorCode;
 }