public void CountItems(string Key, Action<string> y)
        {
            //Console.WriteLine("CountItems enter");
            using (var c = OpenReadOnlyConnection())
            {
                c.Open();

                using (var reader = new SQLiteCommand(
                    "select count(*) from MY_TABLEXX where XKey ='" + Key.Replace("'", "\\'") + "'", c).ExecuteReader()
                    )
                {

                    if (reader.Read())
                    {
                        var Content = (int)reader.GetInt32(0);

                        y("" + Content);

                    }
                }

                c.Close();

            }
            //Console.WriteLine("CountItems exit");
        }
Exemplo n.º 2
0
 private void ReadUsersIntoList(SQLiteConnection db) {
     using (SQLiteDataReader userEntry = new SQLiteCommand("SELECT * FROM users", db).ExecuteReader()) {
         while (userEntry.Read()) {
             overlordRef.Create((int)userEntry["access"],
                 (string)userEntry["nickname"],
                 (string)userEntry["realname"],
                 DateTime.Parse((string)userEntry["seen"]),
                 false,
                 (int)userEntry["id"]);
         }
     }
 }
Exemplo n.º 3
0
 public List<Toon> getAllToons(Toon t)
 {
     List<Toon> list = new List<Toon>();
     string cmd = "SELECT * FROM Toons";
     SQLiteDataReader reader = new SQLiteCommand(cmd, dbConnection).ExecuteReader();
     while (reader.Read()) {
         object[] values = new object[reader.FieldCount];
         reader.GetValues(values);
         list.Add(new Toon(values));
     }
     return list;
 }
Exemplo n.º 4
0
        public static string Read(string contentRead)
        {
            using (var c = new SQLiteConnection(

                new SQLiteConnectionStringBuilder
                {
                    DataSource = "MY_DATABASE.sqlite",
                    Version = 3,
                    ReadOnly = true,

                    // cannot be set while running under .net debugger
                    // php needs to use defaults

                    //Password = "",
                    //Uri = "localhost"              
                }.ConnectionString
                ))
            {
                // Invalid ConnectionString format for parameter "password"
                c.Open();




                var reader = new SQLiteCommand("select Content from MY_TABLE", c).ExecuteReader();

                //var x = from k in MY_TABLE
                //        select new { k.Content };


                //if (reader == null)
                //    contentRead += "Reader was null";
                //else
                //{
                //var i = 6;

                while (reader.Read())
                {
                    //i--;
                    contentRead += "\n";
                    contentRead += (string)reader["Content"];

                    //if (i == 0)
                    //    break;
                }
                //}


                c.Close();

            }
            return contentRead;
        }
        /// <summary>
        /// This Method is a javascript callable method.
        /// </summary>
        /// <param name="e">A parameter from javascript.</param>
        /// <param name="y">A callback to javascript.</param>
        public void AddItem(string Key, string Content, Action<string> y)
        {
#if !DEBUG
            // should jsc do this implictly?
            try
            {
                //DriverManager.registerDriver(new AppEngineDriver());
            }
            catch
            {
                throw;
            }
#endif

            using (var c = new SQLiteConnection(

                  new SQLiteConnectionStringBuilder
                  {
                      DataSource = "MY_DATABASE.sqlite",
                      Version = 3
                  }.ConnectionString

            ))
            {
                c.Open();

                using (var cmd = new SQLiteCommand("create table if not exists MY_TABLEXX (XKey text not null, Content text not null)", c))
                {
                    cmd.ExecuteNonQuery();
                }

                new SQLiteCommand("insert into MY_TABLEXX (XKey, Content) values ('" + Key.Replace("'", "\\'") + "', '" + Content.Replace("'", "\\'") + "')", c).ExecuteNonQuery();

                using (var reader = new SQLiteCommand("select count(*) from MY_TABLEXX", c).ExecuteReader())
                {

                    if (reader.Read())
                    {
                        var count = (int)reader.GetInt32(0);

                        y("" + count);

                    }
                }


                c.Close();
            }

        }
Exemplo n.º 6
0
        public void Init()
        {
            try
            {
                string path = Path.Combine(Program.Config.LauncherDir, "cards.cdb");
                m_cards = new Dictionary<int, CardInfos>();

                if (!File.Exists(path)) return;

                SQLiteConnection connection = new SQLiteConnection("Data Source=" + path);
                connection.Open();
                SQLiteDataReader reader = new SQLiteCommand("SELECT id, alias, type, level, race, attribute, atk, def FROM datas", connection).ExecuteReader();

                while (reader.Read())
                {
                    int id = reader.GetInt32(0);

                    CardInfos infos = new CardInfos(id)
                    {
                        AliasId = reader.GetInt32(1),
                        Type = reader.GetInt32(2),
                        Level = reader.GetInt32(3),
                        Race = reader.GetInt32(4),
                        Attribute = reader.GetInt32(5),
                        Atk = reader.GetInt32(6),
                        Def = reader.GetInt32(7)
                    };
                    m_cards.Add(id, infos);
                }

                reader.Close();
                reader = new SQLiteCommand("SELECT id, name, desc FROM texts", connection).ExecuteReader();

                while (reader.Read())
                {
                    int key = reader.GetInt32(0);
                    if (m_cards.ContainsKey(key))
                    {
                        m_cards[key].Name = reader.GetString(1);
                        m_cards[key].CleanedName = m_cards[key].Name.Trim().ToLower().Replace("-", " ").Replace("'", " ").Replace("   ", " ").Replace("  ", " ");
                        m_cards[key].Description = reader.GetString(2);
                    }
                }
                connection.Close();
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 7
0
 public void Init()
 {
     try
     {
         m_cards = new Dictionary<int, CardInfos>();
         string str = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "";
         string str2 = Path.Combine(str, @"cards.cdb");
         if (!File.Exists(str2)) return;
         SQLiteConnection connection = new SQLiteConnection("Data Source=" + str2);
         connection.Open();
         SQLiteDataReader reader = new SQLiteCommand("SELECT id, alias, type, level, race, attribute, atk, def FROM datas", connection).ExecuteReader();
         while (reader.Read())
         {
             int id = reader.GetInt32(0);
             CardInfos infos = new CardInfos(id)
             {
                 AliasId = reader.GetInt32(1),
                 Type = reader.GetInt32(2),
                 Level = reader.GetInt32(3),
                 Race = reader.GetInt32(4),
                 Attribute = reader.GetInt32(5),
                 Atk = reader.GetInt32(6),
                 Def = reader.GetInt32(7)
             };
             m_cards.Add(id, infos);
         }
         reader.Close();
         reader = new SQLiteCommand("SELECT id, name, desc FROM texts", connection).ExecuteReader();
         while (reader.Read())
         {
             int key = reader.GetInt32(0);
             if (m_cards.ContainsKey(key))
             {
                 m_cards[key].Name = reader.GetString(1);
                 m_cards[key].CleanedName = m_cards[key].Name.Trim().ToLower().Replace("-", " ").Replace("'", " ").Replace("   ", " ").Replace("  ", " ");
                 m_cards[key].Description = reader.GetString(2);
             }
         }
         connection.Close();
         Loaded = true;
     }
     catch (Exception)
     {
         MessageBox.Show("Error loading cards.cdb");
     }
 }
Exemplo n.º 8
0
        Bug IDataAccess.GetBug(int id)
        {
            using (conn = new SQLiteConnection(connectionString))
            {
                conn.Open();

                var bug = new Bug();

                var reader = new SQLiteCommand(SQLFixedQueries.SelectBug(id), conn)
                                                    .ExecuteReader();

                while (reader.Read())
                    bug = ReadBugFromSQL(reader);

                return bug;
            }
        }
Exemplo n.º 9
0
        List<IssueViewModel> IDataAccess.GetAllIssues(string filter)
        {
            using (conn = new SQLiteConnection(connectionString))
            {
                conn.Open();

                var issues = new List<IssueViewModel>();

                var reader = new SQLiteCommand(SQLQueryBuilder.BuildSQLQuery(filter), conn)
                                                    .ExecuteReader();

                while (reader.Read())
                    issues.Add(ReadIssueFromSQL(reader));

                return issues;
            }
        }
Exemplo n.º 10
0
        internal Action GetAction(string actionName)
        {
            var cn = new SQLiteConnection("Data Source=" + DbName + ";Version=3;");
             cn.Open();

             var reader = new SQLiteCommand("select id, command, arg1, arg2 from actions where id = '" + actionName + "'", cn).ExecuteReader();

             Action action = null;
             try
             {
            if (reader.Read())
            {
               action = new Action();
               action.Id = reader.GetString(reader.GetOrdinal("id"));
               action.Arg1 = reader.GetString(reader.GetOrdinal("arg1"));
               var arg2 = reader["arg2"];
               action.Arg2 = arg2.ToString();
               //action.Arg3 = reader.GetString(reader.GetOrdinal("arg3"));

               if (reader.GetString(reader.GetOrdinal("command")) == "pgdb-backup")
               {
                  action.Command = new PostgreSQLBackupCommand(action.Arg1, action.Arg2, action.Arg3, action.Arg4);
               }
               if (reader.GetString(reader.GetOrdinal("command")) == "execute-bat")
               {
                  action.Command = new ExecuteBatCommand(action.Arg1);
               }
               if (reader.GetString(reader.GetOrdinal("command")) == "sync-actions")
               {
                  action.Command = new SyncActionsCommand(action.Arg1);
               }
            }
             }
             finally
             {
            cn.Close();
             }
             return action;
        }
Exemplo n.º 11
0
        //Clocking Log
        private void viewClocking()
        {
            var db = DBMethods.OPENDB();
            //Change query to get time properly.
            string queryString = "SELECT ID, GM, " + DBMethods.GETDATETIME("time") + ", status FROM clocking ORDER BY time DESC;";
            SQLiteDataReader query = new SQLiteCommand(queryString, db).ExecuteReader();

            SearchView.ClearList();

            while (query.Read())
            {
                //Parse datetime from database
                string time = DateTime.Parse(query["datetime"].ToString()).ToString("yyyy-MM-dd HH:mm");

                string GM = query["GM"].ToString();
                bool status = Convert.ToBoolean(int.Parse(query["status"].ToString()));

                SearchView.AddChild(GM + ':' + (status ? "IN" : "OUT"), time, 0);
            }

            db.Close();
            SearchView.Show();
        }
        public void EnumerateItems(string e, Action<string> y)
        {
            //Console.WriteLine("EnumerateItems enter");
            using (var c = OpenReadOnlyConnection())
            {
                c.Open();

                using (var reader = new SQLiteCommand("select Content from MY_TABLE", c).ExecuteReader())
                {

                    while (reader.Read())
                    {
                        var Content = (string)reader["Content"];

                        y(Content);

                    }
                }

                c.Close();

            }
            //Console.WriteLine("EnumerateItems exit");
        }
Exemplo n.º 13
0
 public void menu_Syn_From_SQLite (Object Sender,EventArgs e)
 {
     OpenFileDialog ofd = new OpenFileDialog();
     ofd.FileName = "";
     ofd.DefaultExt = ".db";
     ofd.Filter = "SQLite (.DB)|*.db";
     if(ofd.ShowDialog()==DialogResult.OK)
     {
         String filepath = ofd.FileName;
         using(SQLiteConnection sqliteconn=new SQLiteConnection(String.Format("Data Source={0}",filepath)))
         {
             sqliteconn.Open();
             String sql = "SELECT name From sqlite_master Where type in('table','view') AND name Not Like 'sqlite_%' UNION ALL SELECT name From sqlite_temp_master Where type IN('table','view') ORDER BY 1";
             SQLiteDataReader dr = new SQLiteCommand(sql,sqliteconn).ExecuteReader();
             MPPFORM.ListBoxForm lbf = new MPPFORM.ListBoxForm();
             while (dr.Read())
             {
                 lbf.lb.Items.Add(dr[0].ToString());
             }
             if (lbf.ShowDialog() == DialogResult.OK)
             {
                 OdbcConnection odbcconn = new OdbcConnection(Basic_HTB_Info.Conn_Str);
                 odbcconn.Open();
                 foreach (string s in lbf.lb.CheckedItems)
                 {
                     string sql_tbl = "Select * from " + s;
                     SQLiteDataReader dr_tbl = new SQLiteCommand(sql_tbl,sqliteconn).ExecuteReader();
                     
                     String inc_sql = String.Format("insert into {0} values (?",s);
                     for (int i = 1; i < dr_tbl.FieldCount; i++)
                     {
                         inc_sql += ",?";
                     }
                     inc_sql += ");";
                     OdbcCommand inccmd = new OdbcCommand(inc_sql, odbcconn);
                     for (int i = 0; i < dr_tbl.FieldCount; i++)
                     {
                         inccmd.Parameters.Add(new OdbcParameter());
                     }
                     while (dr_tbl.Read())
                     {
                         for (int i = 0; i < dr_tbl.FieldCount; i++)
                         {
                             inccmd.Parameters[i].Value = dr_tbl[i].ToString();
                         }
                         inccmd.ExecuteNonQuery();
                     }
                 }
                 odbcconn.Close();
                 odbcconn.Dispose();
             }
         }
     }
 }
Exemplo n.º 14
0
        ChangeRequest IDataAccess.GetChangeRequest(int id)
        {
            using (conn = new SQLiteConnection(connectionString))
            {
                conn.Open();

                var changeRequest = new ChangeRequest();

                var reader = new SQLiteCommand(SQLFixedQueries.SelectChangeRequest(id), conn)
                                                    .ExecuteReader();

                while (reader.Read())
                    changeRequest = ReadChangeRequestFromSQL(reader);

                return changeRequest;
            }
        }
            public Point this[string id]
            {
                set
                {
                    Context.Create();

                    if (Context.Connection.SQLiteCountByColumnName(Context.Name, "id", id) == 0)
                    {
                        var sql = "insert into ";
                        sql += Context.Name;
                        sql += " (id, x, y) values (";
                        sql += "'";
                        sql += id;
                        sql += "'";
                        sql += ", ";
                        sql += "'";
                        sql += value.x;
                        sql += "'";

                        sql += ", ";
                        sql += "'";
                        sql += value.y;
                        sql += "'";

                        sql += ")";



                        new SQLiteCommand(sql, Context.Connection).ExecuteNonQuery();

                        return;
                    }

                    #region update
                    {
                        var sql = "update ";
                        sql += Context.Name;

                        sql += " set x = ";
                        sql += "'";
                        sql += value.x;
                        sql += "'";

                        sql += " set y = ";
                        sql += "'";
                        sql += value.y;
                        sql += "'";


                        sql += " where id = ";
                        sql += "'";
                        sql += id;
                        sql += "'";

                        new SQLiteCommand(sql, Context.Connection).ExecuteNonQuery();
                    }
                    #endregion

                }

                get
                {
                    Context.Create();


                    var sql = "select x, y from ";
                    sql += Context.Name;
                    sql += " where id = ";
                    sql += "'";
                    sql += id;
                    sql += "'";

                    //new SQLiteCommand(sql, Connection).ExecuteScalar();

                    var value = default(Point);
                    var reader = new SQLiteCommand(sql, Context.Connection).ExecuteReader();

                    if (reader.Read())
                    {
                        value = new Point { x = reader.GetString(0), y = reader.GetString(1) };
                    }
                    reader.Close();

                    return value;
                }
            }
        public static bool SQLiteTableExists(this SQLiteConnection c, string name)
        {
            // http://www.electrictoolbox.com/check-if-mysql-table-exists/



            //var w = "select name from sqlite_master where type='table' and name=";
            var w = "select table_name from information_schema.tables where table_name=";
            w += "'";
            w += name;
            w += "'";


            var reader = new SQLiteCommand(w, c).ExecuteReader();

            var value = reader.Read();

            reader.Close();

            return value;
        }
        public List<string> GetKeys()
        {
            var sql = "select id from ";
            sql += Name;

            var value = new List<string>();

            var reader = new SQLiteCommand(sql, Connection).ExecuteReader();

            while (reader.Read())
            {
                value.Add(reader.GetString(0));
            }

            reader.Close();

            return value;
        }
 public TimeZoneInfo GetLastTimeZoneEntry()
 {
     try
     {
         var reader = new SQLiteCommand("SELECT timezone FROM " + Settings.TimeZoneTable + " ORDER BY time DESC LIMIT 1;", _connection).ExecuteReader();
         if (reader.HasRows)
         {
             reader.Read(); // read only once
             var timeZone = TimeZoneInfo.FindSystemTimeZoneById((string)reader["timezone"]);
             return timeZone;
         }
         reader.Close();
         return null; // no entry or failed to parse
     }
     catch (Exception e)
     {
         LogError(e.Message);
         return null; // other error
     }
 }
        public DateTime GetUserWorkStart(DateTimeOffset date)
        {
            var firstEntryDateTime = DateTime.Now; // default value
            try
            {
                var firstEntryReader = new SQLiteCommand("SELECT time FROM " + Settings.WindowsActivityTable +
                                                         " WHERE STRFTIME('%s', DATE(time))==STRFTIME('%s', DATE('" + date.Date.ToString("u") + "'))" +
                                                         " AND STRFTIME('%H', TIME(time)) >= STRFTIME('%H', TIME('04:00:00'))" + // day start should be after 04 am
                                                         " AND process != '" + Dict.Idle +
                                                         "' ORDER BY time ASC LIMIT 1;", _connection).ExecuteReader();

                if (firstEntryReader.HasRows)
                {
                    firstEntryReader.Read(); // read only once
                    firstEntryDateTime = DateTime.Parse((string)firstEntryReader["time"]);
                }

                firstEntryReader.Close();
            }
            catch (Exception e)
            {
                LogError(e.Message);
            }
            return firstEntryDateTime;
        }
        public DateTime GetUserWorkEnd(DateTimeOffset date)
        {
            var lastEntryDateTime = DateTime.Now;
            try
            {
                var lastEntryReader = new SQLiteCommand("SELECT time FROM " + Settings.WindowsActivityTable +
                                                        " WHERE STRFTIME('%s', DATE(time))==STRFTIME('%s', DATE('" +
                                                        date.Date.ToString("u") + "'))" +
                                                        " AND process != '" + Dict.Idle + "' ORDER BY time DESC LIMIT 1;",
                    _connection).ExecuteReader();

                if (lastEntryReader.HasRows)
                {

                    lastEntryReader.Read(); // read only once
                    lastEntryDateTime = DateTime.Parse((string)lastEntryReader["time"]);
                }

                lastEntryReader.Close();
            }
            catch (Exception e)
            {
                LogError(e.Message);
            }
            return lastEntryDateTime;
        }
Exemplo n.º 21
0
        private static string Query(string query)
        {
            var report = "";

            if(MODE == DBMODE.SQLITE) {
                //then actually do it

                if(currentDatabaseName.Length > 0) {

                    var conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", currentDatabaseName));
                    conn.Open();

                    IDataReader results = null;
                    string errorText = string.Empty;

                    try{

                        results = new SQLiteCommand(query, conn).ExecuteReader();

                    }catch(Exception e) {

                        errorText = e.Message;
                    }

                    if(results != null) {

                        //i must keep the same order. i could do dict int, dict name type... but meah
                        var columns = new string[results.FieldCount];
                        var columnTypes = new Type[results.FieldCount];

                        for(int i=0; i < results.FieldCount; ++i) {
                            columns[i] = results.GetName(i);
                            columnTypes[i] = results[columns[i]].GetType();
                        }

                        DataTable table = null;

                        while(results.Read()) {

                            if(table == null) {
                                table = new DataTable(columns, columnTypes);}

                            var row = new DataRow();

                            foreach(string columnName in columns) {
                                row[columnName] = results[columnName];}

                            if(table != null) {
                                table.AddRow(row);}
                        }

                        if(table != null){
                            report = table.ToString();
                        }else{
                            report = results.RecordsAffected + " rows affected";}

                    }else{
                        report = errorText;}

                    conn.Close();

                }else{

                    report = "you need to select a database before you can execute a command. use \\u your_database_name";
                }

            }else{

                report = "currently only supporting sqlite mode...";
            }

            return report;
        }
Exemplo n.º 22
0
        IssueViewModel IDataAccess.GetIssue(int id)
        {
            using (conn = new SQLiteConnection(connectionString))
            {
                conn.Open();

                var issue = new IssueViewModel();

                var reader = new SQLiteCommand(SQLFixedQueries.SelectIssue(id), conn)
                                                    .ExecuteReader();

                while (reader.Read())
                    issue = ReadIssueFromSQL(reader);

                return issue;
            }
        }
Exemplo n.º 23
0
        public static bool SQLiteTableExists(this SQLiteConnection c, string name)
        {
            var w = "select name from sqlite_master where type='table' and name=";
            w += "'";
            w += name;
            w += "'";


            var reader = new SQLiteCommand(w, c).ExecuteReader();

            var value = reader.Read();

            reader.Close();

            return value;
        }
Exemplo n.º 24
0
        /// <summary>
        ///     Returns int value of last ID in default database
        /// </summary>
        /// <returns>
        ///     <see cref="int" />
        /// </returns>
        public int GetLastDatabaseId() {
            int id = -1;

            using (SQLiteConnection db = new SQLiteConnection($"Data Source={DatabaseLocation};Version=3;")) {
                db.Open();

                using (SQLiteDataReader r = new SQLiteCommand("SELECT MAX(id) FROM users", db).ExecuteReader()) {
                    while (r.Read()) {
                        id = Convert.ToInt32(r.GetValue(0));
                    }
                }
            }

            return id;
        }
Exemplo n.º 25
0
        /// <summary>
        /// Get the non-spatial columns
        /// </summary>
        private void GetNonSpatialColumns()
        {
            if (!string.IsNullOrEmpty(_columns))
                return;

            if (string.IsNullOrEmpty(ConnectionID))
                return;

            using (var cn = GetConnection(ConnectionString))
            {
                using (var dr = new SQLiteCommand(string.Format("PRAGMA table_info('{0}');", Table), cn).ExecuteReader())
                {
                    if (!dr.HasRows)
                        throw new InvalidOperationException("Provider configuration incomplete or wrong!");

                    var columns = new List<string>
                        {
                            string.Equals(ObjectIdColumn, "rowid", StringComparison.OrdinalIgnoreCase)
                                ? "\"ROWID\" AS \"ROWID\""
                                : string.Format("\"{0}\"", ObjectIdColumn)
                        };

                    while (dr.Read())
                    {
                        var column = dr.GetString(1);
                        if (string.Equals(column, ObjectIdColumn)) continue;
                        if (string.Equals(column, GeometryColumn)) continue;
                        columns.Add(string.Format("\"{0}\"", column));
                    }

                    _columns = string.Join(", ", columns);
                }
            }
        }
Exemplo n.º 26
0
        internal FeatureDataTable GetBaseTable()
        {
            const string sqlPragmaTableInfo ="PRAGMA table_info('{0}');";

            const string sqlSelectHasColumnData =
                "SELECT COUNT(*) FROM \"sqlite_master\" WHERE \"type\"='table' AND \"name\"='gpkg_column_data';";
            const string sqlSelectColumnData =
                "SELECT * FROM \"gpkg_column_data\" WHERE \"table_name\"=? AND \"column_name\"=?;";

            const string sqlSelectColumnConstraint =
                "SELECT * FROM \"gpkg_column_constraint\" WHERE \"constraint_name\"=?;";

            var fdt = new FeatureDataTable();
            
            // Get the geometry column definition if not previously done
            if (string.IsNullOrEmpty(GeometryColumn))
                GetGeometryColumnDefinition();

            using (var cnCI = new SQLiteConnection(_connectionString).OpenAndReturn())
            using (var cnCD = new SQLiteConnection(_connectionString).OpenAndReturn())
            using (var cnCC = new SQLiteConnection(_connectionString).OpenAndReturn())
            {
                var rdrCI = new SQLiteCommand(string.Format(sqlPragmaTableInfo, TableName), cnCI).ExecuteReader();
                if (!rdrCI.HasRows)
                    throw new GeoPackageException("The table '{0}' does not exist in database!");

                // has additional column data?
                var cmdCD = new SQLiteCommand(sqlSelectHasColumnData, cnCD);
                var hasCD = Convert.ToInt32(cmdCD.ExecuteScalar()) == 1;

                // additional column data
                cmdCD = new SQLiteCommand(sqlSelectColumnData, cnCD);
                var parCD0 = cmdCD.Parameters.Add("table_name", DbType.String);
                parCD0.Value = TableName;
                var parCD1 = cmdCD.Parameters.Add("column_name", DbType.String);

                // additional column constaint(s)
                var cmdCC = new SQLiteCommand(sqlSelectColumnConstraint, cnCC);
                var parCC0 = cmdCC.Parameters.Add("pcc", DbType.String);

                while (rdrCI.Read())
                {
                    // Get the column name
                    var columnName = rdrCI.GetString(1);
                    
                    // We don't want the geometry to appear as an attribute in the feature data table;
                    if (columnName == GeometryColumn) continue;
                    
                    // Set up the column
                    // column name and type
                    var dc = new DataColumn(rdrCI.GetString(1), GpkgUtility.GetTypeForDataTypeString(rdrCI.GetString(2)));

                    // Allow DBNull?
                    if (rdrCI.GetInt32(3) == 0) dc.AllowDBNull = true;

                    // Assign default value
                    if (!rdrCI.IsDBNull(4)) dc.DefaultValue = rdrCI.GetValue(4);

                    // Add the column
                    fdt.Columns.Add(dc);

                    // Get additional information
                    if (hasCD)
                    {
                        parCD1.Value = columnName;
                        var rdrCD = cmdCD.ExecuteReader(CommandBehavior.SingleRow);
                        if (rdrCD.HasRows)
                        {
                            rdrCD.Read();
                            if (!rdrCD.IsDBNull(2)) dc.Caption = rdrCD.GetString(2);

                            if (!rdrCD.IsDBNull(3))
                                dc.ExtendedProperties.Add("Title", rdrCD.GetString(3));
                            if (!rdrCD.IsDBNull(4))
                                dc.ExtendedProperties.Add("Description", rdrCD.GetString(4));
                            if (!rdrCD.IsDBNull(5))
                                dc.ExtendedProperties.Add("MimeType", rdrCD.GetString(5));

                            if (!rdrCD.IsDBNull(rdrCD.GetOrdinal("constraint_name")))
                            {
                                parCC0.Value = rdrCD.GetString(rdrCD.GetOrdinal("constraint_name"));
                                var rdrCC = cmdCC.ExecuteReader();
                                while (rdrCC.Read())
                                {
                                }
                            }
                        }
                    }

                    if (rdrCI.GetInt32(5) == 1)
                    {
                        fdt.PrimaryKey = new[] {dc};
                        OidColumn = dc.ColumnName;
                    }
                }
            }
            return fdt;
        }
Exemplo n.º 27
0
        public static int SQLiteCountByColumnName(this SQLiteConnection Connection, string Name, string ByColumnName, string ValueString)
        {
            var sql = "select count(*) from ";
            sql += Name;
            sql += " where ";
            sql += ByColumnName;
            sql += " = ";
            sql += "'";
            sql += ValueString;
            sql += "'";

            var value = 0;
            var reader = new SQLiteCommand(sql, Connection).ExecuteReader();

            if (reader.Read())
            {
                value = reader.GetInt32(0);
            }

            reader.Close();

            return value;
        }
Exemplo n.º 28
0
 private bool KeyValueExists(string tableName, string key, string value) {
     string command = "SELECT * from " + tableName + " WHERE Key = " + key + " AND Value = " + value + ";";
     SQLiteDataReader reader = new SQLiteCommand(command, dbConnection).ExecuteReader();
     return reader.Read();
 }
Exemplo n.º 29
0
            public int this[string Key]
            {
                set
                {
                    Context.Create();

                    if (Context.Connection.SQLiteCountByColumnName(Context.Name, "Key", Key) == 0)
                    {
                        var sql = "insert into ";
                        sql += Context.Name;
                        sql += " (Key, ValueInt32) values (";
                        sql += "'";
                        sql += Key;
                        sql += "'";
                        sql += ", ";
                        sql += ((object)value).ToString();
                        sql += ")";



                        new SQLiteCommand(sql, Context.Connection).ExecuteNonQuery();

                        return;
                    }

                    #region update
                    {
                        var sql = "update ";
                        sql += Context.Name;
                        sql += " set ValueInt32 = ";
                        sql += ((object)value).ToString();
                        sql += " where Key = ";
                        sql += "'";
                        sql += Key;
                        sql += "'";

                        new SQLiteCommand(sql, Context.Connection).ExecuteNonQuery();
                    }
                    #endregion

                }

                get
                {
                    Context.Create();


                    var sql = "select ValueInt32 from ";
                    sql += Context.Name;
                    sql += " where Key = ";
                    sql += "'";
                    sql += Key;
                    sql += "'";

                    //new SQLiteCommand(sql, Connection).ExecuteScalar();

                    var value = 0;
                    var reader = new SQLiteCommand(sql, Context.Connection).ExecuteReader();

                    if (reader.Read())
                    {
                        value = reader.GetInt32(0);
                    }
                    reader.Close();

                    return value;
                }
            }
Exemplo n.º 30
0
 private void ReadMessagesIntoUsers(SQLiteConnection db) {
     try {
         using (SQLiteDataReader m = new SQLiteCommand("SELECT * FROM messages", db).ExecuteReader()) {
             while (m.Read()) {
                 overlordRef.Get(Convert.ToInt32(m["id"]))?.Messages.Add(new Message {
                     Sender = (string)m["sender"],
                     Contents = (string)m["message"],
                     Date = DateTime.Parse((string)m["datetime"])
                 });
             }
         }
     } catch (NullReferenceException) {
         Writer.Log(
             "||| NullReferenceException occured upon loading messages from database. This most likely means a user record was deleted and the ID cannot be referenced from the message entry.",
             EventLogEntryType.Error);
     }
 }