private void PopulateMessageNames(List <ChatHistory> messages)
        {
            var userIds   = messages.Where(m => m.UserId != Guid.Empty).GroupBy(m => m.UserId).Select(m => m.First().UserId).ToList();
            var playerIds = messages.Where(m => m.PlayerId != Guid.Empty).GroupBy(m => m.PlayerId).Select(m => m.First().PlayerId).ToList();
            var targetIds = messages.Where(m => m.TargetId != Guid.Empty && m.MessageType == ChatMessageType.PM).GroupBy(m => m.TargetId).Select(m => m.First().TargetId).ToList();

            var playerSet = new HashSet <Guid>(playerIds);

            playerSet.UnionWith(targetIds);

            using (var db = DbInterface.CreatePlayerContext(true))
            {
                var users   = db.Users.Where(u => userIds.Contains(u.Id)).Select(u => new KeyValuePair <Guid, string>(u.Id, u.Name)).ToDictionary(p => p.Key, p => p.Value);
                var players = db.Players.Where(p => playerSet.Contains(p.Id)).Select(p => new KeyValuePair <Guid, string>(p.Id, p.Name)).ToDictionary(p => p.Key, p => p.Value);

                foreach (var msg in messages)
                {
                    if (users.ContainsKey(msg.UserId))
                    {
                        msg.Username = users[msg.UserId];
                    }

                    if (players.ContainsKey(msg.PlayerId))
                    {
                        msg.PlayerName = players[msg.PlayerId];
                    }

                    if (players.ContainsKey(msg.TargetId))
                    {
                        msg.TargetName = players[msg.TargetId];
                    }
                }
            }
        }
Example #2
0
 /// <summary>
 /// Removes all guilds in which only have 1 member that haven't been online in the configured number of days
 /// </summary>
 public static void WipeStaleGuilds()
 {
     if (Options.Instance.Guild.DeleteStaleGuildsAfterDays > 0)
     {
         using (var context = DbInterface.CreatePlayerContext(readOnly: false))
         {
             foreach (var guild in context.Guilds)
             {
                 var memberCount = context.Players.Where(p => p.DbGuild.Id == guild.Id).Count();
                 if (memberCount == 0)
                 {
                     context.Entry(guild).State = EntityState.Deleted;
                     LogActivity(guild.Id, null, null, GuildActivityType.Disbanded, "Stale");
                 }
                 else if (context.Players.Where(p => p.DbGuild.Id == guild.Id).Count() == 1)
                 {
                     var lastOnline = context.Players.FirstOrDefault(p => p.DbGuild.Id == guild.Id).LastOnline;
                     if (lastOnline != null && DateTime.UtcNow - lastOnline > TimeSpan.FromDays(Options.Instance.Guild.DeleteStaleGuildsAfterDays))
                     {
                         context.Entry(guild).State = EntityState.Deleted;
                         LogActivity(guild.Id, null, null, GuildActivityType.Disbanded, "Stale");
                     }
                 }
             }
             context.SaveChanges();
         }
     }
 }
Example #3
0
        /// <summary>
        /// Loads a guild and it's members from the database
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Guild LoadGuild(Guid id)
        {
            if (!Guilds.TryGetValue(id, out Guild found))
            {
                using (var context = DbInterface.CreatePlayerContext())
                {
                    var guild = context.Guilds.Where(g => g.Id == id).Include(g => g.Bank).FirstOrDefault();
                    if (guild != null)
                    {
                        //Load Members
                        var members = context.Players.Where(p => p.DbGuild.Id == id).ToDictionary(t => t.Id, t => new Tuple <Guid, string, int, int, Guid, Guid>(t.Id, t.Name, t.GuildRank, t.Level, t.ClassId, t.MapId));
                        foreach (var member in members)
                        {
                            var gmember = new GuildMember(member.Value.Item1, member.Value.Item2, member.Value.Item3, member.Value.Item4, ClassBase.GetName(member.Value.Item5), MapBase.GetName(member.Value.Item6));
                            guild.Members.AddOrUpdate(member.Key, gmember, (key, oldValue) => gmember);
                        }

                        SlotHelper.ValidateSlots(guild.Bank, guild.BankSlotsCount);
                        guild.Bank = guild.Bank.OrderBy(bankSlot => bankSlot?.Slot).ToList();

                        Guilds.AddOrUpdate(id, guild, (key, oldValue) => guild);

                        return(guild);
                    }
                }
            }
            else
            {
                return(found);
            }
            return(null);
        }
Example #4
0
        /// <summary>
        /// Joins a player into the guild.
        /// </summary>
        /// <param name="player">The player to join into the guild.</param>
        /// <param name="rank">Integer index of the rank to give this new member.</param>
        /// <param name="initiator">The player who initiated this change (null if done by the api or some other method).</param>
        public void AddMember(Player player, int rank, Player initiator = null)
        {
            if (player != null && !Members.Any(m => m.Key == player.Id))
            {
                using (var context = DbInterface.CreatePlayerContext(readOnly: false))
                {
                    var dbPlayer = context.Players.FirstOrDefault(p => p.Id == player.Id);
                    if (dbPlayer != null)
                    {
                        dbPlayer.DbGuild       = this;
                        dbPlayer.GuildRank     = rank;
                        dbPlayer.GuildJoinDate = DateTime.UtcNow;
                        context.ChangeTracker.DetectChanges();
                        DetachGuildFromDbContext(context, this);
                        context.SaveChanges();

                        player.Guild         = this;
                        player.GuildRank     = rank;
                        player.GuildJoinDate = DateTime.UtcNow;

                        var member = new GuildMember(player.Id, player.Name, player.GuildRank, player.Level, player.ClassName, player.MapName);
                        Members.AddOrUpdate(player.Id, member, (key, oldValue) => member);

                        // Send our new guild list to everyone that's online.
                        UpdateMemberList();

                        // Send our entity data to nearby players.
                        PacketSender.SendEntityDataToProximity(Player.FindOnline(player.Id));

                        LogActivity(Id, player, initiator, GuildActivityType.Joined);
                    }
                }
            }
        }
        public static bool Remove(Guid userId, bool expired = true)
        {
            try
            {
                using (var context = DbInterface.CreatePlayerContext(readOnly: false))
                {
                    var bans = context.Bans.Where(e => e.UserId == userId && (!expired || Expired(e))).ToList();

                    if ((bans?.Count ?? 0) == 0)
                    {
                        return(true);
                    }

                    foreach (var ban in bans)
                    {
                        context.Entry(ban).State = EntityState.Deleted;
                    }
                    context.SaveChanges();
                }
                return(true);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to remove bans for user with id " + userId);
                //ServerContext.DispatchUnhandledException(new Exception("Failed to save user, shutting down to prevent rollbacks!"), true);
            }
            return(false);
        }
        private void PopulateGuildActivityNames(List <GuildHistory> guildActivity)
        {
            var userIds   = guildActivity.Where(m => m.UserId != Guid.Empty).GroupBy(m => m.UserId).Select(m => m.First().UserId).ToList();
            var playerIds = guildActivity.Where(m => m.PlayerId != Guid.Empty).GroupBy(m => m.PlayerId).Select(m => m.First().PlayerId).ToList();
            var targetIds = guildActivity.Where(m => m.InitiatorId != Guid.Empty).GroupBy(m => m.InitiatorId).Select(m => m.First().InitiatorId).ToList();

            var playerSet = new HashSet <Guid>(playerIds);

            playerSet.UnionWith(targetIds);

            using (var db = DbInterface.CreatePlayerContext(true))
            {
                var users   = db.Users.Where(u => userIds.Contains(u.Id)).Select(u => new KeyValuePair <Guid, string>(u.Id, u.Name)).ToDictionary(p => p.Key, p => p.Value);
                var players = db.Players.Where(p => playerSet.Contains(p.Id)).Select(p => new KeyValuePair <Guid, string>(p.Id, p.Name)).ToDictionary(p => p.Key, p => p.Value);

                foreach (var msg in guildActivity)
                {
                    if (users.ContainsKey(msg.UserId))
                    {
                        msg.Username = users[msg.UserId];
                    }

                    if (players.ContainsKey(msg.PlayerId))
                    {
                        msg.PlayerName = players[msg.PlayerId];
                    }

                    if (players.ContainsKey(msg.InitiatorId))
                    {
                        msg.InitiatorName = players[msg.InitiatorId];
                    }
                }
            }
        }
        public object PlayerLevelSet(LookupKey lookupKey, [FromBody] LevelChange change)
        {
            if (lookupKey.IsInvalid)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest, lookupKey.IsIdInvalid ? @"Invalid player id." : @"Invalid player name."
                           ));
            }

            var(client, player) = Player.Fetch(lookupKey);
            if (player != null)
            {
                player.SetLevel(change.Level, true);
                if (player.Online)
                {
                    PacketSender.SendEntityDataToProximity(player);
                }

                using (var context = DbInterface.CreatePlayerContext(false))
                {
                    context.Update(player);
                    context.SaveChanges();
                }

                return(player);
            }

            return(Request.CreateErrorResponse(
                       HttpStatusCode.NotFound,
                       lookupKey.HasId ? $@"No player with id '{lookupKey.Id}'." : $@"No player with name '{lookupKey.Name}'."
                       ));
        }
        public object ItemsGive(LookupKey lookupKey, [FromBody] ItemInfo itemInfo)
        {
            if (lookupKey.IsInvalid)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest, lookupKey.IsIdInvalid ? @"Invalid player id." : @"Invalid player name."
                           ));
            }

            if (ItemBase.Get(itemInfo.ItemId) == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, @"Invalid item id."));
            }

            if (itemInfo.Quantity < 1)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest, "Cannot give 0, or a negative amount of an item."
                           ));
            }

            var(client, player) = Player.Fetch(lookupKey);
            if (player == null)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.NotFound,
                           lookupKey.HasId
                        ? $@"No player with id '{lookupKey.Id}'."
                        : $@"No player with name '{lookupKey.Name}'."
                           ));
            }

            if (!player.TryGiveItem(itemInfo.ItemId, itemInfo.Quantity, ItemHandling.Normal, itemInfo.BankOverflow, true))
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.InternalServerError,
                           $@"Failed to give player {itemInfo.Quantity} of '{itemInfo.ItemId}'."
                           ));
            }

            using (var context = DbInterface.CreatePlayerContext(false))
            {
                context.Update(player);
                context.SaveChanges();
            }

            var quantityBank      = player.CountItems(itemInfo.ItemId, false, true);
            var quantityInventory = player.CountItems(itemInfo.ItemId, true, false);

            return(new
            {
                id = itemInfo.ItemId,
                quantity = new
                {
                    total = quantityBank + quantityInventory,
                    bank = quantityBank,
                    inventory = quantityInventory
                }
            });
        }
        public void AddFriend(Player friend)
        {
            if (friend == null || friend == this)
            {
                return;
            }

            if (CachedFriends.ContainsKey(friend.Id))
            {
                return;
            }

            //No passing in custom contexts here.. they may already have this user in the change tracker and things just get weird.
            //The cost of making a new context is almost nil.
            try
            {
                CachedFriends.Add(friend.Id, friend.Name);

                using (var context = DbInterface.CreatePlayerContext(readOnly: false))
                {
                    var friendship = new Database.PlayerData.Players.Friend(this, friend);
                    context.Entry(friendship).State = EntityState.Added;
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to add friend " + friend.Name + " to " + Name + "'s friends list.");
                //ServerContext.DispatchUnhandledException(new Exception("Failed to save user, shutting down to prevent rollbacks!"), true);
            }
        }
        public static bool PlayerExists(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return(false);
            }

            var player = FindOnline(name);

            if (player != null)
            {
                return(true);
            }

            try
            {
                using (var context = DbInterface.CreatePlayerContext())
                {
                    return(AnyPlayerByName(context, name));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(false);
            }
        }
        public static void RemoveFriendship(Guid id, Guid otherId)
        {
            if (id == Guid.Empty || otherId == Guid.Empty)
            {
                return;
            }

            //No passing in custom contexts here.. they may already have this user in the change tracker and things just get weird.
            //The cost of making a new context is almost nil.
            try
            {
                using (var context = DbInterface.CreatePlayerContext(readOnly: false))
                {
                    var friendship = context.Player_Friends.Where(f => f.Owner.Id == id && f.Target.Id == otherId).FirstOrDefault();
                    if (friendship != null)
                    {
                        context.Entry(friendship).State = EntityState.Deleted;
                    }

                    var otherFriendship = context.Player_Friends.Where(f => f.Owner.Id == otherId && f.Target.Id == id).FirstOrDefault();
                    if (otherFriendship != null)
                    {
                        context.Entry(otherFriendship).State = EntityState.Deleted;
                    }
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Failed to remove friendship between {id} and {otherId}.");
                //ServerContext.DispatchUnhandledException(new Exception("Failed to save user, shutting down to prevent rollbacks!"), true);
            }
        }
        public static Player Find(Guid playerId)
        {
            if (playerId == Guid.Empty)
            {
                return(null);
            }

            var player = Player.FindOnline(playerId);

            if (player != null)
            {
                return(player);
            }

            try
            {
                using (var context = DbInterface.CreatePlayerContext())
                {
                    return(QueryPlayerById(context, playerId));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(null);
            }
        }
Example #13
0
        public static bool Remove(Guid userId, bool expired = true)
        {
            try
            {
                using (var context = DbInterface.CreatePlayerContext(readOnly: false))
                {
                    var mutes = context.Mutes.Where(e => e.UserId == userId && (!expired || Expired(e))).ToList();

                    if ((mutes?.Count ?? 0) == 0)
                    {
                        return(true);
                    }

                    foreach (var mute in mutes)
                    {
                        context.Entry(mute).State = EntityState.Deleted;
                    }
                    context.SaveChanges();
                }
                return(true);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to remove mutes user with id " + userId);
            }
            return(false);
        }
        public static RefreshToken FindForTicket(Guid ticketId)
        {
            if (ticketId == Guid.Empty)
            {
                return(null);
            }

            try
            {
                using (var context = DbInterface.CreatePlayerContext())
                {
                    var refreshToken = context?.RefreshTokens.FirstOrDefault(queryToken => queryToken.TicketId == ticketId);

                    if (refreshToken == null || DateTime.UtcNow < refreshToken.Expires)
                    {
                        return(refreshToken);
                    }

                    Remove(refreshToken, true);

                    return(null);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(null);
            }
        }
        public static Player Find(string playerName)
        {
            if (string.IsNullOrWhiteSpace(playerName))
            {
                return(null);
            }

            var player = Player.FindOnline(playerName);

            if (player != null)
            {
                return(player);
            }

            try
            {
                using (var context = DbInterface.CreatePlayerContext())
                {
                    return(QueryPlayerByName(context, playerName));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(null);
            }
        }
Example #16
0
 /// <summary>
 /// Determines wether or not a guild already exists with a given name
 /// </summary>
 /// <param name="name">Guild name to check</param>
 /// <returns></returns>
 public static bool GuildExists(string name)
 {
     name = name.Trim().ToLower();
     using (var context = DbInterface.CreatePlayerContext())
     {
         return(context.Guilds.Any(g => g.Name.ToLower() == name.ToLower()));
     }
 }
        public object PlayerVariableSet(LookupKey lookupKey, Guid variableId, [FromBody] VariableValue value)
        {
            if (lookupKey.IsInvalid)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest, lookupKey.IsIdInvalid ? @"Invalid player id." : @"Invalid player name."
                           ));
            }

            if (variableId == Guid.Empty || PlayerVariableBase.Get(variableId) == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, $@"Invalid variable id ${variableId}."));
            }

            var(client, player) = Player.Fetch(lookupKey);
            if (player == null)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.NotFound,
                           lookupKey.HasId
                        ? $@"No player with id '{lookupKey.Id}'."
                        : $@"No player with name '{lookupKey.Name}'."
                           ));
            }

            var variable = player.GetVariable(variableId, true);

            var changed = true;

            if (variable?.Value != null)
            {
                if (variable?.Value?.Value != value.Value)
                {
                    changed = false;
                }
                variable.Value.Value = value.Value;
            }

            if (changed)
            {
                var plyr = Player.FindOnline(player.Id);
                if (plyr != null)
                {
                    player.StartCommonEventsWithTrigger(CommonEventTrigger.PlayerVariableChange, "", variableId.ToString());
                }
            }

            using (var context = DbInterface.CreatePlayerContext(false))
            {
                context.Update(player);
                context.SaveChanges();
            }

            return(variable);
        }
Example #18
0
 /// <summary>
 /// Updates the db with this guild state & bank slots
 /// </summary>
 public void Save()
 {
     lock (mLock)
     {
         using (var context = DbInterface.CreatePlayerContext(readOnly: false))
         {
             context.Update(this);
             context.ChangeTracker.DetectChanges();
             context.SaveChanges();
         }
     }
 }
Example #19
0
        /// <summary>
        /// Search for a guild by Id.
        /// </summary>
        /// <param name="id">The guild Id to search for.</param>
        /// <returns>Returns a <see cref="Guild"/> that matches the Id, if any.</returns>
        public static Guild GetGuild(Guid id)
        {
            using (var context = DbInterface.CreatePlayerContext())
            {
                var guild = context.Guilds.FirstOrDefault(g => g.Id == id);
                if (guild != null)
                {
                    return(guild);
                }
            }

            return(null);
        }
Example #20
0
        /// <summary>
        /// Search for a guild by Name.
        /// </summary>
        /// <param name="name">The guild Name to search for.</param>
        /// <returns>Returns a <see cref="Guild"/> that matches the Name, if any.</returns>
        public static Guild GetGuild(string name)
        {
            name = name.Trim();
            using (var context = DbInterface.CreatePlayerContext())
            {
                var guild = context.Guilds.FirstOrDefault(g => g.Name.ToLower() == name.ToLower());
                if (guild != null)
                {
                    return(guild);
                }
            }

            return(null);
        }
        public static IList <Player> List(string query, string sortBy, SortDirection sortDirection, int skip, int take, out int total, Guid guildId = default(Guid))
        {
            try
            {
                using (var context = DbInterface.CreatePlayerContext())
                {
                    var compiledQuery = string.IsNullOrWhiteSpace(query) ? context.Players : context.Players.Where(p => EF.Functions.Like(p.Name, $"%{query}%"));

                    if (guildId != Guid.Empty)
                    {
                        compiledQuery = compiledQuery.Where(p => p.DbGuild.Id == guildId);
                    }

                    total = compiledQuery.Count();

                    switch (sortBy?.ToLower() ?? "")
                    {
                    case "level":
                        compiledQuery = sortDirection == SortDirection.Ascending ? compiledQuery.OrderBy(u => u.Level).ThenBy(u => u.Exp) : compiledQuery.OrderByDescending(u => u.Level).ThenByDescending(u => u.Exp);
                        break;

                    case "creationdate":
                        compiledQuery = sortDirection == SortDirection.Ascending ? compiledQuery.OrderBy(u => u.CreationDate) : compiledQuery.OrderByDescending(u => u.CreationDate);
                        break;

                    case "playtime":
                        compiledQuery = sortDirection == SortDirection.Ascending ? compiledQuery.OrderBy(u => u.PlayTimeSeconds) : compiledQuery.OrderByDescending(u => u.PlayTimeSeconds);
                        break;

                    case "guildrank":
                        compiledQuery = sortDirection == SortDirection.Ascending ? compiledQuery.OrderBy(u => u.GuildRank) : compiledQuery.OrderByDescending(u => u.GuildRank);
                        break;

                    case "name":
                    default:
                        compiledQuery = sortDirection == SortDirection.Ascending ? compiledQuery.OrderBy(u => u.Name.ToUpper()) : compiledQuery.OrderByDescending(u => u.Name.ToUpper());
                        break;
                    }

                    return(compiledQuery.Skip(skip).Take(take).ToList());
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                total = 0;
                return(null);
            }
        }
 public static RefreshToken Find(Guid id)
 {
     try
     {
         using (var context = DbInterface.CreatePlayerContext())
         {
             return(context?.RefreshTokens?.Find(id));
         }
     }
     catch (Exception ex)
     {
         Log.Error(ex);
         return(null);
     }
 }
 public static IList <Player> List(int page, int count)
 {
     try
     {
         using (var context = DbInterface.CreatePlayerContext())
         {
             return(QueryPlayers(context, page * count, count)?.ToList());
         }
     }
     catch (Exception ex)
     {
         Log.Error(ex);
         return(null);
     }
 }
 public static int Count()
 {
     try
     {
         using (var context = DbInterface.CreatePlayerContext())
         {
             return(context.Players.Count());
         }
     }
     catch (Exception ex)
     {
         Log.Error(ex);
         return(0);
     }
 }
 public void LoadFriends()
 {
     try
     {
         using (var context = DbInterface.CreatePlayerContext())
         {
             CachedFriends = context.Player_Friends.Where(f => f.Owner.Id == Id).Select(t => new { t.Target.Id, t.Target.Name }).ToDictionary(t => t.Id, t => t.Name);
         }
     }
     catch (Exception ex)
     {
         Log.Error(ex, $"Failed to load friends for {Name}.");
         //ServerContext.DispatchUnhandledException(new Exception("Failed to save user, shutting down to prevent rollbacks!"), true);
     }
 }
 public static Ban Find(Guid userId)
 {
     try
     {
         using (var context = DbInterface.CreatePlayerContext())
         {
             return(ByUser(context, userId)?.FirstOrDefault());
         }
     }
     catch (Exception ex)
     {
         Log.Error(ex);
         return(null);
     }
 }
        public object ChangeName(LookupKey lookupKey, [FromBody] NameChange change)
        {
            if (lookupKey.IsInvalid)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest, lookupKey.IsIdInvalid ? @"Invalid player id." : @"Invalid player name."
                           ));
            }

            if (!FieldChecking.IsValidUsername(change.Name, Strings.Regex.username))
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest,
                           $@"Invalid name."
                           ));
            }

            if (Player.PlayerExists(change.Name))
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest,
                           $@"Name already taken."
                           ));
            }

            var(client, player) = Player.Fetch(lookupKey);
            if (player != null)
            {
                player.Name = change.Name;
                if (player.Online)
                {
                    PacketSender.SendEntityDataToProximity(player);
                }

                using (var context = DbInterface.CreatePlayerContext(false))
                {
                    context.Update(player);
                    context.SaveChanges();
                }

                return(player);
            }

            return(Request.CreateErrorResponse(
                       HttpStatusCode.NotFound,
                       lookupKey.HasId ? $@"No player with id '{lookupKey.Id}'." : $@"No player with name '{lookupKey.Name}'."
                       ));
        }
Example #28
0
        /// <summary>
        /// Create a new Guild instance.
        /// </summary>
        /// <param name="creator">The <see cref="Player"/> that created the guild.</param>
        /// <param name="name">The Name of the guild.</param>
        public static Guild CreateGuild(Player creator, string name)
        {
            name = name.Trim();

            if (creator != null && FieldChecking.IsValidGuildName(name, Strings.Regex.guildname))
            {
                using (var context = DbInterface.CreatePlayerContext(readOnly: false))
                {
                    var guild = new Guild()
                    {
                        Name         = name,
                        FoundingDate = DateTime.UtcNow
                    };

                    SlotHelper.ValidateSlots(guild.Bank, Options.Instance.Guild.GuildBankSlots);
                    guild.Bank = guild.Bank.OrderBy(bankSlot => bankSlot?.Slot).ToList();

                    var player = context.Players.FirstOrDefault(p => p.Id == creator.Id);
                    if (player != null)
                    {
                        player.DbGuild       = guild;
                        player.GuildRank     = 0;
                        player.GuildJoinDate = DateTime.UtcNow;


                        context.ChangeTracker.DetectChanges();
                        context.SaveChanges();

                        var member = new GuildMember(player.Id, player.Name, player.GuildRank, player.Level, player.ClassName, player.MapName);
                        guild.Members.AddOrUpdate(player.Id, member, (key, oldValue) => member);

                        creator.Guild         = guild;
                        creator.GuildRank     = 0;
                        creator.GuildJoinDate = DateTime.UtcNow;

                        // Send our entity data to nearby players.
                        PacketSender.SendEntityDataToProximity(Player.FindOnline(creator.Id));

                        Guilds.AddOrUpdate(guild.Id, guild, (key, oldValue) => guild);

                        LogActivity(guild.Id, creator, null, GuildActivityType.Created, name);

                        return(guild);
                    }
                }
            }
            return(null);
        }
        public void LoadGuild()
        {
            using (var context = DbInterface.CreatePlayerContext())
            {
                var guildId = context.Players.Where(p => p.Id == Id && p.DbGuild.Id != null && p.DbGuild.Id != Guid.Empty).Select(p => p.DbGuild.Id).FirstOrDefault();
                if (guildId != default)
                {
                    Guild = Guild.LoadGuild(guildId);
                }
            }

            if (GuildRank > Options.Instance.Guild.Ranks.Length - 1)
            {
                GuildRank = Options.Instance.Guild.Ranks.Length - 1;
            }
        }
        public object ItemsTake(LookupKey lookupKey, [FromBody] ItemInfo itemInfo)
        {
            if (lookupKey.IsInvalid)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest, lookupKey.IsIdInvalid ? @"Invalid player id." : @"Invalid player name."
                           ));
            }

            if (itemInfo.Quantity < 1)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest, "Cannot take 0, or a negative amount of an item."
                           ));
            }

            var(client, player) = Player.Fetch(lookupKey);
            if (player == null)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.NotFound,
                           lookupKey.HasId
                        ? $@"No player with id '{lookupKey.Id}'."
                        : $@"No player with name '{lookupKey.Name}'."
                           ));
            }

            if (player.TryTakeItem(itemInfo.ItemId, itemInfo.Quantity))
            {
                using (var context = DbInterface.CreatePlayerContext(false))
                {
                    context.Update(player);
                    context.SaveChanges();
                }

                return(new
                {
                    itemInfo.ItemId,
                    itemInfo.Quantity
                });
            }

            return(Request.CreateErrorResponse(
                       HttpStatusCode.InternalServerError,
                       $@"Failed to take {itemInfo.Quantity} of '{itemInfo.ItemId}' from player."
                       ));
        }