using MongoDB.Driver; using System.Collections.Generic; using System.Linq; namespace Bootstrap.DataAccess.MongoDB { /// /// /// public class Group : DataAccess.Group { /// /// /// public IEnumerable Roles { get; set; } /// /// /// /// public override IEnumerable Retrieves() { return DbManager.Groups.Find(FilterDefinition.Empty).ToList(); } /// /// /// /// /// public override bool Save(DataAccess.Group p) { if (p.Id == "0") { p.Id = null; DbManager.Groups.InsertOne(new Group() { GroupName = p.GroupName, Description = p.Description, Roles = new List() }); return true; } else { DbManager.Groups.UpdateOne(md => md.Id == p.Id, Builders.Update.Set(md => md.GroupName, p.GroupName).Set(md => md.Description, p.Description)); return true; } } /// /// /// /// /// public override bool Delete(IEnumerable value) { var list = new List>(); foreach (var id in value) { list.Add(new DeleteOneModel(Builders.Filter.Eq(g => g.Id, id))); } DbManager.Groups.BulkWrite(list); return true; } /// /// /// /// /// public override IEnumerable RetrievesByUserId(string userId) { var groups = GroupHelper.Retrieves(); var user = UserHelper.Retrieves().Cast().FirstOrDefault(u => u.Id == userId); groups.ToList().ForEach(g => g.Checked = user.Groups.Any(id => id == g.Id) ? "checked" : ""); return groups; } /// /// /// /// /// /// public override bool SaveByUserId(string userId, IEnumerable groupIds) { DbManager.Users.FindOneAndUpdate(u => u.Id == userId, Builders.Update.Set(u => u.Groups, groupIds)); return true; } /// /// /// /// /// public override IEnumerable RetrievesByRoleId(string roleId) { var groups = GroupHelper.Retrieves().Cast().ToList(); groups.ForEach(p => p.Checked = (p.Roles != null && p.Roles.Contains(roleId)) ? "checked" : ""); return groups; } /// /// /// /// /// /// public override bool SaveByRoleId(string roleId, IEnumerable groupIds) { var groups = DbManager.Groups.Find(md => md.Roles != null && md.Roles.Contains(roleId)).ToList(); // Remove roles groups.ForEach(p => { var roles = p.Roles == null ? new List() : p.Roles.ToList(); roles.Remove(roleId); DbManager.Groups.UpdateOne(md => md.Id == p.Id, Builders.Update.Set(md => md.Roles, roles)); }); groups = DbManager.Groups.Find(md => groupIds.Contains(md.Id)).ToList(); // Add roles groups.ForEach(p => { var roles = p.Roles == null ? new List() : p.Roles.ToList(); roles.Add(roleId); DbManager.Groups.UpdateOne(md => md.Id == p.Id, Builders.Update.Set(md => md.Roles, roles)); }); return true; } /// /// /// /// /// public override IEnumerable RetrievesByUserName(string userName) { var groups = new List(); var user = UserHelper.Retrieves().Cast().FirstOrDefault(u => u.UserName == userName); var group = GroupHelper.Retrieves(); groups.AddRange(user.Groups.Select(r => group.FirstOrDefault(rl => rl.Id == r).GroupName)); if (groups.Count == 0) groups.Add("Default"); return groups; } } }