예제 #1
0
        public async Task <IActionResult> OnGetFetchEditPostPartialAsync(CancellationToken cancellationToken)
        {
            //set this value to true as the partial page will include specific
            //elements in the modal based on this value
            EditPost = true;

            var baseAPIUrl = $"api/Posts/{Id}";

            try
            {
                //call the api with a GET request
                //ensure to set the httpcompletion mode to response headers read
                //this allows the response to be read as soon as content starts arriving instead of having to wait
                //until the entire response is read
                //with this option, we can read the response content into a stream and deserialize it
                var response = await(await _apiClient.WithAuthorization()).GetAsync(baseAPIUrl,
                                                                                    HttpCompletionOption.ResponseHeadersRead, cancellationToken);

                //return the same page with an error message if the user is trying to call the API too many times
                if (response.StatusCode == HttpStatusCode.TooManyRequests)
                {
                    TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                    return(Partial("_CreateEditPostPartial", this));
                }

                //ensure success status code else throw an exception
                response.EnsureSuccessStatusCode();

                //read the response content into a stream
                var streamContent = await response.Content.ReadAsStreamAsync();

                //deserialize the stream into an object (see StreamExtensions on how this is done)
                post = streamContent.ReadAndDeserializeFromJson <PostViewDto>();
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(Partial("_CreateEditPostPartial", this));
            }

            //see startup in AddMvc for how this partial is fetched
            //this was an answer found at https://softdevpractice.com/blog/asp-net-core-mvc-ajax-modals/
            return(Partial("_CreateEditPostPartial", this));
        }
예제 #2
0
        private PostViewDto GetTestPostViewDto()
        {
            var posts = new PostViewDto()
            {
                Id         = new Guid("e77551ba-78e2-4a36-8754-3ea5f12e1619"),
                Title      = "Test1",
                Message    = "Test1",
                Important  = false,
                DaysOld    = 0,
                Created    = DateTime.Now,
                OwnerName  = "ABC",
                OwnerEmail = "*****@*****.**"
            };

            return(posts);
        }
예제 #3
0
        public PostViewDto Handle()
        {
            var FriendList = _FriendListStore.GetFriendListOfUser(CurrentUser.Id);

            FriendList.Users = _FriendListStore.GetFriendsOfUser(FriendList.Id);

            var Notifications  = _NotificationBox.GetUserNotifications(ExistingAccount.Username);
            var FriendRequests = _FriendListStore.GetIncomingFriendRequests(FriendList.Id);
            var Posts          = GetCurrentUserPosts().Concat(GetAllFriendPosts(FriendList)).ToList();

            var postViewDTO = new PostViewDto
            {
                FriendRequestCount = FriendRequests.Count,
                NotificationCount  = Notifications.Count,
                Permissions        = ExistingAccount.UserType,
                AllPosts           = Posts
            };

            return(postViewDTO);
        }
        public async Task <IViewComponentResult> InvokeAsync()
        {
            var baseAPIUrl = $"api/posts/getlatestpost";

            try
            {
                //call the api with a GET request
                //ensure to set the httpcompletion mode to response headers read
                //this allows the response to be read as soon as content starts arriving instead of having to wait
                //until the entire response is read
                //with this option, we can read the response content into a stream and deserialize it
                var response = await(await _apiClient.WithGETOnlyAccessAuthorization()).GetAsync(baseAPIUrl,
                                                                                                 HttpCompletionOption.ResponseHeadersRead);

                if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
                {
                    TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                    return(View(new PostViewDto()));
                }

                //ensure success status code else throw an exception
                response.EnsureSuccessStatusCode();

                //read the response content into a stream
                var streamContent = await response.Content.ReadAsStreamAsync();

                //deserialize the stream into an object (see StreamExtensions on how this is done)
                PostForView = streamContent.ReadAndDeserializeFromJson <PostViewDto>();

                if (PostForView == null)
                {
                    return(View(new PostViewDto()));
                }

                //cut down the size of the message if its longer than 75 characters
                if (PostForView.Message.Length > 150)
                {
                    PostForView.Message = PostForView.Message.Substring(0, 150);

                    if (PostForView.Message.Contains("<a"))
                    {
                        PostForView.Message = PostForView.Message + "\"</a>" + "...";
                    }
                    else
                    {
                        PostForView.Message = PostForView.Message + "...";
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(View(new PostViewDto()));
            }


            return(View(PostForView));
        }
예제 #5
0
        /// <inheritdoc cref="IPostsService"/>
        public async Task <PostsViewDto> GetUserPostsAsync(string userId, PostsSearchParametersDto searchParameters)
        {
            var posts     = new PostsViewDto();
            var postsList = await this.Repository.TableNoTracking
                            .Where(post => post.AuthorId.Equals(userId))
                            .Include(x => x.Author)
                            .ThenInclude(x => x.Profile)
                            .Include(x => x.Comments)
                            .Include(x => x.PostsTagsRelations)
                            .ThenInclude(x => x.Tag)
                            .ToListAsync();

            if (!string.IsNullOrEmpty(searchParameters.Search))
            {
                postsList = postsList.Where(post => post.Title.ToLower().Contains(searchParameters.Search.ToLower())).ToList();
            }

            if (!string.IsNullOrEmpty(searchParameters.Tag))
            {
                postsList = postsList.Where(post =>
                                            post.PostsTagsRelations.Any(x => x.Tag.Title.ToLower().Equals(searchParameters.Tag.ToLower()))).ToList();
            }

            postsList = postsList.AsQueryable().OrderBy(searchParameters.SortParameters).ToList();

            var postsCount = postsList.Count;

            if (searchParameters.SortParameters.CurrentPage != null && searchParameters.SortParameters.PageSize != null)
            {
                postsList = postsList.AsQueryable().OrderBy(searchParameters.SortParameters)
                            .Skip((searchParameters.SortParameters.CurrentPage.Value - 1) *
                                  searchParameters.SortParameters.PageSize.Value)
                            .Take(searchParameters.SortParameters.PageSize.Value).ToList();
            }

            posts.Posts = new List <PostViewDto>();
            postsList.ForEach(post =>
            {
                var p = new PostViewDto
                {
                    Id            = post.Id,
                    Title         = post.Title,
                    Description   = post.Description,
                    Content       = post.Content,
                    Seen          = post.Seen,
                    Likes         = post.Likes,
                    Dislikes      = post.Dislikes,
                    ImageUrl      = post.ImageUrl,
                    AuthorId      = post.AuthorId,
                    Author        = this.mapper.Map <ApplicationUser, ApplicationUserDto>(post.Author),
                    CommentsCount = post.Comments.Count,
                    Tags          = post.PostsTagsRelations.Select(x => new TagViewDto
                    {
                        Id    = x.Tag.Id,
                        Title = x.Tag.Title,
                    }).ToList(),
                };
                post.Author.Profile.User = null;
                posts.Posts.Add(p);
            });

            if (searchParameters.SortParameters.CurrentPage != null && searchParameters.SortParameters.PageSize != null)
            {
                posts.PageInfo = new PageInfo
                {
                    PageNumber = searchParameters.SortParameters.CurrentPage.Value,
                    PageSize   = searchParameters.SortParameters.PageSize.Value,
                    TotalItems = postsCount,
                };
            }

            return(posts);
        }
예제 #6
0
        public async Task <IActionResult> OnGetAsync(CancellationToken cancellationToken)
        {
            TempData["PageNum"]  = PageParameters.PageNum;
            TempData["PageSize"] = PageParameters.PageSize;

            baseAPIUrl = $"api/Posts/{PostId}";

            try
            {
                //call the api with a GET request
                //ensure to set the httpcompletion mode to response headers read
                //this allows the response to be read as soon as content starts arriving instead of having to wait
                //until the entire response is read
                //with this option, we can read the response content into a stream and deserialize it
                var response = await(await _apiClient.WithGETOnlyAccessAuthorization()).GetAsync(baseAPIUrl,
                                                                                                 HttpCompletionOption.ResponseHeadersRead, cancellationToken);

                if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
                {
                    TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                    return(Page());
                }

                //ensure success status code else throw an exception
                response.EnsureSuccessStatusCode();

                //read the response content into a stream
                var streamContent = await response.Content.ReadAsStreamAsync();

                //deserialize the stream into an object (see StreamExtensions on how this is done)
                PostForView = streamContent.ReadAndDeserializeFromJson <PostViewDto>();
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(Page());
            }

            //change base api url to fetch comments
            baseAPIUrl = $"api/Posts/{PostId}/Comments";

            try
            {
                //call the api with a GET request
                //ensure to set the httpcompletion mode to response headers read
                //this allows the response to be read as soon as content starts arriving instead of having to wait
                //until the entire response is read
                //with this option, we can read the response content into a stream and deserialize it
                var response = await(await _apiClient.WithGETOnlyAccessAuthorization()).GetAsync(baseAPIUrl,
                                                                                                 HttpCompletionOption.ResponseHeadersRead, cancellationToken);

                if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
                {
                    TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                    return(Page());
                }

                //ensure success status code else throw an exception
                response.EnsureSuccessStatusCode();

                var header = response.Headers.GetValues("X-Pagination").FirstOrDefault();
                XPaginationDto = JsonConvert.DeserializeObject <XPaginationHeaderDto>(header);

                //read the response content into a stream
                var streamContent = await response.Content.ReadAsStreamAsync();

                //deserialize the stream into an object (see StreamExtensions on how this is done)
                CommentsForView = streamContent.ReadAndDeserializeFromJson <IEnumerable <CommentViewDto> >();
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(Page());
            }

            //set if the user is an administrator or not. This will allow user to delete/edit all items on the page
            UserIsAdmin = (User?.IsAdministrator() ?? false);

            return(Page());
        }