Ejemplo n.º 1
0
        public int SetMembers(uint roleId, IEnumerable <Member> members, bool shouldResetting = false)
        {
            if (members == null)
            {
                return(0);
            }

            using (var transaction = new Zongsoft.Transactions.Transaction())
            {
                int count = 0;

                //清空指定角色的所有成员
                if (shouldResetting)
                {
                    count = this.DataAccess.Delete <Member>(Condition.Equal(nameof(Member.RoleId), roleId));
                }

                //写入指定的角色成员集到数据库中
                count = this.DataAccess.UpsertMany <Member>(members.Select(m => new Member(roleId, m.MemberId, m.MemberType)));

                //提交事务
                transaction.Commit();

                return(count);
            }
        }
Ejemplo n.º 2
0
        public bool Downvote(ulong postId, byte value = 1)
        {
            var credential = this.EnsureCredential();

            if (value == 0)
            {
                value = 1;
            }

            using (var transaction = new Zongsoft.Transactions.Transaction())
            {
                this.DataAccess.Delete <Post.PostVoting>(Condition.Equal("PostId", postId) & Condition.Equal("UserId", credential.UserId));
                this.DataAccess.Insert(new Post.PostVoting(postId, credential.UserId, (sbyte)-Math.Min(value, (byte)100))
                {
                    UserName   = credential.User.FullName,
                    UserAvatar = credential.User.Avatar,
                });

                //如果帖子投票统计信息更新成功
                if (this.SetPostVotes(postId))
                {
                    //提交事务
                    transaction.Commit();

                    //返回成功
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 3
0
        public int SetPermissions(uint memberId, MemberType memberType, string schemaId, IEnumerable <Permission> permissions, bool shouldResetting = false)
        {
            var conditions = Condition.Equal(nameof(Permission.MemberId), memberId) & Condition.Equal(nameof(Permission.MemberType), memberType);

            if (!string.IsNullOrWhiteSpace(schemaId))
            {
                conditions.Add(Condition.Equal(nameof(Permission.SchemaId), schemaId));
            }

            using (var transaction = new Zongsoft.Transactions.Transaction())
            {
                int count = 0;

                //清空指定成员的所有权限设置
                if (shouldResetting || permissions == null)
                {
                    count = this.DataAccess.Delete <Permission>(conditions);
                }

                //写入指定的权限设置集到数据库中
                if (permissions != null)
                {
                    count = this.DataAccess.UpsertMany(
                        permissions.Select(p => new Permission(memberId, memberType, (string.IsNullOrEmpty(schemaId) ? p.SchemaId : schemaId), p.ActionId, p.Granted)));
                }

                //提交事务
                transaction.Commit();

                return(count);
            }
        }
Ejemplo n.º 4
0
        protected override int OnInsert(IDataDictionary <Thread> data, ISchema schema, IDictionary <string, object> states)
        {
            if (!data.TryGetValue(p => p.Post, out var post) || string.IsNullOrEmpty(post.Content))
            {
                throw new InvalidOperationException("Missing content of the thread.");
            }

            //确保数据模式含有“主题内容贴”复合属性
            schema.Include("Post{*}");

            //更新主题内容贴的相关属性
            post.Visible = false;

            using (var transaction = new Zongsoft.Transactions.Transaction())
            {
                //调用基类同名方法,插入主题数据
                var count = base.OnInsert(data, schema, states);

                if (count < 1)
                {
                    return(count);
                }

                //更新发帖人关联的主题统计信息
                this.SetMostRecentThread(data);

                //提交事务
                transaction.Commit();

                return(count);
            }
        }
Ejemplo n.º 5
0
        public bool Downvote(ulong postId, byte value = 1)
        {
            if (value == 0)
            {
                value = 1;
            }

            using (var transaction = new Zongsoft.Transactions.Transaction())
            {
                this.DataAccess.Delete <Post.PostVoting>(Condition.Equal("PostId", postId) & Condition.Equal("UserId", this.User.UserId));
                this.DataAccess.Insert(Model.Build <Post.PostVoting>(voting =>
                {
                    voting.PostId     = postId;
                    voting.UserId     = this.User.UserId;
                    voting.UserName   = this.User.Name;
                    voting.UserAvatar = this.User.Avatar;
                    voting.Value      = (sbyte)-Math.Min(value, (byte)100);
                    voting.Timestamp  = DateTime.Now;
                }));

                //如果帖子投票统计信息更新成功
                if (this.SetPostVotes(postId))
                {
                    //提交事务
                    transaction.Commit();

                    //返回成功
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 6
0
        protected override int OnInsert(DataDictionary <Thread> data, string scope, object state)
        {
            var post = data.Get(p => p.Post, null);

            if (post == null || string.IsNullOrEmpty(post.Content))
            {
                throw new InvalidOperationException("Missing content of the thread.");
            }

            using (var transaction = new Zongsoft.Transactions.Transaction())
            {
                //设置主题内容贴编号为零
                data.Set(p => p.PostId, (ulong)0);

                //调用基类同名方法,插入主题数据
                var count = base.OnInsert(data, scope, state);

                if (count < 1)
                {
                    return(count);
                }

                //更新主题内容贴的相关属性
                post.ThreadId    = data.Get(p => p.ThreadId);
                post.SiteId      = data.Get(p => p.SiteId);
                post.CreatorId   = data.Get(p => p.CreatorId);
                post.CreatedTime = data.Get(p => p.CreatedTime);

                //通过帖子服务来新增主题的内容贴
                count = this.Posting.Insert(post, data);

                //如果主题内容贴新增成功则提交事务
                if (count > 0)
                {
                    //更新新增主题的内容帖子编号
                    this.DataAccess.Update(this.Name, new
                    {
                        ThreadId = data.Get(p => p.ThreadId),
                        PostId   = post.PostId,
                    });

                    //更新主题数据字典中的内容帖子编号
                    data.Set(p => p.PostId, post.PostId);

                    //更新发帖人关联的主题统计信息
                    this.SetMostRecentThread(data);

                    //提交事务
                    transaction.Commit();
                }

                return(count);
            }
        }
Ejemplo n.º 7
0
        protected override int OnDelete(ICondition condition, string[] cascades, object state)
        {
            var ids = this.DataAccess.Select <Thread>(this.Name, condition, Paging.Disable).Select(p => p.ThreadId).ToArray();

            using (var transaction = new Zongsoft.Transactions.Transaction())
            {
                //调用基类同名方法
                var count = base.OnDelete(condition, cascades, state);

                if (count > 0)
                {
                    this.DataAccess.Delete <Post>(Condition.In("ThreadId", ids));
                }

                //提交事务
                transaction.Commit();

                //返回被删除的主题记录数
                return(count);
            }
        }
Ejemplo n.º 8
0
		public bool CreateUser(User user, string password)
		{
			if(user == null)
				throw new ArgumentNullException("user");

			if(string.IsNullOrWhiteSpace(user.Name))
				throw new ArgumentException("The user name is empty.");

			//确保用户名是审核通过的
			this.Censor(user.Name);

			//确认指定用户的用户名、手机号、邮箱地址是否已经存在
			this.EnsureConflict(user, null, false);

			if(user.UserId < 1)
				user.UserId = (int)this.Sequence.GetSequenceNumber(MembershipHelper.SEQUENCE_USERID, 1, MembershipHelper.MINIMUM_ID);

			using(var transaction = new Zongsoft.Transactions.Transaction())
			{
				if(this.DataAccess.Insert(MembershipHelper.DATA_ENTITY_USER, user) < 1)
					return false;

				//有效的密码不能为空或全空格字符串
				if(!string.IsNullOrWhiteSpace(password))
				{
					//生成密码随机数
					var passwordSalt = Zongsoft.Common.RandomGenerator.Generate(8);

					this.DataAccess.Update(MembershipHelper.DATA_ENTITY_USER, new
					{
						Password = PasswordUtility.HashPassword(password, passwordSalt),
						PasswordSalt = passwordSalt,
					}, new Condition("UserId", user.UserId));
				}

				//提交事务
				transaction.Commit();
			}

			return true;
		}
Ejemplo n.º 9
0
        protected override int OnInsert(DataDictionary <Post> data, string scope, object state)
        {
            string filePath = null;

            //获取原始的内容类型
            var rawType = data.Get(p => p.ContentType, null);

            //调整内容类型为嵌入格式
            data.Set(p => p.ContentType, Utility.GetContentType(rawType, true));

            //尝试更新帖子内容
            data.TryGet(p => p.Content, (key, value) =>
            {
                if (string.IsNullOrWhiteSpace(value) || value.Length < 500)
                {
                    return;
                }

                //设置内容文件的存储路径
                filePath = this.GetContentFilePath(data.Get(p => p.PostId), data.Get(p => p.ContentType));

                //将内容文本写入到文件中
                Utility.WriteTextFile(filePath, value);

                //更新内容文件的存储路径
                data.Set(p => p.Content, filePath);

                //更新内容类型为非嵌入格式(即外部文件)
                data.Set(p => p.ContentType, Utility.GetContentType(data.Get(p => p.ContentType), false));
            });

            //定义附加数据是否为关联的主题对象
            var thread = state as DataDictionary <Thread>;

            if (thread != null)
            {
                //判断当前用户是否是新增主题所在论坛的版主
                var isModerator = this.ServiceProvider.ResolveRequired <ForumService>().IsModerator(thread.Get(p => p.SiteId), thread.Get(p => p.ForumId));

                if (isModerator)
                {
                    data.Set(p => p.IsApproved, true);
                }
                else
                {
                    var forum = this.DataAccess.Select <Forum>(Condition.Equal("SiteId", thread.Get(p => p.SiteId)) & Condition.Equal("ForumId", thread.Get(p => p.ForumId))).FirstOrDefault();

                    if (forum == null)
                    {
                        throw new InvalidOperationException("The specified forum is not existed about the new thread.");
                    }

                    data.Set(p => p.IsApproved, forum.ApproveEnabled ? false : true);
                }
            }

            try
            {
                using (var transaction = new Zongsoft.Transactions.Transaction())
                {
                    //调用基类同名方法
                    var count = base.OnInsert(data, scope, state);

                    if (count > 0)
                    {
                        //尝试新增帖子的附件集
                        data.TryGet(p => p.Attachments, (key, attachments) =>
                        {
                            if (attachments == null)
                            {
                                return;
                            }

                            foreach (var attachment in attachments)
                            {
                                attachment.PostId = data.Get(p => p.PostId);
                            }

                            this.DataAccess.InsertMany(attachments);
                        });

                        //更新发帖人的关联帖子统计信息
                        //注意:只有当前帖子不是主题贴才需要更新对应的统计信息
                        if (thread == null)
                        {
                            this.SetMostRecentPost(data);
                        }

                        //提交事务
                        transaction.Commit();
                    }
                    else
                    {
                        //如果新增记录失败则删除刚创建的文件
                        if (filePath != null && filePath.Length > 0)
                        {
                            Utility.DeleteFile(filePath);
                        }
                    }

                    return(count);
                }
            }
            catch
            {
                //删除新建的文件
                if (filePath != null && filePath.Length > 0)
                {
                    Utility.DeleteFile(filePath);
                }

                throw;
            }
        }
Ejemplo n.º 10
0
        protected override int OnInsert(DataDictionary <Message> data, string scope, object state)
        {
            string filePath = null;

            //获取原始的内容类型
            var rawType = data.Get(p => p.ContentType, null);

            //调整内容类型为嵌入格式
            data.Set(p => p.ContentType, Utility.GetContentType(rawType, true));

            data.TryGet(p => p.Content, (key, value) =>
            {
                if (string.IsNullOrWhiteSpace(value) || value.Length < 500)
                {
                    return;
                }

                //设置内容文件的存储路径
                filePath = this.GetContentFilePath(data.Get(p => p.MessageId), data.Get(p => p.ContentType));

                //将内容文本写入到文件中
                Utility.WriteTextFile(filePath, value);

                //更新内容文件的存储路径
                data.Set(p => p.Content, filePath);

                //更新内容类型为非嵌入格式(即外部文件)
                data.Set(p => p.ContentType, Utility.GetContentType(data.Get(p => p.ContentType), false));
            });

            using (var transaction = new Zongsoft.Transactions.Transaction())
            {
                var count = base.OnInsert(data, scope, state);

                if (count < 1)
                {
                    //如果新增记录失败则删除刚创建的文件
                    if (filePath != null && filePath.Length > 0)
                    {
                        Utility.DeleteFile(filePath);
                    }

                    return(count);
                }

                data.TryGet(p => p.Users, (key, users) =>
                {
                    if (users == null)
                    {
                        return;
                    }

                    IEnumerable <Message.MessageUser> GetMembers(ulong messageId, IEnumerable <Message.MessageUser> members)
                    {
                        foreach (var member in members)
                        {
                            yield return(new Message.MessageUser(messageId, member.UserId));
                        }
                    }

                    this.DataAccess.InsertMany(GetMembers(data.Get(p => p.MessageId), users));
                });

                //提交事务
                transaction.Commit();

                return(count);
            }
        }
Ejemplo n.º 11
0
		public void SetMembers(int roleId, IEnumerable<Member> members)
		{
			if(members == null)
				return;

			var dataAccess = this.EnsureService<IDataAccess>();

			foreach(var member in members)
			{
				member.RoleId = roleId;
			}

			using(var transaction = new Zongsoft.Transactions.Transaction())
			{
				//清空指定角色的所有成员
				dataAccess.Delete(MembershipHelper.DATA_ENTITY_MEMBER, new Condition("RoleId", roleId));

				//插入指定的角色成员集到数据库中
				dataAccess.Insert(MembershipHelper.DATA_ENTITY_MEMBER, members);

				//提交事务
				transaction.Commit();
			}
		}
Ejemplo n.º 12
0
		public int SetMembers(int roleId, IEnumerable<Member> members, bool shouldResetting = false)
		{
			if(members == null)
				return 0;

			//如果指定角色编号不存在则退出
			if(!this.DataAccess.Exists(MembershipHelper.DATA_ENTITY_ROLE, Condition.Equal("RoleId", roleId)))
				return -1;

			int count = 0;

			using(var transaction = new Zongsoft.Transactions.Transaction())
			{
				//清空指定角色的所有成员
				if(shouldResetting)
					this.DataAccess.Delete(MembershipHelper.DATA_ENTITY_MEMBER, Condition.Equal("RoleId", roleId));

				foreach(var member in members)
				{
					if(member == null)
						continue;

					//更新成员的角色编号
					member.RoleId = roleId;

					bool existed;

					if(member.MemberType == MemberType.Role)
						existed = this.DataAccess.Exists(MembershipHelper.DATA_ENTITY_ROLE, Condition.Equal("RoleId", member.MemberId));
					else
						existed = this.DataAccess.Exists(MembershipHelper.DATA_ENTITY_USER, Condition.Equal("UserId", member.MemberId));

					if(existed)
					{
						//插入指定的角色成员集到数据库中
						count += this.DataAccess.Insert(MembershipHelper.DATA_ENTITY_MEMBER, member);
					}
				}

				//提交事务
				transaction.Commit();
			}

			return count;
		}
Ejemplo n.º 13
0
		public int DeleteRoles(params int[] roleIds)
		{
			if(roleIds == null || roleIds.Length < 1)
				return 0;

			int result = 0;

			using(var transaction = new Zongsoft.Transactions.Transaction())
			{
				result = this.DataAccess.Delete(MembershipHelper.DATA_ENTITY_ROLE, Condition.In("RoleId", roleIds));

				if(result > 0)
				{
					this.DataAccess.Delete(MembershipHelper.DATA_ENTITY_MEMBER, Condition.Equal("MemberType", MemberType.Role) & Condition.In("MemberId", roleIds));
					this.DataAccess.Delete(MembershipHelper.DATA_ENTITY_PERMISSION, Condition.Equal("MemberType", MemberType.Role) & Condition.In("MemberId", roleIds));
					this.DataAccess.Delete(MembershipHelper.DATA_ENTITY_PERMISSION_FILTER, Condition.Equal("MemberType", MemberType.Role) & Condition.In("MemberId", roleIds));
				}

				transaction.Commit();
			}

			return result;
		}
		private void SetPermissions(string name, int memberId, MemberType memberType, IEnumerable<Permission> permissions)
		{
			if(permissions == null)
				throw new ArgumentNullException("permissions");

			foreach(var permission in permissions)
			{
				permission.MemberId = memberId;
				permission.MemberType = memberType;
			}

			using(var transaction = new Zongsoft.Transactions.Transaction())
			{
				//清空指定成员的所有权限设置
				this.DataAccess.Delete(name, Condition.Equal("MemberId", memberId) & Condition.Equal("MemberType", memberType));

				//插入指定的权限设置集到数据库中
				this.DataAccess.Insert(name, permissions);

				//提交事务
				transaction.Commit();
			}
		}
Ejemplo n.º 15
0
        protected override int OnInsert(IDataDictionary <Post> data, ISchema schema, IDictionary <string, object> states)
        {
            string filePath = null;

            //获取原始的内容类型
            var rawType = data.GetValue(p => p.ContentType, null);

            //调整内容类型为嵌入格式
            data.SetValue(p => p.ContentType, Utility.GetContentType(rawType, true));

            //尝试更新帖子内容
            data.TryGetValue(p => p.Content, (key, value) =>
            {
                if (string.IsNullOrWhiteSpace(value) || value.Length < 500)
                {
                    return;
                }

                //设置内容文件的存储路径
                filePath = this.GetContentFilePath(data.GetValue(p => p.PostId), data.GetValue(p => p.ContentType));

                //将内容文本写入到文件中
                Utility.WriteTextFile(filePath, value);

                //更新内容文件的存储路径
                data.SetValue(p => p.Content, filePath);

                //更新内容类型为非嵌入格式(即外部文件)
                data.SetValue(p => p.ContentType, Utility.GetContentType(data.GetValue(p => p.ContentType), false));
            });

            object threadObject = null;

            //附加数据是否包含了关联的主题对象
            if (states != null && states.TryGetValue("Thread", out threadObject) && threadObject != null)
            {
                uint   siteId  = 0;
                ushort forumId = 0;

                if (threadObject is Thread thread)
                {
                    siteId  = thread.SiteId;
                    forumId = thread.ForumId;
                }
                else if (threadObject is IDataDictionary <Thread> dictionary)
                {
                    siteId  = dictionary.GetValue(p => p.SiteId);
                    forumId = dictionary.GetValue(p => p.ForumId);
                }

                //判断当前用户是否是新增主题所在论坛的版主
                var isModerator = this.ServiceProvider.ResolveRequired <ForumService>()
                                  .IsModerator(forumId);

                if (isModerator)
                {
                    data.SetValue(p => p.Approved, true);
                }
                else
                {
                    var forum = this.DataAccess.Select <Forum>(
                        Condition.Equal(nameof(Forum.SiteId), siteId) &
                        Condition.Equal(nameof(Forum.ForumId), forumId)).FirstOrDefault();

                    if (forum == null)
                    {
                        throw new InvalidOperationException("The specified forum is not existed about the new thread.");
                    }

                    data.SetValue(p => p.Approved, forum.Approvable ? false : true);
                }
            }

            try
            {
                using (var transaction = new Zongsoft.Transactions.Transaction())
                {
                    //调用基类同名方法
                    var count = base.OnInsert(data, schema.Include(nameof(Post.Attachments)), states);

                    if (count > 0)
                    {
                        //更新发帖人的关联帖子统计信息
                        //注意:只有当前帖子不是主题贴才需要更新对应的统计信息
                        if (threadObject == null)
                        {
                            this.SetMostRecentPost(data);
                        }

                        //提交事务
                        transaction.Commit();
                    }
                    else
                    {
                        //如果新增记录失败则删除刚创建的文件
                        if (filePath != null && filePath.Length > 0)
                        {
                            Utility.DeleteFile(filePath);
                        }
                    }

                    return(count);
                }
            }
            catch
            {
                //删除新建的文件
                if (filePath != null && filePath.Length > 0)
                {
                    Utility.DeleteFile(filePath);
                }

                throw;
            }
        }
Ejemplo n.º 16
0
        public virtual void Delete(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw HttpResponseExceptionUtility.BadRequest("Missing the id argument.");
            }

            string[] parts;
            var      entries = id.Split('|');

            if (entries != null && entries.Length > 1)
            {
                int count = 0;

                using (var transaction = new Zongsoft.Transactions.Transaction())
                {
                    foreach (var entry in entries)
                    {
                        parts = entry.Split('-');

                        switch (parts.Length)
                        {
                        case 1:
                            count += this.DataService.Delete <string>(parts[0]);
                            break;

                        case 2:
                            count += this.DataService.Delete <string, string>(parts[0], parts[1]);
                            break;

                        case 3:
                            count += this.DataService.Delete <string, string, string>(parts[0], parts[1], parts[2]);
                            break;

                        default:
                            throw HttpResponseExceptionUtility.BadRequest("The parts of id argument too many.");
                        }
                    }

                    transaction.Commit();
                }

                return;
            }

            parts = id.Split('-');
            var succeed = false;

            switch (parts.Length)
            {
            case 1:
                succeed = this.DataService.Delete <string>(parts[0]) > 0;
                break;

            case 2:
                succeed = this.DataService.Delete <string, string>(parts[0], parts[1]) > 0;
                break;

            case 3:
                succeed = this.DataService.Delete <string, string, string>(parts[0], parts[1], parts[2]) > 0;
                break;

            default:
                throw HttpResponseExceptionUtility.BadRequest("The parts of id argument too many.");
            }

            if (!succeed)
            {
                throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
            }
        }
Ejemplo n.º 17
0
		public bool CreateUser(User user, string password)
		{
			if(user == null)
				throw new ArgumentNullException("user");

			if(string.IsNullOrWhiteSpace(user.Name))
				throw new ArgumentException("The user name is empty.");

			if(user.UserId < 1)
				user.UserId = (int)this.EnsureService<Zongsoft.Common.ISequence>().GetSequenceNumber(MembershipHelper.SEQUENCE_USERID, 1, MembershipHelper.MINIMUM_ID);

			//确保用户名是审核通过的
			this.Censor(user.Name);

			var dataAccess = this.EnsureService<IDataAccess>();

			using(var transaction = new Zongsoft.Transactions.Transaction())
			{
				if(dataAccess.Insert(MembershipHelper.DATA_ENTITY_USER, user) < 1)
					return false;

				if(password != null && password.Length > 0)
				{
					//生成密码随机数
					var passwordSalt = Zongsoft.Common.RandomGenerator.Generate(8);

					dataAccess.Update(MembershipHelper.DATA_ENTITY_USER, new
					{
						Password = PasswordUtility.HashPassword(password, passwordSalt),
						PasswordSalt = passwordSalt,
					}, new Condition("UserId", user.UserId));
				}

				//提交事务
				transaction.Commit();
			}

			return true;
		}