ExecuteReader() public method

Overrides the default behavior of DbDataReader to return a specialized SqliteDataReader class
public ExecuteReader ( ) : SqliteDataReader
return SqliteDataReader
Example #1
0
        public static bool Init()
        {
            try
            {
                m_cards = new Dictionary <int, CardData>();

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

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

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

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

                    SQLiteCommand command = new SQLiteCommand(select, connection);
                    using (SQLiteDataReader reader = command.ExecuteReader())
                        InitCards(reader);
                    command.Dispose();
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #2
0
        public static void Init()
        {
            try
            {
                _cards = new Dictionary<int, CardData>();

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

                if (!File.Exists(absolutePath))
                {
                    throw new Exception("Could not find the cards database.");
                }

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

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

                    using (SqliteCommand command = new SqliteCommand(select, connection))
                    using (SqliteDataReader reader = command.ExecuteReader())
                        InitCards(reader);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not initialize the cards database. Check the inner exception for more details.", ex);
            }
        }
Example #3
0
        /**
         * Try and move an item from an oldowner to a new owner
         * @param oldOwner the owner trying to move the item from
         * @param newOwner the owner tyring to move the item too.
         * @param item the name of the item to be moved.
         */
        public String MoveItem(String oldOwner, String newOwner, String item)
        {
            var command = new sqliteCommand("select * from " + itemTableName + " where owner =:owner AND name =:item ", Database);

            command.Parameters.Add("owner", DbType.String).Value = oldOwner;
            command.Parameters.Add("item", DbType.String).Value  = item;

            try
            {
                var reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    reader.Read();
                    if (ChangeItemOwner(reader["uniqueID"].ToString(), newOwner))
                    {
                        return("You ");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write("Item Not recognised: " + ex);
            }

            return("Failed To ");
        }
Example #4
0
        /**
         * Get all items with where the owner field is equal to that of the players name
         * @param owner the entity to whom the items belong.
         */
        public String GetOwnedItems(String owner)
        {
            String rString = U.NL("");
            var    command = new sqliteCommand("select * from " + itemTableName + " where owner =:name ", Database);

            command.Parameters.Add("name", DbType.String).Value = owner;

            try
            {
                var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    //make the description
                    String id = reader["itemID"].ToString();
                    rString += U.NL("Name: " + gameObjectList.GetItem(id).itemName);
                    rString += U.NL("Description: " + gameObjectList.GetItem(id).description);
                    U.NL("");
                }
            }
            catch (Exception ex)
            {
                Console.Write("Failed to get inventory" + ex);
                rString += "Could not find items";
            }
            return(rString);
        }
Example #5
0
 public void InsertData(string scene, string posx,string posy)
 {
     _query = "INSERT INTO continar VALUES('PEPE','"+scene+"','"+posx+"','"+ posy +"')";//continar?
     _command = _conexion.CreateCommand ();
     _command.CommandText = _query;
     _command.ExecuteReader ();
 }
Example #6
0
    public void InsertMonsters()
    {
        string[] nombres = SaveMonster.GetMonsterList();
        Monstruo temp;

        if (PlayerPrefs.GetString ("botonPresionado") == "new") {
            DeleteMonsters();
        }

        for(int i = 0;i < nombres.Length;++i){
            temp = SaveMonster.LoadMonster(nombres[i]);
            _query="SELECT * FROM tablaMonstruos WHERE owner='PEPE' and name='"+temp.nombre+"'";
            _command = _conexion.CreateCommand ();
            _command.CommandText = _query;
            _reader = _command.ExecuteReader ();
            int cont=0;
            if(_reader != null){
                while(_reader.Read()){
                    cont++;
                }
                if(cont!=0){
                    _query= "UPDATE tablaMonstruos set specie='"+temp.especie+"',exp='"+temp.exp.ToString()+"',modStats='"+temp.modStats.ToString()+"',estado='"+temp.estado.ToString()+"' WHERE owner='PEPE' and name='"+temp.nombre+"'";
                }else{
                    _query = "INSERT INTO tablaMonstruos VALUES('"+temp.nombre+"','"+temp.especie+"','"+temp.exp.ToString()+"','"+temp.modStats.ToString()+"','"+temp.estado.ToString()+"','PEPE')";
                }

            }
            _command = _conexion.CreateCommand();
            _command.CommandText = _query;
            _command.ExecuteReader();
        }
    }
Example #7
0
 public void DeleteMonsters()
 {
     _query = "DELETE FROM tablaMonstruos WHERE owner='PEPE'";
     _command = _conexion.CreateCommand ();
     _command.CommandText = _query;
     _command.ExecuteReader ();
 }
Example #8
0
 public void CrearTablaMonstruos(string tabla)
 {
     _query = "CREATE TABLE "+tabla+" (name CHAR(20), specie CHAR(20), exp CHAR(40), modstats CHAR(100), estado CHAR(100), owner CHAR(20));";
     _command = _conexion.CreateCommand();
     _command.CommandText = _query;
     _command.ExecuteReader();
 }
Example #9
0
 public void CrearTabla(string tabla)
 {
     _query = "CREATE TABLE "+tabla+"(name CHAR(20) NOT NULL, scene CHAR(20), posicionX CHAR (20), posicionY CHAR(20));";
     _command = _conexion.CreateCommand();
     _command.CommandText = _query;
     _command.ExecuteReader();
 }
Example #10
0
        /**
         * Adds a new player to the player table
         * @param tempPlayer the player so far that we will add.
         * @param password the salted-hashes password the player used to login
         * @param salt the salt used to hash the password and used for encryption
         */
        public bool AddPlayer(Player tempPlayer, String password, String salt)
        {
            var command = new sqliteCommand("select * from " + playerTableName + " where name =:id", Database);

            command.Parameters.Add("id", DbType.String).Value = tempPlayer.PlayerName;
            var reader = command.ExecuteReader();

            if (reader.HasRows == false && !U.HasBadChars(tempPlayer.PlayerName) && !U.HasBadChars(password))
            {
                try
                {
                    command = new sqliteCommand("INSERT INTO " + playerTableName +
                                                " (name, password, salt,  rIndex) " +
                                                "VALUES ($n, $p, $s, $i) ", Database);

                    command.Parameters.Add("$n", DbType.String).Value = tempPlayer.PlayerName;
                    command.Parameters.Add("$p", DbType.String).Value = password;
                    command.Parameters.Add("$s", DbType.String).Value = salt;
                    command.Parameters.Add("$i", DbType.Int32).Value  = tempPlayer.RoomIndex;
                    command.ExecuteNonQuery();

                    ActivePlayers.Add(tempPlayer.PlayerName);
                    return(true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed Adding to DB: " + ex);
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Example #11
0
        public GUIhosts(GUImain gui, SqliteConnection connection, SqliteCommand command)
        {
            InitializeComponent();
            InitializeList();

            this.gui = gui;
            _connection = connection;
            _command = command;

            using (_command = new SqliteCommand("SELECT host, port, password FROM hosts ORDER BY id DESC", _connection))
            {

                using (SqliteDataReader reader = _command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        String host = gui.GetSafeString(reader, 0);
                        String port = gui.GetSafeString(reader, 1);
                        String password = gui.GetSafeString(reader, 2);

                        String[] items = { host, port, password };
                        ListViewItem item = new ListViewItem(items);
                        list.Items.Add(item);
                    }
                }
            }
        }
Example #12
0
        public static bool Init()
        {
            try
            {
                m_cards = new Dictionary<int, CardData>();

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

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

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

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

                    SQLiteCommand command = new SQLiteCommand(select, connection);
                    using (SQLiteDataReader reader = command.ExecuteReader())
                        InitCards(reader);
                    command.Dispose();
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public static List<string[]> ExecuteStringCommand(SqliteCommand command, int columncount)
        {
            try
            {
            var values = new List<string[]>();
            SqliteDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                var row = new List<string>();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    row.Add(reader[i].ToString());
                }
                values.Add(row.ToArray());
            }
            reader.Close();
            return values;

            }
            catch (Exception ex)
            {
            MessageBox.Show(ex.Message);
            return new List<string[]>();
            }
        }
    public void UpdateOrders()
    {
        MainClass.StatusMessage("Получаем таблицу заказов...");

        string sql = "SELECT orders.id, orders.customer, orders.contract, orders.address, orders.phone1, orders.phone2, orders.arrval, orders.deadline_s, orders.deadline_e FROM orders ";
        SqliteCommand cmd = new SqliteCommand(sql, (SqliteConnection) QSMain.ConnectionDB);

        using(SqliteDataReader rdr = cmd.ExecuteReader())
        {
            OrdersListStore.Clear();
            while (rdr.Read())
            {
                OrdersListStore.AppendValues(rdr.GetInt32(rdr.GetOrdinal("id")),
                    rdr["customer"].ToString(),
                    rdr["contract"].ToString(),
                    rdr["phone1"].ToString() + rdr["phone2"].ToString(),
                    rdr["address"].ToString(),
                    String.Format("{0:d}", rdr["arrval"]),
                    DateWorks.GetDateRangeText(DBWorks.GetDateTime(rdr, "deadline_s", new DateTime()), DBWorks.GetDateTime(rdr, "deadline_e", new DateTime()))
                );
            }

        }
        MainClass.StatusMessage("Ok");
    }
Example #15
0
        public void CommitTransaction()
        {
            var lst = new List<string>();
            using (var cmd = new SqliteCommand(String.Format("SELECT DISTINCT [TableName] FROM {0}", TranStatusTable), ActiveConnection))
            {
                using (SqliteDataReader r = cmd.ExecuteReader())
                {
                    while (r.Read())
                    {
                        lst.Add(r.GetString(0));
                    }
                }
            }

            SqliteTransaction tran = ActiveConnection.BeginTransaction();
            try
            {
                foreach (String tableName in lst)
                {
                    using (var cmd = new SqliteCommand(String.Format("DELETE FROM __{0}", tableName), tran.Connection, tran))
                        cmd.ExecuteNonQuery();
                }
                using (var cmd = new SqliteCommand(String.Format("DELETE FROM {0}", TranStatusTable), tran.Connection, tran))
                    cmd.ExecuteNonQuery();

                tran.Commit();
            }
            catch
            {
                tran.Rollback();
                throw;
            }
        }
Example #16
0
        public static void Init(string databaseFullPath)
        {
            try
            {
                if (!File.Exists(databaseFullPath))
                {
                    throw new Exception("Could not find the cards database.");
                }

                _cards = new Dictionary<int, NamedCard>();

                using (SqliteConnection connection = new SqliteConnection("Data Source=" + databaseFullPath))
                {
                    connection.Open();

                    using (IDbCommand command = new SqliteCommand(
                        "SELECT datas.id, ot, alias, setcode, type, level, race, attribute, atk, def, texts.name, texts.desc"
                        + " FROM datas INNER JOIN texts ON datas.id = texts.id",
                        connection))
                    {
                        using (IDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                LoadCard(reader);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not initialize the cards database. Check the inner exception for more details.", ex);
            }
        }
        /// <summary>
        /// Returns all categories.
        /// </summary>
        public IEnumerable<Category> GetAllCategories()
        {
            var categories = new List<Category>();

            using (var connection = new SqliteConnection("Data Source=" + dbPath))
            using (var query = new SqliteCommand("SELECT * FROM Categories", connection))
            {
                connection.Open();

                var reader = query.ExecuteReader(CommandBehavior.CloseConnection);

                while (reader.Read())
                {
                    var category = new Category();
                    category.Id = int.Parse(reader["id"].ToString());
                    category.Name = reader ["name"].ToString();

                    categories.Add(category);
                }

                reader.Close();
            }

            return categories;
        }
        public void Fill(int id)
        {
            ItemId = id;
            NewItem = false;

            MainClass.StatusMessage(String.Format ("Запрос выставки №{0}...", id));
            string sql = "SELECT exhibition.* FROM exhibition WHERE exhibition.id = @id";
            try
            {
                SqliteCommand cmd = new SqliteCommand(sql, (SqliteConnection) QSMain.ConnectionDB);

                cmd.Parameters.AddWithValue("@id", id);

                using(SqliteDataReader rdr = cmd.ExecuteReader())
                {
                    rdr.Read();

                    labelID.Text = rdr["id"].ToString();
                    entryName.Text = rdr["name"].ToString();
                    entryPhone1.Text = DBWorks.GetString(rdr, "phone", "");
                    entryPhone2.Text = DBWorks.GetString(rdr, "phone2", "");
                    textAddress.Buffer.Text = DBWorks.GetString(rdr, "address", "");
                }

                MainClass.StatusMessage("Ok");
                this.Title = entryName.Text;
            }
            catch (Exception ex)
            {
                QSMain.ErrorMessageWithLog(this, "Ошибка получения информации о номенклатуре!", logger, ex);
            }
            TestCanSave();
        }
Example #19
0
    public static List<Dictionary<string, string>> QueryImpl(string handler, string statement, string[] param)
    {
        List<Dictionary<string,string>> result = new List<Dictionary<string,string>>();
         var db = dbs[handler];
         var dbcmd = new SqliteCommand(ConvertStatment(statement), db);

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

          	return result;
    }
Example #20
0
        /**
         * Used if loading from an exsisitng dungeon. It will cycle through the dungeon table
         * getting all the rooms and adding them to the new dungeons room list
         * Having the dungeon as dynamic memory, allows for quicker sanity checks incase
         * players try and break things. The databse is always written to if the player
         * actuallty does anything.
         */
        public Dungeon GetDungeon()
        {
            Dungeon d = new Dungeon();

            try
            {
                var command = new sqliteCommand("select * from " + dungeonTableName, Database);
                var reader  = command.ExecuteReader();

                while (reader.Read())
                {
                    Room r = new Room();
                    r.name      = reader["name"].ToString();
                    r.desc      = reader["description"].ToString();
                    r.RoomIndex = Int32.Parse(reader["rIndex"].ToString());
                    r.north     = Int32.Parse(reader["north"].ToString());
                    r.east      = Int32.Parse(reader["east"].ToString());
                    r.south     = Int32.Parse(reader["south"].ToString());
                    r.west      = Int32.Parse(reader["west"].ToString());
                    d.GetRoomList().Add(r);
                }

                reader.Close();
                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to display DB" + ex);
            }
            return(d);
        }
        private void liqviscdata()
        {

            con.Open();

            string stm = "SELECT * FROM windowsdata WHERE comp='"+comppicker.SelectedItem+"' ORDER BY comp ";

            using (SqliteCommand cmd = new SqliteCommand(stm, con))
            {
                using (SqliteDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        tcenti = double.Parse(temp.Text);
                        tk = tcenti + 273.15;
                        viscb =double.Parse( rdr["viscb"].ToString());
                        viscc = double.Parse(rdr["viscc"].ToString());
                        if (viscc != 0)
                        {
                            double visc1 = viscb * ((1 / tk) - (1 / viscc));
                            double viscocity = Math.Pow(10, visc1);
                            Liqvisc.Text = viscocity.ToString();
                        }
                        else
                        {
                            Liqvisc.Text = "0"; 
                        }
                        
                    }
                }
            }
            con.Close();
        }
Example #22
0
 static List<Dictionary<string, object>> ExecuteQuery(string query, List<SqliteParameter> pars)
 {
     List<Dictionary<string, object>> res = new List<Dictionary<string, object>>();
     using (var Conn = GetConnection())
     {
         Conn.Open();
         using (SqliteCommand command = new SqliteCommand(query, Conn))
         {
             foreach (var par in pars)
                 command.Parameters.Add(par);
             using (var reader = command.ExecuteReader())
             {
                 if (reader.HasRows)
                 {
                     while (reader.Read())
                     {
                         res.Add(new Dictionary<string, object>());
                         for (int i = 0; i < reader.FieldCount; i++)
                         {
                             res[res.Count - 1][reader.GetName(i)] = reader[i];
                         }
                     }
                 }
             }
         }
     }
     return res;
 }
        private void vapdata()
        {
            tcenti = int.Parse(temp.Text);
            tk = 273.15 + tcenti;
            con.Open();
            
            string stm = "SELECT * FROM VAPDATA2 WHERE Name ='"+comppicker.SelectedItem+"'";

            using (SqliteCommand cmd = new SqliteCommand(stm, con))
            {
                using (SqliteDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        ct1 = double.Parse(rdr["C1"].ToString());
                        ct2 = double.Parse(rdr["C2"].ToString());
                        ct3 = double.Parse(rdr["C3"].ToString());
                        ct4 = double.Parse(rdr["C4"].ToString());
                        ct5 = double.Parse(rdr["C5"].ToString());
                    }
                }
            }
            con.Close();

            vpresure = (Math.Exp(ct1 + (ct2 / tk) + ct3 * Math.Log(tk) + ct4 * Math.Pow(tk, ct5)) / 100000);
            vp.Text = vpresure.ToString();
        }
Example #24
0
 static public SqliteDataReader ExecuteQuery(string sqlQuery)
 {
     dbCommand = OpenDB("monsters.db").CreateCommand();
     dbCommand.CommandText = sqlQuery;
     reader = dbCommand.ExecuteReader();
     return reader;
 }
Example #25
0
        public override void update(ActionTimer timer)
        {
            List <Account> _list = new List <Account>();

            using (SQLiteCommand command = new SQLiteCommand(Sqlite.getSqlite().connection))
            {
                command.CommandText = "SELECT id, name FROM `account`";

                using (SQLiteDataReader sdrITM = command.ExecuteReader())
                {
                    if (sdrITM.HasRows)
                    {
                        while (sdrITM.Read())
                        {
                            int    accID = Convert.ToInt32(sdrITM["id"]);
                            string name  = Convert.ToString(sdrITM["name"]);
                            _list.Add(new Account()
                            {
                                accountID = accID, name = name
                            });
                        }
                    }
                }
            }
            list = _list.ToArray();


            isFinished = true;
            timer.removeAction(this);
        }
Example #26
0
        /// <summary>
        /// Returns all subscribed feeds.
        /// </summary>
        public IEnumerable<Feed> GetAllFeeds()
        {
            var feeds = new List<Feed>();

            using (var connection = new SqliteConnection("Data Source=" + dbPath))
            using (var query = new SqliteCommand("SELECT * FROM Feeds", connection))
            {
                connection.Open();

                var reader = query.ExecuteReader(CommandBehavior.CloseConnection);

                while (reader.Read())
                {
                    var feed = new Feed();
                    feed.Id = int.Parse(reader["id"].ToString());
                    feed.Name = reader ["name"].ToString();
                    feed.Url = reader ["url"].ToString();
                    feed.LastUpdated = DateTime.Parse (reader ["LastUpdated"].ToString ());
                    feed.CategoryId = int.Parse(reader["categoryId"].ToString());

                    feeds.Add(feed);
                }

                reader.Close();
            }

            return feeds;
        }
Example #27
0
        public void RoomInfo(Socket UserSocket, SQLiteConnection connection, Dictionary <Socket, Character> clientDictonary)
        {
            ASCIIEncoding encoder       = new ASCIIEncoding();
            string        returnMessage = "";

            Character character = clientDictonary[UserSocket];

            command = new sqliteCommand("select * from " + "table_characters" + " where name = " + "'" + character.name + "'", connection);

            var characterSearch = command.ExecuteReader();

            while (characterSearch.Read())
            {
                command = new sqliteCommand("select * from " + "table_dungeon" + " where name = " + "'" + characterSearch["room"] + "'", connection);
            }
            characterSearch.Close();

            var dungeonSearch = command.ExecuteReader();

            while (dungeonSearch.Read())
            {
                returnMessage += "-------------------------------";
                returnMessage += "\nName: " + dungeonSearch["name"];
                returnMessage += "\nDescription: " + dungeonSearch["description"];
                returnMessage += "\nNorth: " + dungeonSearch["North"];
                returnMessage += "\nSouth: " + dungeonSearch["South"];
                returnMessage += "\nEast: " + dungeonSearch["East"];
                returnMessage += "\nWest: " + dungeonSearch["West"];
                returnMessage += "\nUp: " + dungeonSearch["Up"];
                returnMessage += "\nDown: " + dungeonSearch["Down"];
                returnMessage += "\n-------------------------------";
            }

            connection.Close();

            byte[] sendbuffer = encoder.GetBytes(returnMessage);

            int bytesSent = UserSocket.Send(sendbuffer);


            //try
            //{
            //    Console.WriteLine("");
            //    command = new sqliteCommand("select * from " + "table_dungeon" + " order by name asc", connection);
            //    var reader = command.ExecuteReader();

            //    while (reader.Read())
            //    {
            //        Console.WriteLine("Name: " + reader["name"]);
            //    }

            //    reader.Close();
            //    Console.WriteLine("");
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("Failed to display DB" + ex);
            //}
        }
Example #28
0
        public static void Main(string[] args)
        {
            var db = "../../stalkr.db";

            if (args.Length > 0) {
                db = args[0];
            }

            // COUCHSURFING

            var profiles = new Dictionary<int, string>();

            using (var conn = new SqliteConnection("Data Source=" + db + ";Version=3;")) {
                conn.Open();
                var sql = "SELECT * FROM person_profile WHERE profile_type = 'couchsurfing'";
                using (var cmd = new SqliteCommand(sql, conn)) {
                    var reader = cmd.ExecuteReader();

                    while (reader.Read()) {
                        int id = Convert.ToInt32(reader["person_id"]);
                        string profile = reader["profile"] as string;
                        profiles[id] = profile;
                    }
                }

                foreach (var profile in profiles) {
                    Console.WriteLine("{0}: {1}", profile.Key, profile.Value);

                    var name = "";
                    var age = 0;
                    var gender = "";

                    try {
                        var url = profile.Value; //"https://www.couchsurfing.com/people/casey";
                        var html = new HtmlDocument();
                        html.LoadHtml(new WebClient().DownloadString(url));

                        var root = html.DocumentNode;
                        name = root.SelectSingleNode("/html/body/main/div[2]/div/section/header/h1/a").InnerHtml;
                        var ageAndGender = root.SelectSingleNode("/html/body/main/div[2]/section[3]/div/div/div[1]/ul/li[3]").InnerText
                        .Split(new char[]{ ',' }, 2);
                        age = int.Parse(ageAndGender[0].Trim());
                        gender = ageAndGender[1].Trim();
                    } catch (Exception) {
                    }

                    Console.WriteLine(name);
                    Console.WriteLine(age);
                    Console.WriteLine(gender);

                    sql = string.Format("INSERT INTO fact_couchsurfing(person_id, timestamp, name, age, gender) VALUES ({0}, {1}, '{2}', {3}, '{4}')", profile.Key, "DATETIME('now')", name, age, gender);
                    using (var cmd = new SqliteCommand(sql, conn)) {
                        cmd.ExecuteNonQuery();
                    }

                    Thread.Sleep(1000);
                }
            }
        }
Example #29
0
        protected IDataReader ExecuteReader(SqliteCommand cmd)
        {
            SqliteConnection dbcon = new SqliteConnection(m_connectionString);
            dbcon.Open();
            cmd.Connection = dbcon;

            return cmd.ExecuteReader();
        }
    public SqliteDataReader ExecuteQuery(string q)
    {
        databaseCommand = databaseConnection.CreateCommand();
        databaseCommand.CommandText = q;
        reader = databaseCommand.ExecuteReader();

        return reader;
    }
Example #31
0
        private int _GetDataBaseSongID(string artist, string title, int defNumPlayed, SQLiteCommand command)
        {
            command.CommandText = "SELECT id FROM Songs WHERE [Title] = @title AND [Artist] = @artist";
            command.Parameters.Add("@title", DbType.String, 0).Value  = title;
            command.Parameters.Add("@artist", DbType.String, 0).Value = artist;

            SQLiteDataReader reader = command.ExecuteReader();

            if (reader != null && reader.HasRows)
            {
                reader.Read();
                int id = reader.GetInt32(0);
                reader.Dispose();
                return(id);
            }

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

            command.CommandText = "INSERT INTO Songs (Title, Artist, NumPlayed, DateAdded) " +
                                  "VALUES (@title, @artist, @numplayed, @dateadded)";
            command.Parameters.Add("@title", DbType.String, 0).Value    = title;
            command.Parameters.Add("@artist", DbType.String, 0).Value   = artist;
            command.Parameters.Add("@numplayed", DbType.Int32, 0).Value = defNumPlayed;
            command.Parameters.Add("@dateadded", DbType.Int64, 0).Value = DateTime.Now.Ticks;
            command.ExecuteNonQuery();

            command.CommandText = "SELECT id FROM Songs WHERE [Title] = @title AND [Artist] = @artist";
            command.Parameters.Add("@title", DbType.String, 0).Value  = title;
            command.Parameters.Add("@artist", DbType.String, 0).Value = artist;

            reader = command.ExecuteReader();

            if (reader != null)
            {
                reader.Read();
                int id = reader.GetInt32(0);
                reader.Dispose();
                return(id);
            }

            return(-1);
        }
Example #32
0
        //depending on what the client sent (1 or 2) add a username to databse or retreive a name from the database
        static bool username(string Key, Socket client)
        {
            int           bytesSent;
            ASCIIEncoding encoder = new ASCIIEncoding();
            sqliteCommand command;
            var           input = Key.Split(' ');

            switch (input[0])
            {
            case "1":
                for (int i = 1; i < input.Length; i++)
                {
                    name += input[i];
                }

                try
                {
                    var sql = "insert into " + "table_usernames" + " (name) values ";
                    sql    += "('" + name + "'";
                    sql    += ")";
                    command = new sqliteCommand(sql, conn);
                    command.ExecuteNonQuery();
                }

                catch (Exception ex)
                {
                    Console.WriteLine("Failed to add: " + name + " : to DB " + ex);
                }
                return(true);

            case "2":
                for (int i = 1; i < input.Length; i++)
                {
                    name += input[i];
                }

                try
                {
                    command = new sqliteCommand("select * from  table_usernames where name == '" + name + "'", conn);
                    var reader = command.ExecuteReader();


                    if (reader.HasRows == true)
                    {
                        byte[] sendBuffer = encoder.GetBytes("signed in");
                        bytesSent = client.Send(sendBuffer);
                    }
                }

                catch (Exception ex)
                {
                    Console.WriteLine("Failed to find: " + name + " : to DB " + ex);
                }
                return(true);
            }
            return(false);
        }
Example #33
0
        public bool GetCreditsRessource(string fileName, ref CTextureRef tex)
        {
            if (_Connection == null)
            {
                return(false);
            }
            bool result = false;

            using (var command = new SQLiteCommand(_Connection))
            {
                command.CommandText = "SELECT id, width, height FROM Images WHERE [Path] = @path";
                command.Parameters.Add("@path", DbType.String, 0).Value = fileName;

                SQLiteDataReader reader = command.ExecuteReader();

                if (reader != null && reader.HasRows)
                {
                    reader.Read();
                    int id = reader.GetInt32(0);
                    int w  = reader.GetInt32(1);
                    int h  = reader.GetInt32(2);
                    reader.Close();

                    command.CommandText = "SELECT Data FROM ImageData WHERE ImageID = @id";
                    command.Parameters.Add("@id", DbType.Int32).Value = id;
                    reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        result = true;
                        reader.Read();
                        byte[] data = _GetBytes(reader);
                        tex = CDraw.AddTexture(w, h, data);
                    }
                }

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

            return(result);
        }
Example #34
0
        private bool _ConvertV2toV3(SQLiteConnection connection)
        {
            var command = new SQLiteCommand(connection)
            {
                CommandText = "ALTER TABLE Songs ADD DateAdded BIGINT"
            };

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

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

            SQLiteDataReader reader;

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

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

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

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

            return(true);
        }
Example #35
0
 public bool InTransaction()
 {
     using (var cmd = new SqliteCommand(String.Format("SELECT DISTINCT [TableName] FROM {0}", TranStatusTable), ActiveConnection))
     {
         using (SqliteDataReader r = cmd.ExecuteReader())
         {
             return r.HasRows;
         }
     }
 }
        private void vapdata()
        {          
            tk = double.Parse(temp.Text)+273.15 ;
            con.Open();

                        string str = "SELECT * FROM VAPDATA2 WHERE Name='"+comppicker.SelectedItem+"' ORDER BY Name";

                        using (SqliteCommand cmd2 = new SqliteCommand(str, con))
                        {
                            using (SqliteDataReader rdr1 = cmd2.ExecuteReader())
                            {
                                while (rdr1.Read())
                                {                                   
                                            ct1 = double.Parse(rdr1["C1"].ToString());
                                            ct2 = double.Parse(rdr1["C2"].ToString());
                                            ct3 = double.Parse(rdr1["C3"].ToString());
                                            ct4 = double.Parse(rdr1["C4"].ToString());
                                            ct5 = double.Parse(rdr1["C5"].ToString());
                                            molwt = double.Parse(rdr1["molwt"].ToString());                                            

                                            if (molwt != 0 )
                                            {
                                                double vapP_derivative,latentheatdat;
                                                omega = double.Parse(rdr1["omega"].ToString());
                                                tc = double.Parse(rdr1["Tc"].ToString());
                                                pc = double.Parse(rdr1["Pc"].ToString()) * 1000; 
                                                vpresure = (Math.Exp(ct1 + (ct2 / tk) + ct3 * Math.Log(tk) + ct4 * Math.Pow(tk, ct5))); 

                                                if (tk > tc)
                                                { MessageBox.Show("Latent heat for supercritical phase is not defined"); }
                                                else
                                                {
                                                  //  lh.Text = vpresure.ToString();
                                                    double r = 8.314;
                                                    double gasvol,liqvol;
                                                    vapP_derivative = (Math.Exp(ct1 + (ct2 / tk) + ct3 * Math.Log(tk) + ct4 * Math.Pow(tk, ct5))) * (-ct2 / Math.Pow(tk, 2) + ct3 / tk + ct4 * ct5 * Math.Pow(tk, (ct5 - 1)));
                                                    gasvol = eosrkvv(tc, pc, r, vpresure);
                                                    liqvol = eosrklv(tc, pc, tk, r, vpresure);
                                                    latentheatdat = ((tk * (gasvol - liqvol) * vapP_derivative)) / molwt;
                                                    lh.Text = latentheatdat.ToString();
                                                }                                       
                                                }                                                
                                    
                                    else
                                    {
                                        lh.Text = "No data avialable";
                                    }
                                }
                            }
                        }

                    
            con.Close();
            
        }
Example #37
0
    void Awake()
    {
        Debug.Log("ASd");
        SqliteConnection connection = new SqliteConnection(string.Format("Data Source={0}", "Test.db"));
        connection.Open();
        Debug.Log("Connected DB");
        //Debug.Log(connection.ConnectionString);

        SqliteCommand sqlCmd = new SqliteCommand(connection);
        sqlCmd.CommandText = "SELECT * FROM Position";
        SqliteDataReader reader = sqlCmd.ExecuteReader();

        string[] readArray = new string[reader.RecordsAffected];
        //Debug.Log(reader.RecordsAffected);
        //Debug.Log(reader.FieldCount);
        //Debug.Log(reader.HasRows);
        //Debug.Log(reader.VisibleFieldCount);

        posList = new List<Vector3>();
        while (reader.Read())
        {
            //Debug.Log("(" + reader.GetFloat(0) + ", " + reader.GetFloat(1) + ", " + reader.GetFloat(2) + ")");
            posList.Add(new Vector3(reader.GetFloat(0), reader.GetFloat(1), reader.GetFloat(2)));
        }

        reader.Close();
        connection.Close();

        // reading database code

        //connection.ConnectionString = "URI=file:" + "EventDB.db";
        //connection.Open();

        //SqliteCommand sqlCmd2 = new SqliteCommand(connection);
        //sqlCmd2.CommandText = "SELECT * FROM Event";
        //SqliteDataReader reader2 = sqlCmd2.ExecuteReader();

        //string eventName = "";
        //while (reader2.Read())
        //{
        //    eventName = reader2.GetString(0);
        //    Contents content = new Contents(reader2.GetString(1), reader2.GetString(2));
        //    //Debug.Log("Event Name : " + eventName);
        //    //Debug.Log("Character Name : " + content.charName);
        //    //Debug.Log("Description : " + content.description);
        //    contentsList.Add(content);
        //}

        //eventMap.Add(eventName, contentsList);

        //reader2.Close();
        //connection.Close();

        text = this.GetComponent<GUIText>();
    }
Example #38
0
        public bool queryExists(String query, String field)
        {
            sqliteCommand command = new sqliteCommand("select * from " + m_TableName + " where " + field + " = @query", m_Connection);

            command.Parameters.Add("@query", System.Data.DbType.String).Value = query;
            command.Parameters.Add("@field", System.Data.DbType.String).Value = field;

            sqliteDataReader reader = command.ExecuteReader();

            return(reader.HasRows);
        }
Example #39
0
        private bool _GetDataBaseSongInfos(int songID, out string artist, out string title, out int numPlayed, out DateTime dateAdded, string filePath)
        {
            artist    = String.Empty;
            title     = String.Empty;
            numPlayed = 0;
            dateAdded = DateTime.Today;

            using (var connection = new SQLiteConnection())
            {
                connection.ConnectionString = "Data Source=" + filePath;

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

                using (var command = new SQLiteCommand(connection))
                {
                    command.CommandText = "SELECT Artist, Title, NumPlayed, DateAdded FROM Songs WHERE [id] = @id";
                    command.Parameters.Add("@id", DbType.String, 0).Value = songID;

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

                    if (reader != null && reader.HasRows)
                    {
                        reader.Read();
                        artist    = reader.GetString(0);
                        title     = reader.GetString(1);
                        numPlayed = reader.GetInt32(2);
                        dateAdded = new DateTime(reader.GetInt64(3));
                        reader.Dispose();
                        return(true);
                    }
                    if (reader != null)
                    {
                        reader.Dispose();
                    }
                }
            }

            return(false);
        }
Example #40
0
        public static bool SaveToDB(string dataSource, string completeQuery)
        {
            using (SqliteConnection con = new SqliteConnection())
            {
                con.ConnectionString = dataSource;
                try { con.Open(); }
                catch (Exception ex)
                {
                    MakeLogErrorStatic(typeof(DBReader), ex);
                    if (con.State.ToString() == "Open")
                    {
                        con.Close();
                        con.Dispose();
                    }

                    return(false);
                }

                // security check and close connection if necessary
                if (!DBSecurity.IsSecureSQLCommand(completeQuery))
                {
                    MakeLogWarningStatic(typeof(DBReader),
                                         "SaveToDB: Prevented forwarding of insecure sql-command: "
                                         + completeQuery);

                    return(false);
                }

                using (SQLiteCommand cmd = new SQLiteCommand(completeQuery, con))
                {
                    cmd.CommandText = completeQuery;

                    SQLiteDataReader rdr = null;
                    try
                    {
                        cmd.ExecuteReader();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Could not execute SQLiteDataReader in SaveToDB: " + ex);
                    }
                    finally
                    {
                        if (rdr != null)
                        {
                            rdr.Close();
                        }
                    }
                }
            }

            return(true);
        }
Example #41
0
        //sets players in room and where they can move to
        public void SetClientInRoom(Socket client, String room)
        {
            if (socketToRoomLookup.ContainsKey(client) == false)
            {
                var command = new sqliteCommand("select * from  table_rooms where name == '" + room + "'", conn);
                var reader  = command.ExecuteReader();

                reader.Read();
                Room currentRoom = new Room(reader["name"] as String, reader["desc"] as String);
                socketToRoomLookup[client] = currentRoom;
            }
        }
Example #42
0
 /// <summary>
 /// Allows programmer to run a query against the Database.
 /// </summary>
 /// <param name="sql">The SQL to run</param>
 /// <returns>A DataTable containing the result set.</returns>
 public DataTable GetDataTable(string sql)
 {
     DataTable dt = new DataTable();
     SqliteConnection cnn = new SqliteConnection(dbConnection);
     cnn.Open();
     SqliteCommand cmd = new SqliteCommand(cnn) { CommandText = sql };
     SqliteDataReader reader = cmd.ExecuteReader();
     dt.Load(reader);
     reader.Close();
     cnn.Close();
     return dt;
 }
Example #43
0
        public Mono.Data.Sqlite.SqliteDataReader ExecuteReader(bool bKillConnectionOnError = false)
        {
            if (_SqlConnection.State != System.Data.ConnectionState.Open || _SqlCommand.Connection == null)
            {
                throw new Exception("Connection not initialised");
            }

            try
            {
                return(_SqlCommand.ExecuteReader());
            }
            catch (Exception ex)
            {
                LogFault(String.Format("Query execution failed {0}.", _SqlCommand.CommandText), ex, true);
                if (bKillConnectionOnError)
                {
                    Dispose();
                }

                return(null);
            }
        }
Example #44
0
		public Dictionary<string, FileObject> GetFilelist()
		{
			using (SqliteCommand sqc = new SqliteCommand(connection)) {
				sqc.CommandText = "SELECT path, hash, size, changedate FROM Files";
				using (SqliteDataReader sqr = sqc.ExecuteReader()) {
					Dictionary<string, FileObject> filelist = new Dictionary<string, FileObject>();
					while (sqr.Read()) {
						filelist.Add(sqr.GetString(0), new FileObject(sqr.GetString(0), sqr.GetString(1), sqr.GetInt64(2), sqr.GetInt64(3)));
					}
					return filelist;
				}
			}
		}
Example #45
0
 List<MatchingTable> GetMatchingList(SqliteCommand command, string sql)
 {
     command.CommandText = sql;
     List<MatchingTable> matchingList = new List<MatchingTable>();
     using (SqliteDataReader reader = command.ExecuteReader())
     {
         while (reader.Read())
         {
             matchingList.Add(CreateMatchingTable(reader));
         }
     }
     return matchingList;
 }
Example #46
0
        public override void update(ActionTimer timer)
        {
            using (SQLiteCommand command = new SQLiteCommand(Sqlite.getSqlite().connection))
            {
                command.CommandText = "SELECT name FROM `account` WHERE `id`=@id";
                command.Parameters.AddWithValue("@id", this.accID);
                using (SQLiteDataReader sdrITM = command.ExecuteReader())
                {
                    if (sdrITM.HasRows)
                    {
                        sdrITM.Read();

                        this.name = Convert.ToString(sdrITM["name"]);
                        accExists = true;
                    }
                }
            }


            if (accExists)
            {
                using (SQLiteCommand command = new SQLiteCommand(Accounts.Logs.SQLiteLogger.connection))
                {
                    command.CommandText = "SELECT * FROM `logStats` WHERE `accountID`=@id";
                    command.Parameters.AddWithValue("@id", this.accID);
                    using (SQLiteDataReader sdrITM = command.ExecuteReader())
                    {
                        if (sdrITM.HasRows)
                        {
                            List <AccountLogChar> alcList = new List <AccountLogChar>();
                            while (sdrITM.Read())
                            {
                                AccountLogChar alc = new AccountLogChar();
                                alc.type  = Convert.ToInt32(sdrITM["type"]);
                                alc.value = Convert.ToInt32(sdrITM["value"]);
                                alc.time  = Convert.ToInt64(sdrITM["time"]);


                                alcList.Add(alc);
                            }
                            charStatList = alcList.ToArray();
                        }
                    }
                }
            }



            isFinished = true;
            timer.removeAction(this);
        }
Example #47
0
        public static Hashtable[] Query(string qry)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            SqliteDataReader reader = null;

            cmd = conn.CreateCommand();
            cmd.CommandText = qry;

            try
            {
            reader = cmd.ExecuteReader();
            }
            catch (Exception ex)
            {
            MainClass.AddLog("Query error: '" + ex.Message + "'", true);
            MainClass.AddLog("Query was: '" + qry + "'", true);
            return null;
            }

            List<Hashtable> ret = new List<Hashtable>();

            while (reader.Read())
            {
            Hashtable row = new Hashtable();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                if (reader[i].GetType() == typeof(Int64))
                {
                    if ((long)reader[i] > int.MaxValue)
                        row[reader.GetName(i)] = (long)reader[i];
                    else
                        row[reader.GetName(i)] = (int)(long)reader[i];
                }
                else
                    row[reader.GetName(i)] = reader[i];
            }

            ret.Add(row);
            }

            sw.Stop();

            if (sw.ElapsedMilliseconds >= 1000)
            MainClass.AddLog("SQL Query took very long: " + sw.ElapsedMilliseconds + "ms", true);

            return ret.ToArray();
        }
Example #48
0
    public void MakeCvsThenSend()
    {
        /*Make CVS file*/
        //Filepath for the data.csv file
        string fileName = Application.persistentDataPath + "/" + "data.csv";

        //timestamp, page, date, feeling, urge, intensity, thoughts
        using (StreamWriter writer = new StreamWriter(fileName, false, Encoding.UTF8))
        {
            //Write the each columns title, for each field in pateint_info
            writer.Write("Timestamp | Page | Date | Feeling | Urge | Intensity | Thoughts");
            writer.Write(Environment.NewLine);

            //Write data from the the db
            conn = new sqliteConnection("URI=file:" + Application.persistentDataPath + "/" + dbName + ";Version=3;FailIfMissing=True;mode=cvs");
            conn.Open();
            var Sqlcommand = new sqliteCommand("select * from patient_info", conn);
            var reader     = Sqlcommand.ExecuteReader();
            while (reader.Read())
            {
                writer.Write(reader["timestamp"] + "|" + reader["page"] + "|" + reader["date"] + "|" + reader["feeling"] + "|" + reader["urge"] + "|" + reader["intensity"] + "|" + reader["thoughts"]);
                writer.Write(Environment.NewLine);
            }

            conn.Close();
        }


        /*SendMail*/
        MailMessage mail = new MailMessage();

        mail.From = new MailAddress("*****@*****.**");
        mail.To.Add(email.text);
        mail.Subject = "Patients Data from App";
        mail.Body    = "The File attached is the patients data (every entry is seperated by '|' when importing into excel or google sheets that custom seporator should be used) ";
        //Add the data.csv file to the email
        mail.Attachments.Add(new Attachment(fileName));

        SmtpClient smtpServer = new SmtpClient();

        smtpServer.Host           = "smtp.gmail.com";
        smtpServer.Port           = 587; //Has to be 587 so it works on Networks with port protections.
        smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpServer.Credentials    = new System.Net.NetworkCredential("*****@*****.**", "HeartRateAppFxu2018") as ICredentialsByHost;
        smtpServer.EnableSsl      = true;
        ServicePointManager.ServerCertificateValidationCallback =
            delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        { return(true); };
        smtpServer.Send(mail);
    }
Example #49
0
        public virtual bool Init()
        {
            lock (_Mutex)
            {
                if (_Connection != null)
                {
                    return(false);
                }
                _Connection = new SQLiteConnection("Data Source=" + _FilePath);
                try
                {
                    _Connection.Open();
                }
                catch (Exception)
                {
                    _Connection.Dispose();
                    _Connection = null;
                    return(false);
                }

                using (var command = new SQLiteCommand(_Connection))
                {
                    command.CommandText = "SELECT Value FROM Version";

                    SQLiteDataReader reader = null;

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

                    if (reader == null || !reader.Read() || reader.FieldCount == 0)
                    {
                        _Version = -1;
                    }
                    else
                    {
                        _Version = reader.GetInt32(0);
                    }

                    if (reader != null)
                    {
                        reader.Dispose();
                    }
                }
            }
            return(true);
        }
Example #50
0
        public static bool existsName(String name)
        {
            using (SQLiteCommand command = new SQLiteCommand(Sqlite.getSqlite().connection)) {
                command.CommandText = "SELECT name FROM `account` WHERE `name`=@name";
                command.Parameters.AddWithValue("@name", name);
                using (SQLiteDataReader sdrITM = command.ExecuteReader()) {
                    if (!sdrITM.HasRows)
                    {
                        return(false);
                    }

                    return(true);
                }
            }
        }
Example #51
0
        /*
         * Returns the string found at the field column for 'id' id
         */
        public String getStringFieldFromId(int id, String field)
        {
            sqliteCommand command = new sqliteCommand("select " + field + " from " + m_TableName + " where id = @id", m_Connection);

            command.Parameters.Add("@id", System.Data.DbType.UInt32).Value    = id;
            command.Parameters.Add("@field", System.Data.DbType.String).Value = field;

            sqliteDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                return(reader[field].ToString());
            }
            return(null);
        }
Example #52
0
    public static void ModifyPlayerWinCount(uint ID, int value)
    {
        for (int i = 0; i < players.Count; i++)
        {
            if (players [i].ID == ID)
            {
                //Confirm log in credentials through database
                string   databasePath = "";
                Platform platform     = RunningPlatform();
                if (platform == Platform.Windows)
                {
                    databasePath = "Data Source=" + System.Environment.CurrentDirectory + "\\database.db; FailIfMissing=True";
                }
                else if (platform == Platform.Mac)
                {
                    databasePath = "Data Source=" + System.Environment.CurrentDirectory + "/data/database.db; FailIfMissing=True";
                }

                SQLiteConnection db_connection = new SQLiteConnection(databasePath);
                db_connection.Open();

                string        query   = "select * from Users where ID = @id";
                SQLiteCommand command = new SQLiteCommand(query, db_connection);
                command.Parameters.AddWithValue("@id", players[i].ID);

                SQLiteDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        uint currentWinCount = Convert.ToUInt32(reader ["WINCOUNT"]);
                        players [i] = SetPlayerWinCount(players [i], currentWinCount + 1);

                        string sql = "update Users set WINCOUNT = @wincount where ID = @id";
                        command = new SQLiteCommand(sql, db_connection);
                        command.Parameters.AddWithValue("@wincount", currentWinCount + 1);
                        command.Parameters.AddWithValue("@id", players[i].ID);

                        command.ExecuteNonQuery();
                    }
                }

                db_connection.Close();
                break;
            }
        }
    }
Example #53
0
        /**
         * Given a user name this will return the salt for that username
         * if no user by that name exists it will return blank
         * @param username the user to check for.
         */
        public String GetSalt(String username)
        {
            var command = new sqliteCommand("select * from " + playerTableName + " where name =:id", Database);

            command.Parameters.Add("id", DbType.String).Value = username;
            var reader = command.ExecuteReader();

            if (reader.Read())
            {
                return(reader["salt"].ToString());
            }
            else
            {
                return("");
            }
        }
Example #54
0
        //Gets the room of the player so that it can be cross referenced
        public String GetRoom(Socket client)
        {
            var name = socket2player[client];

            var command = new sqliteCommand("select * from  table_players where name == '" + name + "'", conn);
            var reader  = command.ExecuteReader();


            reader.Read();
            {
                return(reader["room"] as string);
            }


            throw new Exception();
        }
Example #55
0
        /*
         * Returns the string found at the field column for 'name' name
         */
        public String getStringFieldFromName(String name, String field)
        {
            sqliteCommand command = new sqliteCommand("select " + field + " from " + m_TableName + " where name = @name", m_Connection);

            command.Parameters.Add("@name", System.Data.DbType.String).Value  = name;
            command.Parameters.Add("@field", System.Data.DbType.String).Value = field;

            sqliteDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                String Debug = reader[field].ToString();
                return(reader[field].ToString());
            }
            return(null);
        }
    void Start() //When the Emergency Contacts Scene is opened Should display Contacts if they have been saved in the Database
    {
        conn = new sqliteConnection("URI=file:" + Application.persistentDataPath + "/" + dbName + ";Version=3;FailIfMissing=True");
        conn.Open();

        try
        {
            //Read from contact1 table and put that into text fields on the Emergency Contacts Screen
            var Sqlcommand = new sqliteCommand("select * from contact1", conn);
            var reader     = Sqlcommand.ExecuteReader();
            reader.Read();
            if (reader.HasRows == true)
            {
                name1.text         = reader["name"] as String;
                relationship1.text = reader["relationship"] as String;
                mobile1.text       = reader["mobile"] as String;
                home1.text         = reader["home"] as String;
            }
            else
            {
                Debug.Log("There are no rows in contact1");
            }

            //Read from contact2 table and put that into text fields on the Emergency Contacts Screen
            Sqlcommand = new sqliteCommand("select * from contact2", conn);
            reader     = Sqlcommand.ExecuteReader();
            reader.Read();
            if (reader.HasRows == true)
            {
                name2.text         = reader["name"] as String;
                relationship2.text = reader["relationship"] as String;
                mobile2.text       = reader["mobile"] as String;
                home2.text         = reader["home"] as String;
            }
            else
            {
                Debug.Log("There are no rows in contact2");
            }
        }
        catch (Exception ex)
        {
            Debug.Log("Failed to read from Database " + ex);
        }
        conn.Close();
    }
Example #57
0
        /*
         * Returns true if the query exists in the field in this table for entry name in column Name
         */
        public bool queryOtherFieldFromName(String name, String query, String field)
        {
            sqliteCommand command = new sqliteCommand("select " + field + " from " + m_TableName + " where name = @name", m_Connection);

            command.Parameters.Add("@name", System.Data.DbType.String).Value  = name;
            command.Parameters.Add("@field", System.Data.DbType.String).Value = field;

            sqliteDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                if (reader[field].ToString() == query)
                {
                    return(true);
                }
            }
            return(false);
        }
Example #58
0
        //prints description of room players are in
        public String RoomDescription(Socket client)
        {
            var    command = new sqliteCommand("select * from  table_rooms where name == '" + socketToRoomLookup[client].name + "'", conn);
            var    reader  = command.ExecuteReader();
            String desc    = "";

            while (reader.Read())
            {
                desc += reader["desc"] + "\nExits: \n";
                String[] Temp = { "north", "west", "south", "east" };
                for (var i = 0; i < Temp.Length; i++)
                {
                    String result = reader[Temp[i]] as String;

                    if (result != "")
                    {
                        desc += Temp[i] + " ";
                    }
                }
            }

            var players = 0;

            //for each player in room players + 1
            foreach (var kvp in socketToRoomLookup)
            {
                if ((kvp.Key != client) &&
                    (kvp.Value != socketToRoomLookup[client])
                    )
                {
                    players++;
                }
            }
            //if players more than 1 print
            if (players > 0)
            {
                desc += "\n";
                desc += "There are " + players + " other dungeoneers in this room";
            }

            desc += "\n";

            return(desc);
        }
Example #59
0
        /// <summary>
        /// Method that makes a select on the database
        /// </summary>
        /// <param name="command_sql">Command to be executed</param>
        /// <returns>Returns a DataReader that provides the returns of consult</returns>
        public static SqliteDataReader Select(string command_sql)
        {
            try
            {
                if (!is_open)
                {
                    OpenConnection();
                }

                SqliteCommand    command = new Mono.Data.Sqlite.SqliteCommand(command_sql, m_dbConnection);
                SqliteDataReader reader  = command.ExecuteReader();
                return(reader);
            }
            catch (Exception e)
            {
                Agenda_de_Saude.Util.CL_Files.WriteOnTheLog("Problem on the sentence. Sentence: " + command_sql + " Error: " + e.Message);
                return(null);
            }
        }
Example #60
0
 public static void Init(string absolutePath = "cards.cdb")
 {
     m_cards = new Dictionary <int, Card>();
     using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + absolutePath)){
         connection.Open();
         using (SQLiteCommand command = new SQLiteCommand("SELECT datas.id, ot, alias, "
                                                          + "setcode, type, level, race, attribute, atk, def ,"
                                                          + " name , desc FROM datas,texts WHERE datas.id=texts.id",
                                                          connection)){
             using (SQLiteDataReader reader = command.ExecuteReader()){
                 while (reader.Read())
                 {
                     int           id        = reader.GetInt32(0);
                     int           ot        = reader.GetInt32(1);
                     int           levelinfo = reader.GetInt32(5);
                     int           level     = levelinfo & 0xff;
                     int           lscale    = (levelinfo >> 24) & 0xff;
                     int           rscale    = (levelinfo >> 16) & 0xff;
                     Card.CardData data      = new Card.CardData
                     {
                         Code      = id,
                         Alias     = reader.GetInt32(2),
                         Setcode   = reader.GetInt64(3),
                         Type      = reader.GetInt32(4),
                         Level     = level,
                         LScale    = lscale,
                         RScale    = rscale,
                         Race      = reader.GetInt32(6),
                         Attribute = reader.GetInt32(7),
                         Attack    = reader.GetInt32(8),
                         Defense   = reader.GetInt32(9)
                     };
                     string name = reader.GetString(10);
                     string desc = reader.GetString(11);
                     m_cards.Add(id, new Card(data, ot, name, desc));
                 }
                 reader.Close();
             }
         }
         connection.Close();
     }
 }