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 RetrieveGroups() { return MongoDbAccessManager.Groups.Find(FilterDefinition.Empty).ToList(); } /// /// /// /// /// public override bool SaveGroup(DataAccess.Group p) { if (p.Id == "0") { p.Id = null; MongoDbAccessManager.Groups.InsertOne(p as Group); return true; } else { MongoDbAccessManager.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 DeleteGroup(IEnumerable value) { var list = new List>(); foreach (var id in value) { list.Add(new DeleteOneModel(Builders.Filter.Eq(g => g.Id, id))); } MongoDbAccessManager.Groups.BulkWrite(list); return true; } /// /// /// /// /// public override IEnumerable RetrieveGroupsByUserId(string userId) { var groups = GroupHelper.RetrieveGroups(); var user = UserHelper.RetrieveUsers().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 SaveGroupsByUserId(string userId, IEnumerable groupIds) { MongoDbAccessManager.Users.FindOneAndUpdate(u => u.Id == userId, Builders.Update.Set(u => u.Groups, groupIds)); return true; } /// /// /// /// /// public override IEnumerable RetrieveGroupsByRoleId(string roleId) { var groups = GroupHelper.RetrieveGroups().Cast().ToList(); groups.ForEach(p => p.Checked = (p.Roles != null && p.Roles.Contains(roleId)) ? "checked" : ""); return groups; } /// /// /// /// /// /// public override bool SaveGroupsByRoleId(string roleId, IEnumerable groupIds) { var groups = MongoDbAccessManager.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); MongoDbAccessManager.Groups.UpdateOne(md => md.Id == p.Id, Builders.Update.Set(md => md.Roles, roles)); }); groups = MongoDbAccessManager.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); MongoDbAccessManager.Groups.UpdateOne(md => md.Id == p.Id, Builders.Update.Set(md => md.Roles, roles)); }); return true; } } }