コード例 #1
0
        public async Task <IActionResult> CreateComment([FromBody] AddCommentResource commentResource)
        {
            Models.Photo photo = await this.photoRepository.GetAsync(commentResource.PhotoId);

            Models.Comment parentComment = commentResource.ParentId.HasValue ? await commentRepository.GetAsync(commentResource.ParentId.Value) : null;

            bool isParentCommentFromSamePhoto = (parentComment != null) && (parentComment.Photo.Id == commentResource.PhotoId);

            if (photo != null && (!commentResource.ParentId.HasValue || isParentCommentFromSamePhoto))
            {
                var comment     = this.mapper.Map <AddCommentResource, Models.Comment>(commentResource);
                var currentUser = new Models.User()
                {
                    UserName = User.FindFirstValue(ClaimTypes.Name)
                };
                comment.Author = this.userRepository.GetOrAdd(currentUser);
                comment.Photo  = photo;
                this.commentRepository.Add(comment);
                await this.unitOfWork.CompleteAsync();

                CommentResource resourceResult = mapper.Map <Models.Comment, CommentResource>(comment);
                resourceResult.ConnectionId = commentResource.ConnectionId;
                NotifyCommentAdded(comment.Id, commentResource.ConnectionId);

                return(Ok(resourceResult));
            }
            else
            {
                return(BadRequest());
            }
        }
コード例 #2
0
ファイル: CommentController.cs プロジェクト: GedeonHuy/PMS
        public async Task <IActionResult> UpdateComment(int id, [FromBody] CommentResource commentResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var comment = await commentRepository.GetComment(id);

            if (comment == null)
            {
                return(NotFound());
            }

            mapper.Map <CommentResource, Comment>(commentResource, comment);

            comment.Task = await taskRepository.GetTask(commentResource.TaskId);

            comment.User = userRepository.GetUserByEmail(commentResource.Email);

            await unitOfWork.Complete();

            var result = mapper.Map <Comment, CommentResource>(comment);

            return(Ok(result));
        }
コード例 #3
0
        public async Task <IActionResult> CreateComment([FromBody] CommentResource commentResource)
        {
            Photo photo = await this.photoRepository.GetAsync(commentResource.PhotoId);

            if (photo != null)
            {
                var comment     = this.mapper.Map <CommentResource, Comment>(commentResource);
                var currentUser = new User()
                {
                    UserName = User.FindFirstValue(ClaimTypes.Name)
                };
                comment.Author = this.userRepository.GetOrAdd(currentUser);
                comment.Photo  = photo;
                this.commentRepository.Add(comment);
                await this.unitOfWork.CompleteAsync();

                CommentResource resourceResult = mapper.Map <Comment, CommentResource>(comment);
                resourceResult.ConnectionId = commentResource.ConnectionId;
                NotifyCommentAdded(comment.Id, commentResource.ConnectionId);

                return(Ok(resourceResult));
            }
            else
            {
                return(NoContent());
            }
        }
コード例 #4
0
        public async Task <IActionResult> UpdateComment([FromRoute] int id, [FromForm] CommentResource commentResource)
        {
            Models.Comment comment = await commentRepository.GetAsync(id);

            if (comment != null)
            {
                var userName = User.FindFirstValue(ClaimTypes.Name);
                if (comment.Author.UserName != userName)
                {
                    return(Forbid());
                }
                if (string.IsNullOrEmpty(commentResource.Content))
                {
                    return(BadRequest());
                }

                comment.Content      = commentResource.Content;
                comment.ModifiedDate = DateTime.UtcNow;
                await this.unitOfWork.CompleteAsync();

                var outputCommentResource = mapper.Map <Models.Comment, CommentResource>(comment);
                return(Ok(outputCommentResource));
            }
            else
            {
                return(NotFound());
            }
        }
コード例 #5
0
        /// <inheritdoc />
        /// <summary>
        /// Add a new comment &lt;b&gt;Permissions Needed:&lt;/b&gt; COMMENTS_USER or COMMENTS_ADMIN
        /// </summary>
        /// <param name="commentResource">The comment to be added</param>
        public void AddComment(CommentResource commentResource)
        {
            mWebCallEvent.WebPath = "/comments";
            if (!string.IsNullOrEmpty(mWebCallEvent.WebPath))
            {
                mWebCallEvent.WebPath = mWebCallEvent.WebPath.Replace("{format}", "json");
            }

            mWebCallEvent.HeaderParams.Clear();
            mWebCallEvent.QueryParams.Clear();
            mWebCallEvent.AuthSettings.Clear();
            mWebCallEvent.PostBody = null;

            mWebCallEvent.PostBody = KnetikClient.Serialize(commentResource); // http body (model) parameter

            // authentication settings
            mWebCallEvent.AuthSettings.Add("oauth2_client_credentials_grant");

            // authentication settings
            mWebCallEvent.AuthSettings.Add("oauth2_password_grant");

            // make the HTTP request
            mAddCommentStartTime      = DateTime.Now;
            mWebCallEvent.Context     = mAddCommentResponseContext;
            mWebCallEvent.RequestType = KnetikRequestType.POST;

            KnetikLogger.LogRequest(mAddCommentStartTime, "AddComment", "Sending server request...");
            KnetikGlobalEventSystem.Publish(mWebCallEvent);
        }
コード例 #6
0
ファイル: AddComment.cs プロジェクト: NhatTanVu/myalbum
        public async Task AddComment()
        {
            // Arrange
            string seed        = Guid.NewGuid().ToString();
            int    seedPhotoId = new Random().Next(1, 100);

            string            expectedUserName  = string.Format("test_{0}@gmail.com", seed);
            ControllerContext controllerContext = Utilities.SetupCurrentUserForController(expectedUserName);

            var  mockUserRepository = new Mock <IUserRepository>();
            User expectedUser       = new User()
            {
                Id       = seed,
                UserName = expectedUserName
            };

            mockUserRepository.Setup(m => m.GetOrAdd(It.IsAny <User>())).Returns(expectedUser);

            var mockPhotoRepository = new Mock <IPhotoRepository>();

            mockPhotoRepository.Setup(m => m.GetAsync(seedPhotoId, true)).ReturnsAsync(new Photo()
            {
                Id = seedPhotoId
            });

            var mockHubClients = new Mock <IHubClients>();

            mockHubClients.SetupGet(m => m.All).Returns(new Mock <IClientProxy>().Object);
            var mockCommentHub = new Mock <IHubContext <CommentHub> >();

            mockCommentHub.SetupGet(m => m.Clients).Returns(mockHubClients.Object);

            var mockCommentRepository = new Mock <ICommentRepository>();
            var mockUnitOfWork        = new Mock <IUnitOfWork>();

            CommentsController controller = new CommentsController(this._mapper, mockCommentHub.Object,
                                                                   mockCommentRepository.Object, mockUserRepository.Object, mockPhotoRepository.Object, mockUnitOfWork.Object);

            controller.ControllerContext = controllerContext;
            CommentResource originalResource = new CommentResource()
            {
                Id      = new Random().Next(1, 100),
                Content = seed,
                PhotoId = seedPhotoId,
                Author  = new UserResource()
                {
                    UserName = expectedUserName
                }
            };
            // Act
            var result = await controller.CreateComment(originalResource);

            // Assert
            Assert.IsType <OkObjectResult>(result);
            Assert.IsType <CommentResource>(((OkObjectResult)result).Value);
            CommentResource returnedPhotoResource = (CommentResource)((OkObjectResult)result).Value;

            Assert.True(returnedPhotoResource.Equals(originalResource));
        }
コード例 #7
0
        /// <summary>
        /// Create a comment.
        /// </summary>
        /// <param name="comment">The comment to create.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The comment that was returned from the server.</returns>
        public async Task <CommentResource> CreateAsync(CommentResource comment, CancellationToken cancellationToken = default(CancellationToken))
        {
            var response = await _httpClient.PostAsync("v1/comments", new JsonApiContent <CommentResource>(comment, _contractResolver), cancellationToken);

            response.EnsureSuccessStatusCode();

            return(await response.Content.ReadAsJsonApiAsync <CommentResource>(_contractResolver));
        }
コード例 #8
0
        public async Task <IActionResult> PutCommentForExperiencePostAsync(Guid experiencePostUuid, [FromBody] NewCommentResource newComment)
        {
            Comment comment = mapper.Map <NewCommentResource, Comment>(newComment);

            comment.UserMail = httpContextRetriever.HttpContext.User.Identity.Name;

            await commentService.AddRootCommentToExperiencePostAsync(experiencePostUuid, comment);

            CommentResource retComment = mapper.Map <Comment, CommentResource>(comment);

            return(Ok(retComment));
        }
コード例 #9
0
        public async Task <IActionResult> ReplyToCommentAsync(Guid commentUuid, [FromBody] NewCommentResource newComment)
        {
            if (commentUuid == null)
            {
                return(BadRequest("Invalid comment UUID"));
            }

            Comment comment = mapper.Map <NewCommentResource, Comment>(newComment);

            comment.UserMail          = httpContextRetriever.HttpContext.User.Identity.Name;
            comment.ParentCommentUuid = commentUuid;

            await commentService.ReplyToCommentAsync(comment);

            CommentResource retComment = mapper.Map <Comment, CommentResource>(comment);

            return(Ok(retComment));
        }
        public async Task <IActionResult> Create([FromBody] CommentResource model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var userId = Int32.Parse((HttpContext.User.FindFirst("id").Value));

            Comment comment = _mapper.Map <CommentResource, Comment>(model);

            comment.UserId = userId;

            var commentResponse = await _commentService.CreateAsync(comment);

            if (!commentResponse.Success)
            {
                return(BadRequest(commentResponse.Message));
            }

            return(Ok(commentResponse.Extra));
        }
コード例 #11
0
        /// <summary>
        /// Create a comment.
        /// </summary>
        /// <param name="comment">The comment to create.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The comment that was returned from the server.</returns>
        public async Task UpdateAsync(CommentResource comment, CancellationToken cancellationToken = default(CancellationToken))
        {
            var response = await _httpClient.PatchAsync($"v1/comments/{comment.Id}", new JsonApiContent <CommentResource>(comment, _contractResolver), cancellationToken);

            response.EnsureSuccessStatusCode();
        }
コード例 #12
0
        /// <summary>
        /// Add a new comment &lt;b&gt;Permissions Needed:&lt;/b&gt; COMMENTS_USER or COMMENTS_ADMIN
        /// </summary>
        /// <exception cref="com.knetikcloud.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="commentResource">The comment to be added (optional)</param>
        /// <returns>ApiResponse of CommentResource</returns>
        public ApiResponse <CommentResource> AddCommentWithHttpInfo(CommentResource commentResource = null)
        {
            var    localVarPath         = "/comments";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (commentResource != null && commentResource.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(commentResource); // http body (model) parameter
            }
            else
            {
                localVarPostBody = commentResource; // byte array
            }

            // authentication (oauth2_client_credentials_grant) required
            // oauth required
            if (!String.IsNullOrEmpty(Configuration.AccessToken))
            {
                localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
            }
            // authentication (oauth2_password_grant) required
            // oauth required
            if (!String.IsNullOrEmpty(Configuration.AccessToken))
            {
                localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
            }

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)Configuration.ApiClient.CallApi(localVarPath,
                                                                                            Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                            localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("AddComment", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <CommentResource>(localVarStatusCode,
                                                     localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                                     (CommentResource)Configuration.ApiClient.Deserialize(localVarResponse, typeof(CommentResource))));
        }
コード例 #13
0
        /// <summary>
        /// Add a new comment &lt;b&gt;Permissions Needed:&lt;/b&gt; COMMENTS_USER or COMMENTS_ADMIN
        /// </summary>
        /// <exception cref="com.knetikcloud.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="commentResource">The comment to be added (optional)</param>
        /// <returns>CommentResource</returns>
        public CommentResource AddComment(CommentResource commentResource = null)
        {
            ApiResponse <CommentResource> localVarResponse = AddCommentWithHttpInfo(commentResource);

            return(localVarResponse.Data);
        }
コード例 #14
0
 public IHttpActionResult Execute([FromBody] CommentResource comment)
 {
     throw new NotImplementedException();
 }