static void Main(string[] args)
      {        
         Stopwatch sw = new Stopwatch();
         SqlCommandParamQueryPerformanceMonitor monitor = new SqlCommandParamQueryPerformanceMonitor(Configuration.SqlConnectionString);

         var dbManager = new SqlDatabaseManager(Configuration.SqlConnectionString);          
         dbManager.DeleteAll();
         int id = 0;
         foreach (var count in new[] { 4, 4, 16, 128, 256, 512, 1000 }) //new[] { 10, 128, 1000, 10000 }
         {
           // int count = 1000;
            for (int i = 0; i < count; i++)
               monitor.Insert(new Department { Id = ++id, DateAdded = DateTime.Now, Name = "dep " + i }, sw);
            sw.Stop();
            Console.WriteLine(((double)sw.ElapsedTicks / (double)System.Diagnostics.Stopwatch.Frequency) * 1000);
         }
         Console.ReadLine();
      }
        public async void SendRewardAndStop(Player player)
        {
            EndDate = DateTime.Now;
            Program.TickManager.RemoveTick(this);

            player.ChangeData(DataType.URIDIUM, 25000);
            player.ChangeData(DataType.EXPERIENCE, 2500000);
            player.ChangeData(DataType.HONOR, 25000);

            GameManager.SendPacketToAll($"0|A|STD|{player.Name} has won the Jacpot Battle!");
            player.SendPacket("0|n|KSMSG|label_traininggrounds_results_victory");

            var title     = "title_jackpot_battle_winner";
            var oldWinner = GameManager.GameSessions.FirstOrDefault(x => x.Value?.Player.Title == title).Value?.Player;

            if (oldWinner != null)
            {
                oldWinner.SetTitle("");
            }

            using (var mySqlClient = SqlDatabaseManager.GetClient())
            {
                mySqlClient.ExecuteNonQuery($"INSERT INTO log_event_jpb (players, finalists, winner_id, start_date, end_date) VALUES ('{JsonConvert.SerializeObject(Players.Keys.ToList())}', '{JsonConvert.SerializeObject(Finalists.ToList())}', {player.Id}, '{StartDate.ToString("yyyy-MM-dd HH:mm:ss")}', '{EndDate.ToString("yyyy-MM-dd HH:mm:ss")}')");
                mySqlClient.ExecuteNonQuery($"UPDATE player_accounts SET title = '' WHERE title = '{title}'");
            }

            player.SetTitle(title, true);

            await Task.Delay(5000);

            player.SetPosition(player.GetBasePosition());
            player.Jump(player.GetBaseMapId(), player.Position);

            Active      = false;
            radiationX  = 12800;
            radiationY  = 1600;
            timerSecond = 1;
            Players.Clear();
            Finalists.Clear();
            Spacemap.Characters.Clear();
            Spacemap.Objects.Clear();
            Spacemap.POIs.Clear();
        }
示例#3
0
        private static void GetRecentRooms(Session Session, ClientMessage Message)
        {
            ServerMessage Response = TryGetResponseFromCache(Session.CharacterId, Message);

            if (Response != null)
            {
                Session.SendData(Response);
                return;
            }

            List <uint>     VisitedUids = new List <uint>();
            List <RoomInfo> Rooms       = new List <RoomInfo>();

            using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
            {
                MySqlClient.SetParameter("userid", Session.CharacterId);
                DataTable Table = MySqlClient.ExecuteQueryTable("SELECT room_id FROM room_visits WHERE user_id = @userid ORDER BY timestamp_entered DESC LIMIT 50");

                foreach (DataRow Row in Table.Rows)
                {
                    uint Id = (uint)Row["room_id"];

                    if (VisitedUids.Contains(Id))
                    {
                        continue;
                    }

                    RoomInfo Info = RoomInfoLoader.GetRoomInfo(Id);

                    if (Info == null || Info.Type == RoomType.Public)
                    {
                        continue;
                    }

                    Rooms.Add(Info);
                    VisitedUids.Add(Info.Id);
                }
            }

            Response = NavigatorRoomListComposer.Compose(0, 7, string.Empty, Rooms);
            AddToCacheIfNeeded(Session.CharacterId, Message, Response);
            Session.SendData(Response);
        }
        public void SavePlayerSettings(Player player)
        {
            try
            {
                var settings = JsonConvert.SerializeObject(player.Settings.PackSettings(), Formatting.None, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Auto
                });

                using (var mySqlClient = SqlDatabaseManager.GetClient())
                {
                    mySqlClient.ExecuteNonQuery($"UPDATE player_extra_data SET SETTINGS='{settings}' WHERE PLAYER_ID=" + player.Id);
                }
            }
            catch (Exception)
            {
                Out.QuickLog("Critical error occured", LogKeys.ERROR_LOG);
            }
        }
示例#5
0
        private static void OnSendIm(Session Session, ClientMessage Message)
        {
            uint   UserId = Message.PopWiredUInt32();
            string Text   = UserInputFilter.FilterString(Message.PopString()).Trim();

            if (UserId <= 0 || Text.Length < 1)
            {
                return;
            }

            if (Session.CharacterInfo.IsMuted)
            {
                Session.SendData(MessengerImErrorComposer.Compose(4, UserId));
                return;
            }

            if (!Session.MessengerFriendCache.Friends.Contains(UserId))
            {
                Session.SendData(MessengerImErrorComposer.Compose(6, UserId));
                return;
            }

            Session TargetSession = SessionManager.GetSessionByCharacterId(UserId);

            if (TargetSession == null)
            {
                Session.SendData(MessengerImErrorComposer.Compose(5, UserId));
                return;
            }

            if (TargetSession.CharacterInfo.IsMuted)
            {
                Session.SendData(MessengerImErrorComposer.Compose(3, UserId));
            }

            TargetSession.SendData(MessengerImMessageComposer.Compose(Session.CharacterId, Wordfilter.Filter(Text)));

            using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
            {
                ModerationLogs.LogChatMessage(MySqlClient, Session.CharacterId, 0, "(MESSAGE to " + TargetSession.CharacterInfo.Username + " [" + TargetSession.CharacterId + "]) " + Text);
            }
        }
示例#6
0
        private static void ProcessThread()
        {
            Int32 user_peak = 0;

            using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
            {
                DataRow Row = MySqlClient.ExecuteQueryRow("SELECT sval FROM server_statistics WHERE skey = 'online_peak' LIMIT 1");
                if (Row != null)
                {
                    user_peak = Convert.ToInt32(Row[0]);
                }
            }

            while (Program.Alive)
            {
                using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
                {
                    MySqlClient.SetParameter("skey", "active_connections");
                    MySqlClient.SetParameter("sval", SessionManager.ActiveConnections);
                    MySqlClient.ExecuteNonQuery("UPDATE server_statistics SET sval = @sval WHERE skey = @skey LIMIT 1");

                    MySqlClient.SetParameter("skey", "stamp");
                    MySqlClient.SetParameter("sval", UnixTimestamp.GetCurrent());
                    MySqlClient.ExecuteNonQuery("UPDATE server_statistics SET sval = @sval WHERE skey = @skey LIMIT 1");

                    if (SessionManager.ActiveConnections > user_peak)
                    {
                        user_peak = SessionManager.ActiveConnections;

                        MySqlClient.SetParameter("skey", "online_peak");
                        MySqlClient.SetParameter("sval", user_peak);
                        MySqlClient.ExecuteNonQuery("UPDATE server_statistics SET sval = @sval WHERE skey = @skey LIMIT 1");

                        MySqlClient.SetParameter("skey", "online_peak_stamp");
                        MySqlClient.SetParameter("sval", UnixTimestamp.GetCurrent());
                        MySqlClient.ExecuteNonQuery("UPDATE server_statistics SET sval = @sval WHERE skey = @skey LIMIT 1");
                    }
                }

                Thread.Sleep(60 * 1000);
            }
        }
示例#7
0
 public void TryAuthenticate(string Username, string Password, string RemoteAddress, bool Register = false)
 {
     using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
     {
         uint characterId = UserCredentialsAuthenticator.TryAuthenticate(client, Username, Password, RemoteAddress);
         if (characterId == 0)
         {
             this.SendData(AuthenticationKoComposer.Compose(false), false);
         }
         else
         {
             BoomBang.Game.Characters.CharacterInfo info = CharacterInfoLoader.GetCharacterInfo(client, characterId, this.uint_0, true);
             if (ModerationBanManager.IsUserIdBlacklisted(info.UInt32_0))
             {
                 this.SendData(ModerationBanComposer.Compose(ModerationBanManager.GetBanDetails(info.UInt32_0)), false);
                 SessionManager.StopSession(this.uint_0);
             }
             else if ((info != null) && info.HasLinkedSession)
             {
                 this.characterInfo_0 = info;
                 this.characterInfo_0.TimestampLastOnline = UnixTimestamp.GetCurrent();
                 CharacterResolverCache.AddToCache(this.characterInfo_0.UInt32_0, this.characterInfo_0.Username, true);
                 this.sessionLaptopFriendCache_0 = new SessionLaptopFriendCache(client, this.CharacterId);
                 this.userIgnoreCache_0          = new UserIgnoreCache(client, this.CharacterId);
                 this.bool_1 = true;
                 if (Register)
                 {
                     this.SendData(RegisterComposer.Compose(this.characterInfo_0), false);
                 }
                 else
                 {
                     this.SendData(AuthenticationOkComposer.Compose(this.characterInfo_0), false);
                 }
                 LaptopHandler.MarkUpdateNeeded(this, 0, true);
             }
             else
             {
                 SessionManager.StopSession(this.uint_0);
             }
         }
     }
 }
示例#8
0
        private static void SetBadgeOrder(Session Session, ClientMessage Message)
        {
            int i = 0;
            Dictionary <int, Badge> NewSettings = new Dictionary <int, Badge>();

            while (Message.RemainingLength > 0)
            {
                if (i > 5)
                {
                    continue;
                }

                int    SlotId    = Message.PopWiredInt32();
                string BadgeCode = Message.PopString();
                Badge  BadgeRef  = new Badge(BadgeCode);

                if (BadgeRef == null || !Session.BadgeCache.ContainsCode(BadgeCode) || SlotId >= 6 ||
                    SlotId <= 0 || NewSettings.ContainsKey(SlotId))
                {
                    continue;
                }

                NewSettings.Add(SlotId, BadgeRef);

                i++;
            }

            using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
            {
                Session.BadgeCache.UpdateBadgeOrder(MySqlClient, NewSettings);
            }

            RoomInstance Instance = RoomManager.GetInstanceByRoomId(Session.CurrentRoomId);

            if (Instance == null)
            {
                return;
            }

            Instance.BroadcastMessage(RoomUserBadgesComposer.Compose(Session.CharacterId, Session.BadgeCache.EquippedBadges));
            QuestManager.ProgressUserQuest(Session, QuestType.PROFILE_BADGE);
        }
示例#9
0
            public static void Modules(BattleStation battleStation)
            {
                var modules = new List <EquippedModuleBase>();

                foreach (var equipped in battleStation.EquippedStationModule)
                {
                    var module = new List <SatelliteBase>();

                    foreach (var equippedModule in battleStation.EquippedStationModule[equipped.Key])
                    {
                        module.Add(new SatelliteBase(equippedModule.OwnerId, equippedModule.ItemId, equippedModule.SlotId, equippedModule.DesignId, equippedModule.Type, equippedModule.CurrentHitPoints,
                                                     equippedModule.MaxHitPoints, equippedModule.CurrentShieldPoints, equippedModule.MaxShieldPoints, equippedModule.InstallationSecondsLeft, equippedModule.Installed));
                    }

                    modules.Add(new EquippedModuleBase(equipped.Key, module));
                }

                using (var mySqlClient = SqlDatabaseManager.GetClient())
                    mySqlClient.ExecuteNonQuery($"UPDATE server_battlestations SET modules = '{JsonConvert.SerializeObject(modules)}' WHERE name = '{battleStation.AsteroidName}'");
            }
示例#10
0
        private static void smethod_17(Session session_0, ClientMessage clientMessage_0)
        {
            clientMessage_0.ReadUnsignedInteger();
            string        motto             = clientMessage_0.ReadString();
            SpaceInstance instanceBySpaceId = SpaceManager.GetInstanceBySpaceId(session_0.CurrentSpaceId);

            if (instanceBySpaceId != null)
            {
                SpaceActor actorByReferenceId = instanceBySpaceId.GetActorByReferenceId(session_0.CharacterId, SpaceActorType.UserCharacter);
                if (actorByReferenceId != null)
                {
                    CharacterInfo referenceObject = (CharacterInfo)actorByReferenceId.ReferenceObject;
                    using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
                    {
                        referenceObject.UpdateMotto(client, motto);
                    }
                    instanceBySpaceId.BroadcastMessage(SpaceUserMottoUpdateComposer.Compose(actorByReferenceId.UInt32_0, motto), 0, false);
                }
            }
        }
示例#11
0
        public static long InsertNewAdministratorToDB(LocalUser user, byte[] password)
        {
            long lastInsertedMember = 0;

            try
            {
                using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
                {
                    string sql = "INSERT INTO Administrator (member_id, password_hash) VALUES(@member_id, @password_hash);";

                    lastInsertedMember = InsertNewMemberToDB(user, client);
                    if (lastInsertedMember > 0)
                    {
                        client.SetParameter("@member_id", lastInsertedMember);
                        client.SetParameter("@password_hash", password);

                        if (client.ExecuteNonQuery(sql) == 0)
                        {
                            return(0);
                        }
                    }
                }
            }
            catch (DbException e)
            {
                if (e.Message.Contains("unique_member_name_ck"))
                {
                    return(-2);
                }
                else if (e.Message.Contains("unique_member_administrator_ck"))
                {
                    return(-3);
                }
                else
                {
                    Logger.WriteLine(e.ToString(), Logger.LOG_LEVEL.WARN);
                }
            }

            return(lastInsertedMember);
        }
示例#12
0
        private static bool HandleRental(Session Session, Item Item, RoomInstance Instance, ItemEventType Event, int RequestData, uint Opcode)
        {
            switch (Event)
            {
            case ItemEventType.Placed:
            case ItemEventType.InstanceLoaded:

                if (Item.PendingExpiration)
                {
                    int DesiredTicks = (int)((double)(Math.Ceiling(Item.ExpireTimeLeft * 2)));

                    if (DesiredTicks <= 0)
                    {
                        goto case ItemEventType.UpdateTick;
                    }

                    Item.RequestUpdate(DesiredTicks);
                    return(true);
                }

                break;

            case ItemEventType.UpdateTick:

                if (Item.PendingExpiration)
                {
                    using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
                    {
                        Item.RemovePermanently(MySqlClient);
                        Instance.TakeItem(Item.Id);
                        Instance.RegenerateRelativeHeightmap();
                    }

                    return(true);
                }

                break;
            }

            return(HandleGenericSwitch(Session, Item, Instance, Event, RequestData, 0));
        }
示例#13
0
        public static SongData GetSong(uint SongId)
        {
            lock (mSyncRoot)
            {
                if (mSongCache.ContainsKey(SongId))
                {
                    double CacheTime = UnixTimestamp.GetCurrent() - mCacheTimer[SongId];

                    if (CacheTime >= CACHE_LIFETIME)
                    {
                        mSongCache.Remove(SongId);
                        mCacheTimer.Remove(SongId);
                    }
                    else
                    {
                        return(mSongCache[SongId]);
                    }
                }
            }

            SongData Song = null;

            using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
            {
                MySqlClient.SetParameter("id", SongId);
                DataRow Row = MySqlClient.ExecuteQueryRow("SELECT * FROM songs WHERE id = @id LIMIT 1");

                if (Row != null)
                {
                    Song = GetSongFromDataRow(Row);

                    lock (mSyncRoot)
                    {
                        mSongCache.Add(Song.Id, Song);
                        mCacheTimer.Add(Song.Id, UnixTimestamp.GetCurrent());
                    }
                }
            }

            return(Song);
        }
示例#14
0
        private static void CautionUser(Session Session, ClientMessage Message)
        {
            if (!Session.HasRight("moderation_tool"))
            {
                return;
            }

            uint   UserId      = Message.PopWiredUInt32();
            string MessageText = Message.PopString();

            Session TargetSession = SessionManager.GetSessionByCharacterId(UserId);

            if (TargetSession != null)
            {
                TargetSession.SendData(HotelManagerNotificationComposer.Compose("Caution from moderator:\n\n" + MessageText));
                ModerationTicketManager.MarkTicketRespondedToForUser(UserId);
            }
            else
            {
                Session.SendData(NotificationMessageComposer.Compose("That user is not online at this point in time."));
            }

            CharacterInfo Info = (TargetSession != null ? TargetSession.CharacterInfo : null);

            using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
            {
                if (Info == null)
                {
                    Info = CharacterInfoLoader.GetCharacterInfo(MySqlClient, UserId);
                }

                if (Info != null)
                {
                    Info.ModerationCautions++;
                }

                ModerationLogs.LogModerationAction(MySqlClient, Session, "Sent caution to user",
                                                   "User " + TargetSession.CharacterInfo.Username + " (ID " + TargetSession.CharacterId + "): '" +
                                                   MessageText + "'.");
            }
        }
示例#15
0
        public static void LogRoomEntry(uint UserId, uint RoomId)
        {
            if (!(bool)ConfigManager.GetValue("moderation.roomlogs.enabled"))
            {
                return;
            }

            using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
            {
                double Stamp = UnixTimestamp.GetCurrent();

                MySqlClient.SetParameter("userid", UserId);
                MySqlClient.SetParameter("timestamp", Stamp);
                MySqlClient.ExecuteNonQuery("UPDATE room_visits SET timestamp_left = @timestamp WHERE user_id = @userid AND timestamp_left = 0 LIMIT 1");

                MySqlClient.SetParameter("userid", UserId);
                MySqlClient.SetParameter("roomid", RoomId);
                MySqlClient.SetParameter("timestamp", Stamp);
                MySqlClient.ExecuteNonQuery("INSERT INTO room_visits (user_id,room_id,timestamp_entered) VALUES (@userid,@roomid,@timestamp)");
            }
        }
示例#16
0
        public bool RemoveRoomFromFavorites(uint RoomId)
        {
            lock (mInner)
            {
                if (!mInner.Contains(RoomId))
                {
                    return(false);
                }

                using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
                {
                    MySqlClient.SetParameter("userid", mCharacterId);
                    MySqlClient.SetParameter("roomid", RoomId);
                    MySqlClient.ExecuteNonQuery("DELETE FROM user_favorites WHERE user_id = @userid AND room_id = @roomid LIMIT 1");
                }

                mInner.Remove(RoomId);
            }

            return(true);
        }
示例#17
0
        public bool AddRoomToFavorites(uint RoomId)
        {
            lock (mInner)
            {
                if (mInner.Contains(RoomId) || mInner.Count >= Navigator.MaxFavoritesPerUser)
                {
                    return(false);
                }

                using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
                {
                    MySqlClient.SetParameter("userid", mCharacterId);
                    MySqlClient.SetParameter("roomid", RoomId);
                    MySqlClient.ExecuteNonQuery("INSERT INTO user_favorites (user_id,room_id) VALUES (@userid,@roomid)");
                }

                mInner.Add(RoomId);
            }

            return(true);
        }
    public static void ChangeCompany(Player player, int uridiumPrice, int honorPrice)
    {
        if (player?.GameSession != null)
        {
            using (var mySqlClient = SqlDatabaseManager.GetClient())
            {
                var result = mySqlClient.ExecuteQueryRow($"SELECT data, factionId FROM player_accounts WHERE userId = {player.Id}");
                player.Data      = JsonConvert.DeserializeObject <DataBase>(result["data"].ToString());
                player.FactionId = Convert.ToInt32(result["factionId"]);
            }

            player.SendPacket($"0|LM|ST|URI|-{uridiumPrice}|{player.Data.uridium}");

            if (honorPrice > 0)
            {
                player.SendPacket($"0|LM|ST|HON|-{honorPrice}|{player.Data.honor}");
            }

            player.Jump(player.GetBaseMapId(), player.GetBasePosition());
        }
    }
示例#19
0
        public static void LoadMaps()
        {
            using (var mySqlClient = SqlDatabaseManager.GetClient())
            {
                var data = (DataTable)mySqlClient.ExecuteQueryTable("SELECT * FROM server_maps");
                foreach (DataRow row in data.Rows)
                {
                    int    mapId     = Convert.ToInt32(row["mapID"]);
                    string name      = Convert.ToString(row["name"]);
                    int    factionId = Convert.ToInt32(row["factionID"]);
                    var    npcs      = JsonConvert.DeserializeObject <List <NpcsBase> >(row["npcs"].ToString());
                    var    portals   = JsonConvert.DeserializeObject <List <PortalBase> >(row["portals"].ToString());
                    var    stations  = JsonConvert.DeserializeObject <List <StationBase> >(row["stations"].ToString());
                    var    options   = JsonConvert.DeserializeObject <OptionsBase>(row["options"].ToString());
                    var    spacemap  = new Spacemap(mapId, name, factionId, npcs, portals, stations, options);
                    GameManager.Spacemaps.TryAdd(spacemap.Id, spacemap);
                }
            }

            LoadBattleStations();
        }
示例#20
0
        public static bool DeleteUserFromDB(long userId)
        {
            try
            {
                using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
                {
                    string sql = "DELETE FROM Member WHERE id = @user_id;";
                    client.SetParameter("@user_id", userId);

                    if (client.ExecuteNonQuery(sql) == 1)
                    {
                        return(true);
                    }
                }
            }
            catch (DbException)
            {
            }

            return(false);
        }
 public static void ProcessThread()
 {
     try
     {
         while (Program.Alive)
         {
             Thread.Sleep(0x927c0);
             using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
             {
                 ReloadCache(client);
                 continue;
             }
         }
     }
     catch (ThreadAbortException)
     {
     }
     catch (ThreadInterruptedException)
     {
     }
 }
示例#22
0
        private static void smethod_10(Session session_0, ClientMessage clientMessage_0)
        {
            uint          actorId           = clientMessage_0.ReadUnsignedInteger();
            uint          colorId           = clientMessage_0.ReadUnsignedInteger();
            int           vote              = clientMessage_0.ReadInteger();
            SpaceInstance instanceBySpaceId = SpaceManager.GetInstanceBySpaceId(session_0.CurrentSpaceId);

            if (instanceBySpaceId != null)
            {
                SpaceActor actorByReferenceId = instanceBySpaceId.GetActorByReferenceId(session_0.CharacterId, SpaceActorType.UserCharacter);
                if (actorByReferenceId != null)
                {
                    CharacterInfo referenceObject = (CharacterInfo)actorByReferenceId.ReferenceObject;
                    using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
                    {
                        referenceObject.UpdateVotes(client, colorId, vote);
                    }
                    instanceBySpaceId.BroadcastMessage(SpaceUserVoteUpdateComposer.Compose(actorId, colorId, vote), 0, false);
                }
            }
        }
 public static string GetNameFromUid(uint UserId)
 {
     lock (dictionary_0)
     {
         if (dictionary_0.ContainsKey(UserId))
         {
             return(dictionary_0[UserId]);
         }
         using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
         {
             client.SetParameter("id", UserId);
             string str = (string)client.ExecuteScalar("SELECT usuario FROM usuarios WHERE id = @id LIMIT 1");
             if ((str != null) && (str.Length > 0))
             {
                 dictionary_0.Add(UserId, str);
                 return(str);
             }
         }
     }
     return("Usuario desconocido");
 }
示例#24
0
        private static void LoadClanDiplomacy(Clan clan)
        {
            using (var mySqlClient = SqlDatabaseManager.GetClient())
            {
                var data = (DataTable)mySqlClient.ExecuteQueryTable($"SELECT * FROM server_clan_diplomacy WHERE senderClan = {clan.Id}");
                foreach (DataRow row in data.Rows)
                {
                    int       id       = Convert.ToInt32(row["toClan"]);
                    Diplomacy relation = (Diplomacy)Convert.ToInt32(row["diplomacyType"]);
                    clan.Diplomacy.Add(id, relation);
                }

                var data2 = (DataTable)mySqlClient.ExecuteQueryTable($"SELECT * FROM server_clan_diplomacy WHERE toClan = {clan.Id}");
                foreach (DataRow row in data2.Rows)
                {
                    int       id       = Convert.ToInt32(row["senderClan"]);
                    Diplomacy relation = (Diplomacy)Convert.ToInt32(row["diplomacyType"]);
                    clan.Diplomacy.Add(id, relation);
                }
            }
        }
示例#25
0
        /*public static int GetImagesByUserFromDB(uint userId, out List<String> images)
         * {
         *  images = new List<String>();
         *
         *  DataTable table = null;
         *  try
         *  {
         *      using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
         *      {
         *          client.SetParameter("@user_id", userId);
         *          table = client.ExecuteQueryTable("SELECT p.id " +
         *              "FROM Photo AS p " +
         *              "INNER JOIN Member AS m ON m.id = p.member_id " +
         *              "WHERE m.id = @user_id;");
         *
         *      }
         *  }
         *  catch (Exception e)
         *  {
         *      Logger.WriteLine(e.ToString(), Logger.LOG_LEVEL.WARN);
         *  }
         *
         *  if (table == null)
         *      return -1;
         *
         *  foreach (DataRow row in table.Rows)
         *  {
         *      images.Add(URL_TO_IMAGE + row["id"].ToString());
         *  }
         *
         *  return 0;
         * }*/

        public static int GetUserFromDB(uint userId, out LocalUser user)
        {
            DataRow row = null;

            user = null;

            try
            {
                using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
                {
                    client.SetParameter("@user_id", userId);
                    row = client.ExecuteQueryRow("SELECT m.id, m.name, m.role, m.profile_photo_format, a.id AS admin_id " +
                                                 "FROM Member AS m " +
                                                 "LEFT JOIN Administrator AS a ON m.id = a.member_id " +
                                                 "WHERE m.id = @user_id;");
                }
            }
            catch (Exception e)
            {
                Logger.WriteLine(e.ToString(), Logger.LOG_LEVEL.WARN);
            }

            if (row == null)
            {
                return(-1);
            }

            //uint profilePhoto = UInt32.TryParse(row["profile_photo"].ToString(), out profilePhoto) ? profilePhoto : 0;
            uint adminID = UInt32.TryParse(row["admin_id"].ToString(), out adminID) ? adminID : 0;

            user                    = new LocalUser();
            user.UserID             = userId;
            user.Role               = row["role"].ToString();
            user.IsOwner            = adminID > 0;
            user.Name               = row["name"].ToString();
            user.ProfilePhoto       = URL_USER_IMAGE + userId.ToString() + URL_USER_PROFILE_IMAGE;
            user.ProfilePhotoFormat = row["profile_photo_format"].ToString() == "2" ? "image/png" : "image/jpeg";

            return(0);
        }
示例#26
0
        public bool UpdateDatabase(ConnectionSettings settings, string scriptDirectory, RequestedDatabaseAction action)
        {
            var manager = new SqlDatabaseManager();

            var taskAttributes = new TaskAttributes(settings, scriptDirectory)
            {
                RequestedDatabaseAction = action,
            };

            try
            {
                manager.Upgrade(taskAttributes, this);

                foreach (var property in _properties)
                {
                    Log(property.Key + ": " + property.Value);
                }
                return(true);
            }
            catch (Exception exception)
            {
                var ex = exception;
                do
                {
                    Log("Failure: " + ex.Message);
                    if (ex.Data["Custom"] != null)
                    {
                        Log(ex.Data["Custom"].ToString());
                    }
                    ex = ex.InnerException;
                } while (ex != null);
            }

            if (Debugger.IsAttached)
            {
                System.Console.ReadLine();
            }

            return(false);
        }
示例#27
0
        private static void RespectUser(Session Session, ClientMessage Message)
        {
            RoomInstance Instance = RoomManager.GetInstanceByRoomId(Session.CurrentRoomId);

            if (Instance == null || Session.CharacterInfo.RespectCreditHuman <= 0)
            {
                return;
            }

            RoomActor TargetActor = Instance.GetActorByReferenceId(Message.PopWiredUInt32());

            if (TargetActor == null)
            {
                return;
            }

            Session TargetSession = SessionManager.GetSessionByCharacterId(TargetActor.ReferenceId);

            if (TargetSession == null)
            {
                return;
            }

            TargetSession.CharacterInfo.RespectPoints++;
            Session.CharacterInfo.RespectCreditHuman--;

            Instance.BroadcastMessage(RoomUserRespectedComposer.Compose(TargetSession.CharacterId,
                                                                        TargetSession.CharacterInfo.RespectPoints));

            using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
            {
                TargetSession.CharacterInfo.SynchronizeRespectData(MySqlClient);
                Session.CharacterInfo.SynchronizeRespectData(MySqlClient);

                AchievementManager.ProgressUserAchievement(MySqlClient, TargetSession, "ACH_RespectEarned", 1);
                AchievementManager.ProgressUserAchievement(MySqlClient, Session, "ACH_RespectGiven", 1);
            }

            QuestManager.ProgressUserQuest(Session, QuestType.SOCIAL_RESPECT);
        }
示例#28
0
        protected override void ExecuteTask()
        {
            try
            {
                var manager        = new SqlDatabaseManager();
                var settings       = new ConnectionSettings(Server, Database, IntegratedAuthentication, Username, Password);
                var taskAttributes = new TaskAttributes(settings, ScriptDirectory.FullName)
                {
                    SkipFileNameContaining  = SkipFileNameContaining,
                    RequestedDatabaseAction = Action,
                };

                manager.Upgrade(taskAttributes, this);
            }
            catch
            {
                if (FailOnError)
                {
                    throw;
                }
            }
        }
示例#29
0
        private static void GetUserInfo(Session Session, ClientMessage Message)
        {
            if (!Session.HasRight("moderation_tool"))
            {
                return;
            }

            CharacterInfo Info = null;

            using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
            {
                Info = CharacterInfoLoader.GetCharacterInfo(MySqlClient, Message.PopWiredUInt32());
            }

            if (Info == null)
            {
                Session.SendData(NotificationMessageComposer.Compose("Could not retrieve user information."));
                return;
            }

            Session.SendData(ModerationUserInfoComposer.Compose(Info, SessionManager.GetSessionByCharacterId(Info.Id)));
        }
示例#30
0
        private static void IsNameTaken(Session Session, ClientMessage Message)
        {
            String Username = Message.PopString();

            using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient())
            {
                MySqlClient.SetParameter("username", Username);
                DataRow Taken = MySqlClient.ExecuteQueryRow("SELECT null FROM characters WHERE username = @username LIMIT 1");
                if (Taken == null)
                {
                    ServerMessage awnser = new ServerMessage(571);
                    awnser.AppendInt32(0);
                    awnser.AppendStringWithBreak(Username);
                    awnser.AppendInt32(0);
                    Session.SendData(awnser);
                }
                else
                {
                    Session.SendData(NameTaken.Compose(Username));
                }
            }
        }
示例#31
0
        public static bool UpdateImageFormatUserFromDB(long userId, int format)
        {
            try
            {
                using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
                {
                    string sql = "UPDATE Member SET profile_photo_format = @format WHERE id = @user_id;";
                    client.SetParameter("@user_id", userId);
                    client.SetParameter("@format", format);

                    if (client.ExecuteNonQuery(sql) == 1)
                    {
                        return(true);
                    }
                }
            }
            catch (DbException)
            {
            }

            return(false);
        }