Example #1
0
 private SQLite create()
 {
     if (textFile.Text == "")
     {
         MessageBox.Show("请选择文件");
         return null;
     }            
     try
     {
         SQLite r = new SQLite();
         r.open(textFile.Text);
         if (textKey.Text != "")
         {
             r.key(textKey.Text);
         }
         string sql;
         sql = "create table if not exists files(path TEXT PRIMARY KEY, content BLOB, time INTEGER);";
         r.doExec(sql);
         sql = "create table if not exists dirs(path TEXT PRIMARY KEY, orderkey INTEGER);";
         r.doExec(sql);
         return r;
     }
     catch (Exception e)
     {
         MessageBox.Show("打开错误:" + e.Message);
         return null;
     }
 }
Example #2
0
        public void loadTours()
        {
            toursList.Items.Clear();

            SQLite connection = new SQLite();
            SQLiteDataReader reader = connection.ReadData("SELECT ID, SID, CID, Date, Count, Discount, Price FROM Tours ORDER BY Date");
            while (reader.Read())
            {
                var readclient = connection.ReadData(string.Format("SELECT Surname, Name, Secname FROM Clients WHERE ID = '{0}'", reader.GetInt32(2)));
                readclient.Read();
                var readroute = connection.ReadData(string.Format("SELECT Country, Hotel, Duration FROM Scopes WHERE ID = '{0}'", reader.GetInt32(1)));
                readroute.Read();

                toursList.Items.Add(new Tour
                    (reader.GetInt32(0), 
                    string.Format("{0} {1} {2}", readclient.GetString(0), readclient.GetString(1), readclient.GetString(2)),
                    readroute.GetString(0),
                    readroute.GetString(1),
                    readroute.GetInt32(2),
                    reader.GetString(3), 
                    reader.GetInt32(4), 
                    reader.GetString(5),
                    reader.GetFloat(6)));

            }
            connection.Close();
        }
Example #3
0
 private LocalDB(string path, SQLite.SQLiteOpenFlags flags) : base(path, flags)
 {
     Printer.PrintDiagnostics("Local DB Open.");
     if ((flags & SQLite.SQLiteOpenFlags.Create) != 0)
     {
         PrepareTables();
     }
 }
Example #4
0
        // 생성자
        public WeekSpendPage(NeoTabPage Tab, DateTimePicker dtp)
        {
            W_SpendTab = Tab;

            SQLite = new SQLite(); // DB Object
            cmd = SQLite.GetSQLCommand(); // Command Object

            dateTimePicker1 = dtp;
            dateTimePicker1.CloseUp += DateTimePicker1_CloseUp;
        }
Example #5
0
        public WhisperBot( SQLite sqlite )
        {
            _sqlite = sqlite;

            _irc = new IrcClient( "199.9.253.119", 6667, Credentials.login, Credentials.oauth );
            _irc.sendIrcMessage( "CAP REQ :twitch.tv/commands" );

            ThreadStart ts = delegate { this.listnerThread(); };
            Thread thread = new Thread( ts );
            thread.Start();
        }
Example #6
0
        /* вывод маршрутов из БД в таблицу */
        public void loadRoutes()
        {
            routesList.Items.Clear();

            SQLite connection = new SQLite();
            SQLiteDataReader reader = connection.ReadData("SELECT ID, Climat, Country, Hotel, Duration, Cost FROM Scopes ORDER BY Climat, Country, Hotel, Duration, Cost");
            while (reader.Read())
            {
                routesList.Items.Add(new Route(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetInt32(4), reader.GetFloat(5)));
            }
            connection.Close();
        }
Example #7
0
        /* вывод клиентов из БД в таблицу */
        public void UpdateClientsList(string surname)
        {
            clientsList.Items.Clear();

            if (surname == null) { surname = ""; } else { surname = string.Format("WHERE Surname LIKE '%{0}%'", surname); }

            SQLite connection = new SQLite();
            SQLiteDataReader reader = connection.ReadData(string.Format("SELECT ID, Surname, Name, Secname FROM Clients {0} ORDER BY Surname, Name, Secname", surname));
            while (reader.Read())
            {
                clientsList.Items.Add(new Client(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3)));
            }
            connection.Close();
        }
Example #8
0
        static void Main( string[] args )
        {
            _sqlite = new SQLite();
            _sqlite.setup();

            Zones.init();
            Weapons.init();

            _mainBot = new MainBot( _sqlite );
            _whisperBot = new WhisperBot( _sqlite );

            while ( true ) {
                ;
            }
        }
Example #9
0
        public MainBot( SQLite sqlite )
        {
            _sqlite = sqlite;

            _irc = new IrcClient( "irc.twitch.tv", 6667, Credentials.login, Credentials.oauth );
            string[] rooms = Resources.rooms.Split( ',' );
            foreach ( string room in rooms )
                _irc.joinRoom( room.Trim() );
            _irc.sendIrcMessage( "CAP REQ :twitch.tv/membership" );
            _irc.sendIrcMessage( "CAP REQ :twitch.tv/commands" );
            _irc.sendIrcMessage( "CAP REQ :twitch.tv/tags" );

            ThreadStart ts = delegate { this.ListnerThread(); };
            Thread thread = new Thread( ts );
            thread.Start();
        }
Example #10
0
        public Budget(DMode d, DateTimePicker dtp, DateTime dt)
        {
            InitializeComponent();
            mode = d;
            dateTimePicker1 = dtp;
            date = dt;

            SQLite = new SQLite();

            if( mode == DMode.spend)
            {
                spend = new DataGridView();
                spend_Worship = new DataGridView();
                spend_Mission = new DataGridView();
                spend_Edu = new DataGridView();
                spend_Human = new DataGridView();
                spend_Vol = new DataGridView();
                spend_Main = new DataGridView();
                spend_Loan = new DataGridView();

                spend.CellEndEdit += Spend_CellEndEdit;
                spend_Worship.CellEndEdit += Spend_Worship_CellEndEdit;
                spend_Mission.CellEndEdit += Spend_Mission_CellEndEdit;
                spend_Edu.CellEndEdit += Spend_Edu_CellEndEdit;
                spend_Human.CellEndEdit += Spend_Human_CellEndEdit;
                spend_Vol.CellEndEdit += Spend_Vol_CellEndEdit;
                spend_Main.CellEndEdit += Spend_Main_CellEndEdit;
                spend_Loan.CellEndEdit += Spend_Loan_CellEndEdit;
                spend.CellMouseDown += Spend_CellMouseDown;

                AddGridView();
            }

            before.Hide();
            dgv.Hide();
            SetView();
            CreateTable();
            GetValues();
            SetRows();
            dgv.CellEndEdit += Dgv_CellEndEdit;

        }
Example #11
0
        public DatabaseManager()
        {
            byte x = 0;
            Log.Debug("DatabaseManager", sLConsole.GetString("Started the database loading."));

            if(SQLiteConfig.Enabled)
            {
                x++;
                sdatabase = new SQLite(SQLiteConfig.FileName);
            }

            if(MySqlConfig.Enabled)
            {
                x++;
                mdatabase = new MySql(MySqlConfig.Host, MySqlConfig.Port, MySqlConfig.User, MySqlConfig.Password, MySqlConfig.Database, MySqlConfig.Charset);
            }

            Log.Debug("DatabaseManager", sLConsole.GetString("Selecting the Database."));

            if(x == 0)
            {
                Log.LargeError(sLConsole.GetString("MAJOR ERROR"));
                Log.Error("DatabaseManager", sLConsole.GetString("Database type's is not selected!"));
                SchumixBase.ServerDisconnect(false);
                Thread.Sleep(1000);
                Environment.Exit(1);
            }
            else if(x == 2)
            {
                Log.LargeError(sLConsole.GetString("MAJOR ERROR"));
                Log.Error("DatabaseManager", sLConsole.GetString("2 Database are selected!"));
                SchumixBase.ServerDisconnect(false);
                Thread.Sleep(1000);
                Environment.Exit(1);
            }
        }
Example #12
0
        /* удаление маршрута */
        private void DeleteRouteBtn_Click(object sender, RoutedEventArgs e)
        {
            if (routesList.SelectedItem != null)
            {
                if (Confirm("Удалить выбранный маршрут?"))
                {
                    var id = (routesList.SelectedItem as Route).Id;

                    SQLite connection = new SQLite();
                    connection.WriteData(string.Format("DELETE FROM Scopes WHERE ID = '{0}'", id));
                    loadRoutes();
                }
            }
            else
            {
                MessageBox.Show("Маршрут не выбран!", "Предупреждение", MessageBoxButton.OK);
            }
        }
Example #13
0
        private void getClosestStop(SQLite.SQLiteAsyncConnection conn)
        //Executes created SQL to determine closest public transport stops to the user
        {
            if (conn == null)
            {
                return;
            }
            string sql = createStopSQL();
            ClosestStops = conn.QueryAsync<Stop>(sql).Result;
            if (ClosestStops.Count > 0) 
            {
                NoLocationsText.Visibility = System.Windows.Visibility.Collapsed;
                foreach (Stop stop in ClosestStops)
                {
                    stop.distance = Distance(myLocation, new GeoCoordinate(stop.stop_lat, stop.stop_lon), DistanceType.Kilometers);
                }
                ClosestStops = ClosestStops.OrderBy(x => x.distance).ToList();
                MarkStopsLocations(ClosestStops);
            }
            else
            {
                ApplicationBarIconButton btn = (ApplicationBarIconButton)ApplicationBar.Buttons[2];
                NoLocationsText.Text = string.Format("No {0} stops found near you.",btn.Text) ;
                NoLocationsText.Visibility = System.Windows.Visibility.Visible;
            }
            App.ViewModel.LoadData(ClosestStops, myLocation);
            //todo removed to see if it solves the multiple route issue
            //if (MainLongListSelector.ItemsSource.Count > 0)
            //{
            //    walkingRoute(myLocation, ParseGeoCoordinate(((GetThere.ViewModels.ItemViewModel)(MainLongListSelector.ItemsSource[0])).LineTwo.ToString()));

            //}
        }
Example #14
0
        public void SetPlayerChipCount(string seat, string name, Data.ChipStack stack, SQLite.DataStore store)
        {
            HandPlayer player = new HandPlayer();
            player.SeatNumber = long.Parse(seat);
            player.PlayerName = name;
            player.Stack = stack.ToInt64();
            player.SiteId = this.SiteId;
            player.Saved = false;

            this.HandPlayers.Add(player);
        }
Example #15
0
 public void SaveScoreExpSPAndLevel(User u)
 => SQLite.GetConnection().Query("UPDATE userstats SET score = @score, exp = @exp, level = @level, skillpoints = @sp WHERE userstats.UID = @uid AND userstats.LID = @lid", new { uid = u.ID, lid = u.LID, score = u.userStats.score, exp = u.userStats.exp, level = u.userStats.level, sp = u.userStats.skillpoints });
Example #16
0
 public List <User> GetTop10ByLeauge(int lid)
 => SQLite.GetConnection().Query(@"SELECT * FROM users INNER JOIN userstats ON users.LID = @lid AND userstats.LID = @lid AND users.ID = userstats.UID ORDER BY userstats.score DESC LIMIT 10", (User user, UserStats stats) =>
 {
     user.userStats = stats; return(user);
 }, new { lid = lid }).ToList();
Example #17
0
        public void Load()
        {
            _templates = new Dictionary <uint, NpcTemplate>();

            using (var connection = SQLite.CreateConnection())
            {
                _log.Info("Loading npc templates...");
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * from npcs";
                    command.Prepare();
                    using (var sqliteDataReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteDataReader))
                        {
                            while (reader.Read())
                            {
                                var template = new NpcTemplate();
                                template.Id                                = reader.GetUInt32("id");
                                template.CharRaceId                        = reader.GetInt32("char_race_id");
                                template.NpcGradeId                        = (NpcGradeType)reader.GetByte("npc_grade_id");
                                template.NpcKindId                         = (NpcKindType)reader.GetByte("npc_kind_id");
                                template.Level                             = reader.GetByte("level");
                                template.NpcTemplateId                     = (NpcTemplateType)reader.GetByte("npc_template_id");
                                template.ModelId                           = reader.GetUInt32("model_id");
                                template.FactionId                         = reader.GetUInt32("faction_id");
                                template.SkillTrainer                      = reader.GetBoolean("skill_trainer", true);
                                template.AiFileId                          = reader.GetInt32("ai_file_id");
                                template.Merchant                          = reader.GetBoolean("merchant", true);
                                template.NpcNicknameId                     = reader.GetInt32("npc_nickname_id");
                                template.Auctioneer                        = reader.GetBoolean("auctioneer", true);
                                template.ShowNameTag                       = reader.GetBoolean("show_name_tag", true);
                                template.VisibleToCreatorOnly              = reader.GetBoolean("visible_to_creator_only", true);
                                template.NoExp                             = reader.GetBoolean("no_exp", true);
                                template.PetItemId                         = reader.GetInt32("pet_item_id", 0);
                                template.BaseSkillId                       = reader.GetInt32("base_skill_id");
                                template.TrackFriendship                   = reader.GetBoolean("track_friendship", true);
                                template.Priest                            = reader.GetBoolean("priest", true);
                                template.NpcTedencyId                      = reader.GetInt32("npc_tendency_id", 0);
                                template.Blacksmith                        = reader.GetBoolean("blacksmith", true);
                                template.Teleporter                        = reader.GetBoolean("teleporter", true);
                                template.Opacity                           = reader.GetFloat("opacity");
                                template.AbilityChanger                    = reader.GetBoolean("ability_changer", true);
                                template.Scale                             = reader.GetFloat("scale");
                                template.SightRangeScale                   = reader.GetFloat("sight_range_scale");
                                template.SightFovScale                     = reader.GetFloat("sight_fov_scale");
                                template.MilestoneId                       = reader.GetInt32("milestone_id", 0);
                                template.AttackStartRangeScale             = reader.GetFloat("attack_start_range_scale");
                                template.Aggression                        = reader.GetBoolean("aggression", true);
                                template.ExpMultiplier                     = reader.GetFloat("exp_multiplier");
                                template.ExpAdder                          = reader.GetInt32("exp_adder");
                                template.Stabler                           = reader.GetBoolean("stabler", true);
                                template.AcceptAggroLink                   = reader.GetBoolean("accept_aggro_link", true);
                                template.RecrutingBattlefieldId            = reader.GetInt32("recruiting_battle_field_id");
                                template.ReturnDistance                    = reader.GetFloat("return_distance");
                                template.NpcAiParamId                      = reader.GetInt32("npc_ai_param_id");
                                template.NonPushableByActor                = reader.GetBoolean("non_pushable_by_actor", true);
                                template.Banker                            = reader.GetBoolean("banker", true);
                                template.AggroLinkSpecialRuleId            = reader.GetInt32("aggro_link_special_rule_id");
                                template.AggroLinkHelpDist                 = reader.GetFloat("aggro_link_help_dist");
                                template.AggroLinkSightCheck               = reader.GetBoolean("aggro_link_sight_check", true);
                                template.Expedition                        = reader.GetBoolean("expedition", true);
                                template.HonorPoint                        = reader.GetInt32("honor_point");
                                template.Trader                            = reader.GetBoolean("trader", true);
                                template.AggroLinkSpecialGuard             = reader.GetBoolean("aggro_link_special_guard", true);
                                template.AggroLinkSpecialIgnoreNpcAttacker =
                                    reader.GetBoolean("aggro_link_special_ignore_npc_attacker", true);
                                template.AbsoluteReturnDistance = reader.GetFloat("absolute_return_distance");
                                template.Repairman                  = reader.GetBoolean("repairman", true);
                                template.ActivateAiAlways           = reader.GetBoolean("activate_ai_always", true);
                                template.Specialty                  = reader.GetBoolean("specialty", true);
                                template.UseRangeMod                = reader.GetBoolean("use_range_mod", true);
                                template.NpcPostureSetId            = reader.GetInt32("npc_posture_set_id");
                                template.MateEquipSlotPackId        = reader.GetInt32("mate_equip_slot_pack_id", 0);
                                template.MateKindId                 = reader.GetInt32("mate_kind_id", 0);
                                template.EngageCombatGiveQuestId    = reader.GetInt32("engage_combat_give_quest_id", 0);
                                template.NoApplyTotalCustom         = reader.GetBoolean("no_apply_total_custom", true);
                                template.BaseSkillStrafe            = reader.GetBoolean("base_skill_strafe", true);
                                template.BaseSkillDelay             = reader.GetFloat("base_skill_delay");
                                template.NpcInteractionSetId        = reader.GetInt32("npc_interaction_set_id", 0);
                                template.UseAbuserList              = reader.GetBoolean("use_abuser_list", true);
                                template.ReturnWhenEnterHousingArea =
                                    reader.GetBoolean("return_when_enter_housing_area", true);
                                template.LookConverter      = reader.GetBoolean("look_converter", true);
                                template.UseDDCMSMountSkill = reader.GetBoolean("use_ddcms_mount_skill", true);
                                template.CrowdEffect        = reader.GetBoolean("crowd_effect", true);

                                var bodyPack      = reader.GetInt32("equip_bodies_id", 0);
                                var clothPack     = reader.GetInt32("equip_cloths_id", 0);
                                var weaponPack    = reader.GetInt32("equip_weapons_id", 0);
                                var totalCustomId = reader.GetInt32("total_custom_id", 0);
                                if (clothPack > 0)
                                {
                                    using (var command2 = connection.CreateCommand())
                                    {
                                        command2.CommandText = "SELECT * FROM equip_pack_cloths WHERE id=@id";
                                        command2.Prepare();
                                        command2.Parameters.AddWithValue("id", clothPack);
                                        using (var sqliteReader2 = command2.ExecuteReader())
                                            using (var reader2 = new SQLiteWrapperReader(sqliteReader2))
                                            {
                                                while (reader2.Read())
                                                {
                                                    template.Items.Headgear         = reader2.GetUInt32("headgear_id");
                                                    template.Items.HeadgearGrade    = reader2.GetByte("headgear_grade_id");
                                                    template.Items.Necklace         = reader2.GetUInt32("necklace_id");
                                                    template.Items.NecklaceGrade    = reader2.GetByte("necklace_grade_id");
                                                    template.Items.Shirt            = reader2.GetUInt32("shirt_id");
                                                    template.Items.ShirtGrade       = reader2.GetByte("shirt_grade_id");
                                                    template.Items.Belt             = reader2.GetUInt32("belt_id");
                                                    template.Items.BeltGrade        = reader2.GetByte("belt_grade_id");
                                                    template.Items.Pants            = reader2.GetUInt32("pants_id");
                                                    template.Items.PantsGrade       = reader2.GetByte("pants_grade_id");
                                                    template.Items.Gloves           = reader2.GetUInt32("glove_id");
                                                    template.Items.GlovesGrade      = reader2.GetByte("glove_grade_id");
                                                    template.Items.Shoes            = reader2.GetUInt32("shoes_id");
                                                    template.Items.ShoesGrade       = reader2.GetByte("shoes_grade_id");
                                                    template.Items.Bracelet         = reader2.GetUInt32("bracelet_id");
                                                    template.Items.BraceletGrade    = reader2.GetByte("bracelet_grade_id");
                                                    template.Items.Back             = reader2.GetUInt32("back_id");
                                                    template.Items.BackGrade        = reader2.GetByte("back_grade_id");
                                                    template.Items.Cosplay          = reader2.GetUInt32("cosplay_id");
                                                    template.Items.CosplayGrade     = reader2.GetByte("cosplay_grade_id");
                                                    template.Items.Undershirts      = reader2.GetUInt32("undershirt_id");
                                                    template.Items.UndershirtsGrade = reader2.GetByte("undershirt_grade_id");
                                                    template.Items.Underpants       = reader2.GetUInt32("underpants_id");
                                                    template.Items.UnderpantsGrade  = reader2.GetByte("underpants_grade_id");
                                                }
                                            }
                                    }
                                }

                                if (weaponPack > 0)
                                {
                                    using (var command2 = connection.CreateCommand())
                                    {
                                        command2.CommandText = "SELECT * FROM equip_pack_weapons WHERE id=@id";
                                        command2.Prepare();
                                        command2.Parameters.AddWithValue("id", weaponPack);
                                        using (var sqliteReader2 = command2.ExecuteReader())
                                            using (var reader2 = new SQLiteWrapperReader(sqliteReader2))
                                            {
                                                while (reader2.Read())
                                                {
                                                    template.Items.Mainhand      = reader2.GetUInt32("mainhand_id");
                                                    template.Items.MainhandGrade = reader2.GetByte("mainhand_grade_id");
                                                    template.Items.Offhand       = reader2.GetUInt32("offhand_id");
                                                    template.Items.OffhandGrade  = reader2.GetByte("offhand_grade_id");
                                                    template.Items.Ranged        = reader2.GetUInt32("ranged_id");
                                                    template.Items.RangedGrade   = reader2.GetByte("ranged_grade_id");
                                                    template.Items.Musical       = reader2.GetUInt32("musical_id");
                                                    template.Items.MusicalGrade  = reader2.GetByte("musical_grade_id");
                                                }
                                            }
                                    }
                                }

                                if (totalCustomId > 0)
                                {
                                    using (var command2 = connection.CreateCommand())
                                    {
                                        command2.CommandText = "SELECT * FROM total_character_customs WHERE id=@id";
                                        command2.Prepare();
                                        command2.Parameters.AddWithValue("id", totalCustomId);
                                        using (var sqliteReader2 = command2.ExecuteReader())
                                            using (var reader2 = new SQLiteWrapperReader(sqliteReader2))
                                            {
                                                while (reader2.Read())
                                                {
                                                    template.HairId = reader2.GetUInt32("hair_id");

                                                    template.ModelParams = new UnitCustomModelParams(UnitCustomModelType.Face);
                                                    template.ModelParams
                                                    .SetHairColorId(reader2.GetUInt32("hair_color_id"))
                                                    .SetSkinColorId(reader2.GetUInt32("skin_color_id"));

                                                    template.ModelParams.Face.MovableDecalAssetId =
                                                        reader2.GetUInt32("face_movable_decal_asset_id");
                                                    template.ModelParams.Face.MovableDecalScale =
                                                        reader2.GetFloat("face_movable_decal_scale");
                                                    template.ModelParams.Face.MovableDecalRotate =
                                                        reader2.GetFloat("face_movable_decal_rotate");
                                                    template.ModelParams.Face.MovableDecalMoveX =
                                                        reader2.GetInt16("face_movable_decal_move_x");
                                                    template.ModelParams.Face.MovableDecalMoveY =
                                                        reader2.GetInt16("face_movable_decal_move_y");

                                                    template.ModelParams.Face.SetFixedDecalAsset(0,
                                                                                                 reader2.GetUInt32("face_fixed_decal_asset_0_id"),
                                                                                                 reader2.GetFloat("face_fixed_decal_asset_0_weight"));
                                                    template.ModelParams.Face.SetFixedDecalAsset(1,
                                                                                                 reader2.GetUInt32("face_fixed_decal_asset_1_id"),
                                                                                                 reader2.GetFloat("face_fixed_decal_asset_1_weight"));
                                                    template.ModelParams.Face.SetFixedDecalAsset(2,
                                                                                                 reader2.GetUInt32("face_fixed_decal_asset_2_id"),
                                                                                                 reader2.GetFloat("face_fixed_decal_asset_2_weight"));
                                                    template.ModelParams.Face.SetFixedDecalAsset(3,
                                                                                                 reader2.GetUInt32("face_fixed_decal_asset_3_id"),
                                                                                                 reader2.GetFloat("face_fixed_decal_asset_3_weight"));

                                                    template.ModelParams.Face.DiffuseMapId =
                                                        reader2.GetUInt32("face_diffuse_map_id");
                                                    template.ModelParams.Face.NormalMapId =
                                                        reader2.GetUInt32("face_normal_map_id");
                                                    template.ModelParams.Face.EyelashMapId =
                                                        reader2.GetUInt32("face_eyelash_map_id");
                                                    template.ModelParams.Face.LipColor       = reader2.GetUInt32("lip_color");
                                                    template.ModelParams.Face.LeftPupilColor =
                                                        reader2.GetUInt32("left_pupil_color");
                                                    template.ModelParams.Face.RightPupilColor =
                                                        reader2.GetUInt32("right_pupil_color");
                                                    template.ModelParams.Face.EyebrowColor = reader2.GetUInt32("eyebrow_color");
                                                    reader2.GetBytes("modifier", 0, template.ModelParams.Face.Modifier, 0, 128);
                                                    template.ModelParams.Face.MovableDecalWeight =
                                                        reader2.GetFloat("face_movable_decal_weight");
                                                    template.ModelParams.Face.NormalMapWeight =
                                                        reader2.GetFloat("face_normal_map_weight");
                                                    template.ModelParams.Face.DecoColor = reader2.GetUInt32("deco_color");
                                                }
                                            }
                                    }
                                }
                                else
                                {
                                    template.ModelParams = new UnitCustomModelParams(UnitCustomModelType.Skin);
                                }

                                if (template.NpcPostureSetId > 0)
                                {
                                    using (var command2 = connection.CreateCommand())
                                    {
                                        command2.CommandText = "SELECT * FROM npc_postures WHERE npc_posture_set_id=@id";
                                        command2.Prepare();
                                        command2.Parameters.AddWithValue("id", template.NpcPostureSetId);
                                        using (var sqliteReader2 = command2.ExecuteReader())
                                            using (var reader2 = new SQLiteWrapperReader(sqliteReader2))
                                            {
                                                if (reader2.Read())
                                                {
                                                    template.AnimActionId = reader2.GetUInt32("anim_action_id");
                                                }
                                            }
                                    }
                                }

                                using (var command2 = connection.CreateCommand())
                                {
                                    command2.CommandText = "SELECT * FROM item_body_parts WHERE model_id = @model_id";
                                    command2.Prepare();
                                    command2.Parameters.AddWithValue("model_id", template.ModelId);
                                    using (var sqliteReader2 = command2.ExecuteReader())
                                        using (var reader2 = new SQLiteWrapperReader(sqliteReader2))
                                        {
                                            while (reader2.Read())
                                            {
                                                var itemId = reader2.GetUInt32("item_id", 0);
                                                var slot   = reader2.GetInt32("slot_type_id") - 23;
                                                template.BodyItems[slot] = itemId;
                                            }
                                        }
                                }

                                if (template.CharRaceId > 0)
                                {
                                    using (var command2 = connection.CreateCommand())
                                    {
                                        command2.CommandText =
                                            "SELECT char_race_id, char_gender_id FROM characters WHERE model_id = @model_id";
                                        command2.Prepare();
                                        command2.Parameters.AddWithValue("model_id", template.ModelId);
                                        using (var sqliteReader2 = command2.ExecuteReader())
                                            using (var reader2 = new SQLiteWrapperReader(sqliteReader2))
                                            {
                                                if (reader2.Read())
                                                {
                                                    template.Race   = reader2.GetByte("char_race_id");
                                                    template.Gender = reader2.GetByte("char_gender_id");
                                                }
                                            }
                                    }
                                }

                                _templates.Add(template.Id, template);
                            }
                        }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM unit_modifiers WHERE owner_type='Npc'";
                    command.Prepare();
                    using (var sqliteDataReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteDataReader))
                        {
                            while (reader.Read())
                            {
                                var npcId = reader.GetUInt32("owner_id");
                                if (!_templates.ContainsKey(npcId))
                                {
                                    continue;
                                }
                                var npc      = _templates[npcId];
                                var template = new BonusTemplate();
                                template.Attribute        = (UnitAttribute)reader.GetByte("unit_attribute_id");
                                template.ModifierType     = (UnitModifierType)reader.GetByte("unit_modifier_type_id");
                                template.Value            = reader.GetInt32("value");
                                template.LinearLevelBonus = reader.GetInt32("linear_level_bonus");
                                npc.Bonuses.Add(template);
                            }
                        }
                }

                _log.Info("Loaded {0} npc templates", _templates.Count);
            }
        }
Example #18
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            dal = new SQLite(System.Web.HttpContext.Current.Server.MapPath("\\Bowtech.db"));

            if (context.Request.QueryString["funType"] == "load")
            {
                string where = " and ID in (";
                string strWhere = context.Request.QueryString["Where"];
                if (strWhere != "")
                {
                    string[] sp = strWhere.Split(',');
                    for (int i = 0; i < sp.Length; i++)
                    {
                        where += "'" + sp[i] + "',";
                    }
                    where = where.TrimEnd(',') + ")";
                }
                string    sql = "Select ID,Name,Type,FatherID,GrandID,OrderBy,IsNet,Visble from Notes where FatherID=0 and Visble=0 " + where + " Order by OrderBy";
                DataTable dt  = dal.ExecuteDataTable(sql);
                context.Response.Write(ConvertDataTableToJson(dt));
            }
            else if (context.Request.QueryString["funType"] == "getFather")
            {
                string    sql      = "Select ID,Name,Type,FatherID,GrandID,OrderBy,IsNet,Visble from Notes where FatherID='" + context.Request.QueryString["ID"] + "' Order by OrderBy";
                DataTable dtDetail = dal.ExecuteDataTable(sql);
                context.Response.Write(ConvertDataTableToJson(dtDetail));
            }
            else if (context.Request.QueryString["funType"] == "GetMemu")
            {
                context.Response.Write(GetMemu(context.Request.QueryString["ID"]));
            }
            else if (context.Request.QueryString["funType"] == "GetContent")
            {
                context.Response.Write(GetContent(context.Request.QueryString["ID"]));
            }
            else if (context.Request.QueryString["funType"] == "GetTitle")
            {
                context.Response.Write(GetTitle(context.Request.QueryString["ID"]));
            }
            else if (context.Request.QueryString["funType"] == "Find")
            {
                DataTable dt = FindContent(context.Request.QueryString["where"], context.Request.QueryString["AndWhere"]);
                context.Response.Write(ConvertDataTableToJson(FindContent(context.Request.QueryString["where"], context.Request.QueryString["AndWhere"])));
            }
            else if (context.Request.QueryString["funType"] == "GetType")
            {
                context.Response.Write(GetTypeByID(context.Request.QueryString["ID"]));
            }
            else if (context.Request.QueryString["funType"] == "GetFirst")
            {
                string    sql = "Select ID,Title,OrderDate,Content,Type,AllBNTime,AllBNDay,AllJMTime,AllJmDay from TimeAxis Order by ID desc  limit 0,5";
                DataTable dt  = dal.ExecuteDataTable(sql);
                context.Response.Write(ConvertDataTableToJson(dt));
            }
            else if (context.Request.QueryString["funType"] == "GetImg")
            {
                string sql = "Select Img from TimeAxisIMG where ID='" + context.Request.QueryString["ID"] + "'";
                context.Response.Write(dal.ExecuteString(sql));
            }
            else if (context.Request.QueryString["funType"] == "GetImgList")
            {
                string    sql = "Select Img from TimeAxisIMG where ID='" + context.Request.QueryString["ID"] + "'";
                DataTable dt  = dal.ExecuteDataTable(sql);
                context.Response.Write(ConvertDataTableToJson(dt));
            }
            else if (context.Request.QueryString["funType"] == "GetTimeAxis")
            {
                string    sql = "Select ID,Title,OrderDate,Content,Type,AllBNTime,AllBNDay,AllJMTime,AllJmDay from TimeAxis Order by ID desc  limit " + context.Request.QueryString["Size"] + " offset " + context.Request.QueryString["Size"] + "*" + context.Request.QueryString["index"];
                DataTable dt  = dal.ExecuteDataTable(sql);
                context.Response.Write(ConvertDataTableToJson(dt));
            }
            else if (context.Request.QueryString["funType"] == "ImgXZ")
            {
                string img    = context.Request.QueryString["Img"];
                string path   = System.Web.HttpContext.Current.Server.MapPath("\\UploadTimeAxis\\" + img);
                Image  i      = Image.FromFile(path);
                Image  newImg = RotateImg(i, 90);
                i.Dispose();
                File.Delete(path);
                newImg.Save(path);
            }
        }
Example #19
0
 public void UpdateLastLoggedIn(User u)
 => SQLite.GetConnection().Query("UPDATE users SET lastloggedin=@time WHERE users.ID = @uid", new { uid = u.ID, time = Helper.GetTimestamp() });
Example #20
0
        public void Load()
        {
            // TODO Funcs: min, max, clamp, if_zero, if_positive, if_negative, floor, log, sqrt
            CalculationEngine = new CalculationEngine(CultureInfo.InvariantCulture, ExecutionMode.Compiled, true, true, false);
            CalculationEngine.AddFunction("clamp", (a, b, c) => a < b ? b : (a > c ? c : a));
            CalculationEngine.AddFunction("if_negative", (a, b, c) => a < 0 ? b : c);
            CalculationEngine.AddFunction("if_positive", (a, b, c) => a > 0 ? b : c);
            CalculationEngine.AddFunction("if_zero", (a, b, c) => a == 0 ? b : c);

            _unitFormulas = new Dictionary <FormulaOwnerType, Dictionary <UnitFormulaKind, UnitFormula> >();
            foreach (var owner in Enum.GetValues(typeof(FormulaOwnerType)))
            {
                _unitFormulas.Add((FormulaOwnerType)owner, new Dictionary <UnitFormulaKind, UnitFormula>());
            }
            _wearableFormulas = new Dictionary <WearableFormulaType, WearableFormula>();
            _unitVariables    =
                new Dictionary <uint, Dictionary <UnitFormulaVariableType, Dictionary <uint, UnitFormulaVariable> > >();

            using (var connection = SQLite.CreateConnection())
            {
                _log.Info("Loading formulas...");
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * from unit_formulas";
                    command.Prepare();
                    using (var sqliteReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteReader))
                        {
                            while (reader.Read())
                            {
                                var formula = new UnitFormula
                                {
                                    Id          = reader.GetUInt32("id"),
                                    TextFormula = reader.GetString("formula"),
                                    Kind        = (UnitFormulaKind)reader.GetByte("kind_id"),
                                    Owner       = (FormulaOwnerType)reader.GetByte("owner_type_id")
                                };
                                if (formula.Prepare())
                                {
                                    _unitFormulas[formula.Owner].Add(formula.Kind, formula);
                                }
                            }
                        }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * from unit_formula_variables";
                    command.Prepare();
                    using (var sqliteReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteReader))
                        {
                            while (reader.Read())
                            {
                                var variable = new UnitFormulaVariable
                                {
                                    FormulaId = reader.GetUInt32("unit_formula_id"),
                                    Type      = (UnitFormulaVariableType)reader.GetByte("variable_kind_id"),
                                    Key       = reader.GetUInt32("key"),
                                    Value     = reader.GetFloat("value")
                                };
                                if (!_unitVariables.ContainsKey(variable.FormulaId))
                                {
                                    _unitVariables.Add(variable.FormulaId,
                                                       new Dictionary <UnitFormulaVariableType, Dictionary <uint, UnitFormulaVariable> >());
                                }
                                if (!_unitVariables[variable.FormulaId].ContainsKey(variable.Type))
                                {
                                    _unitVariables[variable.FormulaId].Add(variable.Type,
                                                                           new Dictionary <uint, UnitFormulaVariable>());
                                }
                                _unitVariables[variable.FormulaId][variable.Type].Add(variable.Key, variable);
                            }
                        }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * from wearable_formulas";
                    command.Prepare();
                    using (var sqliteReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteReader))
                        {
                            while (reader.Read())
                            {
                                var formula = new WearableFormula
                                {
                                    Id          = reader.GetUInt32("id"),
                                    Type        = (WearableFormulaType)reader.GetByte("kind_id"),
                                    TextFormula = reader.GetString("formula")
                                };
                                if (formula.Prepare())
                                {
                                    _wearableFormulas.Add(formula.Type, formula);
                                }
                            }
                        }
                }

                _log.Info("Formulas loaded");
            }
        }
Example #21
0
        public void TestCustomMetData()
        {
            // Open an in-memory database.
            IDatabaseConnection database = new SQLite();

            database.OpenDatabase(":memory:", readOnly: false);

            string weatherData = ReflectionUtilities.GetResourceAsString("UnitTests.Weather.CustomMetData.met");
            string metFile     = Path.GetTempFileName();

            File.WriteAllText(metFile, weatherData);
            try
            {
                Simulation sim = new Simulation()
                {
                    Children = new List <IModel>()
                    {
                        new Clock(),
                        new MockSummary(),
                        new Models.Climate.Weather()
                        {
                            FullFileName = metFile
                        },
                        new Models.Report()
                        {
                            VariableNames = new[]
                            {
                                "[Manager].Script.MyColumn as x"
                            },
                            EventNames = new[]
                            {
                                "[Clock].DoReport"
                            }
                        },
                        new Manager()
                        {
                            Code = "using System;\nusing Models.Core;\nusing Models.Climate;\n\nnamespace Models\n{\n    [Serializable]\n    public class Script : Model\n    {\n        [Link] private Weather weather;\n        \n        public double MyColumn\n        {\n        \tget\n        \t{\n        \t\treturn weather.GetValue(\"my_column_name\");\n        \t}\n        }\n    }\n}\n"
                        }
                    }
                };

                Simulations sims = new Simulations()
                {
                    Children = new List <IModel>()
                    {
                        new DataStore(database),
                        sim
                    }
                };

                // Run simulations.
                Runner           runner = new Runner(sims);
                List <Exception> errors = runner.Run();
                Assert.NotNull(errors);
                if (errors.Count != 0)
                {
                    throw new AggregateException(errors);
                }

                int[]           rawData  = new int[] { 6, 7, 2, 3, 4 };
                List <object[]> rowData  = rawData.Select(x => new object[] { x }).ToList();
                DataTable       expected = Utilities.CreateTable(new string[] { "x" }, rowData);
                Assert.IsTrue(
                    expected
                    .IsSame(database.ExecuteQuery("SELECT [x] FROM Report")));
            }
            finally
            {
                database.CloseDatabase();
                File.Delete(metFile);
            }
        }
Example #22
0
        public void Load()
        {
            _crafts = new Dictionary <uint, Craft>();
            _log.Info("Loading crafts...");

            using (var connection = SQLite.CreateConnection())
            {
                /* Crafts */
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM crafts";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var template = new Craft();
                            template.Id              = reader.GetUInt32("id");
                            template.CastDelay       = reader.GetInt32("cast_delay");
                            template.ToolId          = reader.GetUInt32("tool_id", 0);
                            template.SkillId         = reader.GetUInt32("skill_id", 0);
                            template.WiId            = reader.GetUInt32("wi_id");
                            template.MilestoneId     = reader.GetUInt32("milestone_id", 0); // нет такого поля в базе 3.5.5.3
                            template.ReqDoodadId     = reader.GetUInt32("req_doodad_id", 0);
                            template.NeedBind        = reader.GetBoolean("need_bind");
                            template.AcId            = reader.GetUInt32("ac_id", 0);
                            template.ActabilityLimit = reader.GetInt32("actability_limit");
                            template.ShowUpperCraft  = reader.GetBoolean("show_upper_crafts");
                            template.RecommendLevel  = reader.GetInt32("recommend_level");
                            template.VisibleOrder    = reader.GetInt32("visible_order");
                            _crafts.Add(template.Id, template);
                        }
                    }
                }

                /* Craft products (item you get at the end) */
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM craft_products";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var craftId = reader.GetUInt32("craft_id");
                            if (!_crafts.ContainsKey(craftId))
                            {
                                continue;
                            }

                            var template = new CraftProduct();
                            template.Id              = reader.GetUInt32("id");
                            template.CraftId         = reader.GetUInt32("craft_id");
                            template.ItemId          = reader.GetUInt32("item_id");
                            template.Amount          = reader.GetInt32("amount", 1); //We always want to produce at least 1 item ?
                            template.Rate            = reader.GetInt32("rate");
                            template.ShowLowerCrafts = reader.GetBoolean("show_lower_crafts");
                            template.UseGrade        = reader.GetBoolean("use_grade");
                            template.ItemGradeId     = reader.GetUInt32("item_grade_id");

                            _crafts[template.CraftId].CraftProducts.Add(template);
                        }
                    }
                }

                /* Craft products (item you get at the end) */
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM craft_materials";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var craftId = reader.GetUInt32("craft_id");
                            if (!_crafts.ContainsKey(craftId))
                            {
                                continue;
                            }

                            var template = new CraftMaterial();
                            template.Id        = reader.GetUInt32("id");
                            template.CraftId   = craftId;
                            template.ItemId    = reader.GetUInt32("item_id");
                            template.Amount    = reader.GetInt32("amount", 1); //We always want to cost at least 1 item ?
                            template.MainGrade = reader.GetBoolean("main_grade");

                            _crafts[craftId].CraftMaterials.Add(template);
                        }
                    }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM craft_pack_crafts";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var craftId = reader.GetUInt32("craft_id");
                            if (!_crafts.ContainsKey(craftId))
                            {
                                continue;
                            }
                            _crafts[craftId].IsPack = true;
                        }
                    }
                }
            }

            _log.Info("Loaded crafts", _crafts.Count);
        }
Example #23
0
        private async void OnFirstLoad()
        {
            await SQLite.GetInstance().GetDownloadHistoryAsync();

            var FavList = await SQLite.GetInstance().GetWebFavouriteListAsync();

            if (FavList.Count > 0)
            {
                FavouriteCollection = new ObservableCollection <WebSiteItem>(FavList);
                FavouriteDictionary = new Dictionary <string, WebSiteItem>();

                foreach (var Item in FavList)
                {
                    FavouriteDictionary.Add(Item.WebSite, Item);
                }
            }
            else
            {
                FavouriteCollection = new ObservableCollection <WebSiteItem>();
                FavouriteDictionary = new Dictionary <string, WebSiteItem>();
            }

            var HistoryList = await SQLite.GetInstance().GetWebHistoryListAsync();

            if (HistoryList.Count > 0)
            {
                HistoryCollection = new ObservableCollection <KeyValuePair <DateTime, WebSiteItem> >(HistoryList);
                bool ExistToday = false, ExistYesterday = false, ExistEarlier = false;
                foreach (var HistoryItem in HistoryCollection)
                {
                    if (HistoryItem.Key == DateTime.Today.AddDays(-1))
                    {
                        ExistYesterday = true;
                    }
                    else if (HistoryItem.Key == DateTime.Today)
                    {
                        ExistToday = true;
                    }
                    else
                    {
                        ExistEarlier = true;
                    }
                }

                if (ExistYesterday && ExistToday && ExistEarlier)
                {
                    HistoryFlag = HistoryTreeCategoryFlag.Today | HistoryTreeCategoryFlag.Yesterday | HistoryTreeCategoryFlag.Earlier;
                }
                else if (!ExistYesterday && ExistToday && ExistEarlier)
                {
                    HistoryFlag = HistoryTreeCategoryFlag.Today | HistoryTreeCategoryFlag.Earlier;
                }
                else if (ExistYesterday && !ExistToday && ExistEarlier)
                {
                    HistoryFlag = HistoryTreeCategoryFlag.Yesterday | HistoryTreeCategoryFlag.Earlier;
                }
                else if (ExistYesterday && ExistToday && !ExistEarlier)
                {
                    HistoryFlag = HistoryTreeCategoryFlag.Today | HistoryTreeCategoryFlag.Yesterday;
                }
                else if (!ExistYesterday && !ExistToday && ExistEarlier)
                {
                    HistoryFlag = HistoryTreeCategoryFlag.Earlier;
                }
                else if (!ExistYesterday && ExistToday && !ExistEarlier)
                {
                    HistoryFlag = HistoryTreeCategoryFlag.Today;
                }
                else if (ExistYesterday && !ExistToday && !ExistEarlier)
                {
                    HistoryFlag = HistoryTreeCategoryFlag.Yesterday;
                }
            }
            else
            {
                HistoryCollection = new ObservableCollection <KeyValuePair <DateTime, WebSiteItem> >();
                HistoryFlag       = HistoryTreeCategoryFlag.None;
            }

            TabControl.ItemsSource = TabCollection;

            FavouriteCollection.CollectionChanged += (s, e) =>
            {
                CurrentWebPage.FavEmptyTips.Visibility = FavouriteCollection.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
            };

            HistoryCollection.CollectionChanged += (s, e) =>
            {
                CurrentWebPage.HistoryEmptyTips.Visibility = HistoryCollection.Count == 0 ? Visibility.Visible : Visibility.Collapsed;

                lock (SyncRootProvider.SyncRoot)
                {
                    if (e.Action == NotifyCollectionChangedAction.Add)
                    {
                        var TreeNode = from Item in CurrentWebPage.HistoryTree.RootNodes
                                       where (Item.Content as WebSiteItem).Subject == "今天"
                                       select Item;
                        if (TreeNode.Count() == 0)
                        {
                            CurrentWebPage.HistoryTree.RootNodes.Insert(0, new TreeViewNode
                            {
                                Content = new WebSiteItem("今天", string.Empty),
                                HasUnrealizedChildren = true,
                                IsExpanded            = true
                            });
                            HistoryFlag = HistoryTreeCategoryFlag.Today;
                            foreach (KeyValuePair <DateTime, WebSiteItem> New in e.NewItems)
                            {
                                CurrentWebPage.HistoryTree.RootNodes[0].Children.Insert(0, new TreeViewNode
                                {
                                    Content = New.Value,
                                    HasUnrealizedChildren = false,
                                    IsExpanded            = false
                                });

                                SQLite.GetInstance().SetWebHistoryList(New);
                            }
                        }
                        else
                        {
                            foreach (KeyValuePair <DateTime, WebSiteItem> New in e.NewItems)
                            {
                                TreeNode.First().Children.Insert(0, new TreeViewNode
                                {
                                    Content = New.Value,
                                    HasUnrealizedChildren = false,
                                    IsExpanded            = false
                                });
                                SQLite.GetInstance().SetWebHistoryList(New);
                            }
                        }
                    }
                }
            };

            switch (ApplicationData.Current.LocalSettings.Values["WebTabOpenMethod"]?.ToString() ?? "空白页")
            {
            case "空白页":
                CreateNewTab(new Uri("about:blank"));
                break;

            case "主页":
                string TabMain = ApplicationData.Current.LocalSettings.Values["WebTabMainPage"].ToString();
                if (Uri.TryCreate(TabMain, UriKind.Absolute, out Uri uri))
                {
                    CreateNewTab(uri);
                }
                else
                {
                    ContentDialog dialog = new ContentDialog
                    {
                        Content         = "导航失败,请检查网址或网络连接",
                        Title           = "提示",
                        CloseButtonText = "确定",
                        Background      = Application.Current.Resources["DialogAcrylicBrush"] as Brush
                    };
                    _ = dialog.ShowAsync();
                    CreateNewTab(new Uri("about:blank"));
                }
                break;

            case "特定页":
                string SpecifiedPage = ApplicationData.Current.LocalSettings.Values["WebTabSpecifiedPage"].ToString();
                if (Uri.TryCreate(SpecifiedPage, UriKind.Absolute, out Uri uri1))
                {
                    CreateNewTab(uri1);
                }
                else
                {
                    ContentDialog dialog = new ContentDialog
                    {
                        Content         = "导航失败,请检查网址或网络连接",
                        Title           = "提示",
                        CloseButtonText = "确定",
                        Background      = Application.Current.Resources["DialogAcrylicBrush"] as Brush
                    };
                    _ = dialog.ShowAsync();
                    CreateNewTab(new Uri("about:blank"));
                }
                break;
            }
        }
Example #24
0
        /// <summary>
        /// Validate model
        /// </summary>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            // check for file
            if (!this.FileExists)
            {
                string[] memberNames = new string[] { "FileName" };
                results.Add(new ValidationResult("The SQLite database [x=" + FullFileName + "] could not be found for [" + this.Name + "]", memberNames));
            }
            else
            {
                // check SQL file
                SQLiteReader = new SQLite();
                try
                {
                    SQLiteReader.OpenDatabase(FullFileName, false);
                }
                catch (Exception ex)
                {
                    throw new ApsimXException(this, "There was a problem opening the SQLite database [x=" + FullFileName + "] for [" + this.Name + "]\r\n" + ((ex.Message == "file is not a database")?"The file is not a supported SQLite database":ex.Message));
                }

                // check all columns present
                List <string> expectedColumns = new List <string>()
                {
                    RegionColumnName,
                    LandIdColumnName,
                    GrassBAColumnName,
                    LandConColumnName,
                    StkRateColumnName,
                    YearColumnName,
                    MonthColumnName,
                    GrowthColumnName
                };

                // add extra data columns if specified
                if (ErosionColumnName != null || ErosionColumnName != "")
                {
                    expectedColumns.Add(ErosionColumnName);
                }
                if (RunoffColumnName != null || RunoffColumnName != "")
                {
                    expectedColumns.Add(RunoffColumnName);
                }
                if (RainfallColumnName != null || RainfallColumnName != "")
                {
                    expectedColumns.Add(RainfallColumnName);
                }
                if (CoverColumnName != null || CoverColumnName != "")
                {
                    expectedColumns.Add(CoverColumnName);
                }
                if (TBAColumnName != null || TBAColumnName != "")
                {
                    expectedColumns.Add(TBAColumnName);
                }

                try
                {
                    DataTable     res       = SQLiteReader.ExecuteQuery("PRAGMA table_info(" + TableName + ")");
                    List <string> dBcolumns = new List <string>();
                    foreach (DataRow row in res.Rows)
                    {
                        dBcolumns.Add(row[1].ToString());
                    }

                    foreach (string col in expectedColumns)
                    {
                        if (!dBcolumns.Contains(col))
                        {
                            string[] memberNames = new string[] { "Missing SQLite database column" };
                            results.Add(new ValidationResult("Unable to find column [o=" + col + "] in pasture database [x=" + FullFileName + "] for [" + this.Name + "]", memberNames));
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new ApsimXException(this, "There was a problem opening the SQLite database [x=" + FullFileName + "] for [" + this.Name + "]\r\n" + ((ex.Message == "file is not a database") ? "The file is not a supported SQLite database" : ex.Message));
                }
            }
            return(results);
        }
Example #25
0
 private void UpdateDatabase(int versionFrom, int versionTo)
 {
     FileBackup.BackupWithTime(Info.GetDirectory() + "\\data.db");
     SQLite sqlite = new SQLite("data.db");
     switch (versionTo)
     {
         case 2:
             sqlite.AddColumns(LIST_FAMILIES_TABLE_NAME, new List<string> { FIELD_NAME_SHOW_FINISHED_ITEM, FIELD_NAME_SHOW_ABANDONED_ITEM, FIELD_NAME_SHOW_OVERDUE_ITEM, FIELD_NAME_SORT_TYPE }, new List<string> { "INTEGER", "INTEGER", "INTEGER", "INTEGER" });
             sqlite.Update(LIST_FAMILIES_TABLE_NAME, new List<string> { FIELD_NAME_SHOW_FINISHED_ITEM, FIELD_NAME_SHOW_ABANDONED_ITEM, FIELD_NAME_SHOW_OVERDUE_ITEM, FIELD_NAME_SORT_TYPE }, new List<string> { "1", "0", "1", "1" }, "list_family_id > '0'");
             break;
     }
 }
        public void Load()
        {
            Log.Info("Loading character templates...");

            using (var connection = SQLite.CreateConnection())
            {
                var temp = new Dictionary <uint, byte>();
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM characters";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var template = new CharacterTemplate();
                            var id       = reader.GetUInt32("id");
                            template.Race                   = (Race)reader.GetByte("char_race_id");
                            template.Gender                 = (Gender)reader.GetByte("char_gender_id");
                            template.ModelId                = reader.GetUInt32("model_id");
                            template.FactionId              = reader.GetUInt32("faction_id");
                            template.ZoneId                 = reader.GetUInt32("starting_zone_id");
                            template.ReturnDictrictId       = reader.GetUInt32("default_return_district_id");
                            template.ResurrectionDictrictId =
                                reader.GetUInt32("default_resurrection_district_id");
                            using (var command2 = connection.CreateCommand())
                            {
                                command2.CommandText = "SELECT * FROM item_body_parts WHERE model_id=@model_id";
                                command2.Prepare();
                                command2.Parameters.AddWithValue("model_id", template.ModelId);
                                using (var reader2 = new SQLiteWrapperReader(command2.ExecuteReader()))
                                {
                                    while (reader2.Read())
                                    {
                                        var itemId = reader2.GetUInt32("item_id", 0);
                                        var slot   = reader2.GetInt32("slot_type_id") - 23;
                                        template.Items[slot] = itemId;
                                    }
                                }
                            }

                            var templateId = (byte)(16 * (byte)template.Gender + (byte)template.Race);
                            _templates.Add(templateId, template);
                            temp.Add(id, templateId);
                        }
                    }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM character_buffs";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var characterId = reader.GetUInt32("character_id");
                            var buffId      = reader.GetUInt32("buff_id");
                            var template    = _templates[temp[characterId]];
                            template.Buffs.Add(buffId);
                        }
                    }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM character_supplies";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var ability = reader.GetByte("ability_id");
                            var item    = new AbilitySupplyItem
                            {
                                Id     = reader.GetUInt32("item_id"),
                                Amount = reader.GetInt32("amount"),
                                Grade  = reader.GetByte("grade_id")
                            };

                            if (!_abilityItems.ContainsKey(ability))
                            {
                                _abilityItems.Add(ability, new AbilityItems());
                            }
                            _abilityItems[ability].Supplies.Add(item);
                        }
                    }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM character_equip_packs";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var ability  = reader.GetByte("ability_id");
                            var template = new AbilityItems {
                                Ability = ability, Items = new EquipItemsTemplate()
                            };
                            var clothPack  = reader.GetUInt32("newbie_cloth_pack_id", 0);
                            var weaponPack = reader.GetUInt32("newbie_weapon_pack_id", 0);
                            if (clothPack > 0)
                            {
                                using (var command2 = connection.CreateCommand())
                                {
                                    command2.CommandText = "SELECT * FROM equip_pack_cloths WHERE id=@id";
                                    command2.Prepare();
                                    command2.Parameters.AddWithValue("id", clothPack);
                                    using (var reader2 = new SQLiteWrapperReader(command2.ExecuteReader()))
                                    {
                                        while (reader2.Read())
                                        {
                                            template.Items.Headgear         = reader2.GetUInt32("headgear_id");
                                            template.Items.HeadgearGrade    = reader2.GetByte("headgear_grade_id");
                                            template.Items.Necklace         = reader2.GetUInt32("necklace_id");
                                            template.Items.NecklaceGrade    = reader2.GetByte("necklace_grade_id");
                                            template.Items.Shirt            = reader2.GetUInt32("shirt_id");
                                            template.Items.ShirtGrade       = reader2.GetByte("shirt_grade_id");
                                            template.Items.Belt             = reader2.GetUInt32("belt_id");
                                            template.Items.BeltGrade        = reader2.GetByte("belt_grade_id");
                                            template.Items.Pants            = reader2.GetUInt32("pants_id");
                                            template.Items.PantsGrade       = reader2.GetByte("pants_grade_id");
                                            template.Items.Gloves           = reader2.GetUInt32("glove_id");
                                            template.Items.GlovesGrade      = reader2.GetByte("glove_grade_id");
                                            template.Items.Shoes            = reader2.GetUInt32("shoes_id");
                                            template.Items.ShoesGrade       = reader2.GetByte("shoes_grade_id");
                                            template.Items.Bracelet         = reader2.GetUInt32("bracelet_id");
                                            template.Items.BraceletGrade    = reader2.GetByte("bracelet_grade_id");
                                            template.Items.Back             = reader2.GetUInt32("back_id");
                                            template.Items.BackGrade        = reader2.GetByte("back_grade_id");
                                            template.Items.Cosplay          = reader2.GetUInt32("cosplay_id");
                                            template.Items.CosplayGrade     = reader2.GetByte("cosplay_grade_id");
                                            template.Items.Undershirts      = reader2.GetUInt32("undershirt_id");
                                            template.Items.UndershirtsGrade = reader2.GetByte("undershirt_grade_id");
                                            template.Items.Underpants       = reader2.GetUInt32("underpants_id");
                                            template.Items.UnderpantsGrade  = reader2.GetByte("underpants_grade_id");
                                        }
                                    }
                                }
                            }

                            if (weaponPack > 0)
                            {
                                using (var command2 = connection.CreateCommand())
                                {
                                    command2.CommandText = "SELECT * FROM equip_pack_weapons WHERE id=@id";
                                    command2.Prepare();
                                    command2.Parameters.AddWithValue("id", weaponPack);
                                    using (var reader2 = new SQLiteWrapperReader(command2.ExecuteReader()))
                                    {
                                        while (reader2.Read())
                                        {
                                            template.Items.Mainhand      = reader2.GetUInt32("mainhand_id");
                                            template.Items.MainhandGrade = reader2.GetByte("mainhand_grade_id");
                                            template.Items.Offhand       = reader2.GetUInt32("offhand_id");
                                            template.Items.OffhandGrade  = reader2.GetByte("offhand_grade_id");
                                            template.Items.Ranged        = reader2.GetUInt32("ranged_id");
                                            template.Items.RangedGrade   = reader2.GetByte("ranged_grade_id");
                                            template.Items.Musical       = reader2.GetUInt32("musical_id");
                                            template.Items.MusicalGrade  = reader2.GetByte("musical_grade_id");
                                        }
                                    }
                                }
                            }

                            _abilityItems.Add(template.Ability, template);
                        }
                    }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM bag_expands";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var expand = new Expand();
                            expand.IsBank     = reader.GetBoolean("is_bank", true);
                            expand.Step       = reader.GetInt32("step");
                            expand.Price      = reader.GetInt32("price");
                            expand.ItemId     = reader.GetUInt32("item_id", 0);
                            expand.ItemCount  = reader.GetInt32("item_count");
                            expand.CurrencyId = reader.GetInt32("currency_id");

                            if (!_expands.ContainsKey(expand.Step))
                            {
                                _expands.Add(expand.Step, new List <Expand> {
                                    expand
                                });
                            }
                            else
                            {
                                _expands[expand.Step].Add(expand);
                            }
                        }
                    }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT id, buff_id FROM appellations";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var template = new AppellationTemplate();
                            template.Id     = reader.GetUInt32("id");
                            template.BuffId = reader.GetUInt32("buff_id", 0);

                            _appellations.Add(template.Id, template);
                        }
                    }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM actability_groups";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var template = new ActabilityTemplate();
                            template.Id              = reader.GetUInt32("id");
                            template.Name            = reader.GetString("name");
                            template.UnitAttributeId = reader.GetInt32("unit_attr_id");
                            _actabilities.Add(template.Id, template);
                        }
                    }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM expert_limits ORDER BY up_limit ASC";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        var step = 0;
                        while (reader.Read())
                        {
                            var template = new ExpertLimit();
                            template.Id               = reader.GetUInt32("id");
                            template.UpLimit          = reader.GetInt32("up_limit");
                            template.ExpertLimitCount = reader.GetByte("expert_limit");
                            template.Advantage        = reader.GetInt32("advantage");
                            template.CastAdvantage    = reader.GetInt32("cast_adv");
                            template.UpCurrencyId     = reader.GetUInt32("up_currency_id", 0);
                            template.UpPrice          = reader.GetInt32("up_price");
                            template.DownCurrencyId   = reader.GetUInt32("down_currency_id", 0);
                            template.DownPrice        = reader.GetInt32("down_price");
                            _expertLimits.Add(step++, template);
                        }
                    }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM expand_expert_limits ORDER BY expand_count ASC";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        var step = 0;
                        while (reader.Read())
                        {
                            var template = new ExpandExpertLimit();
                            template.Id          = reader.GetUInt32("id");
                            template.ExpandCount = reader.GetByte("expand_count");
                            template.LifePoint   = reader.GetInt32("life_point");
                            template.ItemId      = reader.GetUInt32("item_id", 0);
                            template.ItemCount   = reader.GetInt32("item_count");
                            _expandExpertLimits.Add(step++, template);
                        }
                    }
                }
            }

            var content = FileManager.GetFileContents($"{FileManager.AppPath}Data/CharTemplates.json");

            if (string.IsNullOrWhiteSpace(content))
            {
                throw new IOException(
                          $"File {FileManager.AppPath + "Data/CharTemplates.json"} doesn't exists or is empty.");
            }

            if (JsonHelper.TryDeserializeObject(content, out List <CharacterTemplateConfig> charTemplates, out _))
            {
                foreach (var charTemplate in charTemplates)
                {
                    var point = new Point(charTemplate.Pos.X, charTemplate.Pos.Y, charTemplate.Pos.Z);
                    point.WorldId = charTemplate.Pos.WorldId;
                    point.ZoneId  = WorldManager
                                    .Instance
                                    .GetZoneId(charTemplate.Pos.WorldId, charTemplate.Pos.X, charTemplate.Pos.Y); // TODO ...

                    var template = _templates[(byte)(16 + charTemplate.Id)];
                    template.Position         = point;
                    template.NumInventorySlot = charTemplate.NumInventorySlot;
                    template.NumBankSlot      = charTemplate.NumBankSlot;

                    template                  = _templates[(byte)(32 + charTemplate.Id)];
                    template.Position         = point;
                    template.NumInventorySlot = charTemplate.NumInventorySlot;
                    template.NumBankSlot      = charTemplate.NumBankSlot;
                }
            }
            else
            {
                throw new Exception($"CharacterManager: Parse {FileManager.AppPath + "Data/CharTemplates.json"} file");
            }

            Log.Info("Loaded {0} character templates", _templates.Count);
        }
 private void btn_Refresh_Click(object sender, EventArgs e)
 {
     dgv_Guru.DataSource = null;
     dgv_Guru.DataSource = SQLite.Adapter("SELECT * FROM Guru", Program.ConnString).Tables[0];
 }
Example #28
0
        public override void aktualizuj(params string[] elementy)
        {
            if (wylaczEdycje == true)
            {
                throw new Exception("wlacz pierw edycje!");
            }
            if ((elementy.Length == 1) && (elementy[0] == "*"))
            {
                SQLite.Zapytanie = "UPDATE uczen_na_lekcji SET ocena = '" + ocena + "' WHERE uczen_na_lekcjiID= " + uczen_na_lekcjiID + ";"; SQLite.wykonajZapytanie(ERodzajZapytania.wyslij);
                SQLite.Zapytanie = "UPDATE uczen_na_lekcji SET obecnosc = '" + obecnosc + "' WHERE uczen_na_lekcjiID= " + uczen_na_lekcjiID + ";"; SQLite.wykonajZapytanie(ERodzajZapytania.wyslij);
                return;
            }
            foreach (string element in elementy)
            {
                switch (element)
                {
                case "ocena": SQLite.Zapytanie = "UPDATE uczen_na_lekcji SET ocena = '" + ocena + "' WHERE uczen_na_lekcjiID= " + uczen_na_lekcjiID + ";"; SQLite.wykonajZapytanie(ERodzajZapytania.wyslij); break;

                case "obecnosc": SQLite.Zapytanie = "UPDATE uczen_na_lekcji SET obecnosc = '" + obecnosc + "' WHERE uczen_na_lekcjiID= " + uczen_na_lekcjiID + ";"; SQLite.wykonajZapytanie(ERodzajZapytania.wyslij); break;

                default: throw new Exception("niepoprawny parametr do aktualizacji danych");
                }
            }
        }
Example #29
0
		public static void SetDatabaseConnection (SQLite.Net.SQLiteConnection connection)
		{
			conn = connection;
			database = new TodoItemDatabase (conn);
		}
Example #30
0
        public override void Use(Player p, string message)
        {
            string[] command = message.Trim().Split(' ');
            string   par0    = String.Empty;
            string   par1    = String.Empty;
            string   par2    = String.Empty;
            string   par3    = String.Empty;
            string   par4    = String.Empty;
            string   par5    = String.Empty;
            string   par6    = String.Empty;
            string   par7    = String.Empty;
            string   par8    = String.Empty;

            try
            {
                par0 = command[0].ToLower();
                par1 = command[1].ToLower();
                par2 = command[2];
                par3 = command[3];
                par4 = command[4];
                par5 = command[5];
                par6 = command[6];
                par7 = command[7];
                par8 = command[8];
            }
            catch { }

            switch (par0)
            {
            case "setup":
                if ((int)p.group.Permission >= CommandOtherPerms.GetPerm(this))
                {
                    switch (par1)
                    {
                    case "maps":
                    case "levels":
                    case "map":
                    case "level":
                        Economy.Settings.Level lvl = Economy.FindLevel(par3);
                        switch (par2)
                        {
                        case "new":
                        case "create":
                        case "add":
                            if (Economy.FindLevel(par3) != null)
                            {
                                Player.SendMessage(p, "That preset level already exists"); break;
                            }
                            else
                            {
                                Economy.Settings.Level level = new Economy.Settings.Level();
                                level.name = par3;
                                if (isGood(par4))
                                {
                                    level.x = par4;
                                }
                                if (isGood(par5))
                                {
                                    level.y = par5;
                                }
                                if (isGood(par6))
                                {
                                    level.z = par6;
                                }
                                else
                                {
                                    Player.SendMessage(p, "A Dimension was wrong, it must a power of 2"); break;
                                }
                                switch (par7.ToLower())
                                {
                                case "flat":
                                case "pixel":
                                case "island":
                                case "mountains":
                                case "ocean":
                                case "forest":
                                case "desert":
                                case "space":
                                    level.type = par7.ToLower();
                                    break;

                                default:
                                    Player.SendMessage(p, "Valid types: island, mountains, forest, ocean, flat, pixel, desert, space");
                                    break;
                                }
                                level.price = int.Parse(par8);
                                Economy.Settings.LevelsList.Add(level);
                                Player.SendMessage(p, "Added map to presets");
                                break;
                            }

                        case "delete":
                        case "remove":
                            if (lvl == null)
                            {
                                Player.SendMessage(p, "That preset level doesn't exist"); break;
                            }
                            else
                            {
                                Economy.Settings.LevelsList.Remove(lvl); Player.SendMessage(p, "Removed preset"); break;
                            }

                        case "edit":
                        case "change":
                            if (lvl == null)
                            {
                                Player.SendMessage(p, "That preset level doesn't exist"); break;
                            }
                            else
                            {
                                switch (par4)
                                {
                                case "name":
                                case "title":
                                    Economy.Settings.LevelsList.Remove(lvl);
                                    lvl.name = par5;
                                    Economy.Settings.LevelsList.Add(lvl);
                                    Player.SendMessage(p, "Changed preset name");
                                    break;

                                case "x":
                                    if (isGood(par5))
                                    {
                                        Economy.Settings.LevelsList.Remove(lvl);
                                        lvl.x = par5;
                                        Economy.Settings.LevelsList.Add(lvl);
                                        Player.SendMessage(p, "Changed preset x size");
                                    }
                                    else
                                    {
                                        Player.SendMessage(p, "Dimension was wrong, it must a power of 2"); break;
                                    }
                                    break;

                                case "y":
                                    if (isGood(par5))
                                    {
                                        Economy.Settings.LevelsList.Remove(lvl);
                                        lvl.y = par5;
                                        Economy.Settings.LevelsList.Add(lvl);
                                        Player.SendMessage(p, "Changed preset y size");
                                    }
                                    else
                                    {
                                        Player.SendMessage(p, "Dimension was wrong, it must a power of 2"); break;
                                    }
                                    break;

                                case "z":
                                    if (isGood(par5))
                                    {
                                        Economy.Settings.LevelsList.Remove(lvl);
                                        lvl.z = par5;
                                        Economy.Settings.LevelsList.Add(lvl);
                                        Player.SendMessage(p, "Changed preset z size");
                                    }
                                    else
                                    {
                                        Player.SendMessage(p, "Dimension was wrong, it must a power of 2"); break;
                                    }
                                    break;

                                case "type":
                                    Economy.Settings.LevelsList.Remove(lvl);
                                    switch (par5.ToLower())
                                    {
                                    case "flat":
                                    case "pixel":
                                    case "island":
                                    case "mountains":
                                    case "ocean":
                                    case "forest":
                                    case "desert":
                                    case "space":
                                        lvl.type = par5.ToLower();
                                        break;

                                    default:
                                        Player.SendMessage(p, "Valid types: island, mountains, forest, ocean, flat, pixel, desert, space");
                                        Economy.Settings.LevelsList.Add(lvl);
                                        break;
                                    }
                                    Economy.Settings.LevelsList.Add(lvl);
                                    Player.SendMessage(p, "Changed preset type");
                                    break;

                                case "dimensions":
                                case "sizes":
                                case "dimension":
                                case "size":
                                    Economy.Settings.LevelsList.Remove(lvl);
                                    if (isGood(par4))
                                    {
                                        lvl.x = par4;
                                    }
                                    if (isGood(par5))
                                    {
                                        lvl.y = par5;
                                    }
                                    if (isGood(par6))
                                    {
                                        lvl.z = par6;
                                    }
                                    else
                                    {
                                        Player.SendMessage(p, "A Dimension was wrong, it must a power of 2"); Economy.Settings.LevelsList.Add(lvl); break;
                                    }
                                    Economy.Settings.LevelsList.Add(lvl);
                                    Player.SendMessage(p, "Changed preset name");
                                    break;

                                case "price":
                                    Economy.Settings.LevelsList.Remove(lvl);
                                    lvl.price = int.Parse(par5);
                                    Economy.Settings.LevelsList.Add(lvl);
                                    Player.SendMessage(p, "Changed preset price");
                                    break;

                                default:
                                    Player.SendMessage(p, "That wasn't a valid command addition");
                                    break;
                                }
                            }
                            break;

                        case "enable":
                            if (Economy.Settings.Levels == true)
                            {
                                Player.SendMessage(p, "Maps are already enabled for the economy system"); break;
                            }
                            else
                            {
                                Economy.Settings.Levels = true; Player.SendMessage(p, "Maps are now enabled for the economy system"); break;
                            }

                        case "disable":
                            if (Economy.Settings.Levels == false)
                            {
                                Player.SendMessage(p, "Maps are already disabled for the economy system"); break;
                            }
                            else
                            {
                                Economy.Settings.Levels = false; Player.SendMessage(p, "Maps are now disabled for the economy system"); break;
                            }

                        default:
                            Player.SendMessage(p, "That wasn't a valid command addition");
                            break;
                        }
                        break;

                    case "titles":
                    case "title":
                        switch (par2)
                        {
                        case "enable":
                            if (Economy.Settings.Titles == true)
                            {
                                Player.SendMessage(p, "Titles are already enabled for the economy system"); break;
                            }
                            else
                            {
                                Economy.Settings.Titles = true; Player.SendMessage(p, "Titles are now enabled for the economy system"); break;
                            }

                        case "disable":
                            if (Economy.Settings.Titles == false)
                            {
                                Player.SendMessage(p, "Titles are already disabled for the economy system"); break;
                            }
                            else
                            {
                                Economy.Settings.Titles = false; Player.SendMessage(p, "Titles are now disabled for the economy system"); break;
                            }

                        case "price":
                            Economy.Settings.TitlePrice = int.Parse(par3);
                            Player.SendMessage(p, "Changed title price");
                            break;

                        default:
                            Player.SendMessage(p, "That wasn't a valid command addition");
                            break;
                        }
                        break;

                    case "colors":
                    case "colours":
                    case "color":
                    case "colour":
                        switch (par2)
                        {
                        case "enable":
                            if (Economy.Settings.Colors == true)
                            {
                                Player.SendMessage(p, "Colors are already enabled for the economy system"); break;
                            }
                            else
                            {
                                Economy.Settings.Colors = true; Player.SendMessage(p, "Colors are now enabled for the economy system"); break;
                            }

                        case "disable":
                            if (Economy.Settings.Colors == false)
                            {
                                Player.SendMessage(p, "Colors are already disabled for the economy system"); break;
                            }
                            else
                            {
                                Economy.Settings.Colors = false; Player.SendMessage(p, "Colors are now disabled for the economy system"); break;
                            }

                        case "price":
                            Economy.Settings.ColorPrice = int.Parse(par3);
                            Player.SendMessage(p, "Changed color price");
                            break;

                        default:
                            Player.SendMessage(p, "That wasn't a valid command addition");
                            break;
                        }
                        break;

                    case "ranks":
                    case "rank":
                        switch (par2)
                        {
                        case "enable":
                            if (Economy.Settings.Ranks == true)
                            {
                                Player.SendMessage(p, "Ranks are already enabled for the economy system"); break;
                            }
                            else
                            {
                                Economy.Settings.Ranks = true; Player.SendMessage(p, "Ranks are now enabled for the economy system"); break;
                            }

                        case "disable":
                            if (Economy.Settings.Ranks == false)
                            {
                                Player.SendMessage(p, "Ranks are already disabled for the economy system"); break;
                            }
                            else
                            {
                                Economy.Settings.Ranks = false; Player.SendMessage(p, "Ranks are now disabled for the economy system"); break;
                            }

                        case "price":
                            Economy.Settings.Rank rnk = Economy.FindRank(par3);
                            if (rnk == null)
                            {
                                Player.SendMessage(p, "That isn't a rank or it's past the max rank"); break;
                            }
                            else
                            {
                                rnk.price = int.Parse(par4);
                                Player.SendMessage(p, "Changed rank price for " + rnk.group.name);
                                break;
                            }

                        case "maxrank":
                        case "max":
                        case "maximum":
                        case "maximumrank":
                            Group grp = Group.Find(par3);
                            if (grp == null)
                            {
                                Player.SendMessage(p, "That isn't a rank!!"); break;
                            }
                            else
                            {
                                Economy.Settings.MaxRank = grp.Permission; Player.SendMessage(p, "Set max rank");
                                int lasttrueprice = 0;
                                foreach (Group group in Group.GroupList)
                                {
                                    if (group.Permission > grp.Permission)
                                    {
                                        break;
                                    }
                                    if (!(group.Permission <= Group.Find(Server.defaultRank).Permission))
                                    {
                                        Economy.Settings.Rank rank = new Economy.Settings.Rank();
                                        rank = Economy.FindRank(group.name);
                                        if (rank == null)
                                        {
                                            rank       = new Economy.Settings.Rank();
                                            rank.group = group;
                                            if (lasttrueprice == 0)
                                            {
                                                rank.price = 1000;
                                            }
                                            else
                                            {
                                                rank.price = lasttrueprice + 250;
                                            }
                                            Economy.Settings.RanksList.Add(rank);
                                        }
                                        else
                                        {
                                            lasttrueprice = rank.price;
                                        }
                                    }
                                }
                                break;
                            }

                        default:
                            Player.SendMessage(p, "That wasn't a valid command addition");
                            break;
                        }
                        break;

                    case "enable":
                        if (Economy.Settings.Enabled == true)
                        {
                            Player.SendMessage(p, "The economy system is already enabled"); return;
                        }
                        else
                        {
                            Economy.Settings.Enabled = true; Player.SendMessage(p, "The economy system is now enabled"); return;
                        }

                    case "disable":
                        if (Economy.Settings.Enabled == false)
                        {
                            Player.SendMessage(p, "The economy system is already disabled"); return;
                        }
                        else
                        {
                            Economy.Settings.Enabled = false; Player.SendMessage(p, "The economy system is now disabled"); return;
                        }

                    default:
                        Player.SendMessage(p, "That wasn't a valid command addition");
                        return;
                    }
                    Economy.Save();
                    return;
                }
                else
                {
                    Player.SendMessage(p, "You aren't a high enough rank for that"); return;
                }



            case "buy":
                switch (par1)
                {
                case "map":
                case "level":
                case "maps":
                case "levels":
                    Economy.Settings.Level lvl = Economy.FindLevel(par2);
                    if (lvl == null)
                    {
                        Player.SendMessage(p, "That isn't a level preset"); return;
                    }
                    else
                    {
                        if (p.EnoughMoney(lvl.price) == false)
                        {
                            Player.SendMessage(p, "You don't have enough " + Server.moneys + " to buy that map"); return;
                        }
                        else
                        {
                            if (par3 == null)
                            {
                                Player.SendMessage(p, "You didn't specify a name for your level"); return;
                            }
                            else
                            {
                                int old = p.money;
                                try
                                {
                                    Command.all.Find("newlvl").Use(null, p.name + "_" + par3 + " " + lvl.x + " " + lvl.y + " " + lvl.z + " " + lvl.type);
                                    Player.SendMessage(p, "Created level '" + p.name + "_" + par3 + "'");
                                    p.money = p.money - lvl.price;
                                    Player.SendMessage(p, "Your balance is now " + p.money.ToString() + " " + Server.moneys);
                                    Command.all.Find("load").Use(null, p.name + "_" + par3);
                                    Thread.Sleep(250);
                                    Level level = Level.Find(p.name + "_" + par3);
                                    if (level.permissionbuild > p.group.Permission)
                                    {
                                        level.permissionbuild = p.group.Permission;
                                    }
                                    if (level.permissionvisit > p.group.Permission)
                                    {
                                        level.permissionvisit = p.group.Permission;
                                    }
                                    Command.all.Find("goto").Use(p, p.name + "_" + par3);
                                    while (p.Loading)
                                    {
                                        Thread.Sleep(250);
                                    }
                                    try
                                    {
                                        //DB
                                        if (Server.useMySQL)
                                        {
                                            MySQL.executeQuery("INSERT INTO `Zone" + level.name + "` (SmallX, SmallY, SmallZ, BigX, BigY, BigZ, Owner) VALUES (0,0,0," + (level.width - 1) + "," + (level.depth - 1) + "," + (level.height - 1) + ",'" + p.name + "')");
                                        }
                                        else
                                        {
                                            SQLite.executeQuery("INSERT INTO `Zone" + level.name + "` (SmallX, SmallY, SmallZ, BigX, BigY, BigZ, Owner) VALUES (0,0,0," + (level.width - 1) + "," + (level.depth - 1) + "," + (level.height - 1) + ",'" + p.name + "')");                                                                                                                                                                                                                                                            //CHECK!!!!
                                        }
                                        //DB
                                        Player.SendMessage(p, "Zoning Succesful");
                                        return;
                                    }
                                    catch { Player.SendMessage(p, "Zoning Failed"); return; }
                                }
                                catch { Player.SendMessage(p, "Something went wrong, Money restored"); if (old != p.money)
                                        {
                                            p.money = old;
                                        }
                                        return; }
                            }
                        }
                    }

                case "colors":
                case "color":
                case "colours":
                case "colour":
                    if (!par2.StartsWith("&") || !par2.StartsWith("%"))
                    {
                        switch (par2)
                        {
                        case "black":
                            par2 = "&0";
                            break;

                        case "navy":
                            par2 = "&1";
                            break;

                        case "green":
                            par2 = "&2";
                            break;

                        case "teal":
                            par2 = "&3";
                            break;

                        case "maroon":
                            par2 = "&4";
                            break;

                        case "purple":
                            par2 = "&5";
                            break;

                        case "gold":
                            par2 = "&6";
                            break;

                        case "silver":
                            par2 = "&7";
                            break;

                        case "gray":
                            par2 = "&8";
                            break;

                        case "blue":
                            par2 = "&9";
                            break;

                        case "lime":
                            par2 = "&a";
                            break;

                        case "aqua":
                            par2 = "&b";
                            break;

                        case "red":
                            par2 = "&c";
                            break;

                        case "pink":
                            par2 = "&d";
                            break;

                        case "yellow":
                            par2 = "&e";
                            break;

                        case "white":
                            par2 = "&f";
                            break;

                        default:
                            Player.SendMessage(p, "That wasn't a color");
                            return;
                        }
                    }
                    if (par2 == p.color)
                    {
                        Player.SendMessage(p, "You already have that color"); return;
                    }
                    if (p.EnoughMoney(Economy.Settings.ColorPrice) == false)
                    {
                        Player.SendMessage(p, "You don't have enough " + Server.moneys + " to buy a color"); return;
                    }
                    else
                    {
                        Command.all.Find("color").Use(null, p.name + " " + c.Name(par2)); p.money = p.money - Economy.Settings.ColorPrice; Player.SendMessage(p, "Changed color"); Player.SendMessage(p, "Your balance is now " + p.money.ToString() + " " + Server.moneys); return;
                    }

                case "titles":
                case "title":
                    if (par2 == p.title)
                    {
                        Player.SendMessage(p, "You already have that title"); return;
                    }
                    if (p.EnoughMoney(Economy.Settings.TitlePrice) == false)
                    {
                        Player.SendMessage(p, "You don't have enough " + Server.moneys + " to buy a title"); return;
                    }
                    if (par2.Length > 17)
                    {
                        Player.SendMessage(p, "Title cannot be longer than 17 characters."); return;
                    }
                    Command.all.Find("title").Use(null, p.name + " " + par2); p.money = p.money - Economy.Settings.TitlePrice; Player.SendMessage(p, "Changed title"); Player.SendMessage(p, "Your balance is now " + p.money + " " + Server.moneys); return;

                case "ranks":
                case "rank":
                    if (p.group.Permission == Economy.Settings.MaxRank || p.group.Permission >= Economy.Settings.MaxRank)
                    {
                        Player.SendMessage(p, "You are past the max buyable rank"); return;
                    }
                    if (p.EnoughMoney(Economy.NextRank(p).price) == false)
                    {
                        Player.SendMessage(p, "You don't have enough " + Server.moneys + " to buy the next rank"); return;
                    }
                    else
                    {
                        Command.all.Find("promote").Use(null, p.name); p.money = p.money - Economy.FindRank(p.group.name).price; Player.SendMessage(p, "You bought the rank " + p.group.name); Player.SendMessage(p, "Your balance is now " + p.money.ToString() + " " + Server.moneys); return;
                    }

                default:
                    Player.SendMessage(p, "That wasn't a valid command addition");
                    return;
                }

            case "stats":
            case "balance":
            case "amount":
                if (par1 != null)
                {
                    Player who = Player.Find(par1);
                    if (who == null)
                    {
                        Player.SendMessage(p, "That player doesn't exist"); return;
                    }
                    else
                    {
                        Player.SendMessage(p, "Stats for: " + who.color + who.name);
                        Player.SendMessage(p, "============================================================");
                        Player.SendMessage(p, Server.moneys + ": &b$" + who.money);
                        return;
                    }
                }
                else
                {
                    Player.SendMessage(p, "Stats for: " + p.color + p.name);
                    Player.SendMessage(p, "============================================================");
                    Player.SendMessage(p, Server.moneys + ": &b$" + p.money);
                    return;
                }

            case "info":
            case "about":
                if (Economy.Settings.Enabled == true)
                {
                    switch (par1)
                    {
                    case "map":
                    case "level":
                    case "maps":
                    case "levels":
                        if (Economy.Settings.Levels == false)
                        {
                            Player.SendMessage(p, "Maps are not enabled for the economy system"); return;
                        }
                        Player.SendMessage(p, "Maps avaliable:");
                        foreach (Economy.Settings.Level lvl in Economy.Settings.LevelsList)
                        {
                            Player.SendMessage(p, lvl.name + " (" + lvl.x + "," + lvl.y + "," + lvl.z + ") " + lvl.type + ":" + lvl.price);
                        }
                        return;

                    case "title":
                    case "titles":
                        if (Economy.Settings.Titles == false)
                        {
                            Player.SendMessage(p, "Titles are not enabled for the economy system"); return;
                        }
                        Player.SendMessage(p, "Titles cost " + Economy.Settings.TitlePrice.ToString() + " each");
                        return;

                    case "colors":
                    case "color":
                    case "colours":
                    case "colour":
                        if (Economy.Settings.Colors == false)
                        {
                            Player.SendMessage(p, "Colors are not enabled for the economy system"); return;
                        }
                        Player.SendMessage(p, "Colors cost " + Economy.Settings.ColorPrice.ToString() + " each");
                        return;

                    case "ranks":
                    case "rank":
                        if (Economy.Settings.Ranks == false)
                        {
                            Player.SendMessage(p, "Ranks are not enabled for the economy system"); return;
                        }
                        Player.SendMessage(p, "The maximum buyable rank is " + Economy.Settings.MaxRank.ToString());
                        Player.SendMessage(p, "Ranks cost:");
                        foreach (Economy.Settings.Rank rnk in Economy.Settings.RanksList)
                        {
                            Player.SendMessage(p, rnk.group.name + ": " + rnk.price);
                        }
                        return;

                    default:
                        Player.SendMessage(p, "That wasn't a valid command addition");
                        return;
                    }
                }
                else
                {
                    Player.SendMessage(p, "The economy system is currently disabled"); return;
                }

            case "help":
                switch (par1)
                {
                case "":
                    Help(p);
                    return;

                case "buy":
                    Player.SendMessage(p, "Use '/eco buy' to buy things");
                    Player.SendMessage(p, "To buy a map do '/eco buy map [presetname] [custommapname]'");
                    Player.SendMessage(p, "You can view presets with /eco info maps, [custommapname] is the name for your map");
                    Player.SendMessage(p, "To buy a rank just type '/eco buy rank'");
                    Player.SendMessage(p, "To buy a color or title just type '/eco buy [color/title] <color/title>'");
                    return;

                case "stats":
                case "balance":
                case "amount":
                    Player.SendMessage(p, "To find out your own balance of " + Server.moneys + " just do '/eco stats'");
                    Player.SendMessage(p, "To find out someone else's balance of " + Server.moneys + " just do '/eco stats [playername]'");
                    return;

                case "info":
                case "about":
                    Player.SendMessage(p, "To find out info about buying anything just do '/eco info [map/title/color/rank]'");
                    return;

                case "setup":
                    if ((int)p.group.Permission >= CommandOtherPerms.GetPerm(this))
                    {
                        Player.SendMessage(p, "Use '/eco setup' to setup the economy system");
                        Player.SendMessage(p, "Use '/eco setup [title/color] [price]' to setup the prices");
                        Player.SendMessage(p, "Use '/eco setup [title/color/rank/map] [enable/disable]' to enable/disable that feature");
                        Player.SendMessage(p, "Use '/eco setup map new [name] [x] [y] [z] [type] [price]' to setup a map preset");
                        Player.SendMessage(p, "Use '/eco setup map delete [name]' to delete a map");
                        Player.SendMessage(p, "Use '/eco setup map edit [name] [name/x/y/z/type/price] [value]' to edit a map preset");
                        Player.SendMessage(p, "Use '/eco setup rank price [rank] [price]' to set the price for that rank");
                        Player.SendMessage(p, "Use '/eco setup rank maxrank [rank]' to set the max buyable rank");
                        return;
                    }
                    else
                    {
                        Player.SendMessage(p, "You aren't a high enough rank for that"); return;
                    }

                default:
                    Player.SendMessage(p, "That wasn't a valid command addition, Sending you to help");
                    Help(p);
                    return;
                }

            default:
                Player.SendMessage(p, "That wasn't a valid command addition, Sending you to help");
                Help(p);
                return;
            }
        }
Example #31
0
        public void Load()
        {
            _openPortalInlandReagents  = new Dictionary <uint, OpenPortalReagents>();
            _openPortalOutlandReagents = new Dictionary <uint, OpenPortalReagents>();
            _allDistrictPortals        = new Dictionary <uint, Portal>();
            _allDistrictPortalsKey     = new Dictionary <uint, uint>();
            _log.Info("Loading Portals ...");

            #region FileManager

            var filePath = $"{FileManager.AppPath}Data/Portal/SubZonePortalCoords.json";
            var contents = FileManager.GetFileContents(filePath);

            if (string.IsNullOrWhiteSpace(contents))
            {
                throw new IOException($"File {filePath} doesn't exists or is empty.");
            }

            if (JsonHelper.TryDeserializeObject(contents, out List <Portal> portals, out _))
            {
                foreach (var portal in portals)
                {
                    _allDistrictPortals.Add(portal.SubZoneId, portal);
                    _allDistrictPortalsKey.Add(portal.Id, portal.SubZoneId);
                }
            }
            else
            {
                throw new Exception($"PortalManager: Parse {filePath} file");
            }

            _log.Info("Loaded {0} District Portals", _allDistrictPortals.Count);

            #endregion

            #region Sqlite

            using (var connection = SQLite.CreateConnection())
            {
                // NOTE - priority -> to remove item from inventory first
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM open_portal_inland_reagents";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var template = new OpenPortalReagents
                            {
                                Id = reader.GetUInt32("id"),
                                OpenPortalEffectId = reader.GetUInt32("open_portal_effect_id"),
                                ItemId             = reader.GetUInt32("item_id"),
                                Amount             = reader.GetInt32("amount"),
                                Priority           = reader.GetInt32("priority")
                            };
                            _openPortalInlandReagents.Add(template.Id, template);
                        }
                    }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM open_portal_outland_reagents";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var template = new OpenPortalReagents
                            {
                                Id = reader.GetUInt32("id"),
                                OpenPortalEffectId = reader.GetUInt32("open_portal_effect_id"),
                                ItemId             = reader.GetUInt32("item_id"),
                                Amount             = reader.GetInt32("amount"),
                                Priority           = reader.GetInt32("priority")
                            };
                            _openPortalOutlandReagents.Add(template.Id, template);
                        }
                    }
                }
            }
            _log.Info("Loaded Portal Info");

            #endregion
        }
Example #32
0
        /// <summary>
        /// Searches the DataTable created from the Forage File using the specified parameters.
        /// <returns></returns>
        /// </summary>
        /// <param name="soilId">Name of soil or run name in database</param>
        /// <param name="cropName">Name of crop in database</param>
        /// <param name="startDate">Start date of the simulation</param>
        /// <param name="endDate">End date of the simulation</param>
        /// <returns>A struct called CropDataType containing the crop data for this month.
        /// This struct can be null.
        /// </returns>
        public List <CropDataType> GetCropDataForEntireRun(string soilId, string cropName,
                                                           DateTime startDate, DateTime endDate)
        {
            // check SQL file
            SQLite sQLiteReader = new SQLite();

            try
            {
                sQLiteReader.OpenDatabase(FullFileName, true);
            }
            catch (Exception ex)
            {
                ErrorMessage = "@error:There was a problem opening the SQLite database [o=" + FullFileName + "for [x=" + this.Name + "]\n" + ex.Message;
            }

            // check if Npct column exists in database
            nitrogenColumnExists = sQLiteReader.GetColumnNames(TableName).Contains(PercentNitrogenColumnName);

            // define SQL filter to load data
            string sqlQuery = "SELECT " + YearColumnName + "," + MonthColumnName + "," + CropNameColumnName + "," + SoilTypeColumnName + "," + AmountColumnName + "" + (nitrogenColumnExists ? "," + PercentNitrogenColumnName : "") + " FROM " + TableName
                              + " WHERE " + SoilTypeColumnName + " = '" + soilId + "'"
                              + " AND " + CropNameColumnName + " = '" + cropName + "'";

            if (startDate.Year == endDate.Year)
            {
                sqlQuery += " AND (( " + YearColumnName + " = " + startDate.Year + " AND " + MonthColumnName + " >= " + startDate.Month + " AND " + MonthColumnName + " < " + endDate.Month + ")"
                            + ")";
            }
            else
            {
                sqlQuery += " AND (( " + YearColumnName + " = " + startDate.Year + " AND " + MonthColumnName + " >= " + startDate.Month + ")"
                            + " OR  ( " + YearColumnName + " > " + startDate.Year + " AND " + YearColumnName + " < " + endDate.Year + ")"
                            + " OR  ( " + YearColumnName + " = " + endDate.Year + " AND " + MonthColumnName + " < " + endDate.Month + ")"
                            + ")";
            }

            DataTable results;

            try
            {
                results = sQLiteReader.ExecuteQuery(sqlQuery);
            }
            catch (Exception ex)
            {
                string errorMsg = "@error:There was a problem accessing the SQLite database [o=" + FullFileName + "] for [x=" + this.Name + "]\n" + ex.Message;
                throw new ApsimXException(this, errorMsg);
            }

            if (sQLiteReader.IsOpen)
            {
                sQLiteReader.CloseDatabase();
            }

            List <CropDataType> cropDetails = new List <CropDataType>();

            if (results.Rows.Count > 0)
            {
                results.DefaultView.Sort = YearColumnName + "," + MonthColumnName;

                // convert to list<CropDataType>
                foreach (DataRowView row in results.DefaultView)
                {
                    cropDetails.Add(DataRow2CropData(row.Row));
                }
            }

            return(cropDetails);
        }
Example #33
0
        public bool Save(SQLite.DataStore store, System.Data.SQLite.SQLiteConnection connection)
        {
            if (this.Saved == true)
            {
                return false;
            }

            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }

            Hand existing = store.GetHand(this.SiteId, this.HandNumber);
            if (existing == null)
            {
                this.Id = store.InsertHand(this.SiteId, this.HandNumber, connection);

                foreach (HandPlayer player in this.HandPlayers)
                {
                    player.HandId = this.Id;
                    if (player.Saved == false)
                    {
                        player.Save(store, connection);
                    }
                }
            }
            else
            {
                Logger.Error("Hand {0} already imported", this.HandNumber);
            }

            this.Saved = true;
            return true;
        }
 //public constructor
 public PlayerPref()
 {
     db = new SQLite();
 }
Example #35
0
		static void Main(string[] args)
		{
			////MySQL
			{
				Console.WriteLine("MySQL");

				//Connect to MySQL Database
				string mySQLserver="seeseekey.net";
				int mySQLPort=3306;
				string mySQLusername="******";
				string mySQLpassword="******";
				string mySQLDbName="daten";

				MySQL mySQL=new MySQL(mySQLserver, mySQLPort, mySQLDbName, mySQLusername, mySQLpassword);
				mySQL.Connect();

				//get table names
				List<string> tables=mySQL.GetTables();

				foreach(string table in tables)
				{
					Console.WriteLine(table);
				}
			}

			////PostgreSQL
			{
				Console.WriteLine("PostgreSQL");

				//Connect to PostgreSQL Database
				string postgreSQLserver="seeseekey.net";
				int postgreSQLPort=5432;
				string postgreSQLusername="******";
				string postgreSQLpassword="******";
				string postgreSQLDbName="test";

				PostgreSQL postgresql=new PostgreSQL(postgreSQLserver, postgreSQLPort, postgreSQLDbName, postgreSQLusername, postgreSQLpassword);
				postgresql.Connect();

				//get table names
				List<string> tables=postgresql.GetTables();

				foreach(string table in tables)
				{
					Console.WriteLine(table);
				}
			}

			//SQLite
			{
				Console.WriteLine("SQLite");

				//Connect/Open to SQlite Database
				string sqliteDB=@"D:\test.db";
				SQLite sqlite=new SQLite(sqliteDB);

				//get table names
				List<string> tables=sqlite.GetTables();

				foreach(string table in tables)
				{
					Console.WriteLine(table);
				}
			}

			//Ende
			Console.ReadLine();
		}
 private void Siswa_Shown(object sender, EventArgs e)
 {
     dgv_Siswa.DataSource = null;
     dgv_Siswa.DataSource = SQLite.Adapter("SELECT * FROM Siswa", Program.ConnString).Tables[0];
 }
Example #37
0
 public void IncrementStat(string stat, User u)
 => SQLite.GetConnection().Query("UPDATE userstats SET " + stat + " = " + stat + " + 1, skillpoints = skillpoints - 1 WHERE userstats.UID = @uid AND userstats.LID = @lid AND userstats.skillpoints > 0", new { uid = u.ID, lid = u.LID }).FirstOrDefault();
Example #38
0
        public void Load()
        {
            _zoneIdToKey     = new Dictionary <uint, uint>();
            _zones           = new Dictionary <uint, Zone>();
            _groups          = new Dictionary <uint, ZoneGroup>();
            _conflicts       = new Dictionary <ushort, ZoneConflict>();
            _groupBannedTags = new Dictionary <uint, ZoneGroupBannedTag>();
            _climateElem     = new Dictionary <uint, ZoneClimateElem>();
            _log.Info("Loading ZoneManager...");
            using (var connection = SQLite.CreateConnection())
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM zones";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var template = new Zone();
                            template.Id            = reader.GetUInt32("id");
                            template.Name          = (string)reader.GetValue("name");
                            template.ZoneKey       = reader.GetUInt32("zone_key");
                            template.GroupId       = reader.GetUInt32("group_id", 0);
                            template.Closed        = reader.GetBoolean("closed", true);
                            template.FactionId     = reader.GetUInt32("faction_id", 0);
                            template.ZoneClimateId = reader.GetUInt32("zone_climate_id", 0);
                            _zoneIdToKey.Add(template.Id, template.ZoneKey);
                            _zones.Add(template.ZoneKey, template);
                        }
                    }
                }

                _log.Info("Loaded {0} zones", _zones.Count);

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM zone_groups";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var template = new ZoneGroup();
                            template.Id                    = reader.GetUInt32("id");
                            template.Name                  = (string)reader.GetValue("name");
                            template.X                     = reader.GetFloat("x");
                            template.Y                     = reader.GetFloat("y");
                            template.Width                 = reader.GetFloat("w");
                            template.Hight                 = reader.GetFloat("h");
                            template.TargetId              = reader.GetUInt32("target_id");
                            template.FactionChatRegionId   = reader.GetUInt32("faction_chat_region_id");
                            template.PirateDesperado       = reader.GetBoolean("pirate_desperado", true);
                            template.FishingSeaLootPackId  = reader.GetUInt32("fishing_sea_loot_pack_id", 0);
                            template.FishingLandLootPackId = reader.GetUInt32("fishing_land_loot_pack_id", 0);
                            // TODO 1.2 // template.BuffId = reader.GetUInt32("buff_id", 0);
                            _groups.Add(template.Id, template);
                        }
                    }
                }

                _log.Info("Loaded {0} groups", _groups.Count);

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM conflict_zones";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var zoneGroupId = reader.GetUInt16("zone_group_id");
                            if (_groups.ContainsKey(zoneGroupId))
                            {
                                var template = new ZoneConflict(_groups[zoneGroupId]);
                                template.ZoneGroupId = zoneGroupId;

                                for (var i = 0; i < 5; i++)
                                {
                                    template.NumKills[i]  = reader.GetInt32($"num_kills_{i}");
                                    template.NoKillMin[i] = reader.GetInt32($"no_kill_min_{i}");
                                }

                                template.ConflictMin = reader.GetInt32("conflict_min");
                                template.WarMin      = reader.GetInt32("war_min");
                                template.PeaceMin    = reader.GetInt32("peace_min");

                                template.PeaceProtectedFactionId = reader.GetUInt32("peace_protected_faction_id", 0);
                                template.NuiaReturnPointId       = reader.GetUInt32("nuia_return_point_id", 0);
                                template.HariharaReturnPointId   = reader.GetUInt32("harihara_return_point_id", 0);
                                template.WarTowerDefId           = reader.GetUInt32("war_tower_def_id", 0);
                                // TODO 1.2 // template.PeaceTowerDefId = reader.GetUInt32("peace_tower_def_id", 0);

                                _groups[zoneGroupId].Conflict = template;
                                _conflicts.Add(zoneGroupId, template);
                            }
                            else
                            {
                                _log.Warn("ZoneGroupId: {1} doesn't exist for conflict", zoneGroupId);
                            }
                        }
                    }
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM zone_group_banned_tags";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var template = new ZoneGroupBannedTag();
                            template.Id          = reader.GetUInt32("id");
                            template.ZoneGroupId = reader.GetUInt32("zone_group_id");
                            template.TagId       = reader.GetUInt32("tag_id");
                            // TODO 1.2 // template.BannedPeriodsId = reader.GetUInt32("banned_periods_id");
                            _groupBannedTags.Add(template.Id, template);
                        }
                    }
                }

                _log.Info("Loaded {0} group banned tags", _groupBannedTags.Count);
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM zone_climate_elems";
                    command.Prepare();
                    using (var reader = new SQLiteWrapperReader(command.ExecuteReader()))
                    {
                        while (reader.Read())
                        {
                            var template = new ZoneClimateElem();
                            template.Id            = reader.GetUInt32("id");
                            template.ZoneClimateId = reader.GetUInt32("zone_climate_id");
                            template.ClimateId     = reader.GetUInt32("climate_id");
                            _climateElem.Add(template.Id, template);
                        }
                    }
                }

                _log.Info("Loaded {0} climate elems", _climateElem.Count);
            }
        }
Example #39
0
        public void AboutBlockchange(Player p, ushort x, ushort y, ushort z, byte type)
        {
            if (!p.staticCommands)
            {
                p.ClearBlockchange();
            }
            byte b = p.level.GetTile(x, y, z);

            if (b == Block.Zero)
            {
                Player.SendMessage(p, "Invalid Block(" + x + "," + y + "," + z + ")!"); return;
            }
            p.SendBlockchange(x, y, z, b);

            string message = "Block (" + x + "," + y + "," + z + "): ";

            message += "&f" + b + " = " + Block.Name(b);
            Player.SendMessage(p, message + Server.DefaultColor + ".");
            message = p.level.foundInfo(x, y, z);
            if (message != "")
            {
                Player.SendMessage(p, "Physics information: &a" + message);
            }

            DataTable Blocks = Server.useMySQL ? MySQL.fillData("SELECT * FROM `Block" + p.level.name + "` WHERE X=" + (int)x + " AND Y=" + (int)y + " AND Z=" + (int)z) : SQLite.fillData("SELECT * FROM Block" + p.level.name + " WHERE X=" + (int)x + " AND Y=" + (int)y + " AND Z=" + (int)z);

            string Username, TimePerformed, BlockUsed;
            bool   Deleted, foundOne = false;

            for (int i = 0; i < Blocks.Rows.Count; i++)
            {
                foundOne      = true;
                Username      = Blocks.Rows[i]["Username"].ToString();
                TimePerformed = DateTime.Parse(Blocks.Rows[i]["TimePerformed"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                //Server.s.Log(Blocks.Rows[i]["Type"].ToString());
                BlockUsed = Block.Name(Convert.ToByte(Blocks.Rows[i]["Type"])).ToString();
                Deleted   = Convert.ToBoolean(Blocks.Rows[i]["Deleted"]);

                if (!Deleted)
                {
                    Player.SendMessage(p, "&3Created by " + Server.FindColor(Username.Trim()) + Username.Trim() + Server.DefaultColor + ", using &3" + BlockUsed);
                }
                else
                {
                    Player.SendMessage(p, "&4Destroyed by " + Server.FindColor(Username.Trim()) + Username.Trim() + Server.DefaultColor + ", using &3" + BlockUsed);
                }
                Player.SendMessage(p, "Date and time modified: &2" + TimePerformed);
            }

            List <Level.BlockPos> inCache = p.level.blockCache.FindAll(bP => bP.x == x && bP.y == y && bP.z == z);

            for (int i = 0; i < inCache.Count; i++)
            {
                foundOne      = true;
                Deleted       = inCache[i].deleted;
                Username      = inCache[i].name;
                TimePerformed = inCache[i].TimePerformed.ToString("yyyy-MM-dd HH:mm:ss");
                BlockUsed     = Block.Name(inCache[i].type);

                if (!Deleted)
                {
                    Player.SendMessage(p, "&3Created by " + Server.FindColor(Username.Trim()) + Username.Trim() + Server.DefaultColor + ", using &3" + BlockUsed);
                }
                else
                {
                    Player.SendMessage(p, "&4Destroyed by " + Server.FindColor(Username.Trim()) + Username.Trim() + Server.DefaultColor + ", using &3" + BlockUsed);
                }
                Player.SendMessage(p, "Date and time modified: &2" + TimePerformed);
            }

            if (!foundOne)
            {
                Player.SendMessage(p, "This block has not been modified since the map was cleared.");
            }

            Blocks.Dispose();

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Example #40
0
        public void Blockchange1(Player p, ushort x, ushort y, ushort z, byte type)
        {
            p.ClearBlockchange();
            CatchPos cpos = (CatchPos)p.blockchangeObject;

            cpos.message = cpos.message.Replace("'", "\\'");

            DataTable Messages = Server.useMySQL ? MySQL.fillData("SELECT * FROM `Messages" + p.level.name + "` WHERE X=" + (int)x + " AND Y=" + (int)y + " AND Z=" + (int)z) : SQLite.fillData("SELECT * FROM `Messages" + p.level.name + "` WHERE X=" + (int)x + " AND Y=" + (int)y + " AND Z=" + (int)z);

            Messages.Dispose();

            if (Messages.Rows.Count == 0)
            {
                if (Server.useMySQL)
                {
                    MySQL.executeQuery("INSERT INTO `Messages" + p.level.name + "` (X, Y, Z, Message) VALUES (" + (int)x + ", " + (int)y + ", " + (int)z + ", '" + cpos.message + "')");
                }
                else
                {
                    SQLite.executeQuery("INSERT INTO `Messages" + p.level.name + "` (X, Y, Z, Message) VALUES (" + (int)x + ", " + (int)y + ", " + (int)z + ", '" + cpos.message + "')");
                }
            }
            else
            {
                if (Server.useMySQL)
                {
                    MySQL.executeQuery("UPDATE `Messages" + p.level.name + "` SET Message='" + cpos.message + "' WHERE X=" + (int)x + " AND Y=" + (int)y + " AND Z=" + (int)z);
                }
                else
                {
                    SQLite.executeQuery("UPDATE `Messages" + p.level.name + "` SET Message='" + cpos.message + "' WHERE X=" + (int)x + " AND Y=" + (int)y + " AND Z=" + (int)z);
                }
            }

            Player.SendMessage(p, "Message block placed.");
            p.level.Blockchange(p, x, y, z, cpos.type);
            p.SendBlockchange(x, y, z, cpos.type);

            if (p.staticCommands)
            {
                p.Blockchange += new Player.BlockchangeEventHandler(Blockchange1);
            }
        }
Example #41
0
 public DBAccessor()
 {
     m_sqlite = new SQLite(m_strSqlFile);
 }
Example #42
0
        public void showMBs(Player p)
        {
            p.showMBs = !p.showMBs;

            using (DataTable Messages = Server.useMySQL ? MySQL.fillData("SELECT * FROM `Messages" + p.level.name + "`") : SQLite.fillData("SELECT * FROM `Messages" + p.level.name + "`"))
            {
                int i;

                if (p.showMBs)
                {
                    for (i = 0; i < Messages.Rows.Count; i++)
                    {
                        p.SendBlockchange((ushort)Messages.Rows[i]["X"], (ushort)Messages.Rows[i]["Y"], (ushort)Messages.Rows[i]["Z"], Block.MsgWhite);
                    }
                    Player.SendMessage(p, "Now showing &a" + i.ToString() + Server.DefaultColor + " MBs.");
                }
                else
                {
                    for (i = 0; i < Messages.Rows.Count; i++)
                    {
                        p.SendBlockchange((ushort)Messages.Rows[i]["X"], (ushort)Messages.Rows[i]["Y"], (ushort)Messages.Rows[i]["Z"], p.level.GetTile((ushort)Messages.Rows[i]["X"], (ushort)Messages.Rows[i]["Y"], (ushort)Messages.Rows[i]["Z"]));
                    }
                    Player.SendMessage(p, "Now hiding MBs.");
                }
            }
        }
 public SQLWindow()
 {
     InitializeComponent();
     sqlite = new SQLite();
     sqlite.Connect();
 }
Example #44
0
        public override void Use(Player p, string message)
        {
            if (message == "" || message.Split(' ').Length > 2)
            {
                Help(p); return;
            }
            int pos = message.IndexOf(' ');

            if (pos != -1)
            {
                Player who = Player.Find(message.Substring(0, pos));
                if (p != null && who.group.Permission > p.group.Permission)
                {
                    Player.SendMessage(p, "You cannot change the color of someone ranked higher than you!"); return;
                }
                if (who == null)
                {
                    Player.SendMessage(p, "There is no player \"" + message.Substring(0, pos) + "\"!"); return;
                }
                if (message.Substring(pos + 1) == "del")
                {
                    if (Server.useMySQL)
                    {
                        MySQL.executeQuery("UPDATE Players SET color = '' WHERE name = '" + who.name + "'");
                    }
                    else
                    {
                        SQLite.executeQuery("UPDATE Players SET color = '' WHERE name = '" + who.name + "'");
                    }
                    Player.GlobalChat(who, who.color + "*" + Name(who.name) + " color reverted to " + who.group.color + "their group's default" + Server.DefaultColor + ".", false);
                    who.color = who.group.color;

                    Player.GlobalDie(who, false);
                    Player.GlobalSpawn(who, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1], false);
                    who.SetPrefix();
                    return;
                }
                string color = c.Parse(message.Substring(pos + 1));
                if (color == "")
                {
                    Player.SendMessage(p, "There is no color \"" + message + "\".");
                }
                else if (color == who.color)
                {
                    Player.SendMessage(p, who.name + " already has that color.");
                }
                else
                {
                    //Player.GlobalChat(who, p.color + "*" + p.name + "&e changed " + who.color + Name(who.name) +
                    //                  " color to " + color +
                    //                  c.Name(color) + "&e.", false);
                    if (Server.useMySQL)
                    {
                        MySQL.executeQuery("UPDATE Players SET color = '" + c.Name(color) + "' WHERE name = '" + who.name + "'");
                    }
                    else
                    {
                        SQLite.executeQuery("UPDATE Players SET color = '" + c.Name(color) + "' WHERE name = '" + who.name + "'");
                    }

                    Player.GlobalChat(who, who.color + "*" + Name(who.name) + " color changed to " + color + c.Name(color) + Server.DefaultColor + ".", false);
                    if (p == null)
                    {
                        Player.SendMessage(p, "*" + Name(who.name) + " color was changed to " + c.Name(color) + ".");
                    }
                    who.color = color;

                    Player.GlobalDie(who, false);
                    Player.GlobalSpawn(who, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1], false);
                    who.SetPrefix();
                }
            }
            else
            {
                if (p != null)
                {
                    if (message == "del")
                    {
                        if (Server.useMySQL)
                        {
                            MySQL.executeQuery("UPDATE Players SET color = '' WHERE name = '" + p.name + "'");
                        }
                        else
                        {
                            Player.GlobalChat(p, p.color + "*" + Name(p.name) + " color reverted to " + p.group.color + "their group's default" + Server.DefaultColor + ".", false);
                        }
                        p.color = p.group.color;

                        Player.GlobalDie(p, false);
                        Player.GlobalSpawn(p, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1], false);
                        p.SetPrefix();
                        return;
                    }
                    string color = c.Parse(message);
                    if (color == "")
                    {
                        Player.SendMessage(p, "There is no color \"" + message + "\".");
                    }
                    else if (color == p.color)
                    {
                        Player.SendMessage(p, "You already have that color.");
                    }
                    else
                    {
                        if (Server.useMySQL)
                        {
                            MySQL.executeQuery("UPDATE Players SET color = '" + c.Name(color) + "' WHERE name = '" + p.name + "'");
                        }
                        else
                        {
                            SQLite.executeQuery("UPDATE Players SET color = '" + c.Name(color) + "' WHERE name = '" + p.name + "'");
                        }

                        Player.GlobalChat(p, p.color + "*" + Name(p.name) + " color changed to " + color + c.Name(color) + Server.DefaultColor + ".", false);
                        p.color = color;

                        Player.GlobalDie(p, false);
                        Player.GlobalSpawn(p, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1], false);
                        p.SetPrefix();
                    }
                }
            }
        }
Example #45
0
 public override void Init(SQLite.SQLiteConnection db)
 {
     //throw new NotImplementedException("Cannot re-init the main window.");
 }
Example #46
0
        private void LoadNextWord(SQLite.SQLiteConnection conn)
        {
            if (!mDictionarySearcher.IsSearching)
            {
                WordModel nextWord = FindWordByNextNotStarted (conn);

                if (nextWord != null)
                {
                    nextWord.Status = WordStatus.QUERYING_AH;
                    conn.Update (nextWord);
                    mDictionarySearcher.Search (nextWord.Word);
                }
            }
        }
 internal ViewHolder(SQLite.Designer.Design.View parent)
 {
   _triggers = parent.Triggers as List<ViewTrigger>;
 }
Example #48
0
 public List <User> GetCloseUsersByScore(User u)
 => u.userStats == null ? null : SQLite.GetConnection().Query <User>(@"SELECT *, (abs(userstats.score - @score)) as absscore FROM userstats INNER JOIN users ON users.LID = @lid AND userstats.LID = @lid AND users.ID = userstats.UID AND NOT users.ID = @uid ORDER BY absscore LIMIT 10", new { lid = u.LID, score = u.userStats.score, uid = u.ID }).ToList();
Example #49
0
        private void packageDir(SQLite db, string dir,string pdir)
        {
            var files = Directory.EnumerateFileSystemEntries(dir.ToString());
            foreach (var fileName in files)            
            {
                FileInfo finfo = new FileInfo(fileName);
                string vpath = pdir + "/" + finfo.Name;
                
                if (finfo.Attributes.HasFlag(FileAttributes.Directory))
                {
                    packageDir(db, fileName, vpath);
                }
                else
                {
                    Console.WriteLine("package "+ fileName + " >> " + vpath);
                    int len = (int) finfo.Length;
                    byte[] buf;
                    using (var fs = finfo.OpenRead())
                    {          
                        buf = new byte[len];
                        fs.Read(buf, 0, len);
                    }

                    db.bindString(1, vpath.ToString());
                    db.bindBlob(2, buf);
                    db.bindLong(3, timestamp(finfo.LastWriteTime));
                    db.execute();
                    db.reset();
                }
            }            
        }
Example #50
0
        /* удаление клиента */
        private void DeleteClientBtn_Click(object sender, RoutedEventArgs e)
        {
            if (clientsList.SelectedItem != null)
            {
                if (Confirm("Удалить выбранного клиента?"))
                {
                    var id = (clientsList.SelectedItem as Client).Id;

                    SQLite connection = new SQLite();
                    connection.WriteData(string.Format("DELETE FROM Clients WHERE ID = '{0}'", id));
                    UpdateClientsList(null);
                }
            }
            else
            {
                MessageBox.Show("Клиент не выбран!", "Предупреждение", MessageBoxButton.OK);
            }
        }
Example #51
0
 /// <summary>
 /// Establishes a connection to the database.
 /// </summary>
 /// <param name="databaseFile">The database file</param>
 public void Open(string databaseFile)
 {
     database = new SQLite(databaseFile);
 }
Example #52
0
        public override void Use(Player p, string message)
        {
            int bancount = Group.findPerm(LevelPermission.Banned).playerList.All().Count;

            DataTable count = Server.useMySQL ? MySQL.fillData("SELECT COUNT(id) FROM Players") : SQLite.fillData("SELECT COUNT(id) FROM Players");

            Player.SendMessage(p, "A total of " + c.lime + count.Rows[0]["COUNT(id)"] + " unique " + Server.DefaultColor + "players have visited this server.");
            Player.SendMessage(p, "Of these players, " + c.black + bancount + Server.DefaultColor + " have been banned.");
            Player.SendMessage(p, "That means that " + c.lime + String.Format("{0:0.00}", Convert.ToDouble(bancount / Convert.ToDouble(count.Rows[0]["COUNT(id)"]) * 100)) + "%" + Server.DefaultColor + " of the users have been banned.");
            count.Dispose();

            int playerCount = 0;
            int hiddenCount = 0;

            foreach (Player pl in Player.players)
            {
                if (!pl.hidden || p == null || p.group.Permission > LevelPermission.AdvBuilder || Server.devs.Contains(p.name.ToLower()))
                {
                    playerCount++;
                    if (pl.hidden && pl.group.Permission <= p.group.Permission && (p == null || p.group.Permission > LevelPermission.AdvBuilder || Server.devs.Contains(p.name.ToLower())))
                    {
                        hiddenCount++;
                    }
                }
            }
            if (playerCount == 1)
            {
                if (hiddenCount == 0)
                {
                    Player.SendMessage(p, "There is 1 player currently online.");
                }
                else
                {
                    Player.SendMessage(p, "There is 1 player currently online (" + hiddenCount + " hidden).");
                }
            }
            else
            {
                if (hiddenCount == 0)
                {
                    Player.SendMessage(p, "There are " + playerCount + " players online.");
                }
                else
                {
                    Player.SendMessage(p, "There are " + playerCount + " players online (" + hiddenCount + " hidden).");
                }
            }
        }
Example #53
0
        private void RefreshWordsList(SQLite.SQLiteConnection conn)
        {
            mWordsList = GetSortedWordList(conn);

            var method = WordsListChanged;
            if (method != null)
                method(this, EventArgs.Empty);
        }
Example #54
0
 public void SetScore(User u) // Do not use this function.
 => SQLite.GetConnection().Query("UPDATE userstats SET score=@score WHERE userstats.UID = @uid AND userstats.LID = @lid", new { score = u.userStats.score, uid = u.ID, lid = u.LID });
 public CreateViewForm(SQLite database)
 {
     db = database;
     InitializeComponent();
 }
Example #56
0
		private void createDB (SQLite.SQLiteConnection conn)
		{
			//create database
			conn.CreateTable<User> ();
		}
        public override void Use(Player p, string message)
        {
            bool   debug        = false;
            Player who          = null;
            string timespanend  = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string timespan     = "thismonth";
            string timespanname = "This Month";
            bool   tspanoption  = false;

            if (message == "" && p != null)
            {
                who = p;
            }
            else
            {
                who = (message.Split(' ').Length > 1 ? Player.Find(message.Split(' ')[0]) : Player.Find(message));
            }
            if (p != null && (message == "today" || message == "yesterday" || message == "thismonth" || message == "lastmonth" || message == "all"))
            {
                who = p;
            }
            if (p == null && message == "")
            {
                Help(p); return;
            }
            if (message.Split(' ').Length == 1 && (message == "today" || message == "yesterday" || message == "thismonth" || message == "lastmonth" || message == "all"))
            {
                timespan = message;
            }
            if (message.Split(' ').Length == 2 && (message.Split(' ')[1].ToLower() == "today" || message.Split(' ')[1].ToLower() == "yesterday" || message.Split(' ')[1].ToLower() == "thismonth" || message.Split(' ')[1].ToLower() == "lastmonth" || message.Split(' ')[1].ToLower() == "all"))
            {
                timespan = message.Split(' ')[1].ToLower();
            }
            if (debug)
            {
                Player.SendMessage(p, "Message = " + message);
            }
            if (timespan.ToLower() == "today")
            {
                timespan     = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                timespanname = "Today";
                tspanoption  = true;
            }
            if (timespan.ToLower() == "yesterday")
            {
                timespan     = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00");
                timespanend  = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                timespanname = "Yesterday";
                tspanoption  = true;
            }
            if (timespan.ToLower() == "thismonth")
            {
                timespan    = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
                tspanoption = true;
            }
            if (timespan.ToLower() == "lastmonth")
            {
                timespan     = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-01 00:00:00");
                timespanend  = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
                timespanname = "Last Month";
                tspanoption  = true;
            }
            if (timespan.ToLower() == "all")
            {
                timespan     = "0000-00-00 00:00:00";
                timespanname = "ALL";
                tspanoption  = true;
            }
            if (!tspanoption)
            {
                Help(p); return;
            }
            if (debug)
            {
                Player.SendMessage(p, "Timespan = " + timespan);
            }
            if (debug)
            {
                Player.SendMessage(p, "TimespanName = " + timespanname);
            }
            if (who != null)
            {
                message = who.name;
            }                                        // Online full player name is converted to message
            else
            {
                using (DataTable playerDb = Database.fillData("SELECT * FROM Players WHERE Name='" + (message.Split(' ').Length > 1 ? message.Split(' ')[0] : message) + "'"))
                {
                    if (playerDb.Rows != null && playerDb.Rows.Count > 0) // Check if player exists in database since we couldn't find player online
                    {
                        message = playerDb.Rows[0]["Name"].ToString();    // Proper case of player name is pulled from database and converted to message
                        playerDb.Dispose();
                    }
                    else
                    {
                        Player.SendMessage(p, "Unable to find player"); // Player wasn't online and didn't exist in database
                        return;
                    }
                }
            }
            DataTable reviewcount  = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'review' AND Cmdmsg LIKE 'next'") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'review' AND Cmdmsg LIKE 'next'");
            DataTable promotecount = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'promote' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'promote' AND Cmdmsg !=''");
            DataTable demotecount  = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'demote' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'demote' AND Cmdmsg !=''");
            DataTable griefercount = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'griefer' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'griefer' AND Cmdmsg !=''");
            DataTable undocount    = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'undo' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'undo' AND Cmdmsg !=''");
            DataTable freezecount  = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'freeze' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'freeze' AND Cmdmsg !=''");
            DataTable mutecount    = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'mute' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'mute' AND Cmdmsg !=''");
            DataTable warncount    = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'warn' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'warn' AND Cmdmsg !=''");
            DataTable kickcount    = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'kick' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'kick' AND Cmdmsg !=''");
            DataTable tempbancount = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'tempban' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'tempban' AND Cmdmsg !=''");
            DataTable bancount     = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'ban' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'ban' AND Cmdmsg !=''");

            Player.SendMessage(p, (p == null ? "" : "&d") + "OpStats for " + (p == null ? "" : "&c") + message); // Use colorcodes if in game, don't use color if in console
            Player.SendMessage(p, (p == null ? "" : "&d") + "Showing " + timespanname + " Starting from " + timespan);
            Player.SendMessage(p, (p == null ? "" : "&0") + "----------------");
            Player.SendMessage(p, (p == null ? "" : "&a") + "Reviews - " + (p == null ? "" : "&5") + reviewcount.Rows[0]["COUNT(id)"]); // Count results within datatable
            Player.SendMessage(p, (p == null ? "" : "&a") + "Promotes - " + (p == null ? "" : "&5") + promotecount.Rows[0]["COUNT(id)"]);
            Player.SendMessage(p, (p == null ? "" : "&a") + "Demotes - " + (p == null ? "" : "&5") + demotecount.Rows[0]["COUNT(id)"]);
            Player.SendMessage(p, (p == null ? "" : "&a") + "Griefers - " + (p == null ? "" : "&5") + griefercount.Rows[0]["COUNT(id)"]);
            Player.SendMessage(p, (p == null ? "" : "&a") + "Undo - " + (p == null ? "" : "&5") + undocount.Rows[0]["COUNT(id)"]);
            Player.SendMessage(p, (p == null ? "" : "&a") + "Freezes - " + (p == null ? "" : "&5") + freezecount.Rows[0]["COUNT(id)"]);
            Player.SendMessage(p, (p == null ? "" : "&a") + "Mutes - " + (p == null ? "" : "&5") + mutecount.Rows[0]["COUNT(id)"]);
            Player.SendMessage(p, (p == null ? "" : "&a") + "Warns - " + (p == null ? "" : "&5") + warncount.Rows[0]["COUNT(id)"]);
            Player.SendMessage(p, (p == null ? "" : "&a") + "Kicks - " + (p == null ? "" : "&5") + kickcount.Rows[0]["COUNT(id)"]);
            Player.SendMessage(p, (p == null ? "" : "&a") + "Tempbans - " + (p == null ? "" : "&5") + tempbancount.Rows[0]["COUNT(id)"]);
            Player.SendMessage(p, (p == null ? "" : "&a") + "Bans - " + (p == null ? "" : "&5") + bancount.Rows[0]["COUNT(id)"]);
            reviewcount.Dispose();
            promotecount.Dispose();
            demotecount.Dispose();
            griefercount.Dispose();
            undocount.Dispose();
            freezecount.Dispose();
            mutecount.Dispose();
            warncount.Dispose();
            kickcount.Dispose();
            tempbancount.Dispose();
            bancount.Dispose();
        }
Example #58
0
        public void Load()
        {
            _systemFactions = new Dictionary <uint, SystemFaction>();
            _relations      = new List <FactionRelation>();
            using (var connection = SQLite.CreateConnection())
            {
                _log.Info("Loading system factions...");
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM system_factions";
                    command.Prepare();
                    using (var sqliteReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteReader))
                        {
                            while (reader.Read())
                            {
                                var faction = new SystemFaction
                                {
                                    Id              = reader.GetUInt32("id"),
                                    Name            = reader.GetString("name"),
                                    OwnerName       = reader.GetString("owner_name"),
                                    UnitOwnerType   = (sbyte)reader.GetInt16("owner_type_id"),
                                    OwnerId         = reader.GetUInt32("owner_id"),
                                    PoliticalSystem = reader.GetByte("political_system_id"),
                                    MotherId        = reader.GetUInt32("mother_id"),
                                    AggroLink       = reader.GetBoolean("aggro_link", true),
                                    GuardHelp       = reader.GetBoolean("guard_help", true),
                                    DiplomacyTarget = reader.GetBoolean("is_diplomacy_tgt", true)
                                };
                                _systemFactions.Add(faction.Id, faction);
                            }
                        }
                }

                _log.Info("Loaded {0} system factions", _systemFactions.Count);
                _log.Info("Loading faction relations...");
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM system_faction_relations";
                    command.Prepare();
                    using (var sqliteReader = command.ExecuteReader())
                        using (var reader = new SQLiteWrapperReader(sqliteReader))
                        {
                            while (reader.Read())
                            {
                                var relation = new FactionRelation
                                {
                                    Id    = reader.GetUInt32("faction1_id"),
                                    Id2   = reader.GetUInt32("faction2_id"),
                                    State = (RelationState)reader.GetByte("state_id")
                                };
                                _relations.Add(relation);

                                var faction = _systemFactions[relation.Id];
                                faction.Relations.Add(relation.Id2, relation);
                                faction = _systemFactions[relation.Id2];
                                faction.Relations.Add(relation.Id, relation);
                            }
                        }
                }

                _log.Info("Loaded {0} faction relations", _relations.Count);
            }
        }
        public void Save(SQLite.DataStore store, System.Data.SQLite.SQLiteConnection connection)
        {
            if (this.Saved == true)
            {
                return;
            }

            if (string.IsNullOrEmpty(this.PlayerName))
            {
                return;
            }

            this.PlayerId = -1;
            if (store.PlayerIdCache.ContainsKey(this.PlayerName))
            {
                this.PlayerId = store.PlayerIdCache[this.PlayerName];
            }
            else
            {
                Data.Player player = store.GetPlayer(this.SiteId, this.PlayerName, connection);
                if (player == null)
                {
                    this.PlayerId = store.InsertPlayer(this.SiteId, this.PlayerName, connection);
                }
                else
                {
                    this.PlayerId = player.Id;
                }

                store.PlayerIdCache[this.PlayerName] = this.PlayerId;
            }

            long handId = this.HandId;
            long offButton = -1; // TODO

            this.Id = store.InsertHandPlayer(handId, this.PlayerId, this.Stack,
                this.SeatNumber, offButton, this.HoleCard1, this.HoleCard2,
                this.FinalHand, connection);

            this.Saved = true;
        }
Example #60
0
        public override void Use(Player p, string message)
        {
            try
            {
                //safe against SQL injections because no user input is given here
                if (Server.useMySQL)
                {
                    MySQL.executeQuery("CREATE TABLE if not exists `Inbox" + p.name + "` (PlayerFrom CHAR(20), TimeSent DATETIME, Contents VARCHAR(255));");
                }
                else
                {
                    SQLite.executeQuery("CREATE TABLE if not exists `Inbox" + p.name + "` (PlayerFrom TEXT, TimeSent DATETIME, Contents TEXT);");
                }
                if (message == "")
                {
                    //safe against SQL injections because no user input is given here
                    DataTable Inbox = Database.fillData("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent");

                    if (Inbox.Rows.Count == 0)
                    {
                        Player.SendMessage(p, "No messages found."); Inbox.Dispose(); return;
                    }

                    for (int i = 0; i < Inbox.Rows.Count; ++i)
                    {
                        Player.SendMessage(p, i + ": From &5" + Inbox.Rows[i]["PlayerFrom"].ToString() + Server.DefaultColor + " at &a" + Inbox.Rows[i]["TimeSent"].ToString());
                    }
                    Inbox.Dispose();
                }
                else if (message.Split(' ')[0].ToLower() == "del" || message.Split(' ')[0].ToLower() == "delete")
                {
                    int FoundRecord = -1;

                    if (message.Split(' ')[1].ToLower() != "all")
                    {
                        try
                        {
                            FoundRecord = int.Parse(message.Split(' ')[1]);
                        }
                        catch { Player.SendMessage(p, "Incorrect number given."); return; }

                        if (FoundRecord < 0)
                        {
                            Player.SendMessage(p, "Cannot delete records below 0"); return;
                        }
                    }
                    //safe against SQL injections because no user input is given here
                    DataTable Inbox = Database.fillData("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent");

                    if (Inbox.Rows.Count - 1 < FoundRecord || Inbox.Rows.Count == 0)
                    {
                        Player.SendMessage(p, "\"" + FoundRecord + "\" does not exist."); Inbox.Dispose(); return;
                    }

                    string queryString;
                    //safe against SQL injections because no user input is given here
                    if (FoundRecord == -1)
                    {
                        queryString = Server.useMySQL ? "TRUNCATE TABLE `Inbox" + p.name + "`" : "DELETE FROM `Inbox" + p.name + "`";
                    }
                    else
                    {
                        Database.AddParams("@From", Inbox.Rows[FoundRecord]["PlayerFrom"]);
                        Database.AddParams("@Time", Convert.ToDateTime(Inbox.Rows[FoundRecord]["TimeSent"]).ToString("yyyy-MM-dd HH:mm:ss"));
                        queryString = "DELETE FROM `Inbox" + p.name + "` WHERE PlayerFrom=@FROM AND TimeSent=@Time";
                    }
                    Database.executeQuery(queryString);

                    if (FoundRecord == -1)
                    {
                        Player.SendMessage(p, "Deleted all messages.");
                    }
                    else
                    {
                        Player.SendMessage(p, "Deleted message.");
                    }

                    Inbox.Dispose();
                }
                else
                {
                    int FoundRecord;

                    try
                    {
                        FoundRecord = int.Parse(message);
                    }
                    catch { Player.SendMessage(p, "Incorrect number given."); return; }

                    if (FoundRecord < 0)
                    {
                        Player.SendMessage(p, "Cannot read records below 0"); return;
                    }

                    //safe against SQL injections because no user input is given here
                    DataTable Inbox = Database.fillData("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent");

                    if (Inbox.Rows.Count - 1 < FoundRecord || Inbox.Rows.Count == 0)
                    {
                        Player.SendMessage(p, "\"" + FoundRecord + "\" does not exist."); Inbox.Dispose(); return;
                    }

                    Player.SendMessage(p, "Message from &5" + Inbox.Rows[FoundRecord]["PlayerFrom"] + Server.DefaultColor + " sent at &a" + Inbox.Rows[FoundRecord]["TimeSent"] + ":");
                    Player.SendMessage(p, Inbox.Rows[FoundRecord]["Contents"].ToString());
                    Inbox.Dispose();
                }
            }
            catch
            {
                Player.SendMessage(p, "Error accessing inbox. You may have no mail, try again.");
            }
        }