Example #1
0
        public async Task <HttpResponseMessage> DeletePosts([FromBody] SearchPostViewModel conditions)
        {
            try
            {
                #region Parameters validation

                // Conditions haven't been initialized.
                if (conditions == null)
                {
                    conditions = new SearchPostViewModel();
                    Validate(conditions);
                }

                //Request parameters are invalid
                if (!ModelState.IsValid)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState));
                }

                #endregion

                #region Records delete

                // Find posts by using specific conditions.
                var posts = _unitOfWork.RepositoryPosts.Search();
                posts = _unitOfWork.RepositoryPosts.Search(posts, conditions);

                // Find related post reports.
                var postReports         = _unitOfWork.RepositoryPostReports.Search();
                var childrenPostReports = from post in posts
                                          from postReport in postReports
                                          where post.Id == postReport.PostIndex
                                          select postReport;

                // Remove posts & post reports from database.
                _unitOfWork.RepositoryPosts.Remove(posts);
                _unitOfWork.RepositoryPostReports.Remove(childrenPostReports);

                // Save changes and count the number of deleted records.
                var totalRecords = await _unitOfWork.CommitAsync();

                // No record has been deleted.
                if (totalRecords < 1)
                {
                    _log.Error("No post with specific conditions is found");
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, HttpMessages.PostNotFound));
                }

                #endregion

                // Tell the client , deletion is successful.
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception exception)
            {
                _log.Error(exception.Message, exception);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
Example #2
0
        public async Task <HttpResponseMessage> FindPosts([FromBody] SearchPostViewModel conditions)
        {
            try
            {
                #region Parameters validation

                // Conditions haven't been initialized.
                if (conditions == null)
                {
                    conditions = new SearchPostViewModel();
                    Validate(conditions);
                }

                // Parameters are invalid.
                if (!ModelState.IsValid)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }

                #endregion

                // Initiate search result.
                var searchResult = new SearchResult <IQueryable <Post> >();

                // Search posts by using specific conditions.
                var posts = _unitOfWork.RepositoryPosts.Search();
                posts = _unitOfWork.RepositoryPosts.Search(posts, conditions);

                // Count the number of condition matched records.
                searchResult.Total = await posts.CountAsync();

                // Order and paginate record.
                searchResult.Records = UnitOfWork.RepositoryPosts.Paginate(posts, conditions.Pagination);

                return(Request.CreateResponse(HttpStatusCode.OK, searchResult));
            }
            catch (Exception exception)
            {
                _log.Error(exception.Message, exception);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
Example #3
0
        /// <summary>
        ///     Search posts by using specific conditions.
        /// </summary>
        /// <param name="posts"></param>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public IQueryable <Post> Search(IQueryable <Post> posts, SearchPostViewModel conditions)
        {
            // Id is specified.
            if (conditions.Id != null)
            {
                posts = posts.Where(x => x.Id == conditions.Id.Value);
            }

            // Owner index is specified.
            if (conditions.OwnerId != null)
            {
                posts = posts.Where(x => x.OwnerIndex == conditions.OwnerId.Value);
            }

            // Category index is specified.
            if (conditions.CategoryId != null)
            {
                posts = posts.Where(x => x.CategoryIndex == conditions.CategoryId.Value);
            }

            // Title is specified.
            if (conditions.Title != null && !string.IsNullOrEmpty(conditions.Title.Value))
            {
                var szTitle = conditions.Title;
                switch (szTitle.Mode)
                {
                case TextSearchMode.Contain:
                    posts = posts.Where(x => x.Title.Contains(szTitle.Value));
                    break;

                case TextSearchMode.Equal:
                    posts = posts.Where(x => x.Title.Equals(szTitle.Value));
                    break;

                case TextSearchMode.EqualIgnoreCase:
                    posts =
                        posts.Where(x => x.Title.Equals(szTitle.Value, StringComparison.CurrentCultureIgnoreCase));
                    break;

                case TextSearchMode.StartsWith:
                    posts = posts.Where(x => x.Title.StartsWith(szTitle.Value));
                    break;

                case TextSearchMode.StartsWithIgnoreCase:
                    posts =
                        posts.Where(
                            x => x.Title.StartsWith(szTitle.Value, StringComparison.CurrentCultureIgnoreCase));
                    break;

                case TextSearchMode.EndsWith:
                    posts = posts.Where(x => x.Title.EndsWith(szTitle.Value));
                    break;

                case TextSearchMode.EndsWithIgnoreCase:
                    posts =
                        posts.Where(
                            x => x.Title.EndsWith(szTitle.Value, StringComparison.CurrentCultureIgnoreCase));
                    break;

                default:
                    posts = posts.Where(x => x.Title.ToLower().Contains(szTitle.Value.ToLower()));
                    break;
                }
            }

            // Body is specified.
            if (conditions.Body != null && !string.IsNullOrEmpty(conditions.Body.Value))
            {
                var szBody = conditions.Body;
                switch (szBody.Mode)
                {
                case TextSearchMode.Contain:
                    posts = posts.Where(x => x.Body.Contains(szBody.Value));
                    break;

                case TextSearchMode.Equal:
                    posts = posts.Where(x => x.Body.Equals(szBody.Value));
                    break;

                case TextSearchMode.EqualIgnoreCase:
                    posts =
                        posts.Where(x => x.Body.Equals(szBody.Value, StringComparison.CurrentCultureIgnoreCase));
                    break;

                case TextSearchMode.StartsWith:
                    posts = posts.Where(x => x.Body.StartsWith(szBody.Value));
                    break;

                case TextSearchMode.StartsWithIgnoreCase:
                    posts =
                        posts.Where(
                            x => x.Body.StartsWith(szBody.Value, StringComparison.CurrentCultureIgnoreCase));
                    break;

                case TextSearchMode.EndsWith:
                    posts = posts.Where(x => x.Body.EndsWith(szBody.Value));
                    break;

                case TextSearchMode.EndsWithIgnoreCase:
                    posts =
                        posts.Where(
                            x => x.Body.EndsWith(szBody.Value, StringComparison.CurrentCultureIgnoreCase));
                    break;

                default:
                    posts = posts.Where(x => x.Body.ToLower().Contains(szBody.Value.ToLower()));
                    break;
                }
            }

            // CreatedTime is specified.
            if (conditions.CreatedTime != null)
            {
                var created = conditions.CreatedTime;

                // From is defined.
                if (created.From != null)
                {
                    posts = posts.Where(x => x.CreatedTime >= created.From.Value);
                }

                // To is defined.
                if (created.To != null)
                {
                    posts = posts.Where(x => x.CreatedTime <= created.To.Value);
                }
            }

            // Last modified is specified.
            if (conditions.LastModifiedTime != null)
            {
                var lastModifiedTime = conditions.LastModifiedTime;

                // From is defined.
                if (lastModifiedTime.From != null)
                {
                    posts = posts.Where(x => x.LastModifiedTime >= lastModifiedTime.From.Value);
                }

                // To is defined.
                if (lastModifiedTime.To != null)
                {
                    posts = posts.Where(x => x.LastModifiedTime <= lastModifiedTime.To.Value);
                }
            }

            return(posts);
        }
Example #4
0
        /// <summary>
        ///     Initiate a post report with given information.
        /// </summary>
        /// <returns></returns>
        public async Task <HttpResponseMessage> InitiatePostReport([FromBody] InitiatePostReportViewModel parameters)
        {
            try
            {
                #region Parameters validation

                // Parameters haven't been initialized..
                if (parameters == null)
                {
                    // Initiate the parameters.
                    parameters = new InitiatePostReportViewModel();
                    Validate(parameters);
                }

                // Parameters are invalid.
                if (!ModelState.IsValid)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState));
                }

                #endregion

                #region Search post report

                // Search all posts.
                var posts = UnitOfWork.RepositoryPosts.Search();

                // Conditions construction.
                var findPostViewModel = new SearchPostViewModel();
                findPostViewModel.Id = parameters.PostIndex;

                // Search the post information.
                var post = await UnitOfWork.RepositoryPosts.Search(posts, findPostViewModel).FirstOrDefaultAsync();

                // Post is not found.
                if (post == null)
                {
                    _log.Error($"There is no post (ID: {parameters.PostIndex}) has been found in database");
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, HttpMessages.PostNotFound));
                }

                #endregion

                #region Requester search.

                // Search the request sender.
                var requester = _identityService.FindAccount(Request.Properties);

                // Requester is not found.
                if (requester == null)
                {
                    _log.Error("No requester is found in the request.");
                    return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized,
                                                       HttpMessages.RequestIsUnauthenticated));
                }

                #endregion

                #region Report initialization.

                var postReport = new PostReport();
                postReport.PostIndex         = post.Id;
                postReport.PostOwnerIndex    = post.OwnerIndex;
                postReport.PostReporterIndex = requester.Id;
                postReport.Body    = post.Body;
                postReport.Reason  = parameters.Reason;
                postReport.Created = _timeService.DateTimeUtcToUnix(DateTime.UtcNow);

                // Initiate post report into database.
                postReport = UnitOfWork.RepositoryPostReports.Insert(postReport);

                // Commit changes.
                #endregion

                // Tell the client about the post report.
                return(Request.CreateResponse(HttpStatusCode.OK, postReport));
            }
            catch (Exception exception)
            {
                _log.Error(exception.Message, exception);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
Example #5
0
        public async Task <HttpResponseMessage> UpdatePosts([FromUri] int index,
                                                            [FromBody] InitiatePostViewModel parameters)
        {
            try
            {
                #region Parameters validation

                // Parameters haven't been initialized.
                if (parameters == null)
                {
                    parameters = new InitiatePostViewModel();
                    Validate(parameters);
                }

                //Request parameters are invalid
                if (!ModelState.IsValid)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState));
                }

                #endregion

                #region Account identity search

                // Search account from request.
                var account = _identityService.FindAccount(Request.Properties);
                if (account == null)
                {
                    throw new Exception("No account has attached to request");
                }

                #endregion

                #region Information available check

                // Search the post by index.
                var condition = new SearchPostViewModel();
                condition.Id = index;

                // If account is not admin. It can only change its own posts.
                if (account.Role != Roles.Admin)
                {
                    condition.OwnerIndex = account.Id;
                }

                // Search all posts in database.
                var posts = _unitOfWork.RepositoryPosts.Search();
                posts = _unitOfWork.RepositoryPosts.Search(posts, condition);

                #endregion

                #region Update post

                // Search the current time on the system.
                var unixSystemTime = _timeService.DateTimeUtcToUnix(DateTime.UtcNow);

                foreach (var post in posts)
                {
                    post.CategoryIndex = parameters.CategoryIndex;
                    post.Title         = parameters.Title;
                    post.Body          = parameters.Body;
                    post.LastModified  = unixSystemTime;
                }

                // Save changes into database.
                await _unitOfWork.CommitAsync();

                #endregion

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception exception)
            {
                _log.Error(exception.Message, exception);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
                                                   "Error occured while executing post update"));
            }
        }