//public virtual bool Exists(string name)
        //{
        //    if (string.IsNullOrEmpty(name))
        //        throw new ArgumentNullException("name");
        //    int count = _repository.Query.Where(x => x.Name == name.Trim()).Count();
        //    return count > 0 ? true : false;
        //}
        /// <summary>
        /// Adds a item
        /// </summary>
        /// <param name="item">item</param>
        public virtual void Add(ActivityLog item)
        {
            if (item == null)
                throw new ArgumentNullException("item");
            using (var scope = new UnitOfWorkScope())
            {
                _repository.Add(item);
                scope.Commit();
            }

            //event notification
            _eventPublisher.EntityInserted(item);
        }
 /// <summary>
 /// Executes a task
 /// </summary>
 public void Execute()
 {
     var settingService = IoC.GetService<ISettingService>();
     var activityLogService = IoC.GetService<IActivityLogService>();
     StringBuilder message = new StringBuilder();
     message.AppendLine("Scheduled task DeleteActivityLogsTask is started.");
     ActivityLog activityItem = new ActivityLog(ActivityType.StartScheduledTask.ToString(), message.ToString());
     activityLogService.Add(activityItem);
     var olderThanMinutes = settingService.GetSettingByKey<int>(Constants.SETTING_KEYS_SCHEDULEDTASK_ACTIVITY_LOGS_EXPIRATION, 60 * 24 * 180);
     Util.DeleteActivityLogs(DateTime.UtcNow.AddMinutes(-olderThanMinutes).Date);
     message.Clear();
     message.AppendLine("Scheduled task DeleteActivityLogsTask is finished successfully.");
     activityItem = new ActivityLog(ActivityType.EndScheduledTask.ToString(), message.ToString());
     activityLogService.Add(activityItem);
 }
        /// <summary>
        /// Adds a item
        /// </summary>
        /// <param name="item">item</param>
        public virtual void Add(ScheduleTask item)
        {
            if (item == null)
                throw new ArgumentNullException("item");
            using (var scope = new UnitOfWorkScope())
            {
                _repository.Add(item);
                scope.Commit();
            }

            //event notification
            _eventPublisher.EntityInserted(item);
            TaskManager.Instance.Refresh();
            StringBuilder message = new StringBuilder();
            message.AppendFormat("Task {0} is created.", item.Name);
            ActivityLog activityItem = new ActivityLog(ActivityType.AddTask.ToString(), message.ToString());
            _activityLogService.Add(activityItem);
        }
 protected void RemovePermissionsFromRole(List<Permission> permissions, Role role, Func<ICollection<Permission>, Permission, ICollection<Permission>> changePermission)
 {
     if (permissions == null || permissions.Count == 0 || role == null)
         return;
     StringBuilder message = new StringBuilder(), items = new StringBuilder(); ;
     foreach (var perm in permissions)
     {
         if (perm != null)
         {
             if (role.Permissions.Contains<Permission>(perm))
             {
                 changePermission(role.Permissions, perm);
                 items.AppendFormat("{0},", perm.Name);
             }
         }
     }
     using (var scope = new UnitOfWorkScope())
     {
         _roleRepository.Update(role);
         scope.Commit();
     }
     if (items.Length > 0)
     {
         items = items.Remove(items.Length - 1, 1);
         message.AppendFormat("Permission(s) {0} are removed from role {1}.", items.ToString(), role.Name);
         ActivityLog item = new ActivityLog(ActivityType.RemovePermissionFromRole.ToString(), message.ToString());
         _activityLogService.Add(item);
     }
 }
 public virtual bool UpdatePermission(Permission newPermission)
 {
     var permission = _permissionRepository.Query.Where(x => x.Id == newPermission.Id).SingleOrDefault();
     permission.Name = newPermission.Name;
     permission.Description = newPermission.Description;
     using (var scope = new UnitOfWorkScope())
     {
         _permissionRepository.Update(permission);
         scope.Commit();
     }
     StringBuilder message = new StringBuilder();
     message.AppendFormat("Permission {0} is updated.", permission.Name);
     ActivityLog item = new ActivityLog(ActivityType.UpdatePermission.ToString(), message.ToString());
     _activityLogService.Add(item);
     return true;
 }
 public virtual void RemoveAllPermissionsFromRole(Guid roleId)
 {
     StringBuilder message = new StringBuilder();
     var role = _roleRepository.Query.FirstOrDefault(x => x.Id == roleId);
     if (role.Permissions != null && role.Permissions.Count > 0)
     {
         message.AppendFormat("Permission(s) {0} are removed from role {1}.", string.Join(",", role.Permissions.Select(x => x.Name)), role.Name);
         role.Permissions.Clear();
     }
     using (var scope = new UnitOfWorkScope())
     {
         _roleRepository.Update(role);
         scope.Commit();
     }
     if (message.Length>0)
     {
         ActivityLog item = new ActivityLog(ActivityType.RemovePermissionFromRole.ToString(), message.ToString());
         _activityLogService.Add(item);
     }
 }
 public virtual bool DeletePermission(string name)
 {
     if (string.IsNullOrEmpty(name))
         throw new Exception("Permission name cannot be empty.");
     name = name.Trim();
     Permission permission = _permissionRepository.Query.FirstOrDefault(x => x.Name == name);
     var rolesWithPermissionCount = _roleRepository.Query.Where(x => x.Permissions.Any(y => y.Id == permission.Id)).Count();
     if (rolesWithPermissionCount > 0)
         throw new Exception(string.Format("Permission {0} is being used and cannot be deleted.", name));
     if (permission != null && rolesWithPermissionCount == 0)
     {
         using (var scope = new UnitOfWorkScope())
         {
             _permissionRepository.Delete(permission);
             scope.Commit();
         }
         StringBuilder message = new StringBuilder();
         message.AppendFormat("Permission {0} is deleted.", permission.Name);
         ActivityLog item = new ActivityLog(ActivityType.DeletePermission.ToString(), message.ToString());
         _activityLogService.Add(item);
         return true;
     }
     return false;
 }
 public virtual Permission CreatePermission(Permission permission)
 {
     Permission matchedPermission = _permissionRepository.Query.FirstOrDefault(x => x.Name == permission.Name);
     if (matchedPermission != null)
         throw new Exception(string.Format("Permission {0} already exist.", permission.Name));
     using (var scope = new UnitOfWorkScope())
     {
         _permissionRepository.Add(permission);
         scope.Commit();
     }
     StringBuilder message = new StringBuilder();
     message.AppendFormat("Permission {0} is created.", permission.Name);
     ActivityLog item = new ActivityLog(ActivityType.AddPermission.ToString(), message.ToString());
     _activityLogService.Add(item);
     return permission;
 }
        public virtual bool DeleteRole(string roleName)
        {
            if (string.IsNullOrEmpty(roleName))
                return true;
            roleName = roleName.Trim();
            var users = _userRepository.Query.Where(x => x.Roles.Any(r => r.Name == roleName));
            var role = _roleRepository.Query.Where(x => x.Name==roleName).SingleOrDefault();
            if (users.Any())
            {
                throw new Exception(string.Format("Role {0} is being used and cannot be deleted.", roleName));
            }
            using (var scope = new UnitOfWorkScope())
            {
                _roleRepository.Delete(role);
                scope.Commit();
            }
            StringBuilder message=new StringBuilder();
            message.AppendFormat("Role {0} is deleted.",role.Name);
            ActivityLog item=new ActivityLog(ActivityType.DeleteRole.ToString(),message.ToString());
            _activityLogService.Add(item);

            return true;
        }
        /// <summary>
        /// Deletes a item
        /// </summary>
        /// <param name="item">item</param>
        public virtual bool Delete(ScheduleTask item)
        {
            if (item == null)
                throw new ArgumentNullException("item");
            using (var scope = new UnitOfWorkScope())
            {
                _repository.Delete(item);
                scope.Commit();
            }

            //event notification
            _eventPublisher.EntityDeleted(item);
            StringBuilder message = new StringBuilder();
            message.AppendFormat("Task {0} is deleted.", item.Name);
            ActivityLog activityItem = new ActivityLog(ActivityType.DeleteTask.ToString(), message.ToString());
            _activityLogService.Add(activityItem);
            return true;
        }
 public virtual void Save(NhUserAccount user)
 {
     if (user == null)
         throw new ArgumentNullException("User cannot be empty.");
     if (string.IsNullOrEmpty(user.Username))
         throw new Exception("Username cannot be empty.");
     if (string.IsNullOrEmpty(user.Email))
         throw new Exception("User email cannot be empty.");
     if (_membershipConfiguration.UsernamesUniqueAcrossTenants)
     {
         var account = _userRepository.Query.SingleOrDefault(x => x.Username == user.Username);
         if (account != null && account.ID != user.ID)
         {
             throw new Exception(string.Format("Username {0} is not available.", user.Username)); ;
         }
     }
     else
     {
         var account = _userRepository.Query.SingleOrDefault(x => x.Username == user.Username);
         if (account!=null && (user.ID==default(Guid) || account.ID != user.ID))
         {
             throw new Exception(string.Format("Username {0} is not available.", user.Username)); ;
         }
     }
     using (var scope = new UnitOfWorkScope())
     {
         _userRepository.Add(user);//.Save(user);
         scope.Commit();
     }
     StringBuilder message = new StringBuilder();
     message.AppendFormat("User {0} is created.", user.Username);
     ActivityLog activityItem = new ActivityLog(ActivityType.AddUser.ToString(), message.ToString());
     _activityLogService.Add(activityItem);
 }
 public virtual bool Delete(Guid id)
 {
     if (id == default(Guid))
         throw new ArgumentNullException("User id cannot be empty.");
     NhUserAccount user = _userRepository.Query.SingleOrDefault(x => x.ID == id);
     if(user==null)
         throw new Exception(string.Format("Cannot find user {0}",id));
     App.Common.Data.IRepository<PasswordHistory,Guid> passwordRepository = IoC.GetService<App.Common.Data.IRepository<PasswordHistory,Guid>>();
     List<PasswordHistory> passwordHistories = passwordRepository.Query.Where(x => x.User.ID == id).ToList();
     using (var scope = new UnitOfWorkScope())
     {
         foreach (PasswordHistory item in passwordHistories)
         {
             passwordRepository.Delete(item);
         }
         _userRepository.Delete(user);
         scope.Commit();
     }
     StringBuilder message = new StringBuilder();
     message.AppendFormat("User {0} is deleted.", user.Username);
     ActivityLog activityItem = new ActivityLog(ActivityType.DeleteUser.ToString(), message.ToString());
     _activityLogService.Add(activityItem);
     return true;
 }
        public virtual void AddUsersToRoles(List<Guid> userId, List<string> roleName)
        {
            if (userId == null || userId.Count == 0 || roleName == null || roleName.Count == 0)
                return;
            StringBuilder message=new StringBuilder();
            var users = _userRepository.Query.Where(x => userId.Contains(x.ID)).ToList();
            var roles = _roleRepository.Query.Where(x => roleName.Contains(x.Name)).ToList();
            foreach (var userEntity in users)
            {
                if (userEntity.Roles != null && userEntity.Roles.Any())
                {
                    var newRoles = roles.Except(userEntity.Roles);

                    foreach (var role in newRoles)
                        userEntity.Roles.Add(role);
                    if(newRoles!=null && newRoles.Count()>0)
                        message.AppendFormat("User {0} is added to role(s) {1}.",userEntity.Username,string.Join(",", newRoles.Select(x => x.Name)));
                }
                else
                {
                    foreach (var role in roles)
                        userEntity.Roles.Add(role);
                    if(roles!=null && roles.Count()>0)
                        message.AppendFormat("User {0} is added to role(s) {1}.",userEntity.Username,string.Join(",", roles.Select(x => x.Name)));
                }
                using (var scope = new UnitOfWorkScope())
                {
                    _userRepository.Update(userEntity);
                    scope.Commit();
                }
            }
            foreach (var uid in userId)
            {
                if (!users.Any(u => u.ID == uid))
                {
                    var user = _userRepository.Query.Where(x => x.ID == uid).SingleOrDefault();
                    if (user != null)
                    {
                        user.Roles = roles;
                        using (var scope = new UnitOfWorkScope())
                        {
                            _userRepository.Update(user);
                            scope.Commit();
                        }
                        if(roles!=null && roles.Count()>0)
                            message.AppendFormat("User {0} is added to role(s) {1}.",user.Username,string.Join(",", roles.Select(x => x.Name)));
                    }
                }
            }
            if (message.Length > 0)
            {
                ActivityLog item = new ActivityLog(ActivityType.AddUserToRole.ToString(), message.ToString());
                _activityLogService.Add(item);
            }
        }
        private void RemoveUsersFromRoles(List<NhUserAccount> users, List<Role> roles)
        {
            if (users == null || users.Count == 0 || roles == null || roles.Count == 0)
                return;
            StringBuilder message=new StringBuilder();
            using (var scope = new UnitOfWorkScope())
            {
                foreach (var userEntity in users)
                {
                    if (userEntity.Roles != null && userEntity.Roles.Any())
                    {
                        int oldCount = userEntity.Roles.Count;
                        var matchedRoles = roles.Intersect(userEntity.Roles);
                        message.AppendFormat("Role(s) {0} are removed from user {1}.", string.Join(",", matchedRoles.Select(x => x.Name)), userEntity.Username);

                        foreach (var matchedRole in matchedRoles)
                            userEntity.Roles.Remove(matchedRole);

                        if (oldCount != userEntity.Roles.Count)
                        {
                            _userRepository.Update(userEntity);
                        }
                    }
                }
                scope.Commit();
            }
            if (message.Length > 0)
            {
                ActivityLog item = new ActivityLog(ActivityType.RemoveUserFromRole.ToString(), message.ToString());
                _activityLogService.Add(item);
            }
        }
        public virtual bool UpdateRole(Role newRole)
        {
            var role = _roleRepository.Query.Where(x => x.Id == newRole.Id).SingleOrDefault();
            role.Name = newRole.Name;
            role.Description = newRole.Description;
            using (var scope = new UnitOfWorkScope())
            {
                _roleRepository.Update(role);
                scope.Commit();
            }
            StringBuilder message=new StringBuilder();
            message.AppendFormat("Role {0} is updated.",role.Name);
            ActivityLog item=new ActivityLog(ActivityType.UpdateRole.ToString(),message.ToString());
            _activityLogService.Add(item);

            return true;
        }
        public virtual bool Delete(Guid id)
        {
            if (id == default(Guid))
                throw new ArgumentNullException("id");
            ScheduleTask item = _repository.Query.FirstOrDefault(x => x.Id == id);
            if (item == null)
                return false;
            using (var scope = new UnitOfWorkScope())
            {
                _repository.Delete(item);
                scope.Commit();
            }

            //event notification
            _eventPublisher.EntityDeleted(item);
            TaskManager.Instance.Refresh();
            StringBuilder message = new StringBuilder();
            message.AppendFormat("Task {0} is deleted.", item.Name);
            ActivityLog activityItem = new ActivityLog(ActivityType.DeleteTask.ToString(), message.ToString());
            _activityLogService.Add(activityItem);
            return true;
        }
        /// <summary>
        /// Deletes a item
        /// </summary>
        /// <param name="item">item</param>
        public virtual bool Delete(ActivityLog item)
        {
            if (item == null)
                throw new ArgumentNullException("item");
            using (var scope = new UnitOfWorkScope())
            {
                _repository.Delete(item);
                scope.Commit();
            }

            //event notification
            _eventPublisher.EntityDeleted(item);
            return true;
        }
 public virtual void CreateRole(Role role)
 {
     if (role == null)
         throw new ArgumentNullException("Role");
     using (var scope = new UnitOfWorkScope())
     {
         _roleRepository.Add(role);
         scope.Commit();
     }
     StringBuilder message=new StringBuilder();
     message.AppendFormat("Role {0} is created.",role.Name);
     ActivityLog item=new ActivityLog(ActivityType.AddRole.ToString(),message.ToString());
     _activityLogService.Add(item);
 }