public void insertRange(PreparedStatement prepStatement, int startIndex, int endIndex) { System.Threading.Thread.Sleep(500); // Console.WriteLine("Inserting values from " + startIndex + " to " + endIndex); Stopwatch t = Stopwatch.StartNew(); for (int idx = startIndex; idx < endIndex; idx++) { try { Session.Execute( prepStatement .Bind(new object[] { idx, "author"+idx, idx % 2 == 0 ? false : true, "body"+idx }).SetConsistencyLevel(ConsistencyLevel.Quorum)); } catch (Exception ex) { Console.WriteLine("Error while inserting " + ex.StackTrace); } } var elapsedMs = t.ElapsedMilliseconds; Interlocked.Add(ref totalElapsedTime, elapsedMs); var avg = elapsedMs / (endIndex - startIndex); // Console.WriteLine("... Inserted values from " + startIndex + " to " + endIndex + " avg:" + avg + "ms"); }
public void insertRange(PreparedStatement prepStatement, int startIndex, int endIndex) { // Console.WriteLine("Inserting values from " + startIndex + " to " + endIndex); Stopwatch t = Stopwatch.StartNew(); int pendingJobs = 0; for (int idx = startIndex; idx < endIndex; idx++) { Interlocked.Increment(ref pendingJobs); Session.BeginExecute( prepStatement .Bind(new object[] { idx, "author"+idx, idx % 2 == 0 ? false : true, "body"+idx }).SetConsistencyLevel(ConsistencyLevel.One), (ar) => { try { Session.EndExecute(ar); } catch (NoHostAvailableException ex) { foreach( var node in ex.Errors) { Console.WriteLine("Error on " + node.Key.ToString()); var expts = node.Value; foreach(var excpt in expts) Console.WriteLine(" Error while inserting " + excpt.StackTrace + "\n!!!MESSAGE!!!\n" + excpt.Message); } } catch (Exception ex) { Console.WriteLine("Error while inserting " + ex.StackTrace + "\n!!!MESSAGE!!!\n" + ex.Message ); } finally { Interlocked.Decrement(ref pendingJobs); } }, null); } while (true) { Thread.MemoryBarrier(); if (pendingJobs == 0) break; Thread.Sleep(10); } var elapsedMs = t.ElapsedMilliseconds; // _writeHistogram.Update(elapsedMs); Interlocked.Add(ref totalElapsedTime, elapsedMs); var avg = elapsedMs / (endIndex - startIndex); // Console.WriteLine("... Inserted values from " + startIndex + " to " + endIndex + " avg:" + avg +"ms"); }
internal static void ExecutePreparedQuery(Session session, PreparedStatement prepared, object[] values, ConsistencyLevel consistency = ConsistencyLevel.Default, string messageInstead = null) { if (messageInstead != null) Console.WriteLine("CQL<\t" + messageInstead); else Console.WriteLine("CQL< Executing Prepared Query:\t"); session.Execute(prepared.Bind(values).SetConsistencyLevel(consistency)); Console.WriteLine("CQL> (OK)."); }
protected override void TestFixtureSetUp() { base.TestFixtureSetUp(); Session.CreateKeyspaceIfNotExists(Keyspace); try { Session.Execute(String.Format(TestUtils.CreateTableAllTypes, AllTypesTableName)); } catch (Cassandra.AlreadyExistsException) { } var insertQuery = String.Format("INSERT INTO {0} (id, timeuuid_sample) VALUES (?, ?)", AllTypesTableName); var selectQuery = String.Format("SELECT id, timeuuid_sample, dateOf(timeuuid_sample) FROM {0} WHERE id = ?", AllTypesTableName); _insertPrepared = Session.Prepare(insertQuery); _selectPrepared = Session.Prepare(selectQuery); }
private ITestCluster SetupSessionAndCluster(int nodes, Dictionary<string, string> replication = null) { ITestCluster testCluster = TestClusterManager.GetTestCluster(nodes); _session = testCluster.Session; _ksName = TestUtils.GetUniqueKeyspaceName(); _session.CreateKeyspace(_ksName, replication); TestUtils.WaitForSchemaAgreement(_session.Cluster); _session.ChangeKeyspace(_ksName); _table = new Table<ManyDataTypesEntity>(_session, new MappingConfiguration()); _table.Create(); _defaultPocoList = ManyDataTypesEntity.GetDefaultAllDataTypesList(); _preparedStatement = _session.Prepare(_preparedInsertStatementAsString); foreach (var manyDataTypesEntity in _defaultPocoList) _session.Execute(GetBoundInsertStatementBasedOnEntity(manyDataTypesEntity)); return testCluster; }
/// <summary> /// Build the PreparedStatement /// </summary> /// <param name="session"></param> /// <param name="sqlStatement"></param> public void BuildPreparedStatement(ISqlMapSession session, string sqlStatement) { RequestScope request = new RequestScope( _dataExchangeFactory, session, _statement); PreparedStatementFactory factory = new PreparedStatementFactory( session, request, _statement, sqlStatement); _preparedStatement = factory.Prepare(); }
static bool HandleCharacterRenameCommand(StringArguments args, CommandHandler handler) { Player target; ObjectGuid targetGuid; string targetName; if (!handler.extractPlayerTarget(args, out target, out targetGuid, out targetName)) { return(false); } string newNameStr = args.NextString(); if (!string.IsNullOrEmpty(newNameStr)) { string playerOldName; string newName = newNameStr; if (target) { // check online security if (handler.HasLowerSecurity(target, ObjectGuid.Empty)) { return(false); } playerOldName = target.GetName(); } else { // check offline security if (handler.HasLowerSecurity(null, targetGuid)) { return(false); } ObjectManager.GetPlayerNameByGUID(targetGuid, out playerOldName); } if (!ObjectManager.NormalizePlayerName(ref newName)) { handler.SendSysMessage(CypherStrings.BadValue); return(false); } if (ObjectManager.CheckPlayerName(newName, target ? target.GetSession().GetSessionDbcLocale() : Global.WorldMgr.GetDefaultDbcLocale(), true) != ResponseCodes.CharNameSuccess) { handler.SendSysMessage(CypherStrings.BadValue); return(false); } WorldSession session = handler.GetSession(); if (session != null) { if (!session.HasPermission(RBACPermissions.SkipCheckCharacterCreationReservedname) && Global.ObjectMgr.IsReservedName(newName)) { handler.SendSysMessage(CypherStrings.ReservedName); return(false); } } PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_CHECK_NAME); stmt.AddValue(0, newName); SQLResult result = DB.Characters.Query(stmt); if (!result.IsEmpty()) { handler.SendSysMessage(CypherStrings.RenamePlayerAlreadyExists, newName); return(false); } // Remove declined name from db stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_CHAR_DECLINED_NAME); stmt.AddValue(0, targetGuid.GetCounter()); DB.Characters.Execute(stmt); if (target) { target.SetName(newName); session = target.GetSession(); if (session != null) { session.KickPlayer(); } } else { stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_NAME_BY_GUID); stmt.AddValue(0, newName); stmt.AddValue(1, targetGuid.GetCounter()); DB.Characters.Execute(stmt); } Global.WorldMgr.UpdateCharacterInfo(targetGuid, newName); handler.SendSysMessage(CypherStrings.RenamePlayerWithNewName, playerOldName, newName); Player player = handler.GetPlayer(); if (player) { Log.outCommand(session.GetAccountId(), "GM {0} (Account: {1}) forced rename {2} to player {3} (Account: {4})", player.GetName(), session.GetAccountId(), newName, playerOldName, ObjectManager.GetPlayerAccountIdByGUID(targetGuid)); } else { Log.outCommand(0, "CONSOLE forced rename '{0}' to '{1}' ({2})", playerOldName, newName, targetGuid.ToString()); } } else { if (target) { // check online security if (handler.HasLowerSecurity(target, ObjectGuid.Empty)) { return(false); } handler.SendSysMessage(CypherStrings.RenamePlayer, handler.GetNameLink(target)); target.SetAtLoginFlag(AtLoginFlags.Rename); } else { // check offline security if (handler.HasLowerSecurity(null, targetGuid)) { return(false); } string oldNameLink = handler.playerLink(targetName); handler.SendSysMessage(CypherStrings.RenamePlayerGuid, oldNameLink, targetGuid.ToString()); PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_ADD_AT_LOGIN_FLAG); stmt.AddValue(0, AtLoginFlags.Rename); stmt.AddValue(1, targetGuid.GetCounter()); DB.Characters.Execute(stmt); } } return(true); }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (statement != null) { statement.close(); statement = null; } } }
static bool HandleWpShowCommand(StringArguments args, CommandHandler handler) { if (args.Empty()) { return(false); } // first arg: on, off, first, last string show = args.NextString(); if (string.IsNullOrEmpty(show)) { return(false); } // second arg: GUID (optional, if a creature is selected) string guid_str = args.NextString(); uint pathid = 0; Creature target = handler.getSelectedCreature(); // Did player provide a PathID? if (string.IsNullOrEmpty(guid_str)) { // No PathID provided // . Player must have selected a creature if (!target) { handler.SendSysMessage(CypherStrings.SelectCreature); return(false); } pathid = target.GetWaypointPath(); } else { // PathID provided // Warn if player also selected a creature // . Creature selection is ignored <- if (target) { handler.SendSysMessage(CypherStrings.WaypointCreatselected); } if (!uint.TryParse(guid_str, out pathid)) { return(false); } } // Show info for the selected waypoint if (show == "info") { // Check if the user did specify a visual waypoint if (!target || target.GetEntry() != 1) { handler.SendSysMessage(CypherStrings.WaypointVpSelect); return(false); } PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_ALL_BY_WPGUID); stmt.AddValue(0, target.GetSpawnId()); SQLResult result = DB.World.Query(stmt); if (result.IsEmpty()) { handler.SendSysMessage(CypherStrings.WaypointNotfounddbproblem, target.GetSpawnId()); return(true); } handler.SendSysMessage("|cff00ffffDEBUG: wp show info:|r"); do { pathid = result.Read <uint>(0); uint point = result.Read <uint>(1); uint delay = result.Read <uint>(2); uint flag = result.Read <uint>(3); uint ev_id = result.Read <uint>(4); uint ev_chance = result.Read <uint>(5); handler.SendSysMessage("|cff00ff00Show info: for current point: |r|cff00ffff{0}|r|cff00ff00, Path ID: |r|cff00ffff{1}|r", point, pathid); handler.SendSysMessage("|cff00ff00Show info: delay: |r|cff00ffff{0}|r", delay); handler.SendSysMessage("|cff00ff00Show info: Move flag: |r|cff00ffff{0}|r", flag); handler.SendSysMessage("|cff00ff00Show info: Waypoint event: |r|cff00ffff{0}|r", ev_id); handler.SendSysMessage("|cff00ff00Show info: Event chance: |r|cff00ffff{0}|r", ev_chance); }while (result.NextRow()); return(true); } if (show == "on") { PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_POS_BY_ID); stmt.AddValue(0, pathid); SQLResult result = DB.World.Query(stmt); if (result.IsEmpty()) { handler.SendSysMessage("|cffff33ffPath no found.|r"); return(false); } handler.SendSysMessage("|cff00ff00DEBUG: wp on, PathID: |cff00ffff{0}|r", pathid); // Delete all visuals for this NPC stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_WPGUID_BY_ID); stmt.AddValue(0, pathid); SQLResult result2 = DB.World.Query(stmt); if (!result2.IsEmpty()) { bool hasError = false; do { ulong wpguid = result2.Read <ulong>(0); Creature creature = handler.GetCreatureFromPlayerMapByDbGuid(wpguid); if (!creature) { handler.SendSysMessage(CypherStrings.WaypointNotremoved, wpguid); hasError = true; stmt = DB.World.GetPreparedStatement(WorldStatements.DEL_CREATURE); stmt.AddValue(0, wpguid); DB.World.Execute(stmt); } else { creature.CombatStop(); creature.DeleteFromDB(); creature.AddObjectToRemoveList(); } }while (result2.NextRow()); if (hasError) { handler.SendSysMessage(CypherStrings.WaypointToofar1); handler.SendSysMessage(CypherStrings.WaypointToofar2); handler.SendSysMessage(CypherStrings.WaypointToofar3); } } do { uint point = result.Read <uint>(0); float x = result.Read <float>(1); float y = result.Read <float>(2); float z = result.Read <float>(3); uint id = 1; Player chr = handler.GetSession().GetPlayer(); Map map = chr.GetMap(); Position pos = new Position(x, y, z, chr.GetOrientation()); Creature creature = Creature.CreateCreature(id, map, pos); if (!creature) { handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, id); return(false); } creature.CopyPhaseFrom(chr); creature.SaveToDB(map.GetId(), 1ul << (int)map.GetSpawnMode()); ulong dbGuid = creature.GetSpawnId(); // current "wpCreature" variable is deleted and created fresh new, otherwise old values might trigger asserts or cause undefined behavior creature.CleanupsBeforeDelete(); creature.Dispose(); // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells(); creature = Creature.CreateCreatureFromDB(dbGuid, map); if (!creature) { handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, id); return(false); } if (target) { creature.SetDisplayId(target.GetDisplayId()); creature.SetObjectScale(0.5f); creature.SetLevel(Math.Min(point, SharedConst.StrongMaxLevel)); } // Set "wpguid" column to the visual waypoint stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_DATA_WPGUID); stmt.AddValue(0, creature.GetSpawnId()); stmt.AddValue(1, pathid); stmt.AddValue(2, point); DB.World.Execute(stmt); }while (result.NextRow()); handler.SendSysMessage("|cff00ff00Showing the current creature's path.|r"); return(true); } if (show == "first") { handler.SendSysMessage("|cff00ff00DEBUG: wp first, pathid: {0}|r", pathid); PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_POS_FIRST_BY_ID); stmt.AddValue(0, pathid); SQLResult result = DB.World.Query(stmt); if (result.IsEmpty()) { handler.SendSysMessage(CypherStrings.WaypointNotfound, pathid); return(false); } float x = result.Read <float>(0); float y = result.Read <float>(1); float z = result.Read <float>(2); Player chr = handler.GetSession().GetPlayer(); Map map = chr.GetMap(); Position pos = new Position(x, y, z, chr.GetOrientation()); Creature creature = Creature.CreateCreature(1, map, pos); if (!creature) { handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, 1); return(false); } creature.CopyPhaseFrom(chr); creature.SaveToDB(map.GetId(), 1ul << (int)map.GetSpawnMode()); ulong dbGuid = creature.GetSpawnId(); // current "creature" variable is deleted and created fresh new, otherwise old values might trigger asserts or cause undefined behavior creature.CleanupsBeforeDelete(); creature.Dispose(); creature = Creature.CreateCreatureFromDB(dbGuid, map); if (!creature) { handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, 1); return(false); } if (target) { creature.SetDisplayId(target.GetDisplayId()); creature.SetObjectScale(0.5f); } return(true); } if (show == "last") { handler.SendSysMessage("|cff00ff00DEBUG: wp last, PathID: |r|cff00ffff{0}|r", pathid); PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_POS_LAST_BY_ID); stmt.AddValue(0, pathid); SQLResult result = DB.World.Query(stmt); if (result.IsEmpty()) { handler.SendSysMessage(CypherStrings.WaypointNotfoundlast, pathid); return(false); } float x = result.Read <float>(0); float y = result.Read <float>(1); float z = result.Read <float>(2); float o = result.Read <float>(3); Player chr = handler.GetSession().GetPlayer(); Map map = chr.GetMap(); Position pos = new Position(x, y, z, o); Creature creature = Creature.CreateCreature(1, map, pos); if (!creature) { handler.SendSysMessage(CypherStrings.WaypointNotcreated, 1); return(false); } creature.CopyPhaseFrom(chr); creature.SaveToDB(map.GetId(), 1ul << (int)map.GetSpawnMode()); ulong dbGuid = creature.GetSpawnId(); // current "creature" variable is deleted and created fresh new, otherwise old values might trigger asserts or cause undefined behavior creature.CleanupsBeforeDelete(); creature.Dispose(); creature = Creature.CreateCreatureFromDB(dbGuid, map); if (!creature) { handler.SendSysMessage(CypherStrings.WaypointNotcreated, 1); return(false); } if (target) { creature.SetDisplayId(target.GetDisplayId()); creature.SetObjectScale(0.5f); } return(true); } if (show == "off") { PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_CREATURE_BY_ID); stmt.AddValue(0, 1); SQLResult result = DB.World.Query(stmt); if (result.IsEmpty()) { handler.SendSysMessage(CypherStrings.WaypointVpNotfound); return(false); } bool hasError = false; do { ulong lowguid = result.Read <ulong>(0); Creature creature = handler.GetCreatureFromPlayerMapByDbGuid(lowguid); if (!creature) { handler.SendSysMessage(CypherStrings.WaypointNotremoved, lowguid); hasError = true; stmt = DB.World.GetPreparedStatement(WorldStatements.DEL_CREATURE); stmt.AddValue(0, lowguid); DB.World.Execute(stmt); } else { creature.CombatStop(); creature.DeleteFromDB(); creature.AddObjectToRemoveList(); } }while (result.NextRow()); // set "wpguid" column to "empty" - no visual waypoint spawned stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_DATA_ALL_WPGUID); DB.World.Execute(stmt); //DB.World.PExecute("UPDATE creature_movement SET wpguid = '0' WHERE wpguid <> '0'"); if (hasError) { handler.SendSysMessage(CypherStrings.WaypointToofar1); handler.SendSysMessage(CypherStrings.WaypointToofar2); handler.SendSysMessage(CypherStrings.WaypointToofar3); } handler.SendSysMessage(CypherStrings.WaypointVpAllremoved); return(true); } handler.SendSysMessage("|cffff33ffDEBUG: wpshow - no valid command found|r"); return(true); }
public void SendAuctionWonMail(AuctionEntry auction, SQLTransaction trans) { Item item = GetAItem(auction.itemGUIDLow); if (!item) { return; } uint bidderAccId = 0; ObjectGuid bidderGuid = ObjectGuid.Create(HighGuid.Player, auction.bidder); Player bidder = Global.ObjAccessor.FindPlayer(bidderGuid); // data for gm.log string bidderName = ""; bool logGmTrade = false; if (bidder) { bidderAccId = bidder.GetSession().GetAccountId(); bidderName = bidder.GetName(); logGmTrade = bidder.GetSession().HasPermission(RBACPermissions.LogGmTrade); } else { bidderAccId = Global.CharacterCacheStorage.GetCharacterAccountIdByGuid(bidderGuid); logGmTrade = Global.AccountMgr.HasPermission(bidderAccId, RBACPermissions.LogGmTrade, Global.WorldMgr.GetRealm().Id.Realm); if (logGmTrade && !Global.CharacterCacheStorage.GetCharacterNameByGuid(bidderGuid, out bidderName)) { bidderName = Global.ObjectMgr.GetCypherString(CypherStrings.Unknown); } } if (logGmTrade) { ObjectGuid ownerGuid = ObjectGuid.Create(HighGuid.Player, auction.owner); string ownerName; if (!Global.CharacterCacheStorage.GetCharacterNameByGuid(ownerGuid, out ownerName)) { ownerName = Global.ObjectMgr.GetCypherString(CypherStrings.Unknown); } uint ownerAccId = Global.CharacterCacheStorage.GetCharacterAccountIdByGuid(ownerGuid); Log.outCommand(bidderAccId, $"GM {bidderName} (Account: {bidderAccId}) won item in auction: {item.GetTemplate().GetName()} (Entry: {item.GetEntry()} Count: {item.GetCount()}) and pay money: {auction.bid}. Original owner {ownerName} (Account: {ownerAccId})"); } // receiver exist if (bidder || bidderAccId != 0) { // set owner to bidder (to prevent delete item with sender char deleting) // owner in `data` will set at mail receive and item extracting PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_ITEM_OWNER); stmt.AddValue(0, auction.bidder); stmt.AddValue(1, item.GetGUID().GetCounter()); trans.Append(stmt); if (bidder) { bidder.GetSession().SendAuctionWonNotification(auction, item); // FIXME: for offline player need also bidder.UpdateCriteria(CriteriaTypes.WonAuctions, 1); } new MailDraft(auction.BuildAuctionMailSubject(MailAuctionAnswers.Won), AuctionEntry.BuildAuctionMailBody(auction.owner, auction.bid, auction.buyout, 0, 0)) .AddItem(item) .SendMailTo(trans, new MailReceiver(bidder, auction.bidder), new MailSender(auction), MailCheckMask.Copied); } else { // bidder doesn't exist, delete the item Global.AuctionMgr.RemoveAItem(auction.itemGUIDLow, true); } }
/// <summary> /// Build the PreparedStatement /// </summary> /// <param name="session"></param> /// <param name="commandText"></param> /// <param name="request"></param> public PreparedStatement BuildPreparedStatement(ISqlMapSession session, RequestScope request, string commandText) { if ( _preparedStatement == null ) { lock(_synRoot) { if (_preparedStatement==null) { PreparedStatementFactory factory = new PreparedStatementFactory( session, request, _statement, commandText); _preparedStatement = factory.Prepare(); } } } return _preparedStatement; }
static bool HandleWpLoadCommand(StringArguments args, CommandHandler handler) { if (args.Empty()) { return(false); } // optional string path_number = args.NextString(); uint pathid; ulong guidLow; Creature target = handler.getSelectedCreature(); // Did player provide a path_id? if (string.IsNullOrEmpty(path_number)) { return(false); } if (!target) { handler.SendSysMessage(CypherStrings.SelectCreature); return(false); } if (target.GetEntry() == 1) { handler.SendSysMessage("|cffff33ffYou want to load path to a waypoint? Aren't you?|r"); return(false); } if (!uint.TryParse(path_number, out pathid) || pathid == 0) { handler.SendSysMessage("|cffff33ffNo valid path number provided.|r"); return(true); } guidLow = target.GetSpawnId(); PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_CREATURE_ADDON_BY_GUID); stmt.AddValue(0, guidLow); SQLResult result = DB.World.Query(stmt); if (!result.IsEmpty()) { stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_CREATURE_ADDON_PATH); stmt.AddValue(0, pathid); stmt.AddValue(1, guidLow); } else { stmt = DB.World.GetPreparedStatement(WorldStatements.INS_CREATURE_ADDON); stmt.AddValue(0, guidLow); stmt.AddValue(1, pathid); } DB.World.Execute(stmt); stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_CREATURE_MOVEMENT_TYPE); stmt.AddValue(0, (byte)MovementGeneratorType.Waypoint); stmt.AddValue(1, guidLow); DB.World.Execute(stmt); target.LoadPath(pathid); target.SetDefaultMovementType(MovementGeneratorType.Waypoint); target.GetMotionMaster().Initialize(); target.Say("Path loaded.", Language.Universal); return(true); }
public BattlenetRpcErrorCode HandleVerifyWebCredentials(Bgs.Protocol.Authentication.V1.VerifyWebCredentialsRequest verifyWebCredentialsRequest) { if (verifyWebCredentialsRequest.WebCredentials.IsEmpty) { return(BattlenetRpcErrorCode.Denied); } PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_BNET_ACCOUNT_INFO); stmt.AddValue(0, verifyWebCredentialsRequest.WebCredentials.ToStringUtf8()); SQLResult result = DB.Login.Query(stmt); if (result.IsEmpty()) { return(BattlenetRpcErrorCode.Denied); } _accountInfo = new AccountInfo(); _accountInfo.LoadResult(result); if (_accountInfo.LoginTicketExpiry < Time.UnixTime) { return(BattlenetRpcErrorCode.TimedOut); } stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_BNET_CHARACTER_COUNTS_BY_BNET_ID); stmt.AddValue(0, _accountInfo.Id); SQLResult characterCountsResult = DB.Login.Query(stmt); if (!characterCountsResult.IsEmpty()) { do { RealmHandle realmId = new RealmHandle(characterCountsResult.Read <byte>(3), characterCountsResult.Read <byte>(4), characterCountsResult.Read <uint>(2)); _accountInfo.GameAccounts[characterCountsResult.Read <uint>(0)].CharacterCounts[realmId.GetAddress()] = characterCountsResult.Read <byte>(1); } while (characterCountsResult.NextRow()); } stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_BNET_LAST_PLAYER_CHARACTERS); stmt.AddValue(0, _accountInfo.Id); SQLResult lastPlayerCharactersResult = DB.Login.Query(stmt); if (!lastPlayerCharactersResult.IsEmpty()) { do { RealmHandle realmId = new RealmHandle(lastPlayerCharactersResult.Read <byte>(1), lastPlayerCharactersResult.Read <byte>(2), lastPlayerCharactersResult.Read <uint>(3)); LastPlayedCharacterInfo lastPlayedCharacter = new LastPlayedCharacterInfo(); lastPlayedCharacter.RealmId = realmId; lastPlayedCharacter.CharacterName = lastPlayerCharactersResult.Read <string>(4); lastPlayedCharacter.CharacterGUID = lastPlayerCharactersResult.Read <ulong>(5); lastPlayedCharacter.LastPlayedTime = lastPlayerCharactersResult.Read <uint>(6); _accountInfo.GameAccounts[lastPlayerCharactersResult.Read <uint>(0)].LastPlayedCharacters[realmId.GetSubRegionAddress()] = lastPlayedCharacter; } while (lastPlayerCharactersResult.NextRow()); } string ip_address = GetRemoteIpAddress().ToString(); // If the IP is 'locked', check that the player comes indeed from the correct IP address if (_accountInfo.IsLockedToIP) { Log.outDebug(LogFilter.Session, "Session.HandleVerifyWebCredentials: Account '{0}' is locked to IP - '{1}' is logging in from '{2}'", _accountInfo.Login, _accountInfo.LastIP, ip_address); if (_accountInfo.LastIP != ip_address) { return(BattlenetRpcErrorCode.RiskAccountLocked); } } else { Log.outDebug(LogFilter.Session, "Session.HandleVerifyWebCredentials: Account '{0}' is not locked to ip", _accountInfo.Login); if (_accountInfo.LockCountry.IsEmpty() || _accountInfo.LockCountry == "00") { Log.outDebug(LogFilter.Session, "Session.HandleVerifyWebCredentials: Account '{0}' is not locked to country", _accountInfo.Login); } else if (!_accountInfo.LockCountry.IsEmpty() && !_ipCountry.IsEmpty()) { Log.outDebug(LogFilter.Session, "Session.HandleVerifyWebCredentials: Account '{0}' is locked to country: '{1}' Player country is '{2}'", _accountInfo.Login, _accountInfo.LockCountry, _ipCountry); if (_ipCountry != _accountInfo.LockCountry) { return(BattlenetRpcErrorCode.RiskAccountLocked); } } } // If the account is banned, reject the logon attempt if (_accountInfo.IsBanned) { if (_accountInfo.IsPermanenetlyBanned) { Log.outDebug(LogFilter.Session, "{0} Session.HandleVerifyWebCredentials: Banned account {1} tried to login!", GetClientInfo(), _accountInfo.Login); return(BattlenetRpcErrorCode.GameAccountBanned); } else { Log.outDebug(LogFilter.Session, "{0} Session.HandleVerifyWebCredentials: Temporarily banned account {1} tried to login!", GetClientInfo(), _accountInfo.Login); return(BattlenetRpcErrorCode.GameAccountSuspended); } } Bgs.Protocol.Authentication.V1.LogonResult logonResult = new Bgs.Protocol.Authentication.V1.LogonResult(); logonResult.ErrorCode = 0; logonResult.AccountId = new EntityId(); logonResult.AccountId.Low = _accountInfo.Id; logonResult.AccountId.High = 0x100000000000000; foreach (var pair in _accountInfo.GameAccounts) { EntityId gameAccountId = new EntityId(); gameAccountId.Low = pair.Value.Id; gameAccountId.High = 0x200000200576F57; logonResult.GameAccountId.Add(gameAccountId); } if (!_ipCountry.IsEmpty()) { logonResult.GeoipCountry = _ipCountry; } logonResult.SessionKey = ByteString.CopyFrom(new byte[64].GenerateRandomKey(64)); _authed = true; SendRequest((uint)OriginalHash.AuthenticationListener, 5, logonResult); return(BattlenetRpcErrorCode.Ok); }
public void LoadAzeriteItemData(Player owner, AzeriteData azeriteData) { bool needSave = false; if (!CliDB.AzeriteLevelInfoStorage.ContainsKey(azeriteData.Level)) { azeriteData.Xp = 0; azeriteData.Level = 1; azeriteData.KnowledgeLevel = GetCurrentKnowledgeLevel(); needSave = true; } else if (azeriteData.Level > PlayerConst.MaxAzeriteItemLevel) { azeriteData.Xp = 0; azeriteData.Level = PlayerConst.MaxAzeriteItemLevel; needSave = true; } if (azeriteData.KnowledgeLevel != GetCurrentKnowledgeLevel()) { // rescale XP to maintain same progress % ulong oldMax = CalcTotalXPToNextLevel(azeriteData.Level, azeriteData.KnowledgeLevel); azeriteData.KnowledgeLevel = GetCurrentKnowledgeLevel(); ulong newMax = CalcTotalXPToNextLevel(azeriteData.Level, azeriteData.KnowledgeLevel); azeriteData.Xp = (ulong)(azeriteData.Xp / (double)oldMax * newMax); needSave = true; } else if (azeriteData.KnowledgeLevel > PlayerConst.MaxAzeriteItemKnowledgeLevel) { azeriteData.KnowledgeLevel = PlayerConst.MaxAzeriteItemKnowledgeLevel; needSave = true; } SetUpdateFieldValue(m_values.ModifyValue(m_azeriteItemData).ModifyValue(m_azeriteItemData.Xp), azeriteData.Xp); SetUpdateFieldValue(m_values.ModifyValue(m_azeriteItemData).ModifyValue(m_azeriteItemData.Level), azeriteData.Level); SetUpdateFieldValue(m_values.ModifyValue(m_azeriteItemData).ModifyValue(m_azeriteItemData.KnowledgeLevel), azeriteData.KnowledgeLevel); foreach (uint azeriteItemMilestonePowerId in azeriteData.AzeriteItemMilestonePowers) { AddUnlockedEssenceMilestone(azeriteItemMilestonePowerId); } UnlockDefaultMilestones(); foreach (AzeriteEssencePowerRecord unlockedAzeriteEssence in azeriteData.UnlockedAzeriteEssences) { SetEssenceRank((uint)unlockedAzeriteEssence.AzeriteEssenceID, unlockedAzeriteEssence.Tier); } foreach (AzeriteItemSelectedEssencesData selectedEssenceData in azeriteData.SelectedAzeriteEssences) { if (selectedEssenceData.SpecializationId == 0) { continue; } var selectedEssences = new SelectedAzeriteEssences(); selectedEssences.ModifyValue(selectedEssences.SpecializationID).SetValue(selectedEssenceData.SpecializationId); for (int i = 0; i < SharedConst.MaxAzeriteEssenceSlot; ++i) { // Check if essence was unlocked if (GetEssenceRank(selectedEssenceData.AzeriteEssenceId[i]) == 0) { continue; } selectedEssences.ModifyValue(selectedEssences.AzeriteEssenceID, i) = selectedEssenceData.AzeriteEssenceId[i]; } if (owner != null && owner.GetPrimarySpecialization() == selectedEssenceData.SpecializationId) { selectedEssences.ModifyValue(selectedEssences.Enabled).SetValue(1); } AddDynamicUpdateFieldValue(m_values.ModifyValue(m_azeriteItemData).ModifyValue(m_azeriteItemData.SelectedEssences), selectedEssences); } // add selected essences for current spec if (owner != null && GetSelectedAzeriteEssences() == null) { CreateSelectedAzeriteEssences(owner.GetPrimarySpecialization()); } if (needSave) { PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_ITEM_INSTANCE_AZERITE_ON_LOAD); stmt.AddValue(0, azeriteData.Xp); stmt.AddValue(1, azeriteData.KnowledgeLevel); stmt.AddValue(2, GetGUID().GetCounter()); DB.Characters.Execute(stmt); } }
internal static PreparedStatement PrepareQuery(ISession session, string query, string messageInstead = null) { PreparedStatement ret = session.Prepare(query); return(ret); }
private void init(CCMBridge.CCMCluster c, int n) { // We don't use insert for our test because the resultSet don't ship the queriedHost // Also note that we don't use tracing because this would trigger requests that screw up the test' for (int i = 0; i < n; ++i) c.Session.Execute(String.Format("INSERT INTO {0}(k, i) VALUES (0, 0)", TABLE)); prepared = c.Session.Prepare("SELECT * FROM " + TABLE + " WHERE k = ?"); }
static bool HandleGroupListCommand(StringArguments args, CommandHandler handler) { // Get ALL the variables! Player playerTarget; ObjectGuid guidTarget; string nameTarget; string zoneName = ""; string onlineState = ""; // Parse the guid to uint32... ObjectGuid parseGUID = ObjectGuid.Create(HighGuid.Player, args.NextUInt64()); // ... and try to extract a player out of it. if (ObjectManager.GetPlayerNameByGUID(parseGUID, out nameTarget)) { playerTarget = Global.ObjAccessor.FindPlayer(parseGUID); guidTarget = parseGUID; } // If not, we return false and end right away. else if (!handler.extractPlayerTarget(args, out playerTarget, out guidTarget, out nameTarget)) { return(false); } // Next, we need a group. So we define a group variable. Group groupTarget = null; // We try to extract a group from an online player. if (playerTarget) { groupTarget = playerTarget.GetGroup(); } // If not, we extract it from the SQL. if (!groupTarget) { PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GROUP_MEMBER); stmt.AddValue(0, guidTarget.GetCounter()); SQLResult resultGroup = DB.Characters.Query(stmt); if (!resultGroup.IsEmpty()) { groupTarget = Global.GroupMgr.GetGroupByDbStoreId(resultGroup.Read <uint>(0)); } } // If both fails, players simply has no party. Return false. if (!groupTarget) { handler.SendSysMessage(CypherStrings.GroupNotInGroup, nameTarget); return(false); } // We get the group members after successfully detecting a group. var members = groupTarget.GetMemberSlots(); // To avoid a cluster f**k, namely trying multiple queries to simply get a group member count... handler.SendSysMessage(CypherStrings.GroupType, (groupTarget.isRaidGroup() ? "raid" : "party"), members.Count); // ... we simply move the group type and member count print after retrieving the slots and simply output it's size. // While rather dirty codestyle-wise, it saves space (if only a little). For each member, we look several informations up. foreach (var slot in members) { // Check for given flag and assign it to that iterator string flags = ""; if (slot.flags.HasAnyFlag(GroupMemberFlags.Assistant)) { flags = "Assistant"; } if (slot.flags.HasAnyFlag(GroupMemberFlags.MainTank)) { if (!string.IsNullOrEmpty(flags)) { flags += ", "; } flags += "MainTank"; } if (slot.flags.HasAnyFlag(GroupMemberFlags.MainAssist)) { if (!string.IsNullOrEmpty(flags)) { flags += ", "; } flags += "MainAssist"; } if (string.IsNullOrEmpty(flags)) { flags = "None"; } // Check if iterator is online. If is... Player p = Global.ObjAccessor.FindPlayer(slot.guid); string phases = ""; if (p && p.IsInWorld) { // ... than, it prints information like "is online", where he is, etc... onlineState = "online"; phases = string.Join(", ", p.GetPhases()); AreaTableRecord area = CliDB.AreaTableStorage.LookupByKey(p.GetAreaId()); if (area != null) { AreaTableRecord zone = CliDB.AreaTableStorage.LookupByKey(area.ParentAreaID); if (zone != null) { zoneName = zone.AreaName[handler.GetSessionDbcLocale()]; } } } else { // ... else, everything is set to offline or neutral values. zoneName = "<ERROR>"; onlineState = "Offline"; } // Now we can print those informations for every single member of each group! handler.SendSysMessage(CypherStrings.GroupPlayerNameGuid, slot.name, onlineState, zoneName, phases, slot.guid.ToString(), flags, LFGQueue.GetRolesString(slot.roles)); } // And finish after every iterator is done. return(true); }
void HandleOpenItem(OpenItem packet) { Player player = GetPlayer(); // ignore for remote control state if (player.m_unitMovedByMe != player) { return; } Item item = player.GetItemByPos(packet.Slot, packet.PackSlot); if (!item) { player.SendEquipError(InventoryResult.ItemNotFound); return; } ItemTemplate proto = item.GetTemplate(); if (proto == null) { player.SendEquipError(InventoryResult.ItemNotFound, item); return; } // Verify that the bag is an actual bag or wrapped item that can be used "normally" if (!proto.GetFlags().HasAnyFlag(ItemFlags.HasLoot) && !item.HasFlag(ItemFields.Flags, ItemFieldFlags.Wrapped)) { player.SendEquipError(InventoryResult.ClientLockedOut, item); Log.outError(LogFilter.Network, "Possible hacking attempt: Player {0} [guid: {1}] tried to open item [guid: {2}, entry: {3}] which is not openable!", player.GetName(), player.GetGUID().ToString(), item.GetGUID().ToString(), proto.GetId()); return; } // locked item uint lockId = proto.GetLockID(); if (lockId != 0) { LockRecord lockInfo = CliDB.LockStorage.LookupByKey(lockId); if (lockInfo == null) { player.SendEquipError(InventoryResult.ItemLocked, item); Log.outError(LogFilter.Network, "WORLD:OpenItem: item [guid = {0}] has an unknown lockId: {1}!", item.GetGUID().ToString(), lockId); return; } // was not unlocked yet if (item.IsLocked()) { player.SendEquipError(InventoryResult.ItemLocked, item); return; } } if (item.HasFlag(ItemFields.Flags, ItemFieldFlags.Wrapped))// wrapped? { PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_CHARACTER_GIFT_BY_ITEM); stmt.AddValue(0, item.GetGUID().GetCounter()); SQLResult result = DB.Characters.Query(stmt); if (!result.IsEmpty()) { uint entry = result.Read <uint>(0); uint flags = result.Read <uint>(1); item.SetUInt64Value(ItemFields.GiftCreator, 0); item.SetEntry(entry); item.SetUInt32Value(ItemFields.Flags, flags); item.SetState(ItemUpdateState.Changed, player); } else { Log.outError(LogFilter.Network, "Wrapped item {0} don't have record in character_gifts table and will deleted", item.GetGUID().ToString()); player.DestroyItem(item.GetBagSlot(), item.GetSlot(), true); return; } stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_GIFT); stmt.AddValue(0, item.GetGUID().GetCounter()); DB.Characters.Execute(stmt); } else { player.SendLoot(item.GetGUID(), LootType.Corpse); } }
void _ResetOrWarnAll(uint mapid, Difficulty difficulty, bool warn, long resetTime) { // global reset for all instances of the given map MapRecord mapEntry = CliDB.MapStorage.LookupByKey(mapid); if (!mapEntry.Instanceable()) { return; } Log.outDebug(LogFilter.Misc, "InstanceSaveManager.ResetOrWarnAll: Processing map {0} ({1}) on difficulty {2} (warn? {3})", mapEntry.MapName[Global.WorldMgr.GetDefaultDbcLocale()], mapid, difficulty, warn); long now = Time.UnixTime; if (!warn) { // calculate the next reset time long next_reset = GetSubsequentResetTime(mapid, difficulty, resetTime); if (next_reset == 0) { return; } // delete them from the DB, even if not loaded SQLTransaction trans = new SQLTransaction(); PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_EXPIRED_CHAR_INSTANCE_BY_MAP_DIFF); stmt.AddValue(0, mapid); stmt.AddValue(1, (byte)difficulty); trans.Append(stmt); stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_GROUP_INSTANCE_BY_MAP_DIFF); stmt.AddValue(0, mapid); stmt.AddValue(1, (byte)difficulty); trans.Append(stmt); stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_EXPIRED_INSTANCE_BY_MAP_DIFF); stmt.AddValue(0, mapid); stmt.AddValue(1, (byte)difficulty); trans.Append(stmt); stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_EXPIRE_CHAR_INSTANCE_BY_MAP_DIFF); stmt.AddValue(0, mapid); stmt.AddValue(1, (byte)difficulty); trans.Append(stmt); DB.Characters.CommitTransaction(trans); // promote loaded binds to instances of the given map foreach (var pair in m_instanceSaveById.ToList()) { if (pair.Value.GetMapId() == mapid && pair.Value.GetDifficultyID() == difficulty) { _ResetSave(pair); } } SetResetTimeFor(mapid, difficulty, next_reset); ScheduleReset(true, next_reset - 3600, new InstResetEvent(1, mapid, difficulty, 0)); // Update it in the DB stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_GLOBAL_INSTANCE_RESETTIME); stmt.AddValue(0, (uint)next_reset); stmt.AddValue(1, (ushort)mapid); stmt.AddValue(2, (byte)difficulty); DB.Characters.Execute(stmt); } // note: this isn't fast but it's meant to be executed very rarely Map map = Global.MapMgr.CreateBaseMap(mapid); // _not_ include difficulty var instMaps = ((MapInstanced)map).GetInstancedMaps(); uint timeLeft; foreach (var pair in instMaps) { Map map2 = pair.Value; if (!map2.IsDungeon()) { continue; } if (warn) { if (now >= resetTime) { timeLeft = 0; } else { timeLeft = (uint)(resetTime - now); } ((InstanceMap)map2).SendResetWarnings(timeLeft); } else { ((InstanceMap)map2).Reset(InstanceResetMethod.Global); } } // @todo delete creature/gameobject respawn times even if the maps are not loaded }
private void Check_Expected(PreparedStatement select, object[] expected) { var row = Session.Execute(select.Bind(0)).First(); Assert.IsNotNull(row); Assert.AreEqual(expected[1], row.GetValue<int?>("v0")); Assert.AreEqual(expected[2], row.GetValue<int?>("v1")); }
public async Task Handle(UploadedVideoPublished publishedVideo) { // Find the video PreparedStatement prepared = await _statementCache.NoContext.GetOrAddAsync("SELECT * FROM videos WHERE videoid = ?"); BoundStatement bound = prepared.Bind(publishedVideo.VideoId); RowSet rows = await _session.ExecuteAsync(bound).ConfigureAwait(false); Row videoRow = rows.SingleOrDefault(); if (videoRow == null) { throw new InvalidOperationException(string.Format("Could not find video with id {0}", publishedVideo.VideoId)); } var locationType = videoRow.GetValue <int>("location_type"); if (locationType != VideoCatalogConstants.UploadedVideoType) { throw new InvalidOperationException(string.Format("Video {0} is not an uploaded video of type {1} but is type {2}", publishedVideo.VideoId, VideoCatalogConstants.UploadedVideoType, locationType)); } // Get some data from the Row var userId = videoRow.GetValue <Guid>("userid"); var name = videoRow.GetValue <string>("name"); var description = videoRow.GetValue <string>("description"); var tags = videoRow.GetValue <IEnumerable <string> >("tags"); var addDate = videoRow.GetValue <DateTimeOffset>("added_date"); // Update the video locations (and write to denormalized tables) via batch PreparedStatement[] writePrepared = await _statementCache.NoContext.GetOrAddAllAsync( "UPDATE videos USING TIMESTAMP ? SET location = ?, preview_image_location = ? WHERE videoid = ?", "UPDATE user_videos USING TIMESTAMP ? SET preview_image_location = ? WHERE userid = ? AND added_date = ? AND videoid = ?", "INSERT INTO latest_videos (yyyymmdd, added_date, videoid, userid, name, preview_image_location) VALUES (?, ?, ?, ?, ?, ?) USING TIMESTAMP ? AND TTL ?" ); // Calculate date-related data for the video string yyyymmdd = addDate.ToString("yyyyMMdd"); DateTimeOffset timestamp = publishedVideo.Timestamp; var batch = new BatchStatement(); batch.Add(writePrepared[0].Bind(timestamp.ToMicrosecondsSinceEpoch(), publishedVideo.VideoUrl, publishedVideo.ThumbnailUrl, publishedVideo.VideoId)); batch.Add(writePrepared[1].Bind(timestamp.ToMicrosecondsSinceEpoch(), publishedVideo.ThumbnailUrl, userId, addDate, publishedVideo.VideoId)); batch.Add(writePrepared[2].Bind(yyyymmdd, addDate, publishedVideo.VideoId, userId, name, publishedVideo.ThumbnailUrl, timestamp.ToMicrosecondsSinceEpoch(), VideoCatalogConstants.LatestVideosTtlSeconds)); await _session.ExecuteAsync(batch).ConfigureAwait(false); // Tell the world about the uploaded video that was added await _bus.Publish(new UploadedVideoAdded { VideoId = publishedVideo.VideoId, UserId = userId, Name = name, Description = description, Tags = tags.ToHashSet(), Location = publishedVideo.VideoUrl, PreviewImageLocation = publishedVideo.ThumbnailUrl, AddedDate = addDate, Timestamp = timestamp }).ConfigureAwait(false); }
internal static IPEndPoint ExecutePreparedQuery(ISession session, PreparedStatement prepared, object[] values, string messageInstead = null) { RowSet ret = session.Execute(prepared.Bind(values).SetConsistencyLevel(session.Cluster.Configuration.QueryOptions.GetConsistencyLevel())); return(ret.Info.QueriedHost); }
protected void init(CcmClusterInfo clusterInfo, int n, bool batch, ConsistencyLevel cl) { // We don't use insert for our test because the resultSet don't ship the queriedHost // Also note that we don't use tracing because this would trigger requests that screw up the test' for (int i = 0; i < n; ++i) if (batch) // BUG: WriteType == SIMPLE { var bth = new StringBuilder(); bth.AppendLine("BEGIN BATCH"); bth.AppendLine(String.Format("INSERT INTO {0}(k, i) VALUES (0, 0)", TestUtils.SIMPLE_TABLE)); bth.AppendLine("APPLY BATCH"); RowSet qh = clusterInfo.Session.Execute(new SimpleStatement(bth.ToString()).SetConsistencyLevel(cl)); } else { RowSet qh = clusterInfo.Session.Execute( new SimpleStatement(String.Format("INSERT INTO {0}(k, i) VALUES (0, 0)", TestUtils.SIMPLE_TABLE)).SetConsistencyLevel(cl)); } prepared = clusterInfo.Session.Prepare("SELECT * FROM " + TestUtils.SIMPLE_TABLE + " WHERE k = ?").SetConsistencyLevel(cl); }
void UpdateRealms(object source, ElapsedEventArgs e) { PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_REALMLIST); SQLResult result = DB.Login.Query(stmt); Dictionary <RealmHandle, string> existingRealms = new Dictionary <RealmHandle, string>(); foreach (var p in _realms) { existingRealms[p.Key] = p.Value.Name; } _realms.Clear(); // Circle through results and add them to the realm map if (!result.IsEmpty()) { do { var realm = new Realm(); uint realmId = result.Read <uint>(0); realm.Name = result.Read <string>(1); realm.ExternalAddress = IPAddress.Parse(result.Read <string>(2)); realm.LocalAddress = IPAddress.Parse(result.Read <string>(3)); realm.LocalSubnetMask = IPAddress.Parse(result.Read <string>(4)); realm.Port = result.Read <ushort>(5); RealmType realmType = (RealmType)result.Read <byte>(6); if (realmType == RealmType.FFAPVP) { realmType = RealmType.PVP; } if (realmType >= RealmType.MaxType) { realmType = RealmType.Normal; } realm.Type = (byte)realmType; realm.Flags = (RealmFlags)result.Read <byte>(7); realm.Timezone = result.Read <byte>(8); AccountTypes allowedSecurityLevel = (AccountTypes)result.Read <byte>(9); realm.AllowedSecurityLevel = (allowedSecurityLevel <= AccountTypes.Administrator ? allowedSecurityLevel : AccountTypes.Administrator); realm.PopulationLevel = result.Read <float>(10); realm.Build = result.Read <uint>(11); byte region = result.Read <byte>(12); byte battlegroup = result.Read <byte>(13); realm.Id = new RealmHandle(region, battlegroup, realmId); UpdateRealm(realm); var subRegion = new RealmHandle(region, battlegroup, 0).GetAddressString(); if (!_subRegions.Contains(subRegion)) { _subRegions.Add(subRegion); } if (!existingRealms.ContainsKey(realm.Id)) { Log.outInfo(LogFilter.Realmlist, "Added realm \"{0}\" at {1}:{2}", realm.Name, realm.ExternalAddress.ToString(), realm.Port); } else { Log.outDebug(LogFilter.Realmlist, "Updating realm \"{0}\" at {1}:{2}", realm.Name, realm.ExternalAddress.ToString(), realm.Port); } existingRealms.Remove(realm.Id); }while (result.NextRow()); } foreach (var pair in existingRealms) { Log.outInfo(LogFilter.Realmlist, "Removed realm \"{0}\".", pair.Value); } }
static bool HandleCharacterChangeAccountCommand(StringArguments args, CommandHandler handler) { string playerNameStr; string accountName; handler.ExtractOptFirstArg(args, out playerNameStr, out accountName); if (accountName.IsEmpty()) { return(false); } ObjectGuid targetGuid; string targetName; if (!handler.ExtractPlayerTarget(new StringArguments(playerNameStr), out _, out targetGuid, out targetName)) { return(false); } CharacterCacheEntry characterInfo = Global.CharacterCacheStorage.GetCharacterCacheByGuid(targetGuid); if (characterInfo == null) { handler.SendSysMessage(CypherStrings.PlayerNotFound); return(false); } uint oldAccountId = characterInfo.AccountId; uint newAccountId = oldAccountId; PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_ACCOUNT_ID_BY_NAME); stmt.AddValue(0, accountName); SQLResult result = DB.Login.Query(stmt); if (!result.IsEmpty()) { newAccountId = result.Read <uint>(0); } else { handler.SendSysMessage(CypherStrings.AccountNotExist, accountName); return(false); } // nothing to do :) if (newAccountId == oldAccountId) { return(true); } uint charCount = Global.AccountMgr.GetCharactersCount(newAccountId); if (charCount != 0) { if (charCount >= WorldConfig.GetIntValue(WorldCfg.CharactersPerRealm)) { handler.SendSysMessage(CypherStrings.AccountCharacterListFull, accountName, newAccountId); return(false); } } stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_ACCOUNT_BY_GUID); stmt.AddValue(0, newAccountId); stmt.AddValue(1, targetGuid.GetCounter()); DB.Characters.DirectExecute(stmt); Global.WorldMgr.UpdateRealmCharCount(oldAccountId); Global.WorldMgr.UpdateRealmCharCount(newAccountId); Global.CharacterCacheStorage.UpdateCharacterAccountId(targetGuid, newAccountId); handler.SendSysMessage(CypherStrings.ChangeAccountSuccess, targetName, accountName); string logString = $"changed ownership of player {targetName} ({targetGuid}) from account {oldAccountId} to account {newAccountId}"; WorldSession session = handler.GetSession(); if (session != null) { Player player = session.GetPlayer(); if (player != null) { Log.outCommand(session.GetAccountId(), $"GM {player.GetName()} (Account: {session.GetAccountId()}) {logString}"); } } else { Log.outCommand(0, $"{handler.GetCypherString(CypherStrings.Console)} {logString}"); } return(true); }
BattlenetRpcErrorCode GetRealmListTicket(Dictionary <string, Variant> Params, Bgs.Protocol.GameUtilities.V1.ClientResponse response) { Variant identity = GetParam(Params, "Param_Identity"); if (identity != null) { var realmListTicketIdentity = Json.CreateObject <RealmListTicketIdentity>(identity.BlobValue.ToStringUtf8(), true); var gameAccountInfo = _accountInfo.GameAccounts.LookupByKey(realmListTicketIdentity.GameAccountId); if (gameAccountInfo != null) { _gameAccountInfo = gameAccountInfo; } } if (_gameAccountInfo == null) { return(BattlenetRpcErrorCode.UtilServerInvalidIdentityArgs); } if (_gameAccountInfo.IsPermanenetlyBanned) { return(BattlenetRpcErrorCode.GameAccountBanned); } else if (_gameAccountInfo.IsBanned) { return(BattlenetRpcErrorCode.GameAccountSuspended); } bool clientInfoOk = false; Variant clientInfo = GetParam(Params, "Param_ClientInfo"); if (clientInfo != null) { var realmListTicketClientInformation = Json.CreateObject <RealmListTicketClientInformation>(clientInfo.BlobValue.ToStringUtf8(), true); clientInfoOk = true; int i = 0; foreach (var b in realmListTicketClientInformation.Info.Secret.Select(Convert.ToByte)) { _clientSecret[i++] = b; } } if (!clientInfoOk) { return(BattlenetRpcErrorCode.WowServicesDeniedRealmListTicket); } PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_BNET_LAST_LOGIN_INFO); stmt.AddValue(0, GetRemoteIpAddress().ToString()); stmt.AddValue(1, Enum.Parse(typeof(LocaleConstant), _locale)); stmt.AddValue(2, _os); stmt.AddValue(3, _accountInfo.Id); DB.Login.Execute(stmt); var attribute = new Bgs.Protocol.Attribute(); attribute.Name = "Param_RealmListTicket"; attribute.Value = new Variant(); attribute.Value.BlobValue = ByteString.CopyFrom("AuthRealmListTicket", System.Text.Encoding.UTF8); response.Attribute.Add(attribute); return(BattlenetRpcErrorCode.Ok); }
internal static RowSet ExecutePreparedSelectQuery(ISession session, PreparedStatement prepared, object[] values, string messageInstead = null) { RowSet ret = session.Execute(prepared.Bind(values).SetConsistencyLevel(session.Cluster.Configuration.QueryOptions.GetConsistencyLevel())); return ret; }
public override void SaveToDB(SQLTransaction trans) { PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ITEM_INSTANCE_AZERITE); stmt.AddValue(0, GetGUID().GetCounter()); trans.Append(stmt); stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ITEM_INSTANCE_AZERITE_MILESTONE_POWER); stmt.AddValue(0, GetGUID().GetCounter()); trans.Append(stmt); stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ITEM_INSTANCE_AZERITE_UNLOCKED_ESSENCE); stmt.AddValue(0, GetGUID().GetCounter()); trans.Append(stmt); switch (GetState()) { case ItemUpdateState.New: case ItemUpdateState.Changed: stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_ITEM_INSTANCE_AZERITE); stmt.AddValue(0, GetGUID().GetCounter()); stmt.AddValue(1, m_azeriteItemData.Xp); stmt.AddValue(2, m_azeriteItemData.Level); stmt.AddValue(3, m_azeriteItemData.KnowledgeLevel); int specIndex = 0; for (; specIndex < m_azeriteItemData.SelectedEssences.Size(); ++specIndex) { stmt.AddValue(4 + specIndex * 5, m_azeriteItemData.SelectedEssences[specIndex].SpecializationID); for (int j = 0; j < SharedConst.MaxAzeriteEssenceSlot; ++j) { stmt.AddValue(5 + specIndex * 5 + j, m_azeriteItemData.SelectedEssences[specIndex].AzeriteEssenceID[j]); } } for (; specIndex < PlayerConst.MaxSpecializations; ++specIndex) { stmt.AddValue(4 + specIndex * 5, 0); for (int j = 0; j < SharedConst.MaxAzeriteEssenceSlot; ++j) { stmt.AddValue(5 + specIndex * 5 + j, 0); } } trans.Append(stmt); foreach (uint azeriteItemMilestonePowerId in m_azeriteItemData.UnlockedEssenceMilestones) { stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_ITEM_INSTANCE_AZERITE_MILESTONE_POWER); stmt.AddValue(0, GetGUID().GetCounter()); stmt.AddValue(1, azeriteItemMilestonePowerId); trans.Append(stmt); } foreach (var azeriteEssence in m_azeriteItemData.UnlockedEssences) { stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_ITEM_INSTANCE_AZERITE_UNLOCKED_ESSENCE); stmt.AddValue(0, GetGUID().GetCounter()); stmt.AddValue(1, azeriteEssence.AzeriteEssenceID); stmt.AddValue(2, azeriteEssence.Rank); trans.Append(stmt); } break; } base.SaveToDB(trans); }
static bool HandleBanListCharacterCommand(StringArguments args, CommandHandler handler) { if (args.Empty()) { return(false); } string filter = args.NextString(); if (string.IsNullOrEmpty(filter)) { return(false); } PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GUID_BY_NAME_FILTER); stmt.AddValue(0, filter); SQLResult result = DB.Characters.Query(stmt); if (result.IsEmpty()) { handler.SendSysMessage(CypherStrings.BanlistNocharacter); return(true); } handler.SendSysMessage(CypherStrings.BanlistMatchingcharacter); // Chat short output if (handler.GetSession()) { do { PreparedStatement stmt2 = DB.Characters.GetPreparedStatement(CharStatements.SEL_BANNED_NAME); stmt2.AddValue(0, result.Read <ulong>(0)); SQLResult banResult = DB.Characters.Query(stmt2); if (!banResult.IsEmpty()) { handler.SendSysMessage(banResult.Read <string>(0)); } }while (result.NextRow()); } // Console wide output else { handler.SendSysMessage(CypherStrings.BanlistCharacters); handler.SendSysMessage(" =============================================================================== "); handler.SendSysMessage(CypherStrings.BanlistCharactersHeader); do { handler.SendSysMessage("-------------------------------------------------------------------------------"); string char_name = result.Read <string>(1); PreparedStatement stmt2 = DB.Characters.GetPreparedStatement(CharStatements.SEL_BANINFO_LIST); stmt2.AddValue(0, result.Read <ulong>(0)); SQLResult banInfo = DB.Characters.Query(stmt2); if (!banInfo.IsEmpty()) { do { long timeBan = banInfo.Read <long>(0); DateTime tmBan = Time.UnixTimeToDateTime(timeBan); string bannedby = banInfo.Read <string>(2).Substring(0, 15); string banreason = banInfo.Read <string>(3).Substring(0, 15); if (banInfo.Read <long>(0) == banInfo.Read <long>(1)) { handler.SendSysMessage("|{0}|{1:D2}-{2:D2}-{3:D2} {4:D2}:{5:D2}| permanent |{6}|{7}|", char_name, tmBan.Year % 100, tmBan.Month + 1, tmBan.Day, tmBan.Hour, tmBan.Minute, bannedby, banreason); } else { long timeUnban = banInfo.Read <long>(1); DateTime tmUnban = Time.UnixTimeToDateTime(timeUnban); handler.SendSysMessage("|{0}|{1:D2}-{2:D2}-{3:D2} {4:D2}:{5:D2}|{6:D2}-{7:D2}-{8:D2} {9:D2}:{10:D2}|{11}|{12}|", char_name, tmBan.Year % 100, tmBan.Month + 1, tmBan.Day, tmBan.Hour, tmBan.Minute, tmUnban.Year % 100, tmUnban.Month + 1, tmUnban.Day, tmUnban.Hour, tmUnban.Minute, bannedby, banreason); } }while (banInfo.NextRow()); } }while (result.NextRow()); handler.SendSysMessage(" =============================================================================== "); } return(true); }
public void HandleLoginRequest(HttpHeader request) { LogonData loginForm = Json.CreateObject <LogonData>(request.Content); LogonResult loginResult = new LogonResult(); if (loginForm == null) { loginResult.AuthenticationState = "LOGIN"; loginResult.ErrorCode = "UNABLE_TO_DECODE"; loginResult.ErrorMessage = "There was an internal error while connecting to Battle.net. Please try again later."; SendResponse(HttpCode.BadRequest, loginResult); return; } string login = ""; string password = ""; for (int i = 0; i < loginForm.Inputs.Count; ++i) { switch (loginForm.Inputs[i].Id) { case "account_name": login = loginForm.Inputs[i].Value; break; case "password": password = loginForm.Inputs[i].Value; break; } } PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SelBnetAuthentication); stmt.AddValue(0, login); SQLResult result = DB.Login.Query(stmt); if (!result.IsEmpty()) { uint accountId = result.Read <uint>(0); string pass_hash = result.Read <string>(1); uint failedLogins = result.Read <uint>(2); string loginTicket = result.Read <string>(3); uint loginTicketExpiry = result.Read <uint>(4); bool isBanned = result.Read <ulong>(5) != 0; if (CalculateShaPassHash(login.ToUpper(), password.ToUpper()) == pass_hash) { if (loginTicket.IsEmpty() || loginTicketExpiry < Time.UnixTime) { byte[] ticket = new byte[0].GenerateRandomKey(20); loginTicket = "TC-" + ticket.ToHexString(); } stmt = DB.Login.GetPreparedStatement(LoginStatements.UpdBnetAuthentication); stmt.AddValue(0, loginTicket); stmt.AddValue(1, Time.UnixTime + 3600); stmt.AddValue(2, accountId); DB.Login.Execute(stmt); loginResult.LoginTicket = loginTicket; } else if (!isBanned) { uint maxWrongPassword = ConfigMgr.GetDefaultValue("WrongPass.MaxCount", 0u); if (ConfigMgr.GetDefaultValue("WrongPass.Logging", false)) { Log.outDebug(LogFilter.Network, $"[{request.Host}, Account {login}, Id {accountId}] Attempted to connect with wrong password!"); } if (maxWrongPassword != 0) { SQLTransaction trans = new SQLTransaction(); stmt = DB.Login.GetPreparedStatement(LoginStatements.UpdBnetFailedLogins); stmt.AddValue(0, accountId); trans.Append(stmt); ++failedLogins; Log.outDebug(LogFilter.Network, "MaxWrongPass : {maxWrongPassword}, failed_login : {accountId}"); if (failedLogins >= maxWrongPassword) { BanMode banType = ConfigMgr.GetDefaultValue("WrongPass.BanType", BanMode.IP); int banTime = ConfigMgr.GetDefaultValue("WrongPass.BanTime", 600); if (banType == BanMode.Account) { stmt = DB.Login.GetPreparedStatement(LoginStatements.InsBnetAccountAutoBanned); stmt.AddValue(0, accountId); } else { stmt = DB.Login.GetPreparedStatement(LoginStatements.InsIpAutoBanned); stmt.AddValue(0, request.Host); } stmt.AddValue(1, banTime); trans.Append(stmt); stmt = DB.Login.GetPreparedStatement(LoginStatements.UpdBnetResetFailedLogins); stmt.AddValue(0, accountId); trans.Append(stmt); } DB.Login.CommitTransaction(trans); } } loginResult.AuthenticationState = "DONE"; SendResponse(HttpCode.Ok, loginResult); } else { loginResult.AuthenticationState = "LOGIN"; loginResult.ErrorCode = "UNABLE_TO_DECODE"; loginResult.ErrorMessage = "There was an internal error while connecting to Battle.net. Please try again later."; SendResponse(HttpCode.BadRequest, loginResult); } }
static bool HandleBanListIPCommand(StringArguments args, CommandHandler handler) { PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.DelExpiredIpBans); DB.Login.Execute(stmt); string filterStr = args.NextString(); string filter = !string.IsNullOrEmpty(filterStr) ? filterStr : ""; SQLResult result; if (string.IsNullOrEmpty(filter)) { stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_IP_BANNED_ALL); result = DB.Login.Query(stmt); } else { stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_IP_BANNED_BY_IP); stmt.AddValue(0, filter); result = DB.Login.Query(stmt); } if (result.IsEmpty()) { handler.SendSysMessage(CypherStrings.BanlistNoip); return(true); } handler.SendSysMessage(CypherStrings.BanlistMatchingip); // Chat short output if (handler.GetSession()) { do { handler.SendSysMessage("{0}", result.Read <string>(0)); }while (result.NextRow()); } // Console wide output else { handler.SendSysMessage(CypherStrings.BanlistIps); handler.SendSysMessage(" ==============================================================================="); handler.SendSysMessage(CypherStrings.BanlistIpsHeader); do { handler.SendSysMessage("-------------------------------------------------------------------------------"); long timeBan = result.Read <uint>(1); DateTime tmBan = Time.UnixTimeToDateTime(timeBan); string bannedby = result.Read <string>(3).Substring(0, 15); string banreason = result.Read <string>(4).Substring(0, 15); if (result.Read <uint>(1) == result.Read <uint>(2)) { handler.SendSysMessage("|{0}|{1:D2}-{2:D2}-{3:D2} {4:D2}:{5:D2}| permanent |{6}|{7}|", result.Read <string>(0), tmBan.Year % 100, tmBan.Month + 1, tmBan.Day, tmBan.Hour, tmBan.Minute, bannedby, banreason); } else { long timeUnban = result.Read <uint>(2); DateTime tmUnban; tmUnban = Time.UnixTimeToDateTime(timeUnban); handler.SendSysMessage("|{0}|{1:D2}-{2:D2}-{3:D2} {4:D2}:{5:D2}|{6:D2}-{7:D2}-{8:D2} {9:D2}:{10:D2}|{11}|{12}|", result.Read <string>(0), tmBan.Year % 100, tmBan.Month + 1, tmBan.Day, tmBan.Hour, tmBan.Minute, tmUnban.Year % 100, tmUnban.Month + 1, tmUnban.Day, tmUnban.Hour, tmUnban.Minute, bannedby, banreason); } }while (result.NextRow()); handler.SendSysMessage(" ==============================================================================="); } return(true); }
static bool HandleWpModifyCommand(StringArguments args, CommandHandler handler) { if (args.Empty()) { return(false); } // first arg: add del text emote spell waittime move string show = args.NextString(); if (string.IsNullOrEmpty(show)) { return(false); } // Check // Remember: "show" must also be the name of a column! if ((show != "delay") && (show != "action") && (show != "action_chance") && (show != "move_flag") && (show != "del") && (show != "move")) { return(false); } // Next arg is: <PATHID> <WPNUM> <ARGUMENT> string arg_str; // Did user provide a GUID // or did the user select a creature? // . variable lowguid is filled with the GUID of the NPC uint pathid; uint point; Creature target = handler.getSelectedCreature(); // User did select a visual waypoint? if (!target || target.GetEntry() != 1) { handler.SendSysMessage("|cffff33ffERROR: You must select a waypoint.|r"); return(false); } // Check the creature PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_BY_WPGUID); stmt.AddValue(0, target.GetSpawnId()); SQLResult result = DB.World.Query(stmt); if (result.IsEmpty()) { handler.SendSysMessage(CypherStrings.WaypointNotfoundsearch, target.GetGUID().ToString()); // Select waypoint number from database // Since we compare float values, we have to deal with // some difficulties. // Here we search for all waypoints that only differ in one from 1 thousand // See also: http://dev.mysql.com/doc/refman/5.0/en/problems-with-float.html string maxDiff = "0.01"; stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_BY_POS); stmt.AddValue(0, target.GetPositionX()); stmt.AddValue(1, maxDiff); stmt.AddValue(2, target.GetPositionY()); stmt.AddValue(3, maxDiff); stmt.AddValue(4, target.GetPositionZ()); stmt.AddValue(5, maxDiff); result = DB.World.Query(stmt); if (result.IsEmpty()) { handler.SendSysMessage(CypherStrings.WaypointNotfounddbproblem, target.GetGUID().ToString()); return(true); } } do { pathid = result.Read <uint>(0); point = result.Read <uint>(1); }while (result.NextRow()); // We have the waypoint number and the GUID of the "master npc" // Text is enclosed in "<>", all other arguments not arg_str = args.NextString(); // Check for argument if (show != "del" && show != "move" && arg_str == null) { handler.SendSysMessage(CypherStrings.WaypointArgumentreq, show); return(false); } if (show == "del") { handler.SendSysMessage("|cff00ff00DEBUG: wp modify del, PathID: |r|cff00ffff{0}|r", pathid); target.DeleteFromDB(); target.AddObjectToRemoveList(); stmt = DB.World.GetPreparedStatement(WorldStatements.DEL_WAYPOINT_DATA); stmt.AddValue(0, pathid); stmt.AddValue(1, point); DB.World.Execute(stmt); stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_DATA_POINT); stmt.AddValue(0, pathid); stmt.AddValue(1, point); DB.World.Execute(stmt); handler.SendSysMessage(CypherStrings.WaypointRemoved); return(true); } // del if (show == "move") { handler.SendSysMessage("|cff00ff00DEBUG: wp move, PathID: |r|cff00ffff{0}|r", pathid); Player chr = handler.GetSession().GetPlayer(); Map map = chr.GetMap(); // What to do: // Move the visual spawnpoint // Respawn the owner of the waypoints target.DeleteFromDB(); target.AddObjectToRemoveList(); // re-create Creature creature = Creature.CreateCreature(1, map, chr.GetPosition()); if (!creature) { handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, 1); return(false); } creature.CopyPhaseFrom(chr); creature.SaveToDB(map.GetId(), 1ul << (int)map.GetSpawnMode()); ulong dbGuid = creature.GetSpawnId(); // current "wpCreature" variable is deleted and created fresh new, otherwise old values might trigger asserts or cause undefined behavior creature.CleanupsBeforeDelete(); creature.Dispose(); // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells(); creature = Creature.CreateCreatureFromDB(dbGuid, map); if (!creature) { handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, 1); return(false); } stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_DATA_POSITION); stmt.AddValue(0, chr.GetPositionX()); stmt.AddValue(1, chr.GetPositionY()); stmt.AddValue(2, chr.GetPositionZ()); stmt.AddValue(3, pathid); stmt.AddValue(4, point); DB.World.Execute(stmt); handler.SendSysMessage(CypherStrings.WaypointChanged); return(true); } // move if (string.IsNullOrEmpty(arg_str)) { // show_str check for present in list of correct values, no sql injection possible DB.World.Execute("UPDATE waypoint_data SET {0}=null WHERE id='{1}' AND point='{2}'", show, pathid, point); // Query can't be a prepared statement } else { // show_str check for present in list of correct values, no sql injection possible DB.World.Execute("UPDATE waypoint_data SET {0}='{1}' WHERE id='{2}' AND point='{3}'", show, arg_str, pathid, point); // Query can't be a prepared statement } handler.SendSysMessage(CypherStrings.WaypointChangedNo, show); return(true); }
static bool HandleAccountSetAddonCommand(StringArguments args, CommandHandler handler) { if (args.Empty()) { return(false); } // Get the command line arguments string account = args.NextString(); string exp = args.NextString(); if (string.IsNullOrEmpty(account)) { return(false); } string accountName; uint accountId; if (string.IsNullOrEmpty(exp)) { Player player = handler.GetSelectedPlayer(); if (!player) { return(false); } accountId = player.GetSession().GetAccountId(); Global.AccountMgr.GetName(accountId, out accountName); exp = account; } else { // Convert Account name to Upper Format accountName = account.ToUpper(); accountId = Global.AccountMgr.GetId(accountName); if (accountId == 0) { handler.SendSysMessage(CypherStrings.AccountNotExist, accountName); return(false); } } // Let set addon state only for lesser (strong) security level // or to self account if (handler.GetSession() != null && handler.GetSession().GetAccountId() != accountId && handler.HasLowerSecurityAccount(null, accountId, true)) { return(false); } if (!byte.TryParse(exp, out byte expansion)) { return(false); } if (expansion > WorldConfig.GetIntValue(WorldCfg.Expansion)) { return(false); } PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_EXPANSION); stmt.AddValue(0, expansion); stmt.AddValue(1, accountId); DB.Login.Execute(stmt); handler.SendSysMessage(CypherStrings.AccountSetaddon, accountName, accountId, expansion); return(true); }
void HandleWrapItem(WrapItem packet) { if (packet.Inv.Items.Count != 2) { Log.outError(LogFilter.Network, "HandleWrapItem - Invalid itemCount ({0})", packet.Inv.Items.Count); return; } // Gift byte giftContainerSlot = packet.Inv.Items[0].ContainerSlot; byte giftSlot = packet.Inv.Items[0].Slot; // Item byte itemContainerSlot = packet.Inv.Items[1].ContainerSlot; byte itemSlot = packet.Inv.Items[1].Slot; Item gift = GetPlayer().GetItemByPos(giftContainerSlot, giftSlot); if (!gift) { GetPlayer().SendEquipError(InventoryResult.ItemNotFound, gift); return; } if (!gift.GetTemplate().GetFlags().HasAnyFlag(ItemFlags.IsWrapper)) // cheating: non-wrapper wrapper { GetPlayer().SendEquipError(InventoryResult.ItemNotFound, gift); return; } Item item = GetPlayer().GetItemByPos(itemContainerSlot, itemSlot); if (!item) { GetPlayer().SendEquipError(InventoryResult.ItemNotFound, item); return; } if (item == gift) // not possable with pacjket from real client { GetPlayer().SendEquipError(InventoryResult.CantWrapWrapped, item); return; } if (item.IsEquipped()) { GetPlayer().SendEquipError(InventoryResult.CantWrapEquipped, item); return; } if (!item.GetGiftCreator().IsEmpty()) // HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED); { GetPlayer().SendEquipError(InventoryResult.CantWrapWrapped, item); return; } if (item.IsBag()) { GetPlayer().SendEquipError(InventoryResult.CantWrapBags, item); return; } if (item.IsSoulBound()) { GetPlayer().SendEquipError(InventoryResult.CantWrapBound, item); return; } if (item.GetMaxStackCount() != 1) { GetPlayer().SendEquipError(InventoryResult.CantWrapStackable, item); return; } // maybe not correct check (it is better than nothing) if (item.GetTemplate().GetMaxCount() > 0) { GetPlayer().SendEquipError(InventoryResult.CantWrapUnique, item); return; } SQLTransaction trans = new SQLTransaction(); PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_CHAR_GIFT); stmt.AddValue(0, item.GetOwnerGUID().GetCounter()); stmt.AddValue(1, item.GetGUID().GetCounter()); stmt.AddValue(2, item.GetEntry()); stmt.AddValue(3, (uint)item.m_itemData.DynamicFlags); trans.Append(stmt); item.SetEntry(gift.GetEntry()); switch (item.GetEntry()) { case 5042: item.SetEntry(5043); break; case 5048: item.SetEntry(5044); break; case 17303: item.SetEntry(17302); break; case 17304: item.SetEntry(17305); break; case 17307: item.SetEntry(17308); break; case 21830: item.SetEntry(21831); break; } item.SetGiftCreator(GetPlayer().GetGUID()); item.SetItemFlags(ItemFieldFlags.Wrapped); item.SetState(ItemUpdateState.Changed, GetPlayer()); if (item.GetState() == ItemUpdateState.New) // save new item, to have alway for `character_gifts` record in `item_instance` { // after save it will be impossible to remove the item from the queue Item.RemoveItemFromUpdateQueueOf(item, GetPlayer()); item.SaveToDB(trans); // item gave inventory record unchanged and can be save standalone } DB.Characters.CommitTransaction(trans); uint count = 1; GetPlayer().DestroyItemCount(gift, ref count, true); }
static bool HandleListItemCommand(StringArguments args, CommandHandler handler) { if (args.Empty()) { return(false); } string id = handler.extractKeyFromLink(args, "Hitem"); if (string.IsNullOrEmpty(id)) { return(false); } if (!uint.TryParse(id, out uint itemId) || itemId == 0) { handler.SendSysMessage(CypherStrings.CommandItemidinvalid, itemId); return(false); } ItemTemplate itemTemplate = Global.ObjectMgr.GetItemTemplate(itemId); if (itemTemplate == null) { handler.SendSysMessage(CypherStrings.CommandItemidinvalid, itemId); return(false); } if (!uint.TryParse(args.NextString(), out uint count)) { count = 10; } if (count == 0) { return(false); } // inventory case uint inventoryCount = 0; PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_CHAR_INVENTORY_COUNT_ITEM); stmt.AddValue(0, itemId); SQLResult result = DB.Characters.Query(stmt); if (!result.IsEmpty()) { inventoryCount = result.Read <uint>(0); } stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_CHAR_INVENTORY_ITEM_BY_ENTRY); stmt.AddValue(0, itemId); stmt.AddValue(1, count); result = DB.Characters.Query(stmt); if (!result.IsEmpty()) { do { ObjectGuid itemGuid = ObjectGuid.Create(HighGuid.Item, result.Read <ulong>(0)); uint itemBag = result.Read <uint>(1); byte itemSlot = result.Read <byte>(2); ObjectGuid ownerGuid = ObjectGuid.Create(HighGuid.Player, result.Read <ulong>(3)); uint ownerAccountId = result.Read <uint>(4); string ownerName = result.Read <string>(5); string itemPos; if (Player.IsEquipmentPos((byte)itemBag, itemSlot)) { itemPos = "[equipped]"; } else if (Player.IsInventoryPos((byte)itemBag, itemSlot)) { itemPos = "[in inventory]"; } else if (Player.IsBankPos((byte)itemBag, itemSlot)) { itemPos = "[in bank]"; } else { itemPos = ""; } handler.SendSysMessage(CypherStrings.ItemlistSlot, itemGuid.ToString(), ownerName, ownerGuid.ToString(), ownerAccountId, itemPos); count--; }while (result.NextRow()); } // mail case uint mailCount = 0; stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_MAIL_COUNT_ITEM); stmt.AddValue(0, itemId); result = DB.Characters.Query(stmt); if (!result.IsEmpty()) { mailCount = result.Read <uint>(0); } if (count > 0) { stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_MAIL_ITEMS_BY_ENTRY); stmt.AddValue(0, itemId); stmt.AddValue(1, count); result = DB.Characters.Query(stmt); } else { result = null; } if (result != null && !result.IsEmpty()) { do { ulong itemGuid = result.Read <ulong>(0); ulong itemSender = result.Read <ulong>(1); ulong itemReceiver = result.Read <ulong>(2); uint itemSenderAccountId = result.Read <uint>(3); string itemSenderName = result.Read <string>(4); uint itemReceiverAccount = result.Read <uint>(5); string itemReceiverName = result.Read <string>(6); string itemPos = "[in mail]"; handler.SendSysMessage(CypherStrings.ItemlistMail, itemGuid, itemSenderName, itemSender, itemSenderAccountId, itemReceiverName, itemReceiver, itemReceiverAccount, itemPos); count--; }while (result.NextRow()); } // auction case uint auctionCount = 0; stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_AUCTIONHOUSE_COUNT_ITEM); stmt.AddValue(0, itemId); result = DB.Characters.Query(stmt); if (!result.IsEmpty()) { auctionCount = result.Read <uint>(0); } if (count > 0) { stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_AUCTIONHOUSE_ITEM_BY_ENTRY); stmt.AddValue(0, itemId); stmt.AddValue(1, count); result = DB.Characters.Query(stmt); } else { result = null; } if (result != null && !result.IsEmpty()) { do { ObjectGuid itemGuid = ObjectGuid.Create(HighGuid.Item, result.Read <ulong>(0)); ObjectGuid owner = ObjectGuid.Create(HighGuid.Player, result.Read <ulong>(1)); uint ownerAccountId = result.Read <uint>(2); string ownerName = result.Read <string>(3); string itemPos = "[in auction]"; handler.SendSysMessage(CypherStrings.ItemlistAuction, itemGuid.ToString(), ownerName, owner.ToString(), ownerAccountId, itemPos); }while (result.NextRow()); } // guild bank case uint guildCount = 0; stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GUILD_BANK_COUNT_ITEM); stmt.AddValue(0, itemId); result = DB.Characters.Query(stmt); if (!result.IsEmpty()) { guildCount = result.Read <uint>(0); } stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GUILD_BANK_ITEM_BY_ENTRY); stmt.AddValue(0, itemId); stmt.AddValue(1, count); result = DB.Characters.Query(stmt); if (!result.IsEmpty()) { do { ObjectGuid itemGuid = ObjectGuid.Create(HighGuid.Item, result.Read <ulong>(0)); ObjectGuid guildGuid = ObjectGuid.Create(HighGuid.Guild, result.Read <ulong>(1)); string guildName = result.Read <string>(2); string itemPos = "[in guild bank]"; handler.SendSysMessage(CypherStrings.ItemlistGuild, itemGuid.ToString(), guildName, guildGuid.ToString(), itemPos); count--; }while (result.NextRow()); } if (inventoryCount + mailCount + auctionCount + guildCount == 0) { handler.SendSysMessage(CypherStrings.CommandNoitemfound); return(false); } handler.SendSysMessage(CypherStrings.CommandListitemmessage, itemId, inventoryCount + mailCount + auctionCount + guildCount, inventoryCount, mailCount, auctionCount, guildCount); return(true); }
public void LoadCreatureTexts() { uint oldMSTime = Time.GetMSTime(); mTextMap.Clear(); // for reload case //all currently used temp texts are NOT reset PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_CREATURE_TEXT); SQLResult result = DB.World.Query(stmt); if (result.IsEmpty()) { Log.outInfo(LogFilter.ServerLoading, "Loaded 0 ceature texts. DB table `creature_texts` is empty."); return; } uint textCount = 0; uint creatureCount = 0; do { CreatureTextEntry temp = new CreatureTextEntry(); temp.creatureId = result.Read <uint>(0); temp.groupId = result.Read <byte>(1); temp.id = result.Read <byte>(2); temp.text = result.Read <string>(3); temp.type = (ChatMsg)result.Read <byte>(4); temp.lang = (Language)result.Read <byte>(5); temp.probability = result.Read <float>(6); temp.emote = (Emote)result.Read <uint>(7); temp.duration = result.Read <uint>(8); temp.sound = result.Read <uint>(9); temp.BroadcastTextId = result.Read <uint>(10); temp.TextRange = (CreatureTextRange)result.Read <byte>(11); if (temp.sound != 0) { if (!CliDB.SoundKitStorage.ContainsKey(temp.sound)) { Log.outError(LogFilter.Sql, "GossipManager: Entry {0}, Group {1} in table `creature_texts` has Sound {2} but sound does not exist.", temp.creatureId, temp.groupId, temp.sound); temp.sound = 0; } } if (ObjectManager.GetLanguageDescByID(temp.lang) == null) { Log.outError(LogFilter.Sql, "GossipManager: Entry {0}, Group {1} in table `creature_texts` using Language {2} but Language does not exist.", temp.creatureId, temp.groupId, temp.lang); temp.lang = Language.Universal; } if (temp.type >= ChatMsg.Max) { Log.outError(LogFilter.Sql, "GossipManager: Entry {0}, Group {1} in table `creature_texts` has Type {2} but this Chat Type does not exist.", temp.creatureId, temp.groupId, temp.type); temp.type = ChatMsg.Say; } if (temp.emote != 0) { if (!CliDB.EmotesStorage.ContainsKey((uint)temp.emote)) { Log.outError(LogFilter.Sql, "GossipManager: Entry {0}, Group {1} in table `creature_texts` has Emote {2} but emote does not exist.", temp.creatureId, temp.groupId, temp.emote); temp.emote = Emote.OneshotNone; } } if (temp.BroadcastTextId != 0) { if (!CliDB.BroadcastTextStorage.ContainsKey(temp.BroadcastTextId)) { Log.outError(LogFilter.Sql, "CreatureTextMgr: Entry {0}, Group {1}, Id {2} in table `creature_texts` has non-existing or incompatible BroadcastTextId {3}.", temp.creatureId, temp.groupId, temp.id, temp.BroadcastTextId); temp.BroadcastTextId = 0; } } if (temp.TextRange > CreatureTextRange.World) { Log.outError(LogFilter.Sql, "CreatureTextMgr: Entry {0}, Group {1}, Id {2} in table `creature_text` has incorrect TextRange {3}.", temp.creatureId, temp.groupId, temp.id, temp.TextRange); temp.TextRange = CreatureTextRange.Normal; } if (!mTextMap.ContainsKey(temp.creatureId)) { mTextMap[temp.creatureId] = new MultiMap <byte, CreatureTextEntry>(); ++creatureCount; } mTextMap[temp.creatureId].Add(temp.groupId, temp); ++textCount; } while (result.NextRow()); Log.outInfo(LogFilter.ServerLoading, "Loaded {0} creature texts for {1} creatures in {2} ms", textCount, creatureCount, Time.GetMSTimeDiffToNow(oldMSTime)); }
static bool HandleListMailCommand(StringArguments args, CommandHandler handler) { if (args.Empty()) { return(false); } Player target; ObjectGuid targetGuid; string targetName; PreparedStatement stmt = null; ObjectGuid parseGUID = ObjectGuid.Create(HighGuid.Player, args.NextUInt64()); if (ObjectManager.GetPlayerNameByGUID(parseGUID, out targetName)) { target = Global.ObjAccessor.FindPlayer(parseGUID); targetGuid = parseGUID; } else if (!handler.extractPlayerTarget(args, out target, out targetGuid, out targetName)) { return(false); } stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_MAIL_LIST_COUNT); stmt.AddValue(0, targetGuid.GetCounter()); SQLResult result = DB.Characters.Query(stmt); if (!result.IsEmpty()) { uint countMail = result.Read <uint>(0); string nameLink = handler.playerLink(targetName); handler.SendSysMessage(CypherStrings.ListMailHeader, countMail, nameLink, targetGuid.ToString()); handler.SendSysMessage(CypherStrings.AccountListBar); stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_MAIL_LIST_INFO); stmt.AddValue(0, targetGuid.GetCounter()); SQLResult result1 = DB.Characters.Query(stmt); if (!result1.IsEmpty()) { do { uint messageId = result1.Read <uint>(0); ulong senderId = result1.Read <ulong>(1); string sender = result1.Read <string>(2); ulong receiverId = result1.Read <ulong>(3); string receiver = result1.Read <string>(4); string subject = result1.Read <string>(5); long deliverTime = result1.Read <uint>(6); long expireTime = result1.Read <uint>(7); ulong money = result1.Read <ulong>(8); byte hasItem = result1.Read <byte>(9); uint gold = (uint)(money / MoneyConstants.Gold); uint silv = (uint)(money % MoneyConstants.Gold) / MoneyConstants.Silver; uint copp = (uint)(money % MoneyConstants.Gold) % MoneyConstants.Silver; string receiverStr = handler.playerLink(receiver); string senderStr = handler.playerLink(sender); handler.SendSysMessage(CypherStrings.ListMailInfo1, messageId, subject, gold, silv, copp); handler.SendSysMessage(CypherStrings.ListMailInfo2, senderStr, senderId, receiverStr, receiverId); handler.SendSysMessage(CypherStrings.ListMailInfo3, Time.UnixTimeToDateTime(deliverTime).ToLongDateString(), Time.UnixTimeToDateTime(expireTime).ToLongDateString()); if (hasItem == 1) { SQLResult result2 = DB.Characters.Query("SELECT item_guid FROM mail_items WHERE mail_id = '{0}'", messageId); if (!result2.IsEmpty()) { do { uint item_guid = result2.Read <uint>(0); stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_MAIL_LIST_ITEMS); stmt.AddValue(0, item_guid); SQLResult result3 = DB.Characters.Query(stmt); if (!result3.IsEmpty()) { do { uint item_entry = result3.Read <uint>(0); uint item_count = result3.Read <uint>(1); SQLResult result4 = DB.World.Query("SELECT name, quality FROM item_template WHERE entry = '{0}'", item_entry); string item_name = result4.Read <string>(0); int item_quality = result4.Read <byte>(1); if (handler.GetSession() != null) { uint color = ItemConst.ItemQualityColors[item_quality]; string itemStr = "|c" + color + "|Hitem:" + item_entry + ":0:0:0:0:0:0:0:0:0|h[" + item_name + "]|h|r"; handler.SendSysMessage(CypherStrings.ListMailInfoItem, itemStr, item_entry, item_guid, item_count); } else { handler.SendSysMessage(CypherStrings.ListMailInfoItem, item_name, item_entry, item_guid, item_count); } }while (result3.NextRow()); } }while (result2.NextRow()); } } handler.SendSysMessage(CypherStrings.AccountListBar); }while (result1.NextRow()); } else { handler.SendSysMessage(CypherStrings.ListMailNotFound); } return(true); } else { handler.SendSysMessage(CypherStrings.ListMailNotFound); } return(true); }
internal void SetStatement(int ordnal, PreparedStatement statement) { if (isTypeSet) { statement.setObject(ordnal, javaValue, javaType); } else { statement.setObject(ordnal, javaValue); } }
static bool HandleResetTalentsCommand(StringArguments args, CommandHandler handler) { Player target; ObjectGuid targetGuid; string targetName; if (!handler.ExtractPlayerTarget(args, out target, out targetGuid, out targetName)) { /* TODO: 6.x remove/update pet talents * // Try reset talents as Hunter Pet * Creature* creature = handler.getSelectedCreature(); * if (!*args && creature && creature.IsPet()) * { * Unit* owner = creature.GetOwner(); * if (owner && owner.GetTypeId() == TYPEID_PLAYER && creature.ToPet().IsPermanentPetFor(owner.ToPlayer())) * { * creature.ToPet().resetTalents(); * owner.ToPlayer().SendTalentsInfoData(true); * * ChatHandler(owner.ToPlayer().GetSession()).SendSysMessage(LANG_RESET_PET_TALENTS); * if (!handler.GetSession() || handler.GetSession().GetPlayer() != owner.ToPlayer()) * handler.PSendSysMessage(LANG_RESET_PET_TALENTS_ONLINE, handler.GetNameLink(owner.ToPlayer()).c_str()); * } * return true; * } */ handler.SendSysMessage(CypherStrings.NoCharSelected); return(false); } if (target) { target.ResetTalents(true); target.ResetTalentSpecialization(); target.SendTalentsInfoData(); target.SendSysMessage(CypherStrings.ResetTalents); if (handler.GetSession() == null || handler.GetSession().GetPlayer() != target) { handler.SendSysMessage(CypherStrings.ResetTalentsOnline, handler.GetNameLink(target)); } /* TODO: 6.x remove/update pet talents * Pet* pet = target.GetPet(); * Pet.resetTalentsForAllPetsOf(target, pet); * if (pet) * target.SendTalentsInfoData(true); */ return(true); } else if (!targetGuid.IsEmpty()) { PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_ADD_AT_LOGIN_FLAG); stmt.AddValue(0, (ushort)(AtLoginFlags.None | AtLoginFlags.ResetPetTalents)); stmt.AddValue(1, targetGuid.GetCounter()); DB.Characters.Execute(stmt); string nameLink = handler.PlayerLink(targetName); handler.SendSysMessage(CypherStrings.ResetTalentsOffline, nameLink); return(true); } handler.SendSysMessage(CypherStrings.NoCharSelected); return(false); }
private void CreateStatement() { if (statement != null) { statement.close(); } try { statement = connection.connection.prepareStatement(template.TrueSql); } catch (org.h2.jdbc.JdbcSQLException ex) { throw new H2Exception(ex); } if (timeoutSet) { statement.setQueryTimeout(commandTimeout); } }
static bool HandleLfgGroupInfoCommand(StringArguments args, CommandHandler handler) { if (args.Empty()) { return(false); } Player playerTarget = null; ObjectGuid guidTarget; string nameTarget; ObjectGuid parseGUID = ObjectGuid.Create(HighGuid.Player, args.NextUInt64()); if (ObjectManager.GetPlayerNameByGUID(parseGUID, out nameTarget)) { playerTarget = Global.ObjAccessor.FindPlayer(parseGUID); guidTarget = parseGUID; } else if (!handler.extractPlayerTarget(args, out playerTarget, out guidTarget, out nameTarget)) { return(false); } Group groupTarget = null; if (playerTarget) { groupTarget = playerTarget.GetGroup(); } else { PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GROUP_MEMBER); stmt.AddValue(0, guidTarget.GetCounter()); SQLResult resultGroup = DB.Characters.Query(stmt); if (!resultGroup.IsEmpty()) { groupTarget = Global.GroupMgr.GetGroupByDbStoreId(resultGroup.Read <uint>(0)); } } if (!groupTarget) { handler.SendSysMessage(CypherStrings.LfgNotInGroup, nameTarget); return(false); } ObjectGuid guid = groupTarget.GetGUID(); handler.SendSysMessage(CypherStrings.LfgGroupInfo, groupTarget.isLFGGroup(), Global.LFGMgr.GetState(guid), Global.LFGMgr.GetDungeon(guid)); foreach (var slot in groupTarget.GetMemberSlots()) { Player p = Global.ObjAccessor.FindPlayer(slot.guid); if (p) { GetPlayerInfo(handler, p); } else { handler.SendSysMessage("{0} is offline.", slot.name); } } return(true); }
////////////////////////////// // Test Helpers ////////////////////////////// private void AssertValid(ISession session, PreparedStatement ps, object value) { try { session.Execute(ps.Bind(Guid.NewGuid(), value)); } catch (Exception e) { string assertFailMsg = string.Format("Exception was thrown, but shouldn't have been! \nException message: {0}, Exception StackTrace: {1}", e.Message, e.StackTrace); Assert.Fail(assertFailMsg); } }
void LoadInstanceData(uint instanceId) { PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_SCENARIO_INSTANCE_CRITERIA_FOR_INSTANCE); stmt.AddValue(0, instanceId); SQLResult result = DB.Characters.Query(stmt); if (!result.IsEmpty()) { SQLTransaction trans = new SQLTransaction(); long now = Time.UnixTime; List <CriteriaTree> criteriaTrees = new List <CriteriaTree>(); do { uint id = result.Read <uint>(0); ulong counter = result.Read <ulong>(1); long date = result.Read <uint>(2); Criteria criteria = Global.CriteriaMgr.GetCriteria(id); if (criteria == null) { // Removing non-existing criteria data for all instances Log.outError(LogFilter.Scenario, "Removing scenario criteria {0} data from the table `instance_scenario_progress`.", id); stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_SCENARIO_INSTANCE_CRITERIA); stmt.AddValue(0, instanceId); stmt.AddValue(1, id); trans.Append(stmt); continue; } if (criteria.Entry.StartTimer != 0 && (date + criteria.Entry.StartTimer) < now) { continue; } switch (criteria.Entry.Type) { // Blizzard appears to only stores creatures killed progress for unknown reasons. Either technical shortcoming or intentional case CriteriaTypes.KillCreature: break; default: continue; } SetCriteriaProgress(criteria, counter, null, ProgressType.Set); List <CriteriaTree> trees = Global.CriteriaMgr.GetCriteriaTreesByCriteria(criteria.Id); if (trees != null) { foreach (CriteriaTree tree in trees) { criteriaTrees.Add(tree); } } }while (result.NextRow()); DB.Characters.CommitTransaction(trans); foreach (CriteriaTree tree in criteriaTrees) { ScenarioStepRecord step = tree.ScenarioStep; if (step == null) { continue; } if (IsCompletedCriteriaTree(tree)) { SetStepState(step, ScenarioStepState.Done); } } } }
//Only for tests purpose: //private class InsertQuery : CqlCommand //{ // string Query; // internal InsertQuery(string query) // { // this.Query = query; // } // public override string GetCql() // { // return Query; // } //} protected void init(CCMBridge.CCMCluster c, int n, bool batch, ConsistencyLevel cl) { CassandraRoutingKey routingKey = new CassandraRoutingKey(); routingKey.RawRoutingKey = Enumerable.Repeat((byte)0x00, 4).ToArray(); // We don't use insert for our test because the resultSet don't ship the queriedHost // Also note that we don't use tracing because this would trigger requests that screw up the test' for (int i = 0; i < n; ++i) if (batch) // BUG: WriteType == SIMPLE { StringBuilder bth = new StringBuilder(); bth.AppendLine("BEGIN BATCH"); bth.AppendLine(String.Format("INSERT INTO {0}(k, i) VALUES (0, 0)", TestUtils.SIMPLE_TABLE)); bth.AppendLine("APPLY BATCH"); var qh = c.Session.Execute(new SimpleStatement(bth.ToString()).SetRoutingKey(routingKey).SetConsistencyLevel(cl)).QueriedHost; } else { var qh = c.Session.Execute(new SimpleStatement(String.Format("INSERT INTO {0}(k, i) VALUES (0, 0)", TestUtils.SIMPLE_TABLE)).SetRoutingKey(routingKey).SetConsistencyLevel(cl)).QueriedHost; } prepared = c.Session.Prepare("SELECT * FROM " + TestUtils.SIMPLE_TABLE + " WHERE k = ?").SetConsistencyLevel(cl); }
public void SaveToDB() { if (_criteriaProgress.Empty()) { return; } DifficultyRecord difficultyEntry = CliDB.DifficultyStorage.LookupByKey(_map.GetDifficultyID()); if (difficultyEntry == null || difficultyEntry.Flags.HasAnyFlag(DifficultyFlags.ChallengeMode)) // Map should have some sort of "CanSave" boolean that returns whether or not the map is savable. (Challenge modes cannot be saved for example) { return; } uint id = _map.GetInstanceId(); if (id == 0) { Log.outDebug(LogFilter.Scenario, "Scenario.SaveToDB: Can not save scenario progress without an instance save. Map.GetInstanceId() did not return an instance save."); return; } SQLTransaction trans = new SQLTransaction(); foreach (var iter in _criteriaProgress) { if (!iter.Value.Changed) { continue; } Criteria criteria = Global.CriteriaMgr.GetCriteria(iter.Key); switch (criteria.Entry.Type) { // Blizzard only appears to store creature kills case CriteriaTypes.KillCreature: break; default: continue; } if (iter.Value.Counter != 0) { PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_SCENARIO_INSTANCE_CRITERIA); stmt.AddValue(0, id); stmt.AddValue(1, iter.Key); trans.Append(stmt); stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_SCENARIO_INSTANCE_CRITERIA); stmt.AddValue(0, id); stmt.AddValue(1, iter.Key); stmt.AddValue(2, iter.Value.Counter); stmt.AddValue(3, (uint)iter.Value.Date); trans.Append(stmt); } iter.Value.Changed = false; } DB.Characters.CommitTransaction(trans); }
public void InitPreparedStatement(ITestCluster testCluster, int numberOfInsertsToMake, bool batch, ConsistencyLevel consistencyLevel) { // We don't use insert for our test because the resultSet don't ship the queriedHost // Also note that we don't use tracing because this would trigger requests that screw up the test for (int i = 0; i < numberOfInsertsToMake; ++i) if (batch) // BUG: WriteType == SIMPLE { var bth = new StringBuilder(); bth.AppendLine("BEGIN BATCH"); bth.AppendLine(String.Format("INSERT INTO {0}(k, i) VALUES (0, 0)", TableName)); bth.AppendLine("APPLY BATCH"); testCluster.Session.Execute(new SimpleStatement(bth.ToString()).SetConsistencyLevel(consistencyLevel)); } else { testCluster.Session.Execute( new SimpleStatement(String.Format("INSERT INTO {0}(k, i) VALUES (0, 0)", TableName)).SetConsistencyLevel(consistencyLevel)); } PreparedStatement = testCluster.Session.Prepare("SELECT * FROM " + TableName + " WHERE k = ?").SetConsistencyLevel(consistencyLevel); }
private Task <string[]> ExecuteMultiple(ITestCluster testCluster, Session session, PreparedStatement ps, bool stopNode, int maxConcurrency, int repeatLength) { var hosts = new ConcurrentDictionary <string, bool>(); var tcs = new TaskCompletionSource <string[]>(); var receivedCounter = 0L; var sendCounter = 0L; var currentlySentCounter = 0L; var stopMark = repeatLength / 8L; Action sendNew = null; sendNew = () => { var sent = Interlocked.Increment(ref sendCounter); if (sent > repeatLength) { return; } Interlocked.Increment(ref currentlySentCounter); var statement = ps.Bind(DateTime.Now.Millisecond, (int)sent); var executeTask = session.ExecuteAsync(statement); executeTask.ContinueWith(t => { if (t.Exception != null) { tcs.TrySetException(t.Exception.InnerException); return; } hosts.AddOrUpdate(t.Result.Info.QueriedHost.ToString(), true, (k, v) => v); var received = Interlocked.Increment(ref receivedCounter); if (stopNode && received == stopMark) { Task.Factory.StartNew(() => { testCluster.StopForce(2); }, TaskCreationOptions.LongRunning); } if (received == repeatLength) { // Mark this as finished tcs.TrySetResult(hosts.Keys.ToArray()); return; } sendNew(); }, TaskContinuationOptions.ExecuteSynchronously); }; for (var i = 0; i < maxConcurrency; i++) { sendNew(); } return(tcs.Task); }