public ReturnValue AddSessionEncounters(List <SessionEncounter> sessionEncounters) { var returnValue = new ReturnValue(); try { string timeElapsed; DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); foreach (var sessionEncounter in sessionEncounters) { dapperDb.SessionEncounterTable.Insert( new //SessionEncounter() { SessionId = sessionEncounter.SessionId, EncounterId = sessionEncounter.EncounterId }); } returnValue.Success = true; return(returnValue); } catch (Exception ex) { returnValue.Message = ex.Message; return(returnValue); } }
public ReturnValue AddNpcDeath(NpcDeath npcDeath) { var returnValue = new ReturnValue(); try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var newId = dapperDb.NpcDeathTable.Insert( new //NpcDeath() { Name = npcDeath.Name, Deaths = npcDeath.Deaths }); returnValue.Success = true; returnValue.Message = newId.ToString(); return(returnValue); } catch (Exception ex) { returnValue.Message = ex.Message; return(returnValue); } }
public ReturnValue AddEncounter(Encounter encounter) { var returnValue = new ReturnValue(); try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var result = dapperDb.EncounterTable.Insert( new //Models.Encounter() { BossFightId = encounter.BossFightId, Date = encounter.Date, Duration = encounter.Duration.ToString(), SuccessfulKill = encounter.SuccessfulKill, ValidForRanking = encounter.ValidForRanking, UploaderId = encounter.UploaderId, GuildId = encounter.GuildId, IsPublic = encounter.IsPublic, EncounterDifficultyId = encounter.EncounterDifficultyId }); returnValue.Message = result.ToString(); returnValue.Success = true; return(returnValue); } catch (Exception ex) { returnValue.Message = ex.Message; return(returnValue); } }
public static bool UpdateUser(FateUserInfo user) { using (DapperDb db = DapperDbFactory.CreateDb()) { return(db.Update <FateUserInfo>(user)); } }
public static bool UpdateUser(LinkAddressInfo linkAddress) { using (DapperDb db = DapperDbFactory.CreateDb()) { return(db.Update <LinkAddressInfo>(linkAddress)); } }
//private static List<ContactDetailsEntity> LoadBadWords() //{ // AzureTableStorage clinet = // new AzureTableStorage( // "DefaultEndpointsProtocol=https;AccountName=phoneusehistory;AccountKey=nHyLOGDDDaNK957Mw5q+lsl6+CeuEYvFh9B7w4joXK059EQqksrXpbmCY43uH38ueJTpDdeYeDlr+JCEheql8Q==", // new MyStateEmptyLogger(null)); // ContactDetailsSuspecetWordsLoader loader = new ContactDetailsSuspecetWordsLoader(new EmptyDb(), clinet, // new MyStateEmptyLogger(null)); // loader.ForEach(batchCount: 1000, dellayInMilliSeconds: 100, // operations: new Func<List<IContactDetails>, bool>[] { AddToFileList }); //} private static void LoadExcelToBadWordsTable(string[] strings) { string[] args; args = new[] { "Curses3.txt" }; if (args.IsNullOrEmpty()) { return; } var items = new HashSet <string>(); foreach (var fileName in args) { using (var stream = new StreamReader(new FileStream(fileName, FileMode.Open))) { while (!stream.EndOfStream) { var collection = stream.ReadLine()?.Split(',', /*' ', */ '\n').Where(x => x != "").ToList(); collection?.ForEach(x => items.Add(x.Trim())); } } } IDbCompleteDataStore sql = new DapperDb("MyState_MainDB"); //sql.SaveBadWords(items); foreach (var item in items) { sql.SaveBadWord(item); } }
public ReturnValue AddPlayers(List <Player> players) { var returnValue = new ReturnValue(); try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); foreach (var player in players) { dapperDb.PlayerTable.Insert( new //Player() { Name = player.Name, PlayerId = player.PlayerId, Shard = player.Shard }); } returnValue.Success = true; return(returnValue); } catch (Exception ex) { returnValue.Message = ex.Message; return(returnValue); } }
public static IList <FateUserInfo> GetUserList() { using (DapperDb db = DapperDbFactory.CreateDb()) { return(db.Query <FateUserInfo>()); } }
public ReturnValue AddAbilities(List <Ability> abilities) { var returnValue = new ReturnValue(); try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); foreach (var ability in abilities) { dapperDb.AbilityTable.Insert( new //Ability() { Name = ability.Name, AbilityId = ability.AbilityId, Description = ability.Description, DamageType = ability.DamageType }); } returnValue.Success = true; return(returnValue); } catch (Exception ex) { returnValue.Message = ex.Message; return(returnValue); } }
/// <summary> /// Updated for MySQL /// </summary> /// <param name="overview"></param> /// <returns></returns> public ReturnValue Add(EncounterOverview overview) { var returnValue = new ReturnValue(); try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var newId = dapperDb.EncounterOverviewTable.Insert( new //EncounterOverview() { EncounterId = overview.EncounterId, AverageDps = overview.AverageDps, PlayerDeaths = overview.PlayerDeaths, AverageHps = overview.AverageHps, AverageAps = overview.AverageAps }); if (newId > 0) { _logger.Debug(string.Format("Overview has successfully created for encounter {0}", overview.EncounterId)); returnValue.Message = newId.ToString(); returnValue.Success = true; } } catch (Exception ex) { returnValue.Message = ex.Message; } return(returnValue); }
public ReturnValue CreateSession(string email, Session session) { var returnValue = new ReturnValue(); try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); _logger.Debug(string.Format("{0} is trying to create a session. Name: {1}, AuthUserCharacterId: {2}, Date: {3}, Public: {4}", email, session.Name, session.AuthUserCharacterId, session.Date, session.EncountersPublic)); var newId = dapperDb.SessionTable.Insert( new //Session() { Name = session.Name, AuthUserCharacterId = session.AuthUserCharacterId, Date = session.Date, Duration = new TimeSpan(0, 0, 1).ToString(), EncountersPublic = session.EncountersPublic }); if (newId != null) { _logger.Debug(string.Format("{0} has successfully created a new session ({1}: {2})", email, newId, session.Name)); returnValue.Message = newId.ToString(); returnValue.Success = true; } } catch (Exception ex) { _logger.Error(string.Format("An error occurred while trying to create a session! {0}", ex.Message)); returnValue.Message = ex.Message; returnValue.Success = false; } return(returnValue); }
public static LinkAddressInfo GetLinkInfo(string linkAddress) { using (DapperDb db = DapperDbFactory.CreateDb()) { SqlQuery filter = SqlQuery <LinkAddressInfo> .Builder(db).AndWhere(o => o.LinkAddress, FilterExpression.Equal, linkAddress); return(db.SingleOrDefault <LinkAddressInfo>(filter)); } }
public static IList <LinkAddressInfo> GetLinkList(LinkAddressType type) { using (DapperDb db = DapperDbFactory.CreateDb()) { SqlQuery filter = SqlQuery <LinkAddressInfo> .Builder(db).AndWhere(o => o.LinkType, FilterExpression.Equal, (int)type); return(db.Query <LinkAddressInfo>(filter)); } }
public HttpLogInterfaceCallBLL() { var conn = System.Configuration.ConfigurationManager.AppSettings["SmartHttpLog"]; DapperDb = new DapperDb("") { conn = conn }; }
public static FateUserInfo GetUser(string userCode) { using (DapperDb db = DapperDbFactory.CreateDb()) { SqlQuery filter = SqlQuery <FateUserInfo> .Builder(db).AndWhere(o => o.UserCode, FilterExpression.Equal, userCode); return(db.SingleOrDefault <FateUserInfo>(filter)); } }
public ReturnValue Remove(int applicationId, string email) { ReturnValue returnValue = new ReturnValue(); // Check that the update ID has actually been set if (applicationId == 0) { const string msg = "Operation failed - The ID of the record to delete has not been set"; _logger.Error(msg); returnValue.Message = msg; return(returnValue); } try { var sw = new Stopwatch(); sw.Start(); DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); bool success = dapperDb.AuthUserCharacterGuildApplicationTable.Delete(applicationId); sw.Stop(); if (success) { _logger.Info(string.Format("The application with the ID of {0} was deleted by {1}", applicationId, email)); _logger.Debug(string.Format("Guild application (ID {0}) delete by {1} completed in {2}", applicationId, email, sw.Elapsed)); } else { _logger.Warn(string.Format("The application with the ID of {0} could not be deleted.", applicationId)); _logger.Debug(string.Format("Guild application {0} delete by {1} failed.", applicationId, email)); } returnValue.Success = success; returnValue.TimeTaken = sw.Elapsed; } catch (Exception ex) { // Check for foreign key constraint failure first if (ex.Message.Contains("DELETE statement conflicted with the REFERENCE constraint") || ex.Message.Contains("Cannot delete or update a parent row")) { string msg = "Delete operation failed - this record is depended upon by other tables within the database and cannot be deleted at this time."; _logger.Error(msg); returnValue.Message = msg; return(returnValue); } returnValue.Message = ex.Message; } return(returnValue); }
/// <summary> /// Updated for MySQL /// </summary> /// <param name="email"></param> /// <param name="password"></param> /// <returns></returns> public ReturnValue ResetPassword(string email, string password) { string hash; string salt; AuthEncryption.GenerateHashAndSalt(password, out salt, out hash); ReturnValue returnValue = new ReturnValue(); try { var sw = new Stopwatch(); sw.Start(); DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var userId = GetIdByEmail(email); if (userId == 0) { returnValue.Message = string.Format("No user was found with the email address {0}", email); return(returnValue); } var userToSet = dapperDb.AuthUserTable.Get(userId); var snapshot = Snapshotter.Start(userToSet); userToSet.ExtraInformation2 = salt; userToSet.PasswordHash = hash; userToSet.PasswordResetToken = null; userToSet.AccessFailedCount = 0; DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { sw.Stop(); returnValue.Message = "There was nothing to update!"; return(returnValue); } dapperDb.AuthUserTable.Update(userId, snapshot.Diff()); sw.Stop(); returnValue.Success = true; returnValue.TimeTaken = sw.Elapsed; } catch (Exception ex) { returnValue.Message = ex.Message; } return(returnValue); }
public ReturnValue KickCharacterFromGuild(int authUserCharacterId, int guildId, string email) { string timeElapsed; // To kick a member from a guild, we just set the 'Removed' value to true, and then add another AuthUserCharacter record with no guild. var returnValue = new ReturnValue(); try { var outgoingMember = Query( q => q.Query <AuthUserCharacter>(MySQL.AuthUserCharacter.Get, new { @id = authUserCharacterId }), out timeElapsed).SingleOrDefault(); if (outgoingMember == null) { returnValue.Message = "Couldn't find the character to remove!"; return(returnValue); } // Set the removed flag first Execute( q => q.Execute(MySQL.AuthUserCharacter.MarkCharacterRemovedIncludingGuildId, new { @id = authUserCharacterId, guildId }), out timeElapsed); _logger.Debug(string.Format("{0} has kicked {1} from guild #{2}", email, outgoingMember.CharacterName, guildId)); // Now, add the new unguilded character DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var newId = dapperDb.AuthUserCharacterTable.Insert( new //AuthUserCharacter() { AuthUserId = outgoingMember.AuthUserId, CharacterName = outgoingMember.CharacterName, ShardId = outgoingMember.ShardId }); if (newId > 0) { returnValue.Success = true; _logger.Debug(string.Format("The character {0} has been successfully recreated.", outgoingMember.CharacterName)); } } catch (Exception ex) { _logger.Debug(string.Format("An error occurred while removing character {0} from guild {1}: {2}", authUserCharacterId, guildId, ex.Message)); returnValue.Message = ex.Message; } return(returnValue); }
// Commands /// <summary> /// Updated for MySQL /// </summary> /// <param name="newItem"></param> /// <param name="username"></param> /// <returns></returns> public ReturnValue Add(AuthUser newItem, string username) { ReturnValue returnValue = new ReturnValue(); try { var sw = new Stopwatch(); sw.Start(); DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var newId = dapperDb.AuthUserTable.Insert( new //AuthUser() { AccessFailedCount = 0, ShortMenuFormat = true, ShowGuildMenu = true, Email = newItem.Email, ExtraInformation1 = newItem.ExtraInformation1, ExtraInformation2 = newItem.ExtraInformation2, LockoutEnabled = true, PasswordHash = newItem.PasswordHash, EmailConfirmed = newItem.EmailConfirmed, TimeZone = newItem.TimeZone }); sw.Stop(); if (newId != null) { returnValue.Success = true; returnValue.TimeTaken = sw.Elapsed; } } catch (Exception ex) { // Check for unique constraint failure first if (ex.Message.Contains("UNIQUE KEY")) { const string msg = "Operation failed - a matching AuthUser already exists."; returnValue.Message = msg; return(returnValue); } returnValue.Message = ex.Message; } return(returnValue); }
public ReturnValue RenameSession(string email, int sessionId, string newName) { var returnValue = new ReturnValue(); try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); // Get the existing session var existingSession = dapperDb.SessionTable.Get(sessionId); if (existingSession == null) { // Something went drastically wrong, this shouldn't happen string msg = string.Format("Couldn't update the session with ID {0} because it didn't exist when we went to update it!", sessionId); _logger.Error(msg); returnValue.Message = msg; return(returnValue); } // Snapshot the current record to track changes var snapshot = Snapshotter.Start(existingSession); existingSession.Name = newName; // Check if we have any changes to make DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { const string msg = "Session name has not changed - nothing to save!"; _logger.Info(msg); returnValue.Message = msg; return(returnValue); } dapperDb.SessionTable.Update(sessionId, snapshot.Diff()); _logger.Debug(string.Format("Updated session {0} with the new name {1}", sessionId, newName)); returnValue.Success = true; return(returnValue); } catch (Exception ex) { string msg = string.Format("An error occurred while trying to update the session name! {0}", ex.Message); _logger.Error(msg); returnValue.Message = msg; return(returnValue); } }
/// <summary> /// Updated for MySQL /// </summary> /// <param name="email"></param> /// <param name="loginTime"></param> /// <param name="loginAddress"></param> /// <returns></returns> public ReturnValue UpdateLastLoginInfo(string email, DateTime loginTime, string loginAddress) { ReturnValue returnValue = new ReturnValue(); try { var sw = new Stopwatch(); sw.Start(); DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var userId = GetIdByEmail(email); if (userId == 0) { returnValue.Message = string.Format("No user was found with the email address {0}", email); return(returnValue); } var userToSet = dapperDb.AuthUserTable.Get(userId); var snapshot = Snapshotter.Start(userToSet); userToSet.PreviousLoginAddress = userToSet.LastLoginAddress; userToSet.PreviousLoginTime = userToSet.LastLoggedIn; userToSet.LastLoggedIn = loginTime; userToSet.LastLoginAddress = loginAddress; userToSet.AccessFailedCount = 0; DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { sw.Stop(); returnValue.Message = "The failed count was not reset!"; return(returnValue); } dapperDb.AuthUserTable.Update(userId, snapshot.Diff()); sw.Stop(); returnValue.Success = true; returnValue.TimeTaken = sw.Elapsed; } catch (Exception ex) { returnValue.Message = ex.Message; } return(returnValue); }
public ReturnValue UpdateMenuFormat(string email, bool isShortMenuFormat) { ReturnValue returnValue = new ReturnValue(); try { var sw = new Stopwatch(); sw.Start(); DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var userId = GetIdByEmail(email); if (userId == 0) { returnValue.Message = string.Format("No user was found with the email address {0}", email); return(returnValue); } var userToSet = dapperDb.AuthUserTable.Get(userId); var snapshot = Snapshotter.Start(userToSet); userToSet.ShortMenuFormat = isShortMenuFormat; DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { sw.Stop(); returnValue.Message = "The menu format was not changed."; return(returnValue); } dapperDb.AuthUserTable.Update(userId, snapshot.Diff()); sw.Stop(); returnValue.Success = true; returnValue.TimeTaken = sw.Elapsed; } catch (Exception ex) { returnValue.Message = ex.Message; } return(returnValue); }
/// <summary> /// Updated for MySQL /// </summary> /// <param name="email"></param> /// <returns></returns> public ReturnValue LockAccount(string email) { ReturnValue returnValue = new ReturnValue(); try { var sw = new Stopwatch(); sw.Start(); DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var userId = GetIdByEmail(email); if (userId == 0) { returnValue.Message = string.Format("No user was found with the email address {0}", email); return(returnValue); } var userToSet = dapperDb.AuthUserTable.Get(userId); var snapshot = Snapshotter.Start(userToSet); userToSet.AccessFailedCount = 0; userToSet.LockoutEndDate = DateTime.UtcNow.AddMinutes(5); DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { sw.Stop(); returnValue.Message = "There was nothing to update!"; return(returnValue); } dapperDb.AuthUserTable.Update(userId, snapshot.Diff()); sw.Stop(); returnValue.Success = true; returnValue.TimeTaken = sw.Elapsed; } catch (Exception ex) { returnValue.Message = ex.Message; } return(returnValue); }
public void UpdateSessionLogTotalPlayedTime(Dictionary <int, long> totalPlayedTimes) { try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3); foreach (var kvp in totalPlayedTimes) { // Get the existing session var sessionLog = dapperDb.SessionLogTable.Get(kvp.Key); if (sessionLog == null) { // Something went drastically wrong, this shouldn't happen _logger.Error(string.Format("Couldn't update the sessionLog with ID {0} because it didn't exist when we went to update it!", kvp.Key)); continue; } // Snapshot the current record to track changes var snapshot = Snapshotter.Start(sessionLog); sessionLog.TotalPlayedTime = kvp.Value; // Check if we have any changes to make DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { continue; } dapperDb.SessionLogTable.Update(kvp.Key, snapshot.Diff()); TimeSpan timeSpan = new TimeSpan(kvp.Value); _logger.Debug(string.Format("Updated sessionLog {0} with TotalPlayedTime {1} ({2})", kvp.Key, kvp.Value, timeSpan)); } } catch (Exception ex) { _logger.Error(string.Format("An error occurred while trying to update the sessionLog TotalPlayedTimes! {0}", ex.Message)); } }
public ReturnValue Create(SessionLog sessionLog) { var returnValue = new ReturnValue(); try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var newId = dapperDb.SessionLogTable.Insert( new //SessionLog() { AuthUserCharacterId = sessionLog.AuthUserCharacterId, Filename = sessionLog.Filename, GuildId = sessionLog.GuildId, LogSize = sessionLog.LogSize, SessionId = sessionLog.SessionId, Token = sessionLog.Token, TotalPlayedTime = sessionLog.TotalPlayedTime }); if (newId != null) { //_logger.Debug(string.Format("{0} has successfully created a new session ({1}: {2})", email, newId, session.Name)); returnValue.Message = newId.ToString(); returnValue.Success = true; _logger.Debug(string.Format("Session log successfully created for Session {0}", sessionLog.SessionId)); } } catch (Exception ex) { _logger.Error(string.Format("An error occurred while trying to add a session log! {0}", ex.Message)); returnValue.Message = ex.Message; returnValue.Success = false; } return(returnValue); }
public MultipleUpdatesDapperMiddleware(RequestDelegate next, DapperDb db) { _next = next; _db = db; }
public SingleQueryDapperMiddleware(RequestDelegate next, DapperDb db) { _next = next; _db = db; }
public PessoaRepository(DapperDb db = null) { Db = db; }
// Command methods /// <summary> /// Create a new character and link it to the user performing the create. /// Validation of existing characters is performed here, prior to the insert. Updated for MySQL /// </summary> /// <param name="email">The email address of the user performing the create</param> /// <param name="character">The character to add</param> /// <returns>A ReturnValue indicating success or failure, along with optional messages</returns> public ReturnValue Create(string email, AuthUserCharacter character) { var returnValue = new ReturnValue(); // Check to see if this character name has been taken on the given shard already. Ignore users that are 'removed' string timeElapsed; var alreadyExists = Query( q => q.Query <long>(MySQL.AuthUserCharacter.CharacterExistsOnShard, new { @characterName = character.CharacterName, @shardId = character.ShardId }), out timeElapsed) .SingleOrDefault() == 1; if (alreadyExists) { returnValue.Message = string.Format("The character '{0}' already exists!", character.CharacterName); return(returnValue); } // Check to see if this user has 6 characters on this shard already var totalCharacters = Query( q => q.Query <long>(MySQL.AuthUserCharacter.CheckMaxCharacterCountForAccount, new { email, @shardId = character.ShardId }), out timeElapsed).SingleOrDefault(); if (totalCharacters > 5) { returnValue.Message = "You have already created the maximum number of characters on this shard."; return(returnValue); } // Get the AuthUserId for this user var userId = GetAuthUserIdByEmail(email); if (userId == 0) { returnValue.Message = string.Format("No user was found with the email address {0}", email); return(returnValue); } // Add the character try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var newId = dapperDb.AuthUserCharacterTable.Insert( new //AuthUserCharacter() { AuthUserId = userId, CharacterName = character.CharacterName, ShardId = character.ShardId }); if (newId > 0) { returnValue.Success = true; } } catch (Exception ex) { returnValue.Message = ex.Message; } return(returnValue); }
/// <summary> /// Removes a character if it belongs to the user attempting to perform the delete. /// Validation of ownership is performed here, prior to the delete. Updated for MySQL /// </summary> /// <param name="email">The email address of the user performing the delete</param> /// <param name="characterId">The ID of the character to remove</param> /// <returns></returns> public ReturnValue Delete(string email, int characterId) { var returnValue = new ReturnValue(); string timeElapsed; // Get the list of characters belonging to this user var myCharacters = GetCharacters(email); // Check that the ID we were passed exists in the list, otherwise this user has tried // to delete a character that does not belong to them var thisCharacter = myCharacters.FirstOrDefault(c => c.Id == characterId); if (thisCharacter != null) { var hasCreatedSessions = Query(q => q.Query <long> (MySQL.AuthUserCharacter.HasCreatedSessions, new { @id = thisCharacter.Id }), out timeElapsed) .SingleOrDefault() == 1; var hasUploadedLogs = Query(q => q.Query <long> (MySQL.AuthUserCharacter.HasUploadedLogs, new { @id = thisCharacter.Id }), out timeElapsed) .SingleOrDefault() == 1; if (hasCreatedSessions || hasUploadedLogs) { // Set to removed rather than delete the character try { _logger.Debug("Can't remove this character as it has uploaded logs or created sessions, so marking as REMOVED"); var result = Execute( e => e.Execute(MySQL.AuthUserCharacter.MarkCharacterRemoved, new { @id = thisCharacter.Id }), out timeElapsed); if (result > 0) { _logger.Debug(string.Format("Character (ID {0}) successfully marked as removed.", thisCharacter.Id)); returnValue.Success = true; return(returnValue); } _logger.Debug(string.Format("Character (ID {0}) update (mark as removed) failed!", thisCharacter.Id)); returnValue.Success = false; returnValue.Message = "Failed to mark character as removed!"; return(returnValue); } catch (Exception ex) { string msg = string.Format("Failed to mark character {0} as removed: {1}", thisCharacter.Id, ex.Message); _logger.Debug(msg); returnValue.Message = msg; return(returnValue); } } else { try { var characterName = thisCharacter.CharacterName; // Check if this user has created any sessions, or uploaded any logs. // If they have, we need to set them to 'removed' rather than delete them. var sw = new Stopwatch(); sw.Start(); DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); bool success = dapperDb.AuthUserCharacterTable.Delete(characterId); sw.Stop(); _logger.Debug(string.Format("{0} successfully removed the character '{1}' from their account.", email, characterName)); if (thisCharacter.GuildId != null) { // Check if there are any remaining members in this guild. If not, delete that too. var guildHasMembers = Query( q => q.Query <long>(MySQL.Guild.GuildHasMembers, new { @guildId = thisCharacter.GuildId }), out timeElapsed).SingleOrDefault() == 1; if (!guildHasMembers) { // There isn't anyone left in this guild, so remove it try { var result = Execute( e => e.Execute(MySQL.Guild.RemoveGuild, new { @guildId = thisCharacter.GuildId }), out timeElapsed); if (result > 0) { _logger.Debug( string.Format( "{0} has also removed the now-empty guild after removing the last character.", email)); returnValue.Success = true; return(returnValue); } } catch (Exception ex) { string msg = string.Format("An error occurred while removing the now-empty guild: {0}", ex.Message); returnValue.Message = msg; _logger.Debug(msg); return(returnValue); } } } returnValue.Success = success; returnValue.TimeTaken = sw.Elapsed; } catch (Exception ex) { // Check for foreign key constraint failure first if (ex.Message.Contains("DELETE statement conflicted with the REFERENCE constraint") || // MSSQL ex.Message.Contains("Cannot delete or update a parent row")) // MySQL { returnValue.Message = "Delete operation failed - this record is depended upon by other tables within the database and cannot be deleted at this time."; } else { returnValue.Message = ex.Message; } } } } else { returnValue.Message = "Invalid character specified"; } return(returnValue); }