Updates UserGroupRepository to ensure that it persists things int he correct order and inside of a transaction, removes new code that is already obsolete, fixes tests

This commit is contained in:
Shannon
2017-05-15 20:27:40 +10:00
parent 9b50d6d251
commit faa6a229e6
15 changed files with 176 additions and 450 deletions
@@ -19,17 +19,11 @@ namespace Umbraco.Core.Persistence.Repositories
IEnumerable<IUserGroup> GetGroupsAssignedToSection(string sectionAlias);
/// <summary>
/// Removes all users from a group
/// Used to add or update a user group and assign users to it
/// </summary>
/// <param name="groupId">Id of group</param>
void RemoveAllUsersFromGroup(int groupId);
/// <summary>
/// Adds a set of users to a group
/// </summary>
/// <param name="groupId">Id of group</param>
/// <param name="userIds">Ids of users</param>
void AddUsersToGroup(int groupId, int[] userIds);
/// <param name="userGroup"></param>
/// <param name="userIds"></param>
void AddOrUpdateGroupWithUsers(IUserGroup userGroup, int[] userIds);
/// <summary>
/// Gets the group permissions for the specified entities
@@ -4,6 +4,7 @@ using System.Linq;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Cache;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.Factories;
@@ -20,11 +21,13 @@ namespace Umbraco.Core.Persistence.Repositories
internal class UserGroupRepository : PetaPocoRepositoryBase<int, IUserGroup>, IUserGroupRepository
{
private readonly CacheHelper _cacheHelper;
private readonly UserGroupWithUsersRepository _userGroupWithUsersRepository;
public UserGroupRepository(IScopeUnitOfWork work, CacheHelper cacheHelper, ILogger logger, ISqlSyntaxProvider sqlSyntax)
: base(work, cacheHelper, logger, sqlSyntax)
{
_cacheHelper = cacheHelper;
_userGroupWithUsersRepository = new UserGroupWithUsersRepository(this, work, cacheHelper, logger, sqlSyntax);
}
public const string GetByAliasCacheKeyPrefix = "UserGroupRepository_GetByAlias_";
@@ -80,32 +83,11 @@ namespace Umbraco.Core.Persistence.Repositories
return ConvertFromDtos(Database.Fetch<UserGroupDto, UserGroup2AppDto, UserGroupDto>(new UserGroupSectionRelator().Map, sql));
}
/// <summary>
/// Removes all users from a group
/// </summary>
/// <param name="groupId">Id of group</param>
public void RemoveAllUsersFromGroup(int groupId)
public void AddOrUpdateGroupWithUsers(IUserGroup userGroup, int[] userIds)
{
Database.Delete<User2UserGroupDto>("WHERE userGroupId = @GroupId", new { GroupId = groupId });
_userGroupWithUsersRepository.AddOrUpdate(new UserGroupWithUsers(userGroup, userIds));
}
/// <summary>
/// Adds a set of users to a group
/// </summary>
/// <param name="groupId">Id of group</param>
/// <param name="userIds">Ids of users</param>
public void AddUsersToGroup(int groupId, int[] userIds)
{
foreach (var userId in userIds)
{
var dto = new User2UserGroupDto
{
UserGroupId = groupId,
UserId = userId,
};
Database.Insert(dto);
}
}
/// <summary>
/// Gets the group permissions for the specified entities
@@ -287,5 +269,119 @@ namespace Umbraco.Core.Persistence.Repositories
{
return dtos.Select(UserGroupFactory.BuildEntity);
}
/// <summary>
/// used to persist a user group with associated users at once
/// </summary>
private class UserGroupWithUsers : Entity, IAggregateRoot
{
public UserGroupWithUsers(IUserGroup userGroup, int[] userIds)
{
UserGroup = userGroup;
UserIds = userIds;
}
public IUserGroup UserGroup { get; private set; }
public int[] UserIds { get; private set; }
}
/// <summary>
/// used to persist a user group with associated users at once
/// </summary>
private class UserGroupWithUsersRepository : PetaPocoRepositoryBase<int, UserGroupWithUsers>
{
private readonly UserGroupRepository _userGroupRepo;
public UserGroupWithUsersRepository(UserGroupRepository userGroupRepo, IScopeUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax)
: base(work, cache, logger, sqlSyntax)
{
_userGroupRepo = userGroupRepo;
}
#region Not implemented (don't need to for the purposes of this repo)
protected override UserGroupWithUsers PerformGet(int id)
{
throw new NotImplementedException();
}
protected override IEnumerable<UserGroupWithUsers> PerformGetAll(params int[] ids)
{
throw new NotImplementedException();
}
protected override IEnumerable<UserGroupWithUsers> PerformGetByQuery(IQuery<UserGroupWithUsers> query)
{
throw new NotImplementedException();
}
protected override Sql GetBaseQuery(bool isCount)
{
throw new NotImplementedException();
}
protected override string GetBaseWhereClause()
{
throw new NotImplementedException();
}
protected override IEnumerable<string> GetDeleteClauses()
{
throw new NotImplementedException();
}
protected override Guid NodeObjectTypeId
{
get { throw new NotImplementedException(); }
}
#endregion
protected override void PersistNewItem(UserGroupWithUsers entity)
{
//save the user group
_userGroupRepo.PersistNewItem(entity.UserGroup);
if (entity.UserIds != null)
{
//now the user association
RemoveAllUsersFromGroup(entity.UserGroup.Id);
AddUsersToGroup(entity.UserGroup.Id, entity.UserIds);
}
}
protected override void PersistUpdatedItem(UserGroupWithUsers entity)
{
//save the user group
_userGroupRepo.PersistUpdatedItem(entity.UserGroup);
if (entity.UserIds != null)
{
//now the user association
RemoveAllUsersFromGroup(entity.UserGroup.Id);
AddUsersToGroup(entity.UserGroup.Id, entity.UserIds);
}
}
/// <summary>
/// Removes all users from a group
/// </summary>
/// <param name="groupId">Id of group</param>
private void RemoveAllUsersFromGroup(int groupId)
{
Database.Delete<User2UserGroupDto>("WHERE userGroupId = @GroupId", new { GroupId = groupId });
}
/// <summary>
/// Adds a set of users to a group
/// </summary>
/// <param name="groupId">Id of group</param>
/// <param name="userIds">Ids of users</param>
private void AddUsersToGroup(int groupId, int[] userIds)
{
//TODO: Check if the user exists?
foreach (var userId in userIds)
{
var dto = new User2UserGroupDto
{
UserGroupId = groupId,
UserId = userId,
};
Database.Insert(dto);
}
}
}
}
}
+7 -5
View File
@@ -189,17 +189,19 @@ namespace Umbraco.Core.Services
/// </summary>
/// <param name="id">Id of the UserGroup to retrieve</param>
/// <returns><see cref="IUserGroup"/></returns>
IUserGroup GetUserGroupById(int id);
IUserGroup GetUserGroupById(int id);
/// <summary>
/// Saves a UserGroup
/// </summary>
/// <param name="userGroup">UserGroup to save</param>
/// <param name="updateUsers">Flag for whether to update the list of users in the group</param>
/// <param name="userIds">List of user Ids</param>
/// <param name="userIds">
/// If null than no changes are made to the users who are assigned to this group, however if a value is passed in
/// than all users will be removed from this group and only these users will be added
/// </param>
/// <param name="raiseEvents">Optional parameter to raise events.
/// Default is <c>True</c> otherwise set to <c>False</c> to not raise events</param>
void SaveUserGroup(IUserGroup userGroup, bool updateUsers = false, int[] userIds = null, bool raiseEvents = true);
void Save(IUserGroup userGroup, int[] userIds = null, bool raiseEvents = true);
/// <summary>
/// Deletes a UserGroup
+6 -10
View File
@@ -682,11 +682,13 @@ namespace Umbraco.Core.Services
/// Saves a UserGroup
/// </summary>
/// <param name="userGroup">UserGroup to save</param>
/// <param name="updateUsers">Flag for whether to update the list of users in the group</param>
/// <param name="userIds">List of user Ids</param>
/// <param name="userIds">
/// If null than no changes are made to the users who are assigned to this group, however if a value is passed in
/// than all users will be removed from this group and only these users will be added
/// </param>
/// <param name="raiseEvents">Optional parameter to raise events.
/// Default is <c>True</c> otherwise set to <c>False</c> to not raise events</param>
public void SaveUserGroup(IUserGroup userGroup, bool updateUsers = false, int[] userIds = null, bool raiseEvents = true)
public void Save(IUserGroup userGroup, int[] userIds = null, bool raiseEvents = true)
{
using (var uow = UowProvider.GetUnitOfWork())
{
@@ -697,14 +699,8 @@ namespace Umbraco.Core.Services
}
var repository = RepositoryFactory.CreateUserGroupRepository(uow);
repository.AddOrUpdate(userGroup);
repository.AddOrUpdateGroupWithUsers(userGroup, userIds);
if (updateUsers)
{
repository.RemoveAllUsersFromGroup(userGroup.Id);
repository.AddUsersToGroup(userGroup.Id, userIds);
}
uow.Commit();
if (raiseEvents)
@@ -339,16 +339,15 @@ namespace Umbraco.Tests.Persistence.Repositories
private static User CreateAndCommitUserWithGroup(IUserRepository repository, IUserGroupRepository userGroupRepository, IDatabaseUnitOfWork unitOfWork)
{
var group = MockedUserGroup.CreateUserGroup();
userGroupRepository.AddOrUpdate(@group);
unitOfWork.Commit();
var user = MockedUser.CreateUser();
repository.AddOrUpdate(user);
unitOfWork.Commit();
userGroupRepository.AddUsersToGroup(@group.Id, new[] { user.Id });
unitOfWork.Commit();
var group = MockedUserGroup.CreateUserGroup();
userGroupRepository.AddOrUpdateGroupWithUsers(@group, new[] {user.Id});
unitOfWork.Commit();
return user;
}
@@ -60,7 +60,8 @@ namespace Umbraco.Tests.Services
};
userGroupA.AddAllowedSection("media");
userGroupA.AddAllowedSection("settings");
ServiceContext.UserService.SaveUserGroup(userGroupA, true, new[] { user.Id }, false);
//TODO: This is failing the test
ServiceContext.UserService.Save(userGroupA, new[] { user.Id }, false);
var userGroupB = new UserGroup
{
@@ -69,7 +70,7 @@ namespace Umbraco.Tests.Services
};
userGroupB.AddAllowedSection("settings");
userGroupB.AddAllowedSection("developer");
ServiceContext.UserService.SaveUserGroup(userGroupB, true, new[] { user.Id }, false);
ServiceContext.UserService.Save(userGroupB, new[] { user.Id }, false);
return ServiceContext.UserService.GetUserById(user.Id);
}
+11 -11
View File
@@ -415,7 +415,7 @@ namespace Umbraco.Tests.Services
};
userGroup.AddAllowedSection("content");
userGroup.AddAllowedSection("mediat");
ServiceContext.UserService.SaveUserGroup(userGroup);
ServiceContext.UserService.Save(userGroup);
var result1 = ServiceContext.UserService.GetUserGroupById(userGroup.Id);
@@ -426,7 +426,7 @@ namespace Umbraco.Tests.Services
userGroup.AddAllowedSection("test2");
userGroup.AddAllowedSection("test3");
userGroup.AddAllowedSection("test4");
ServiceContext.UserService.SaveUserGroup(userGroup);
ServiceContext.UserService.Save(userGroup);
result1 = ServiceContext.UserService.GetUserGroupById(userGroup.Id);
@@ -441,7 +441,7 @@ namespace Umbraco.Tests.Services
//now just re-add a couple
result1.AddAllowedSection("test3");
result1.AddAllowedSection("test4");
ServiceContext.UserService.SaveUserGroup(result1);
ServiceContext.UserService.Save(result1);
//assert
//re-get
@@ -464,14 +464,14 @@ namespace Umbraco.Tests.Services
Alias = "Group2",
Name = "Group 2"
};
ServiceContext.UserService.SaveUserGroup(userGroup1);
ServiceContext.UserService.SaveUserGroup(userGroup2);
ServiceContext.UserService.Save(userGroup1);
ServiceContext.UserService.Save(userGroup2);
//adds some allowed sections
userGroup1.AddAllowedSection("test");
userGroup2.AddAllowedSection("test");
ServiceContext.UserService.SaveUserGroup(userGroup1);
ServiceContext.UserService.SaveUserGroup(userGroup2);
ServiceContext.UserService.Save(userGroup1);
ServiceContext.UserService.Save(userGroup2);
//now clear the section from all users
ServiceContext.UserService.DeleteSectionFromAllUserGroups("test");
@@ -504,9 +504,9 @@ namespace Umbraco.Tests.Services
Alias = "Group3",
Name = "Group 3"
};
ServiceContext.UserService.SaveUserGroup(userGroup1);
ServiceContext.UserService.SaveUserGroup(userGroup2);
ServiceContext.UserService.SaveUserGroup(userGroup3);
ServiceContext.UserService.Save(userGroup1);
ServiceContext.UserService.Save(userGroup2);
ServiceContext.UserService.Save(userGroup3);
//now add the section to specific groups
ServiceContext.UserService.AddSectionToAllUserGroups("test", userGroup1.Id, userGroup2.Id);
@@ -641,7 +641,7 @@ namespace Umbraco.Tests.Services
Name = "Test Group",
Permissions = "ABCDEFGHIJ1234567".ToCharArray().Select(x => x.ToString())
};
ServiceContext.UserService.SaveUserGroup(userGroup);
ServiceContext.UserService.Save(userGroup);
ServiceContext.UserService.AddSectionToAllUserGroups("content", 1);
ServiceContext.UserService.AddSectionToAllUserGroups("media", 1);
return userGroup;
@@ -235,14 +235,6 @@
<delete assembly="umbraco" type="cms.presentation.user.UserTypeTasks" />
</tasks>
</nodeType>
<nodeType alias="userGroups">
<header>User Groups</header>
<usercontrol>/create/simple.ascx</usercontrol>
<tasks>
<create assembly="umbraco" type="cms.presentation.user.UserGroupTasks" />
<delete assembly="umbraco" type="cms.presentation.user.UserGroupTasks" />
</tasks>
</nodeType>
<nodeType alias="partialViews">
<header>Macro</header>
<usercontrol>/Create/PartialView.ascx</usercontrol>
@@ -212,15 +212,7 @@
<tasks>
<delete assembly="umbraco" type="CreatedPackageTasks" />
</tasks>
</nodeType>
<nodeType alias="userGroups">
<header>User Groups</header>
<usercontrol>/create/simple.ascx</usercontrol>
<tasks>
<create assembly="umbraco" type="cms.presentation.user.UserGroupTasks" />
<delete assembly="umbraco" type="cms.presentation.user.UserGroupTasks" />
</tasks>
</nodeType>
</nodeType>
<nodeType alias="partialViews">
<header>Macro</header>
<usercontrol>/Create/PartialView.ascx</usercontrol>
-1
View File
@@ -456,7 +456,6 @@
<Compile Include="umbraco.presentation\umbraco\users\EditUserGroupsBase.cs">
<SubType>ASPXCodeBehind</SubType>
</Compile>
<Compile Include="umbraco.presentation\umbraco\users\UserGroupTasks.cs" />
<Compile Include="UmbracoDefaultOwinStartup.cs" />
<Compile Include="IUmbracoContextAccessor.cs" />
<Compile Include="Models\ContentEditing\Relation.cs" />
@@ -24,12 +24,12 @@ function openUserGroups(id) {
public override void Render(ref XmlTree tree)
{
List<UserGroup> userGroups = UserGroup.GetAllUserGroups();
foreach (UserGroup userGroup in userGroups)
var userGroups = ApplicationContext.Current.Services.UserService.GetAllUserGroups();
foreach (var userGroup in userGroups)
{
XmlTreeNode node = XmlTreeNode.Create(this);
node.NodeID = userGroup.Id.ToString();
node.Action = string.Format("javascript:openUserGroups({0})", userGroup.Id.ToString());
node.Action = string.Format("javascript:openUserGroups({0})", userGroup.Id);
node.Icon = "icon-users";
node.Text = userGroup.Name;
@@ -1,11 +1,14 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.UI.WebControls;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.cms.presentation.Trees;
using umbraco.interfaces;
using Umbraco.Core;
using Umbraco.Core.Models.Membership;
namespace umbraco.cms.presentation.user
{
@@ -65,7 +68,7 @@ namespace umbraco.cms.presentation.user
actions += li.Value;
}
userGroup.DefaultPermissions = actions;
userGroup.Permissions = actions.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); ;
var userIds = new List<int>();
foreach (ListItem li in lstUsersInGroup.Items)
@@ -73,13 +76,13 @@ namespace umbraco.cms.presentation.user
userIds.Add(int.Parse(li.Value));
}
userGroup.ClearApplications();
userGroup.ClearAllowedSections();
foreach (ListItem li in cbl_sections.Items)
{
if (li.Selected) userGroup.AddApplication(li.Value);
if (li.Selected) userGroup.AddAllowedSection(li.Value);
}
userGroup.SaveWithUsers(userIds.ToArray());
Services.UserService.Save(userGroup, userIds.ToArray());
ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editUserGroupSaved", base.getUser()), "");
}
@@ -89,22 +92,22 @@ namespace umbraco.cms.presentation.user
get
{
if (m_userGroupActions == null)
m_userGroupActions = umbraco.BusinessLogic.Actions.Action.FromString(CurrentUserGroup.DefaultPermissions);
m_userGroupActions = umbraco.BusinessLogic.Actions.Action.FromString(string.Join("", CurrentUserGroup.Permissions));
return m_userGroupActions;
}
}
protected UserGroup CurrentUserGroup
protected IUserGroup CurrentUserGroup
{
get
{
if (m_userGroup == null)
m_userGroup = UserGroup.GetUserGroup(m_userGroupID);
m_userGroup = ApplicationContext.Current.Services.UserService.GetUserGroupById(m_userGroupID);
return m_userGroup;
}
}
private UserGroup m_userGroup;
private IUserGroup m_userGroup;
private List<IAction> m_userGroupActions;
private int m_userGroupID;
@@ -135,13 +138,17 @@ namespace umbraco.cms.presentation.user
foreach (Application a in CurrentUser.Applications)
currentUserApps += a.alias + ";";
Application[] gapps = CurrentUserGroup.Applications;
var gapps = CurrentUserGroup.AllowedSections;
foreach (Application app in BusinessLogic.Application.getAll())
{
if (CurrentUser.IsAdmin() || currentUserApps.Contains(";" + app.alias + ";"))
{
ListItem li = new ListItem(ui.Text("sections", app.alias), app.alias);
foreach (Application tmp in gapps) if (app.alias == tmp.alias) li.Selected = true;
foreach (var tmp in gapps)
{
if (app.alias == tmp)
li.Selected = true;
}
cbl_sections.Items.Add(li);
}
}
@@ -1,42 +0,0 @@
using Umbraco.Web.UI;
using umbraco.BusinessLogic;
namespace umbraco.cms.presentation.user
{
public class UserGroupTasks : LegacyDialogTask
{
public override bool PerformSave()
{
try
{
var u = UserGroup.MakeNew(Alias, "", Alias);
_returnUrl = string.Format("users/EditUserGroup.aspx?id={0}", u.Id);
return true;
}
catch
{
return false;
}
}
public override bool PerformDelete()
{
var userGroup = UserGroup.GetUserGroup(ParentID);
if (userGroup == null)
return false;
userGroup.Delete();
return true;
}
private string _returnUrl = "";
public override string ReturnUrl
{
get { return _returnUrl; }
}
public override string AssignedApp
{
get { return DefaultApps.users.ToString(); }
}
}
}
-309
View File
@@ -1,309 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Events;
namespace umbraco.BusinessLogic
{
/// <summary>
/// Represents a umbraco Usergroup
/// </summary>
[Obsolete("Use the UserService instead")]
public class UserGroup
{
internal Umbraco.Core.Models.Membership.IUserGroup UserGroupItem;
/// <summary>
/// Creates a new empty instance of a UserGroup
/// </summary>
public UserGroup()
{
UserGroupItem = new Umbraco.Core.Models.Membership.UserGroup();
}
internal UserGroup(Umbraco.Core.Models.Membership.IUserGroup userGroup)
{
UserGroupItem = userGroup;
}
/// <summary>
/// Creates a new instance of a UserGroup and attempts to
/// load it's values from the database cache.
/// </summary>
/// <remarks>
/// If the UserGroup is not found in the existing ID list, then this object
/// will remain an empty object
/// </remarks>
/// <param name="id">The UserGroup id to find</param>
public UserGroup(int id)
{
this.LoadByPrimaryKey(id);
}
/// <summary>
/// Initializes a new instance of the <see cref="UserGroup"/> class.
/// </summary>
/// <param name="id">The user type id.</param>
/// <param name="name">The name.</param>
public UserGroup(int id, string name)
{
UserGroupItem = new Umbraco.Core.Models.Membership.UserGroup();
UserGroupItem.Id = id;
UserGroupItem.Name = name;
}
/// <summary>
/// Creates a new instance of UserGroup with all parameters
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
/// <param name="defaultPermissions"></param>
/// <param name="alias"></param>
public UserGroup(int id, string name, string defaultPermissions, string alias)
{
UserGroupItem = new Umbraco.Core.Models.Membership.UserGroup();
UserGroupItem.Id = id;
UserGroupItem.Name = name;
UserGroupItem.Alias = alias;
UserGroupItem.Permissions = defaultPermissions.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// The cache storage for all user groups
/// </summary>
private static List<UserGroup> UserGroups
{
get
{
return ApplicationContext.Current.Services.UserService.GetAllUserGroups()
.Select(x => new UserGroup(x))
.ToList();
}
}
#region Public Properties
/// <summary>
/// Gets or sets the user type alias.
/// </summary>
public string Alias
{
get { return UserGroupItem.Alias; }
set { UserGroupItem.Alias = value; }
}
/// <summary>
/// Gets the name of the user type.
/// </summary>
public string Name
{
get { return UserGroupItem.Name; }
set { UserGroupItem.Name = value; }
}
/// <summary>
/// Gets the id the user group
/// </summary>
public int Id
{
get { return UserGroupItem.Id; }
}
/// <summary>
/// Gets the default permissions of the user group
/// </summary>
public string DefaultPermissions
{
get { return UserGroupItem.Permissions == null ? string.Empty : string.Join("", UserGroupItem.Permissions); }
set { UserGroupItem.Permissions = value.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); }
}
/// <summary>
/// Gets the applications which the group has access to.
/// </summary>
/// <value>The users applications.</value>
public Application[] Applications
{
get
{
return GetApplications().ToArray();
}
}
/// <summary>
/// Get the application which the group has access to as a List
/// </summary>
/// <returns></returns>
public List<Application> GetApplications()
{
var allApps = Application.getAll();
var apps = new List<Application>();
var sections = UserGroupItem.AllowedSections;
foreach (var s in sections)
{
var app = allApps.SingleOrDefault(x => x.alias == s);
if (app != null)
apps.Add(app);
}
return apps;
}
/// <summary>
/// Clears the list of applications the user has access to, ensure to call Save afterwords
/// </summary>
public void ClearApplications()
{
foreach (var s in UserGroupItem.AllowedSections.ToArray())
{
UserGroupItem.RemoveAllowedSection(s);
}
}
/// <summary>
/// Adds a application to the list of allowed applications, ensure to call Save() afterwords
/// </summary>
/// <param name="appAlias"></param>
public void AddApplication(string appAlias)
{
UserGroupItem.AddAllowedSection(appAlias);
}
#endregion
/// <summary>
/// Saves this instance
/// </summary>
public void Save()
{
PerformSave();
}
/// <summary>
/// Saves this instance (along with the list of users in the group if provided)
/// </summary>
public void SaveWithUsers(int[] userIds)
{
PerformSave(true, userIds);
}
private void PerformSave(bool updateUsers = false, int[] userIds = null)
{
//ensure that this object has an ID specified (it exists in the database)
if (UserGroupItem.HasIdentity == false)
throw new Exception("The current UserGroup object does not exist in the database. New UserGroups should be created with the MakeNew method");
ApplicationContext.Current.Services.UserService.SaveUserGroup(UserGroupItem, updateUsers, userIds);
//raise event
OnUpdated(this, new EventArgs());
}
/// <summary>
/// Deletes this instance.
/// </summary>
public void Delete()
{
//ensure that this object has an ID specified (it exists in the database)
if (UserGroupItem.HasIdentity == false)
throw new Exception("The current UserGroup object does not exist in the database. New UserGroups should be created with the MakeNew method");
ApplicationContext.Current.Services.UserService.DeleteUserGroup(UserGroupItem);
//raise event
OnDeleted(this, new EventArgs());
}
/// <summary>
/// Load the data for the current UserGroup by it's id
/// </summary>
/// <param name="id"></param>
/// <returns>Returns true if the UserGroup id was found
/// and the data was loaded, false if it wasn't</returns>
public bool LoadByPrimaryKey(int id)
{
UserGroupItem = ApplicationContext.Current.Services.UserService.GetUserGroupById(id);
return UserGroupItem != null;
}
/// <summary>
/// Creates a new user group
/// </summary>
/// <param name="name"></param>
/// <param name="defaultPermissions"></param>
/// <param name="alias"></param>
public static UserGroup MakeNew(string name, string defaultPermissions, string alias)
{
//ensure that the current alias does not exist
//get the id for the new user group
var existing = UserGroups.Find(ut => (ut.Alias == alias));
if (existing != null)
throw new Exception("The UserGroup alias specified already exists");
var userType = new Umbraco.Core.Models.Membership.UserGroup
{
Alias = alias,
Name = name,
Permissions = defaultPermissions.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture))
};
ApplicationContext.Current.Services.UserService.SaveUserGroup(userType);
var legacy = new UserGroup(userType);
//raise event
OnNew(legacy, new EventArgs());
return legacy;
}
/// <summary>
/// Gets the user group with the specfied ID
/// </summary>
/// <param name="id">The id.</param>
/// <returns></returns>
public static UserGroup GetUserGroup(int id)
{
return UserGroups.Find(ut => (ut.Id == id));
}
/// <summary>
/// Returns all user groups
/// </summary>
/// <returns></returns>
public static List<UserGroup> GetAllUserGroups()
{
return UserGroups;
}
internal static event TypedEventHandler<UserGroup, EventArgs> New;
private static void OnNew(UserGroup userType, EventArgs args)
{
if (New != null)
{
New(userType, args);
}
}
internal static event TypedEventHandler<UserGroup, EventArgs> Deleted;
private static void OnDeleted(UserGroup userType, EventArgs args)
{
if (Deleted != null)
{
Deleted(userType, args);
}
}
internal static event TypedEventHandler<UserGroup, EventArgs> Updated;
private static void OnUpdated(UserGroup userType, EventArgs args)
{
if (Updated != null)
{
Updated(userType, args);
}
}
}
}
@@ -242,7 +242,6 @@
<Compile Include="User.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="UserGroup.cs" />
<Compile Include="Utils\EncodedStringWriter.cs">
<SubType>Code</SubType>
</Compile>