Esempio n. 1
0
        public async Task <Comment> CreateAsync(Comment comment)
        {
            var tokenResult = await tokenProvider.RequestAccessToken(new AccessTokenRequestOptions()
            {
                Scopes = new string[] { "commentsgrpc" }
            });

            if (tokenResult.TryGetToken(out var token))
            {
                GrpCore.Metadata headers = new GrpCore.Metadata();
                headers.Add("Authorization", $"Bearer {token.Value}");

                CreateRequest createRequest = new CreateRequest()
                {
                    PhotoId = comment.PhotoId, Subject = comment.Subject, Body = comment.Body
                };
                CreateReply c = await serviceClient.CreateAsync(createRequest, headers);

                return(new Comment {
                    Id = c.Id, PhotoId = c.PhotoId, UserName = c.UserName, Subject = c.Subject, Body = c.Body, SubmittedOn = c.SubmittedOn.ToDateTime()
                });
            }
            else
            {
                throw new UnauthorizedCreateAttemptException <Comment>();
            }
        }
Esempio n. 2
0
        public async Task <Comment> CreateAsync(Comment comment, string tokenValue)
        {
            Grpc.Core.Metadata headers = new Grpc.Core.Metadata();
            headers.Add("Authorization", $"Bearer {tokenValue}");
            CreateReply c = await commentsThingClient.CreateAsync(comment.ToCreateRequest(), headers);

            return(c.ToComment());
        }
Esempio n. 3
0
        public async Task <Photo> CreateAsync(Photo photo, string tokenValue)
        {
            Grpc.Core.Metadata headers = new Grpc.Core.Metadata();
            headers.Add("Authorization", $"Bearer {tokenValue}");
            CreateReply p = await photosThingClient.CreateAsync(photo.ToCreateRequest(), headers);

            return(p.ToPhoto());
        }
Esempio n. 4
0
 public ActionResult CreateReply(int id)
 {
     if (true != User.Identity.IsAuthenticated)
     {
         return(RedirectToAction("Login", "Account"));
     }
     else
     {
         CreateReply rep = new CreateReply(this.PostDB.Find(id));
         return(View(rep));
     }
 }
Esempio n. 5
0
        public void Validate_EverythingOk_SucceedsValidation()
        {
            var create = new CreateReply
            {
                Content = "Valid content"
            };

            var context = new ValidationContext(create);
            var result  = Validator.TryValidateObject(create, context, null, true);

            Assert.True(result, "Validation of all properties failed");
        }
Esempio n. 6
0
        public async Task <Comment> CreateAsync(Comment comment)
        {
            CreateRequest createRequest = new CreateRequest()
            {
                PhotoId = comment.PhotoId, Subject = comment.Subject, Body = comment.Body
            };
            CreateReply c = await serviceClient.CreateAsync(createRequest);

            return(new Comment {
                Id = c.Id, PhotoId = c.PhotoId, UserName = c.UserName, Subject = c.Subject, Body = c.Body, SubmittedOn = c.SubmittedOn.ToDateTime()
            });
        }
Esempio n. 7
0
        public override Task <CreateReply> Create(CreateRequest request, ServerCallContext context)
        {
            (var sim, var gameId) = _patchwork.CreateSimulation(null /*request.RandomSeed*/, request.OpponentStrength);
            //Console.WriteLine("Created game " + gameId);

            var res = new CreateReply
            {
                GameId      = gameId,
                Observation = new Observation()
            };

            PopulateObservation(res.Observation, sim);
            return(Task.FromResult(res));
        }
Esempio n. 8
0
        public void Validate_ContentNotSpecified_FailsValidation()
        {
            var create = new CreateReply
            {
                Content = string.Empty
            };

            var context = new ValidationContext(create)
            {
                MemberName = nameof(create.Content)
            };
            var result = Validator.TryValidateProperty(create.Content, context, null);

            Assert.False(result, "Validation of content succeeded");
        }
Esempio n. 9
0
        public void Map_FromCreateToReply_MapsExpectedProperties()
        {
            var create = new CreateReply
            {
                Content = "This is content"
            };

            var reply = Mapper.Map <Reply>(create);

            Assert.Equal(create.Content, reply.Content);
            var justNow = DateTime.Now.AddMilliseconds(-10);

            Assert.True(justNow < reply.CreatedAt, "justNow < reply.CreatedAt");
            Assert.True(justNow < reply.UpdatedAt, "justNow < reply.UpdatedAt");
        }
Esempio n. 10
0
        public async Task <ActionResult <ReplyResponse> > Create(int postId, CreateReply create)
        {
            var reply = await _replyService.Create(postId, create);

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

            var response = _mapper.Map <ReplyResponse>(reply);

            response.Author = _userService.Auth().Username;

            return(Created($"api/post/{postId}/reply/{response.Id}", response));
        }
Esempio n. 11
0
        //post reply to comment
        public bool CreateReply(CreateReply model)
        {
            var entity =
                new Reply()
            {
                UserId  = _userId,
                Content = model.Content,
            };

            using (var ctx = new ApplicationDbContext())
            {
                ctx.Reply.Add(entity);
                return(ctx.SaveChanges() == 1);
            }
        }
        public bool CreateReply(CreateReply model)
        {
            var entity =
                new Reply()
            {
                Author    = _userId,
                Text      = model.Text,
                CommentId = model.CommentId,
            };

            using (var ctx = new ApplicationDbContext())
            {
                ctx.Replies.Add(entity);

                return(ctx.SaveChanges() == 1);
            }
        }
Esempio n. 13
0
 public ActionResult CreateReply(int id, CreateReply reply)
 {
     if (ModelState.IsValid)
     {
         PostReply pReply = new PostReply();
         pReply.Author     = this.UserDB.GetByUserName(User.Identity.Name);
         pReply.Head       = this.PostDB.Find(id);
         pReply.Text       = reply.Text;
         pReply.TimeOfPost = DateTime.UtcNow;
         this.PostReplyDB.Add(pReply);
         return(RedirectToAction("View", "Post", new { Id = id }));
     }
     else
     {
         return(View(reply));
     }
 }
Esempio n. 14
0
        //CRUD METHODS

        //========CREATE========//

        //POST
        public IHttpActionResult Post(CreateReply comment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            //instantitate service
            ReplyService service = CreateReplyService();

            if (!service.CreateReply(comment))
            {
                return(InternalServerError());
            }

            return(Ok());
        }
Esempio n. 15
0
        public async Task CreateAsync(CreateReply command)
        {
            await _createValidator.ValidateCommandAsync(command);

            var reply = Post.CreateReply(command.Id,
                                         command.TopicId,
                                         command.ForumId,
                                         command.UserId,
                                         command.Content,
                                         command.Status);

            _dbContext.Posts.Add(reply);

            _dbContext.Events.Add(new Event(command.SiteId,
                                            command.UserId,
                                            EventType.Created,
                                            typeof(Post),
                                            command.Id,
                                            new
            {
                command.TopicId,
                command.ForumId,
                command.Content,
                command.Status
            }));

            var topic = await _dbContext.Posts
                        .Include(x => x.Forum)
                        .ThenInclude(x => x.Category)
                        .FirstOrDefaultAsync(x => x.Id == reply.TopicId);

            topic.UpdateLastReply(reply.Id);
            topic.IncreaseRepliesCount();
            topic.Forum.UpdateLastPost(reply.Id);
            topic.Forum.IncreaseRepliesCount();
            topic.Forum.Category.IncreaseRepliesCount();

            var user = await _dbContext.Users.FirstOrDefaultAsync(x => x.Id == reply.CreatedBy);

            user.IncreaseRepliesCount();

            await _dbContext.SaveChangesAsync();

            _cacheManager.Remove(CacheKeys.Forum(topic.ForumId));
        }
Esempio n. 16
0
        public async Task Create_PostDoesNotExist_DoesNotCreateReply()
        {
            var create = new CreateReply();
            var reply  = new Reply {
                Content = "Content"
            };
            const string userId = "User id";

            A.CallTo(() => Mapper.Map <Reply>(create)).Returns(reply);
            A.CallTo(() => User.Exists()).Returns(true);
            A.CallTo(() => PostService.Read(1)).Returns(null as Post);
            A.CallTo(() => User.Id()).Returns(userId);

            var response = await ReplyService.Create(1, create);

            Assert.Null(response);
            A.CallTo(() => ReplyRepository.Create(A <Reply> .Ignored))
            .MustNotHaveHappened();
        }
Esempio n. 17
0
        public async Task Create_Unauthenticated_DoesNotCreateReply()
        {
            var create = new CreateReply();
            var reply  = new Reply {
                Content = "Content"
            };
            var post = new Post {
                Id = 1
            };

            A.CallTo(() => Mapper.Map <Reply>(create)).Returns(reply);
            A.CallTo(() => User.Exists()).Returns(false);
            A.CallTo(() => PostService.Read(1)).Returns(post);

            var response = await ReplyService.Create(1, create);

            Assert.Null(response);
            A.CallTo(() => ReplyRepository.Create(A <Reply> .Ignored))
            .MustNotHaveHappened();
        }
Esempio n. 18
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="threadId">The ID of the database.</param>
        /// <param name="collectionName">The human-readable name for the database.</param>
        /// <param name="values"></param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public async Task <IList <string> > CreateAsync <T>(ThreadId threadId, string collectionName, IEnumerable <T> values, CancellationToken cancellationToken = default)
        {
            CreateRequest request = new()
            {
                DbID           = ByteString.CopyFrom(threadId.Bytes),
                CollectionName = collectionName
            };

            IEnumerable <ByteString> serializedValues = values.Select(v => ByteString.CopyFrom(JsonSerializer.SerializeToUtf8Bytes <T>(v)));

            request.Instances.AddRange(serializedValues);

            try
            {
                CreateReply reply = await _apiClient.CreateAsync(request, headers : _threadContext.Metadata, cancellationToken : cancellationToken);

                return(reply.InstanceIDs.ToList());
            }
            catch (RpcException ex) when(ex.Status.Detail == "app denied net record body")
            {
                throw new InvalidOperationException(ex.Status.Detail);
            }
        }
Esempio n. 19
0
        public async Task <ActionResult> CreateReply(TopicPageModel model)
        {
            var site = await _contextService.CurrentSiteAsync();

            var user = await _contextService.CurrentUserAsync();

            var permissions = await _permissionModelBuilder.BuildPermissionModelsByForumId(site.Id, model.Forum.Id);

            var canReply = _securityService.HasPermission(PermissionType.Reply, permissions) && !user.IsSuspended;

            if (!canReply)
            {
                _logger.LogWarning("Unauthorized access to create reply.", new
                {
                    SiteId  = site.Id,
                    ForumId = model.Forum?.Id,
                    TopicId = model.Topic?.Id,
                    User    = User.Identity.Name
                });

                return(Unauthorized());
            }

            var command = new CreateReply
            {
                ForumId = model.Forum.Id,
                TopicId = model.Topic.Id,
                Content = model.Post.Content,
                Status  = PostStatusType.Published,
                SiteId  = site.Id,
                UserId  = user.Id
            };

            await _replyService.CreateAsync(command);

            return(Ok());
        }
Esempio n. 20
0
        public async Task Create_EverythingOk_CreatesReply()
        {
            const string userId = "User id";
            var          create = new CreateReply();
            var          reply  = new Reply {
                Content = "Content"
            };
            var post = new Post {
                Id = 1
            };

            A.CallTo(() => User.Exists()).Returns(true);
            A.CallTo(() => Mapper.Map <Reply>(create)).Returns(reply);
            A.CallTo(() => User.Id()).Returns(userId);
            A.CallTo(() => PostService.Read(1)).Returns(post);

            await ReplyService.Create(1, create);

            A.CallTo(() => ReplyRepository.Create(A <Reply> .That.Matches(r =>
                                                                          r.Content == reply.Content &&
                                                                          r.UserId == userId &&
                                                                          r.Post.Id == post.Id
                                                                          ))).MustHaveHappenedOnceExactly();
        }
Esempio n. 21
0
        public async Task <Reply> Create(int postId, CreateReply create)
        {
            if (!_userService.Exists())
            {
                _logger.LogWarning("User not authenticated");
                return(null);
            }
            var post = await _postService.Read(postId);

            if (post == null)
            {
                _logger.LogWarning($"Post {postId} not found");
                return(null);
            }

            var reply = _mapper.Map <Reply>(create);

            reply.UserId = _userService.Id();
            reply.Post   = post;

            await _replyRepository.Create(reply);

            return(reply);
        }
Esempio n. 22
0
 public static Photo ToPhoto(this CreateReply p) => new Photo(p.Id, p.Title, p.PhotoFile.ToArray(), p.ImageMimeType, p.Description, p.CreatedDate.ToDateTime(), p.UserName, null);
 public static Comment ToComment(this CreateReply c) => new Comment(c.Id, c.PhotoId, c.UserName, c.Subject, c.Body, c.SubmittedOn.ToDateTime());