Example #1
0
        string Export_GetValueString(SQLiteDataReader rdr)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < rdr.FieldCount; i++)
            {
                if (sb.Length == 0)
                {
                    sb.AppendFormat("(");
                }
                else
                {
                    sb.AppendFormat(",");
                }

                sb.Append(QueryExpress.ConvertToSqlFormat(rdr, i, true, true, Columns[rdr.GetName(i)]));
            }

            sb.AppendFormat(")");

            return(sb.ToString());
        }
Example #2
0
        /// <summary>
        /// Loads properties of an object from the passed reader. For inlined properties, the parent reader is passed
        /// </summary>
        /// <param name="o">Object to be filled with data</param>
        /// <param name="parent">Parent type that has the id for inlined classes</param>
        /// <param name="reader">Reader from which to take the data</param>
        /// <param name="embeddedPrefix">Prefix for 'inlined' properties (complex types)</param>
        private static void Load(object o, Type parent, SQLiteDataReader reader, string embeddedPrefix = "")
        {
            // -50% loading time  
            var readerCache = new Hashtable();
            for (int i = 0; i < reader.FieldCount; i++)
                readerCache.Add(reader.GetName(i), reader[i]);

            var data = readerCache;

            //var data = reader;   

            foreach (var property in PersistentProperty.GetPersistentProperties(o.GetType(), embeddedPrefix, parent))
            {
                string entryId = data["Id"].ToString();

                // Load generic lists by finding the mn-mapping table and loading every entry recursivly
                if (property.IsGenericList)
                {
                    using (var cmd = new SQLiteCommand(String.Format(genericListsql, property.RelationTableName, property.ListType.Name, parent == null ? o.GetType().Name : parent.Name, entryId), DBManager.MPQMirror))
                    {
                        var itemReader = cmd.ExecuteReader();
                        var list = Activator.CreateInstance(property.Type);

                        if (itemReader.HasRows)
                        {
                            while (itemReader.Read())
                            {
                                var item = Activator.CreateInstance(property.ListType);
                                Load(item, null, itemReader);
                                (list as IList).Add(item);
                            }
                        }
                        property.Property.SetValue(o, list, null);

                    }
                    continue;
                }

                // Load generic dictionaires by finding the mn-mapping table and loading every entry recursivly
                if (property.IsGenericDictionary)
                {
                    using (var cmd = new SQLiteCommand(String.Format(genericListsql, property.RelationTableName, property.ListType.Name, parent == null ? o.GetType().Name : parent.Name, entryId), DBManager.MPQMirror))
                    {
                        var itemReader = cmd.ExecuteReader();
                        var dictionary = Activator.CreateInstance(property.Type);

                        if (itemReader.HasRows)
                        {
                            while (itemReader.Read())
                            {
                                var item = Activator.CreateInstance(property.ListType);
                                Load(item, null, itemReader);
                                (dictionary as IDictionary).Add(Convert.ChangeType(itemReader["Key"], property.Type.GetGenericArguments()[0]), item);
                            }
                        }
                        property.Property.SetValue(o, dictionary, null);

                    }
                    continue;
                }

                // load scalar types
                if (property.Type.Namespace == "System")
                {
                    // load array of scalar types. The column name of the i-th array entry is "columnName_i"
                    if (property.Type.IsArray)
                    {
                        if (property.ArrayCount == -1)
                        {
                            byte[] blob = StringToByteArray(data[property.ColumnName].ToString().Replace("-", ""));
                            property.Property.SetValue(o, blob, null);
                        }
                        else
                        {
                            Array vals = (Array)Activator.CreateInstance(property.Type, property.ArrayCount);
                            for (int i = 0; i < vals.Length; i++)
                            {
                                vals.SetValue(Convert.ChangeType(data[property.ColumnName + "_" + i.ToString()], property.Type.GetElementType()), i);
                            }

                            property.Property.SetValue(o, vals, null);
                        }
                    }
                    else
                    {
                        property.Property.SetValue(o, Convert.ChangeType(data[property.ColumnName], property.Type), null);
                    }
                    continue;
                }

                // load enums
                if (property.Type.IsEnum)
                {
                    property.Property.SetValue(o, Enum.Parse(property.Type, data[property.ColumnName].ToString(), true), null);
                    continue;
                }

                // if its none of the earlier types, its a inlined class. class properties
                if (Convert.ToBoolean(data[property.ColumnName + "_"]))
                {
                    var embedded = Activator.CreateInstance(property.Type);
                    Load(embedded, o.GetType(), reader, property.ColumnName + "_");
                    property.Property.SetValue(o, embedded, null);
                }
            }
        }
Example #3
0
        static Bet BetParser(SQLiteDataReader Reader)
        {
            string site = "";
            Bet tmp = new Bet();
            for (int i = 0; i< Reader.FieldCount; i++)
            {

                switch (Reader.GetName(i))
                {
                    case "betid": tmp.Id = (long)Reader[i]; break;
                    case "date": tmp.date = (DateTime)Reader[i]; break;
                    case "stake": tmp.Amount = (decimal)Reader[i]; break;
                    case "profit": tmp.Profit = (decimal)Reader[i]; break;
                    case "chance": tmp.Chance = (decimal)Reader[i]; break;
                    case "high": tmp.high = (short)Reader[i] == 1; break;
                    case "lucky": tmp.Roll = (decimal)Reader[i]; break;
                    case "hash": tmp.serverhash = (string)Reader[i]; break;
                    case "nonce": tmp.nonce = (long)Reader[i]; break;
                    case "uid": tmp.uid = (int)Reader[i]; break;
                    case "Client": tmp.clientseed = (string)Reader[i]; break;
                    case "server": tmp.serverseed = (string)Reader[i]; break;
                    case "site": site = (string)Reader[i]; break;
                }
            }
            if (!string.IsNullOrEmpty(tmp.serverseed) && tmp.nonce != -1 && !string.IsNullOrEmpty(tmp.clientseed) && tmp.Roll!=-1 && site!="")
            {
                switch (site)
                {
                    case "JustDice": tmp.Verified = tmp.Roll == (decimal)DiceSite.sGetLucky(tmp.serverseed, tmp.clientseed, (int)tmp.nonce); break;
                    case "PrimeDice": tmp.Verified = tmp.Roll == (decimal)PD.sGetLucky(tmp.serverseed, tmp.clientseed, (int)tmp.nonce); break;
                    case "999Dice": tmp.Verified = tmp.Roll== (decimal)dice999.sGetLucky(tmp.serverseed, (tmp.clientseed), (int)tmp.nonce, /*(long)(tmp.Roll*10000m),*/ tmp.serverhash); break;
                    //case "SafeDice": tmp.Verified = tmp.Roll == (decimal)SD.sGetLucky(tmp.serverseed, tmp.clientseed, (int)tmp.nonce); break;
                    //case "PRC": tmp.Verified = tmp.Roll == (decimal)PD.sGetLucky(tmp.serverseed, tmp.clientseed, (int)tmp.nonce); break;
                }
            }
            return tmp;
        }
Example #4
0
 /// <summary>
 /// Analyses the SQLiteDataReader passed to it, filling the
 /// Rows collection using the column name and it's respective value
 /// for each row returned.
 /// </summary>
 /// <param name="reader">The SQLiteDataReader object containing the results of a query.</param>
 public void Analyse(SQLiteDataReader reader)
 {
     int currentRow = 0;
     while (reader.Read())
     {
         if (reader.HasRows)
         {
             Dictionary<string, object> columns = new Dictionary<string, object>();
             for (int i = 0; i < reader.FieldCount; i++)
             {
                 columns.Add(reader.GetName(i), reader.GetValue(i));
             }
             this.Rows.Add(currentRow, columns);
         }
         currentRow++;
     }
 }
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region Static "Factory" Methods
        /// <summary>
        /// Creates a <see cref="SQLiteBlob" /> object.  This will not work
        /// for tables that were created WITHOUT ROWID -OR- if the query
        /// does not include the "rowid" column or one of its aliases -OR-
        /// if the <see cref="SQLiteDataReader" /> was not created with the
        /// <see cref="CommandBehavior.KeyInfo" /> flag.
        /// </summary>
        /// <param name="dataReader">
        /// The <see cref="SQLiteDataReader" /> instance with a result set
        /// containing the desired blob column.
        /// </param>
        /// <param name="i">
        /// The index of the blob column.
        /// </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(
            SQLiteDataReader dataReader,
            int i,
            bool readOnly
            )
        {
            SQLiteConnection connection = SQLiteDataReader.GetConnection(
                dataReader);

            if (connection == null)
            {
                throw new InvalidOperationException("Connection not available");
            }

            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.");
            }

            long?rowId = dataReader.GetRowId(i);

            if (rowId == null)
            {
                throw new InvalidOperationException("No RowId is available");
            }

            SQLiteBlobHandle blob = null;

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

                SQLiteErrorCode rc = UnsafeNativeMethods.sqlite3_blob_open(
                    sqlite3._sql, SQLiteConvert.ToUTF8(
                        dataReader.GetDatabaseName(i)), SQLiteConvert.ToUTF8(
                        dataReader.GetTableName(i)), SQLiteConvert.ToUTF8(
                        dataReader.GetName(i)), (long)rowId, readOnly ? 0 : 1,
                    ref ptrBlob);

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

                blob = new SQLiteBlobHandle(handle, ptrBlob);
            }

            SQLiteConnection.OnChanged(null, new ConnectionEventArgs(
                                           SQLiteConnectionEventType.NewCriticalHandle, null,
                                           null, null, dataReader, blob, null, new object[] {
                typeof(SQLiteBlob), dataReader, i, readOnly
            }));

            return(new SQLiteBlob(sqlite3, blob));
        }
Example #6
0
    public List <T> TableAsList <T>() where T : new()
    {
        var map   = GetMapping(typeof(T));
        var str   = typeof(T).Name;
        var query = "select * from " + str;

#if !RUNINSERVER
        var connection = _connection;
        connection.CommandText = query;
        connection.Prepare();
        var n    = connection.GetColumnCont();
        var list = new List <T>(n);
        try
        {
            var cols = new TableMapping.Column[n];
            for (var i = 0; i < n; i++)
            {
                var name = connection.ColumnName16(i);
                var col  = map.FindColumn(name);
                cols[i] = col;
                if (col == null)
                {
                    Debug.LogError("table:" + str + " ,col:" + name + " is Null");
                    throw new Exception();
                }
            }

            var t = map.MappedType;
            while (connection.Step() == SQLite3.Result.Row)
            {
                var obj = Activator.CreateInstance(t);
                for (var i = 0; i < n; i++)
                {
                    var col = cols[i];
                    var val = connection.ReadCol(i, col.ColumnType);
                    col.FieldInfo.SetValue(obj, val);
                }

                list.Add((T)obj);
            }
        }
        catch (Exception e)
        {
            Debug.LogErrorFormat("{0}\n : {1}", str, e);
        }
        finally
        {
            connection.FinalizeStmt();
        }

        return(list);
#else
        System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
        cmd.Connection  = _connection;
        cmd.CommandText = query;

        //cmd.Prepare();
        Debug.Log("query:" + query);
        System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader();

        int n = reader.FieldCount;
        Debug.Log("FieldCount:" + n + " reader.StepCount:" + reader.StepCount);

        //cmd.

        List <T> list = new List <T>(n);

        try
        {
            var cols = new TableMapping.Column[n];
            for (int i = 0; i < cols.Length; i++)
            {
                var name = reader.GetName(i);
                cols[i] = map.FindColumn(name);
                //if (cols[i] == null)
                Debug.LogError("table:" + typeof(T).Name + " ,col:" + name + " " + cols[i].Name);
            }

            //for (int j=0;j<reader.StepCount;j++)
            while (reader.Read())
            {
                //Debug.Log("int read:"+ cols.Length);
                var obj = Activator.CreateInstance(map.MappedType);
                for (int i = 0; i < cols.Length; i++)
                {
                    //if (cols[i] == null)
                    //    continue;
                    var    colType = reader.GetFieldType(i);
                    object val     = reader.GetValue(i);; //  _connection.ReadCol(i, colType, cols[i].ColumnType);
                                                          //Debug.Log("val:" + i + " " + val);
                    if (colType == typeof(double))
                    {
                        //val = 2.5f;//reader.GetFloat(i);
                        float vv = (float)((double)val);
                        cols[i].FieldInfo.SetValue(obj, vv);
                    }
                    else
                    {
                        cols[i].FieldInfo.SetValue(obj, val);
                    }
                }
                list.Add((T)obj);
            }
        }
        catch (Exception e)
        {
            Debug.LogErrorFormat("{0}\n : {1}", typeof(T).Name, e);
        }
        finally
        {
            //_connection.Close();
        }
        return(list);
#endif
    }
Example #7
-1
		public static QueryRow Read(SQLiteDataReader reader)
		{
			var result = new QueryRow();

			reader.GetValues();

			for (var i = 0; i < reader.FieldCount; i++)
			{
				result.queryDefinition.Fields.Add(
					reader.GetName(i),
					new FieldDefinition(
						reader.GetName(i),
						reader.GetFieldType(i).ToSqlDbType(),
						false,
						false
					)
				);

				result.values.Add(
					reader.GetName(i),
					reader.GetValue(i)
				);
			}

			return result;
		}